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MAAMy0E,QAAU,OAC1Bp3G,SAAS81G,eAAe,wBAAwB1tD,QAEpD,CAAE,MAAOx3E,GAEDA,EAAMyF,SACNe,QAAQxG,MAAMA,EAAMyF,SAASlF,OAAQP,EAAMyF,SAAS7E,MAEpD4F,QAAQxG,MAAM,kCAAkCA,EAAMC,WAI1DsmI,GAAUx0E,MAAMy0E,QAAU,MAC9B,CAGJ,CA4CgB8E,CAAWP,EAAavF,GAIpC,CACA,MAAOxlI,GACHwG,QAAQxG,MAAM,iDAAkDA,EACpE,CACJ,CA0IQurI,CAAiB7B,GAASL,GAAoBhsI,MAAOkoI,IAAU15H,MAAK,WAEzCw9H,GAgEvBhsI,MAAQ,GA/DRisI,IACJ,GAER,IAgVAD,GAAoBr4H,iBAAiB,QAASs4H,IAC9CD,GAAoBr4H,iBAAiB,SAAUs4H,IAG/CgB,GAAmBt5H,iBAAiB,SAAS,SAAUtZ,GACnDA,EAAEklE,iBACF4tE,GAAoBp2E,OACxB,IACAo2E,GAAoBx5H,iBAAiB,UAzXrC,SAA6B1K,GACzBA,EAAMs2D,iBACN,IAAIryD,EAAOjE,EAAM6M,OAAOuZ,MAAM,GAG9B69G,GAAiB/qE,QAGZj1D,EAAKxJ,KAAK4T,MAAM,YASjBqzH,MACAvB,GAAiBl8H,EAAMm/H,GAASnE,GAExC","sources":["webpack://friendlychat/webpack/bootstrap","webpack://friendlychat/webpack/runtime/global","webpack://friendlychat/./node_modules/openai/internal/qs/formats.mjs","webpack://friendlychat/./node_modules/openai/internal/qs/utils.mjs","webpack://friendlychat/./node_modules/openai/internal/qs/stringify.mjs","webpack://friendlychat/./node_modules/openai/version.mjs","webpack://friendlychat/./node_modules/openai/_shims/registry.mjs","webpack://friendlychat/./node_modules/openai/_shims/MultipartBody.mjs","webpack://friendlychat/./node_modules/openai/_shims/index.mjs","webpack://friendlychat/./node_modules/openai/_shims/web-runtime.mjs","webpack://friendlychat/./node_modules/openai/error.mjs","webpack://friendlychat/./node_modules/openai/internal/decoders/line.mjs","webpack://friendlychat/./node_modules/openai/internal/stream-utils.mjs","webpack://friendlychat/./node_modules/openai/streaming.mjs","webpack://friendlychat/./node_modules/openai/uploads.mjs","webpack://friendlychat/./node_modules/openai/core.mjs","webpack://friendlychat/./node_modules/openai/resource.mjs","webpack://friendlychat/./node_modules/openai/resources/completions.mjs","webpack://friendlychat/./node_modules/openai/resources/chat/completions/messages.mjs","webpack://friendlychat/./node_modules/openai/pagination.mjs","webpack://friendlychat/./node_modules/openai/resources/chat/completions/completions.mjs","webpack://friendlychat/./node_modules/openai/resources/chat/chat.mjs","webpack://friendlychat/./node_modules/openai/resources/embeddings.mjs","webpack://friendlychat/./node_modules/openai/resources/files.mjs","webpack://friendlychat/./node_modules/openai/resources/images.mjs","webpack://friendlychat/./node_modules/openai/resources/audio/speech.mjs","webpack://friendlychat/./node_modules/openai/resources/audio/transcriptions.mjs","webpack://friendlychat/./node_modules/openai/resources/audio/translations.mjs","webpack://friendlychat/./node_modules/openai/resources/audio/audio.mjs","webpack://friendlychat/./node_modules/openai/resources/moderations.mjs","webpack://friendlychat/./node_modules/openai/resources/models.mjs","webpack://friendlychat/./node_modules/openai/resources/fine-tuning/jobs/checkpoints.mjs","webpack://friendlychat/./node_modules/openai/resources/fine-tuning/jobs/jobs.mjs","webpack://friendlychat/./node_modules/openai/resources/fine-tuning/fine-tuning.mjs","webpack://friendlychat/./node_modules/openai/resources/beta/assistants.mjs","webpack://friendlychat/./node_modules/openai/lib/RunnableFunction.mjs","webpack://friendlychat/./node_modules/openai/lib/chatCompletionUtils.mjs","webpack://friendlychat/./node_modules/openai/lib/EventStream.mjs","webpack://friendlychat/./node_modules/openai/lib/parser.mjs","webpack://friendlychat/./node_modules/openai/lib/AbstractChatCompletionRunner.mjs","webpack://friendlychat/./node_modules/openai/lib/ChatCompletionRunner.mjs","webpack://friendlychat/./node_modules/openai/_vendor/partial-json-parser/parser.mjs","webpack://friendlychat/./node_modules/openai/lib/ChatCompletionStream.mjs","webpack://friendlychat/./node_modules/openai/lib/ChatCompletionStreamingRunner.mjs","webpack://friendlychat/./node_modules/openai/resources/beta/chat/completions.mjs","webpack://friendlychat/./node_modules/openai/resources/beta/chat/chat.mjs","webpack://friendlychat/./node_modules/openai/resources/beta/realtime/sessions.mjs","webpack://friendlychat/./node_modules/openai/resources/beta/realtime/realtime.mjs","webpack://friendlychat/./node_modules/openai/lib/AssistantStream.mjs","webpack://friendlychat/./node_modules/openai/index.mjs","webpack://friendlychat/./node_modules/openai/resources/beta/threads/messages.mjs","webpack://friendlychat/./node_modules/openai/resources/beta/threads/runs/steps.mjs","webpack://friendlychat/./node_modules/openai/resources/beta/threads/runs/runs.mjs","webpack://friendlychat/./node_modules/openai/resources/beta/threads/threads.mjs","webpack://friendlychat/./node_modules/openai/resources/beta/vector-stores/files.mjs","webpack://friendlychat/./node_modules/openai/resources/beta/vector-stores/file-batches.mjs","webpack://friendlychat/./node_modules/openai/lib/Util.mjs","webpack://friendlychat/./node_modules/openai/resources/beta/vector-stores/vector-stores.mjs","webpack://friendlychat/./node_modules/openai/resources/beta/beta.mjs","webpack://friendlychat/./node_modules/openai/resources/batches.mjs","webpack://friendlychat/./node_modules/openai/resources/uploads/parts.mjs","webpack://friendlychat/./node_modules/openai/resources/uploads/uploads.mjs","webpack://friendlychat/./node_modules/@firebase/util/dist/index.esm2017.js","webpack://friendlychat/./node_modules/@firebase/component/dist/esm/index.esm2017.js","webpack://friendlychat/./node_modules/@firebase/logger/dist/esm/index.esm2017.js","webpack://friendlychat/./node_modules/idb/build/wrap-idb-value.js","webpack://friendlychat/./node_modules/idb/build/index.js","webpack://friendlychat/./node_modules/@firebase/app/dist/esm/index.esm2017.js","webpack://friendlychat/./node_modules/tslib/tslib.es6.mjs","webpack://friendlychat/./node_modules/firebase/app/dist/esm/index.esm.js","webpack://friendlychat/./node_modules/@firebase/auth/dist/esm2017/index-e3d5d3f4.js","webpack://friendlychat/./node_modules/@firebase/webchannel-wrapper/dist/esm/index.esm2017.js","webpack://friendlychat/./node_modules/@firebase/firestore/dist/index.esm2017.js","webpack://friendlychat/./node_modules/@firebase/storage/dist/index.esm2017.js","webpack://friendlychat/./node_modules/@firebase/installations/node_modules/idb/build/wrap-idb-value.js","webpack://friendlychat/./node_modules/@firebase/installations/node_modules/idb/build/index.js","webpack://friendlychat/./node_modules/@firebase/installations/dist/esm/index.esm2017.js","webpack://friendlychat/./node_modules/@firebase/messaging/node_modules/idb/build/wrap-idb-value.js","webpack://friendlychat/./node_modules/@firebase/messaging/node_modules/idb/build/index.js","webpack://friendlychat/./node_modules/@firebase/messaging/dist/esm/index.esm2017.js","webpack://friendlychat/./node_modules/@firebase/performance/dist/esm/index.esm2017.js","webpack://friendlychat/./src/firebase-config.js","webpack://friendlychat/./src/index.js"],"sourcesContent":["// The require scope\nvar __webpack_require__ = {};\n\n","__webpack_require__.g = (function() {\n\tif (typeof globalThis === 'object') return globalThis;\n\ttry {\n\t\treturn this || new Function('return this')();\n\t} catch (e) {\n\t\tif (typeof window === 'object') return window;\n\t}\n})();","export const default_format = 'RFC3986';\nexport const formatters = {\n RFC1738: (v) => String(v).replace(/%20/g, '+'),\n RFC3986: (v) => String(v),\n};\nexport const RFC1738 = 'RFC1738';\nexport const RFC3986 = 'RFC3986';\n//# sourceMappingURL=formats.mjs.map","import { RFC1738 } from \"./formats.mjs\";\nconst has = Object.prototype.hasOwnProperty;\nconst is_array = Array.isArray;\nconst hex_table = (() => {\n const array = [];\n for (let i = 0; i < 256; ++i) {\n array.push('%' + ((i < 16 ? '0' : '') + i.toString(16)).toUpperCase());\n }\n return array;\n})();\nfunction compact_queue(queue) {\n while (queue.length > 1) {\n const item = queue.pop();\n if (!item)\n continue;\n const obj = item.obj[item.prop];\n if (is_array(obj)) {\n const compacted = [];\n for (let j = 0; j < obj.length; ++j) {\n if (typeof obj[j] !== 'undefined') {\n compacted.push(obj[j]);\n }\n }\n // @ts-ignore\n item.obj[item.prop] = compacted;\n }\n }\n}\nfunction array_to_object(source, options) {\n const obj = options && options.plainObjects ? Object.create(null) : {};\n for (let i = 0; i < source.length; ++i) {\n if (typeof source[i] !== 'undefined') {\n obj[i] = source[i];\n }\n }\n return obj;\n}\nexport function merge(target, source, options = {}) {\n if (!source) {\n return target;\n }\n if (typeof source !== 'object') {\n if (is_array(target)) {\n target.push(source);\n }\n else if (target && typeof target === 'object') {\n if ((options && (options.plainObjects || options.allowPrototypes)) ||\n !has.call(Object.prototype, source)) {\n target[source] = true;\n }\n }\n else {\n return [target, source];\n }\n return target;\n }\n if (!target || typeof target !== 'object') {\n return [target].concat(source);\n }\n let mergeTarget = target;\n if (is_array(target) && !is_array(source)) {\n // @ts-ignore\n mergeTarget = array_to_object(target, options);\n }\n if (is_array(target) && is_array(source)) {\n source.forEach(function (item, i) {\n if (has.call(target, i)) {\n const targetItem = target[i];\n if (targetItem && typeof targetItem === 'object' && item && typeof item === 'object') {\n target[i] = merge(targetItem, item, options);\n }\n else {\n target.push(item);\n }\n }\n else {\n target[i] = item;\n }\n });\n return target;\n }\n return Object.keys(source).reduce(function (acc, key) {\n const value = source[key];\n if (has.call(acc, key)) {\n acc[key] = merge(acc[key], value, options);\n }\n else {\n acc[key] = value;\n }\n return acc;\n }, mergeTarget);\n}\nexport function assign_single_source(target, source) {\n return Object.keys(source).reduce(function (acc, key) {\n acc[key] = source[key];\n return acc;\n }, target);\n}\nexport function decode(str, _, charset) {\n const strWithoutPlus = str.replace(/\\+/g, ' ');\n if (charset === 'iso-8859-1') {\n // unescape never throws, no try...catch needed:\n return strWithoutPlus.replace(/%[0-9a-f]{2}/gi, unescape);\n }\n // utf-8\n try {\n return decodeURIComponent(strWithoutPlus);\n }\n catch (e) {\n return strWithoutPlus;\n }\n}\nconst limit = 1024;\nexport const encode = (str, _defaultEncoder, charset, _kind, format) => {\n // This code was originally written by Brian White for the io.js core querystring library.\n // It has been adapted here for stricter adherence to RFC 3986\n if (str.length === 0) {\n return str;\n }\n let string = str;\n if (typeof str === 'symbol') {\n string = Symbol.prototype.toString.call(str);\n }\n else if (typeof str !== 'string') {\n string = String(str);\n }\n if (charset === 'iso-8859-1') {\n return escape(string).replace(/%u[0-9a-f]{4}/gi, function ($0) {\n return '%26%23' + parseInt($0.slice(2), 16) + '%3B';\n });\n }\n let out = '';\n for (let j = 0; j < string.length; j += limit) {\n const segment = string.length >= limit ? string.slice(j, j + limit) : string;\n const arr = [];\n for (let i = 0; i < segment.length; ++i) {\n let c = segment.charCodeAt(i);\n if (c === 0x2d || // -\n c === 0x2e || // .\n c === 0x5f || // _\n c === 0x7e || // ~\n (c >= 0x30 && c <= 0x39) || // 0-9\n (c >= 0x41 && c <= 0x5a) || // a-z\n (c >= 0x61 && c <= 0x7a) || // A-Z\n (format === RFC1738 && (c === 0x28 || c === 0x29)) // ( )\n ) {\n arr[arr.length] = segment.charAt(i);\n continue;\n }\n if (c < 0x80) {\n arr[arr.length] = hex_table[c];\n continue;\n }\n if (c < 0x800) {\n arr[arr.length] = hex_table[0xc0 | (c >> 6)] + hex_table[0x80 | (c & 0x3f)];\n continue;\n }\n if (c < 0xd800 || c >= 0xe000) {\n arr[arr.length] =\n hex_table[0xe0 | (c >> 12)] + hex_table[0x80 | ((c >> 6) & 0x3f)] + hex_table[0x80 | (c & 0x3f)];\n continue;\n }\n i += 1;\n c = 0x10000 + (((c & 0x3ff) << 10) | (segment.charCodeAt(i) & 0x3ff));\n arr[arr.length] =\n hex_table[0xf0 | (c >> 18)] +\n hex_table[0x80 | ((c >> 12) & 0x3f)] +\n hex_table[0x80 | ((c >> 6) & 0x3f)] +\n hex_table[0x80 | (c & 0x3f)];\n }\n out += arr.join('');\n }\n return out;\n};\nexport function compact(value) {\n const queue = [{ obj: { o: value }, prop: 'o' }];\n const refs = [];\n for (let i = 0; i < queue.length; ++i) {\n const item = queue[i];\n // @ts-ignore\n const obj = item.obj[item.prop];\n const keys = Object.keys(obj);\n for (let j = 0; j < keys.length; ++j) {\n const key = keys[j];\n const val = obj[key];\n if (typeof val === 'object' && val !== null && refs.indexOf(val) === -1) {\n queue.push({ obj: obj, prop: key });\n refs.push(val);\n }\n }\n }\n compact_queue(queue);\n return value;\n}\nexport function is_regexp(obj) {\n return Object.prototype.toString.call(obj) === '[object RegExp]';\n}\nexport function is_buffer(obj) {\n if (!obj || typeof obj !== 'object') {\n return false;\n }\n return !!(obj.constructor && obj.constructor.isBuffer && obj.constructor.isBuffer(obj));\n}\nexport function combine(a, b) {\n return [].concat(a, b);\n}\nexport function maybe_map(val, fn) {\n if (is_array(val)) {\n const mapped = [];\n for (let i = 0; i < val.length; i += 1) {\n mapped.push(fn(val[i]));\n }\n return mapped;\n }\n return fn(val);\n}\n//# sourceMappingURL=utils.mjs.map","import { encode, is_buffer, maybe_map } from \"./utils.mjs\";\nimport { default_format, formatters } from \"./formats.mjs\";\nconst has = Object.prototype.hasOwnProperty;\nconst array_prefix_generators = {\n brackets(prefix) {\n return String(prefix) + '[]';\n },\n comma: 'comma',\n indices(prefix, key) {\n return String(prefix) + '[' + key + ']';\n },\n repeat(prefix) {\n return String(prefix);\n },\n};\nconst is_array = Array.isArray;\nconst push = Array.prototype.push;\nconst push_to_array = function (arr, value_or_array) {\n push.apply(arr, is_array(value_or_array) ? value_or_array : [value_or_array]);\n};\nconst to_ISO = Date.prototype.toISOString;\nconst defaults = {\n addQueryPrefix: false,\n allowDots: false,\n allowEmptyArrays: false,\n arrayFormat: 'indices',\n charset: 'utf-8',\n charsetSentinel: false,\n delimiter: '&',\n encode: true,\n encodeDotInKeys: false,\n encoder: encode,\n encodeValuesOnly: false,\n format: default_format,\n formatter: formatters[default_format],\n /** @deprecated */\n indices: false,\n serializeDate(date) {\n return to_ISO.call(date);\n },\n skipNulls: false,\n strictNullHandling: false,\n};\nfunction is_non_nullish_primitive(v) {\n return (typeof v === 'string' ||\n typeof v === 'number' ||\n typeof v === 'boolean' ||\n typeof v === 'symbol' ||\n typeof v === 'bigint');\n}\nconst sentinel = {};\nfunction inner_stringify(object, prefix, generateArrayPrefix, commaRoundTrip, allowEmptyArrays, strictNullHandling, skipNulls, encodeDotInKeys, encoder, filter, sort, allowDots, serializeDate, format, formatter, encodeValuesOnly, charset, sideChannel) {\n let obj = object;\n let tmp_sc = sideChannel;\n let step = 0;\n let find_flag = false;\n while ((tmp_sc = tmp_sc.get(sentinel)) !== void undefined && !find_flag) {\n // Where object last appeared in the ref tree\n const pos = tmp_sc.get(object);\n step += 1;\n if (typeof pos !== 'undefined') {\n if (pos === step) {\n throw new RangeError('Cyclic object value');\n }\n else {\n find_flag = true; // Break while\n }\n }\n if (typeof tmp_sc.get(sentinel) === 'undefined') {\n step = 0;\n }\n }\n if (typeof filter === 'function') {\n obj = filter(prefix, obj);\n }\n else if (obj instanceof Date) {\n obj = serializeDate?.(obj);\n }\n else if (generateArrayPrefix === 'comma' && is_array(obj)) {\n obj = maybe_map(obj, function (value) {\n if (value instanceof Date) {\n return serializeDate?.(value);\n }\n return value;\n });\n }\n if (obj === null) {\n if (strictNullHandling) {\n return encoder && !encodeValuesOnly ?\n // @ts-expect-error\n encoder(prefix, defaults.encoder, charset, 'key', format)\n : prefix;\n }\n obj = '';\n }\n if (is_non_nullish_primitive(obj) || is_buffer(obj)) {\n if (encoder) {\n const key_value = encodeValuesOnly ? prefix\n // @ts-expect-error\n : encoder(prefix, defaults.encoder, charset, 'key', format);\n return [\n formatter?.(key_value) +\n '=' +\n // @ts-expect-error\n formatter?.(encoder(obj, defaults.encoder, charset, 'value', format)),\n ];\n }\n return [formatter?.(prefix) + '=' + formatter?.(String(obj))];\n }\n const values = [];\n if (typeof obj === 'undefined') {\n return values;\n }\n let obj_keys;\n if (generateArrayPrefix === 'comma' && is_array(obj)) {\n // we need to join elements in\n if (encodeValuesOnly && encoder) {\n // @ts-expect-error values only\n obj = maybe_map(obj, encoder);\n }\n obj_keys = [{ value: obj.length > 0 ? obj.join(',') || null : void undefined }];\n }\n else if (is_array(filter)) {\n obj_keys = filter;\n }\n else {\n const keys = Object.keys(obj);\n obj_keys = sort ? keys.sort(sort) : keys;\n }\n const encoded_prefix = encodeDotInKeys ? String(prefix).replace(/\\./g, '%2E') : String(prefix);\n const adjusted_prefix = commaRoundTrip && is_array(obj) && obj.length === 1 ? encoded_prefix + '[]' : encoded_prefix;\n if (allowEmptyArrays && is_array(obj) && obj.length === 0) {\n return adjusted_prefix + '[]';\n }\n for (let j = 0; j < obj_keys.length; ++j) {\n const key = obj_keys[j];\n const value = \n // @ts-ignore\n typeof key === 'object' && typeof key.value !== 'undefined' ? key.value : obj[key];\n if (skipNulls && value === null) {\n continue;\n }\n // @ts-ignore\n const encoded_key = allowDots && encodeDotInKeys ? key.replace(/\\./g, '%2E') : key;\n const key_prefix = is_array(obj) ?\n typeof generateArrayPrefix === 'function' ?\n generateArrayPrefix(adjusted_prefix, encoded_key)\n : adjusted_prefix\n : adjusted_prefix + (allowDots ? '.' + encoded_key : '[' + encoded_key + ']');\n sideChannel.set(object, step);\n const valueSideChannel = new WeakMap();\n valueSideChannel.set(sentinel, sideChannel);\n push_to_array(values, inner_stringify(value, key_prefix, generateArrayPrefix, commaRoundTrip, allowEmptyArrays, strictNullHandling, skipNulls, encodeDotInKeys, \n // @ts-ignore\n generateArrayPrefix === 'comma' && encodeValuesOnly && is_array(obj) ? null : encoder, filter, sort, allowDots, serializeDate, format, formatter, encodeValuesOnly, charset, valueSideChannel));\n }\n return values;\n}\nfunction normalize_stringify_options(opts = defaults) {\n if (typeof opts.allowEmptyArrays !== 'undefined' && typeof opts.allowEmptyArrays !== 'boolean') {\n throw new TypeError('`allowEmptyArrays` option can only be `true` or `false`, when provided');\n }\n if (typeof opts.encodeDotInKeys !== 'undefined' && typeof opts.encodeDotInKeys !== 'boolean') {\n throw new TypeError('`encodeDotInKeys` option can only be `true` or `false`, when provided');\n }\n if (opts.encoder !== null && typeof opts.encoder !== 'undefined' && typeof opts.encoder !== 'function') {\n throw new TypeError('Encoder has to be a function.');\n }\n const charset = opts.charset || defaults.charset;\n if (typeof opts.charset !== 'undefined' && opts.charset !== 'utf-8' && opts.charset !== 'iso-8859-1') {\n throw new TypeError('The charset option must be either utf-8, iso-8859-1, or undefined');\n }\n let format = default_format;\n if (typeof opts.format !== 'undefined') {\n if (!has.call(formatters, opts.format)) {\n throw new TypeError('Unknown format option provided.');\n }\n format = opts.format;\n }\n const formatter = formatters[format];\n let filter = defaults.filter;\n if (typeof opts.filter === 'function' || is_array(opts.filter)) {\n filter = opts.filter;\n }\n let arrayFormat;\n if (opts.arrayFormat && opts.arrayFormat in array_prefix_generators) {\n arrayFormat = opts.arrayFormat;\n }\n else if ('indices' in opts) {\n arrayFormat = opts.indices ? 'indices' : 'repeat';\n }\n else {\n arrayFormat = defaults.arrayFormat;\n }\n if ('commaRoundTrip' in opts && typeof opts.commaRoundTrip !== 'boolean') {\n throw new TypeError('`commaRoundTrip` must be a boolean, or absent');\n }\n const allowDots = typeof opts.allowDots === 'undefined' ?\n !!opts.encodeDotInKeys === true ?\n true\n : defaults.allowDots\n : !!opts.allowDots;\n return {\n addQueryPrefix: typeof opts.addQueryPrefix === 'boolean' ? opts.addQueryPrefix : defaults.addQueryPrefix,\n // @ts-ignore\n allowDots: allowDots,\n allowEmptyArrays: typeof opts.allowEmptyArrays === 'boolean' ? !!opts.allowEmptyArrays : defaults.allowEmptyArrays,\n arrayFormat: arrayFormat,\n charset: charset,\n charsetSentinel: typeof opts.charsetSentinel === 'boolean' ? opts.charsetSentinel : defaults.charsetSentinel,\n commaRoundTrip: !!opts.commaRoundTrip,\n delimiter: typeof opts.delimiter === 'undefined' ? defaults.delimiter : opts.delimiter,\n encode: typeof opts.encode === 'boolean' ? opts.encode : defaults.encode,\n encodeDotInKeys: typeof opts.encodeDotInKeys === 'boolean' ? opts.encodeDotInKeys : defaults.encodeDotInKeys,\n encoder: typeof opts.encoder === 'function' ? opts.encoder : defaults.encoder,\n encodeValuesOnly: typeof opts.encodeValuesOnly === 'boolean' ? opts.encodeValuesOnly : defaults.encodeValuesOnly,\n filter: filter,\n format: format,\n formatter: formatter,\n serializeDate: typeof opts.serializeDate === 'function' ? opts.serializeDate : defaults.serializeDate,\n skipNulls: typeof opts.skipNulls === 'boolean' ? opts.skipNulls : defaults.skipNulls,\n // @ts-ignore\n sort: typeof opts.sort === 'function' ? opts.sort : null,\n strictNullHandling: typeof opts.strictNullHandling === 'boolean' ? opts.strictNullHandling : defaults.strictNullHandling,\n };\n}\nexport function stringify(object, opts = {}) {\n let obj = object;\n const options = normalize_stringify_options(opts);\n let obj_keys;\n let filter;\n if (typeof options.filter === 'function') {\n filter = options.filter;\n obj = filter('', obj);\n }\n else if (is_array(options.filter)) {\n filter = options.filter;\n obj_keys = filter;\n }\n const keys = [];\n if (typeof obj !== 'object' || obj === null) {\n return '';\n }\n const generateArrayPrefix = array_prefix_generators[options.arrayFormat];\n const commaRoundTrip = generateArrayPrefix === 'comma' && options.commaRoundTrip;\n if (!obj_keys) {\n obj_keys = Object.keys(obj);\n }\n if (options.sort) {\n obj_keys.sort(options.sort);\n }\n const sideChannel = new WeakMap();\n for (let i = 0; i < obj_keys.length; ++i) {\n const key = obj_keys[i];\n if (options.skipNulls && obj[key] === null) {\n continue;\n }\n push_to_array(keys, inner_stringify(obj[key], key, \n // @ts-expect-error\n generateArrayPrefix, commaRoundTrip, options.allowEmptyArrays, options.strictNullHandling, options.skipNulls, options.encodeDotInKeys, options.encode ? options.encoder : null, options.filter, options.sort, options.allowDots, options.serializeDate, options.format, options.formatter, options.encodeValuesOnly, options.charset, sideChannel));\n }\n const joined = keys.join(options.delimiter);\n let prefix = options.addQueryPrefix === true ? '?' : '';\n if (options.charsetSentinel) {\n if (options.charset === 'iso-8859-1') {\n // encodeURIComponent('✓'), the \"numeric entity\" representation of a checkmark\n prefix += 'utf8=%26%2310003%3B&';\n }\n else {\n // encodeURIComponent('✓')\n prefix += 'utf8=%E2%9C%93&';\n }\n }\n return joined.length > 0 ? prefix + joined : '';\n}\n//# sourceMappingURL=stringify.mjs.map","export const VERSION = '4.85.1'; // x-release-please-version\n//# sourceMappingURL=version.mjs.map","export let auto = false;\nexport let kind = undefined;\nexport let fetch = undefined;\nexport let Request = undefined;\nexport let Response = undefined;\nexport let Headers = undefined;\nexport let FormData = undefined;\nexport let Blob = undefined;\nexport let File = undefined;\nexport let ReadableStream = undefined;\nexport let getMultipartRequestOptions = undefined;\nexport let getDefaultAgent = undefined;\nexport let fileFromPath = undefined;\nexport let isFsReadStream = undefined;\nexport function setShims(shims, options = { auto: false }) {\n if (auto) {\n throw new Error(`you must \\`import 'openai/shims/${shims.kind}'\\` before importing anything else from openai`);\n }\n if (kind) {\n throw new Error(`can't \\`import 'openai/shims/${shims.kind}'\\` after \\`import 'openai/shims/${kind}'\\``);\n }\n auto = options.auto;\n kind = shims.kind;\n fetch = shims.fetch;\n Request = shims.Request;\n Response = shims.Response;\n Headers = shims.Headers;\n FormData = shims.FormData;\n Blob = shims.Blob;\n File = shims.File;\n ReadableStream = shims.ReadableStream;\n getMultipartRequestOptions = shims.getMultipartRequestOptions;\n getDefaultAgent = shims.getDefaultAgent;\n fileFromPath = shims.fileFromPath;\n isFsReadStream = shims.isFsReadStream;\n}\n//# sourceMappingURL=registry.mjs.map","/**\n * Disclaimer: modules in _shims aren't intended to be imported by SDK users.\n */\nexport class MultipartBody {\n constructor(body) {\n this.body = body;\n }\n get [Symbol.toStringTag]() {\n return 'MultipartBody';\n }\n}\n//# sourceMappingURL=MultipartBody.mjs.map","/**\n * Disclaimer: modules in _shims aren't intended to be imported by SDK users.\n */\nimport * as shims from './registry.mjs';\nimport * as auto from 'openai/_shims/auto/runtime';\nif (!shims.kind) shims.setShims(auto.getRuntime(), { auto: true });\nexport * from './registry.mjs';\n","import { MultipartBody } from \"./MultipartBody.mjs\";\nexport function getRuntime({ manuallyImported } = {}) {\n const recommendation = manuallyImported ?\n `You may need to use polyfills`\n : `Add one of these imports before your first \\`import … from 'openai'\\`:\n- \\`import 'openai/shims/node'\\` (if you're running on Node)\n- \\`import 'openai/shims/web'\\` (otherwise)\n`;\n let _fetch, _Request, _Response, _Headers;\n try {\n // @ts-ignore\n _fetch = fetch;\n // @ts-ignore\n _Request = Request;\n // @ts-ignore\n _Response = Response;\n // @ts-ignore\n _Headers = Headers;\n }\n catch (error) {\n throw new Error(`this environment is missing the following Web Fetch API type: ${error.message}. ${recommendation}`);\n }\n return {\n kind: 'web',\n fetch: _fetch,\n Request: _Request,\n Response: _Response,\n Headers: _Headers,\n FormData: \n // @ts-ignore\n typeof FormData !== 'undefined' ? FormData : (class FormData {\n // @ts-ignore\n constructor() {\n throw new Error(`file uploads aren't supported in this environment yet as 'FormData' is undefined. ${recommendation}`);\n }\n }),\n Blob: typeof Blob !== 'undefined' ? Blob : (class Blob {\n constructor() {\n throw new Error(`file uploads aren't supported in this environment yet as 'Blob' is undefined. ${recommendation}`);\n }\n }),\n File: \n // @ts-ignore\n typeof File !== 'undefined' ? File : (class File {\n // @ts-ignore\n constructor() {\n throw new Error(`file uploads aren't supported in this environment yet as 'File' is undefined. ${recommendation}`);\n }\n }),\n ReadableStream: \n // @ts-ignore\n typeof ReadableStream !== 'undefined' ? ReadableStream : (class ReadableStream {\n // @ts-ignore\n constructor() {\n throw new Error(`streaming isn't supported in this environment yet as 'ReadableStream' is undefined. ${recommendation}`);\n }\n }),\n getMultipartRequestOptions: async (\n // @ts-ignore\n form, opts) => ({\n ...opts,\n body: new MultipartBody(form),\n }),\n getDefaultAgent: (url) => undefined,\n fileFromPath: () => {\n throw new Error('The `fileFromPath` function is only supported in Node. See the README for more details: https://www.github.com/openai/openai-node#file-uploads');\n },\n isFsReadStream: (value) => false,\n };\n}\n//# sourceMappingURL=web-runtime.mjs.map","// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.\nimport { castToError } from \"./core.mjs\";\nexport class OpenAIError extends Error {\n}\nexport class APIError extends OpenAIError {\n constructor(status, error, message, headers) {\n super(`${APIError.makeMessage(status, error, message)}`);\n this.status = status;\n this.headers = headers;\n this.request_id = headers?.['x-request-id'];\n this.error = error;\n const data = error;\n this.code = data?.['code'];\n this.param = data?.['param'];\n this.type = data?.['type'];\n }\n static makeMessage(status, error, message) {\n const msg = error?.message ?\n typeof error.message === 'string' ?\n error.message\n : JSON.stringify(error.message)\n : error ? JSON.stringify(error)\n : message;\n if (status && msg) {\n return `${status} ${msg}`;\n }\n if (status) {\n return `${status} status code (no body)`;\n }\n if (msg) {\n return msg;\n }\n return '(no status code or body)';\n }\n static generate(status, errorResponse, message, headers) {\n if (!status || !headers) {\n return new APIConnectionError({ message, cause: castToError(errorResponse) });\n }\n const error = errorResponse?.['error'];\n if (status === 400) {\n return new BadRequestError(status, error, message, headers);\n }\n if (status === 401) {\n return new AuthenticationError(status, error, message, headers);\n }\n if (status === 403) {\n return new PermissionDeniedError(status, error, message, headers);\n }\n if (status === 404) {\n return new NotFoundError(status, error, message, headers);\n }\n if (status === 409) {\n return new ConflictError(status, error, message, headers);\n }\n if (status === 422) {\n return new UnprocessableEntityError(status, error, message, headers);\n }\n if (status === 429) {\n return new RateLimitError(status, error, message, headers);\n }\n if (status >= 500) {\n return new InternalServerError(status, error, message, headers);\n }\n return new APIError(status, error, message, headers);\n }\n}\nexport class APIUserAbortError extends APIError {\n constructor({ message } = {}) {\n super(undefined, undefined, message || 'Request was aborted.', undefined);\n }\n}\nexport class APIConnectionError extends APIError {\n constructor({ message, cause }) {\n super(undefined, undefined, message || 'Connection error.', undefined);\n // in some environments the 'cause' property is already declared\n // @ts-ignore\n if (cause)\n this.cause = cause;\n }\n}\nexport class APIConnectionTimeoutError extends APIConnectionError {\n constructor({ message } = {}) {\n super({ message: message ?? 'Request timed out.' });\n }\n}\nexport class BadRequestError extends APIError {\n}\nexport class AuthenticationError extends APIError {\n}\nexport class PermissionDeniedError extends APIError {\n}\nexport class NotFoundError extends APIError {\n}\nexport class ConflictError extends APIError {\n}\nexport class UnprocessableEntityError extends APIError {\n}\nexport class RateLimitError extends APIError {\n}\nexport class InternalServerError extends APIError {\n}\nexport class LengthFinishReasonError extends OpenAIError {\n constructor() {\n super(`Could not parse response content as the length limit was reached`);\n }\n}\nexport class ContentFilterFinishReasonError extends OpenAIError {\n constructor() {\n super(`Could not parse response content as the request was rejected by the content filter`);\n }\n}\n//# sourceMappingURL=error.mjs.map","var __classPrivateFieldSet = (this && this.__classPrivateFieldSet) || function (receiver, state, value, kind, f) {\n if (kind === \"m\") throw new TypeError(\"Private method is not writable\");\n if (kind === \"a\" && !f) throw new TypeError(\"Private accessor was defined without a setter\");\n if (typeof state === \"function\" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError(\"Cannot write private member to an object whose class did not declare it\");\n return (kind === \"a\" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;\n};\nvar __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (receiver, state, kind, f) {\n if (kind === \"a\" && !f) throw new TypeError(\"Private accessor was defined without a getter\");\n if (typeof state === \"function\" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError(\"Cannot read private member from an object whose class did not declare it\");\n return kind === \"m\" ? f : kind === \"a\" ? f.call(receiver) : f ? f.value : state.get(receiver);\n};\nvar _LineDecoder_carriageReturnIndex;\nimport { OpenAIError } from \"../../error.mjs\";\n/**\n * A re-implementation of httpx's `LineDecoder` in Python that handles incrementally\n * reading lines from text.\n *\n * https://github.com/encode/httpx/blob/920333ea98118e9cf617f246905d7b202510941c/httpx/_decoders.py#L258\n */\nexport class LineDecoder {\n constructor() {\n _LineDecoder_carriageReturnIndex.set(this, void 0);\n this.buffer = new Uint8Array();\n __classPrivateFieldSet(this, _LineDecoder_carriageReturnIndex, null, \"f\");\n }\n decode(chunk) {\n if (chunk == null) {\n return [];\n }\n const binaryChunk = chunk instanceof ArrayBuffer ? new Uint8Array(chunk)\n : typeof chunk === 'string' ? new TextEncoder().encode(chunk)\n : chunk;\n let newData = new Uint8Array(this.buffer.length + binaryChunk.length);\n newData.set(this.buffer);\n newData.set(binaryChunk, this.buffer.length);\n this.buffer = newData;\n const lines = [];\n let patternIndex;\n while ((patternIndex = findNewlineIndex(this.buffer, __classPrivateFieldGet(this, _LineDecoder_carriageReturnIndex, \"f\"))) != null) {\n if (patternIndex.carriage && __classPrivateFieldGet(this, _LineDecoder_carriageReturnIndex, \"f\") == null) {\n // skip until we either get a corresponding `\\n`, a new `\\r` or nothing\n __classPrivateFieldSet(this, _LineDecoder_carriageReturnIndex, patternIndex.index, \"f\");\n continue;\n }\n // we got double \\r or \\rtext\\n\n if (__classPrivateFieldGet(this, _LineDecoder_carriageReturnIndex, \"f\") != null &&\n (patternIndex.index !== __classPrivateFieldGet(this, _LineDecoder_carriageReturnIndex, \"f\") + 1 || patternIndex.carriage)) {\n lines.push(this.decodeText(this.buffer.slice(0, __classPrivateFieldGet(this, _LineDecoder_carriageReturnIndex, \"f\") - 1)));\n this.buffer = this.buffer.slice(__classPrivateFieldGet(this, _LineDecoder_carriageReturnIndex, \"f\"));\n __classPrivateFieldSet(this, _LineDecoder_carriageReturnIndex, null, \"f\");\n continue;\n }\n const endIndex = __classPrivateFieldGet(this, _LineDecoder_carriageReturnIndex, \"f\") !== null ? patternIndex.preceding - 1 : patternIndex.preceding;\n const line = this.decodeText(this.buffer.slice(0, endIndex));\n lines.push(line);\n this.buffer = this.buffer.slice(patternIndex.index);\n __classPrivateFieldSet(this, _LineDecoder_carriageReturnIndex, null, \"f\");\n }\n return lines;\n }\n decodeText(bytes) {\n if (bytes == null)\n return '';\n if (typeof bytes === 'string')\n return bytes;\n // Node:\n if (typeof Buffer !== 'undefined') {\n if (bytes instanceof Buffer) {\n return bytes.toString();\n }\n if (bytes instanceof Uint8Array) {\n return Buffer.from(bytes).toString();\n }\n throw new OpenAIError(`Unexpected: received non-Uint8Array (${bytes.constructor.name}) stream chunk in an environment with a global \"Buffer\" defined, which this library assumes to be Node. Please report this error.`);\n }\n // Browser\n if (typeof TextDecoder !== 'undefined') {\n if (bytes instanceof Uint8Array || bytes instanceof ArrayBuffer) {\n this.textDecoder ?? (this.textDecoder = new TextDecoder('utf8'));\n return this.textDecoder.decode(bytes);\n }\n throw new OpenAIError(`Unexpected: received non-Uint8Array/ArrayBuffer (${bytes.constructor.name}) in a web platform. Please report this error.`);\n }\n throw new OpenAIError(`Unexpected: neither Buffer nor TextDecoder are available as globals. Please report this error.`);\n }\n flush() {\n if (!this.buffer.length) {\n return [];\n }\n return this.decode('\\n');\n }\n}\n_LineDecoder_carriageReturnIndex = new WeakMap();\n// prettier-ignore\nLineDecoder.NEWLINE_CHARS = new Set(['\\n', '\\r']);\nLineDecoder.NEWLINE_REGEXP = /\\r\\n|[\\n\\r]/g;\n/**\n * This function searches the buffer for the end patterns, (\\r or \\n)\n * and returns an object with the index preceding the matched newline and the\n * index after the newline char. `null` is returned if no new line is found.\n *\n * ```ts\n * findNewLineIndex('abc\\ndef') -> { preceding: 2, index: 3 }\n * ```\n */\nfunction findNewlineIndex(buffer, startIndex) {\n const newline = 0x0a; // \\n\n const carriage = 0x0d; // \\r\n for (let i = startIndex ?? 0; i < buffer.length; i++) {\n if (buffer[i] === newline) {\n return { preceding: i, index: i + 1, carriage: false };\n }\n if (buffer[i] === carriage) {\n return { preceding: i, index: i + 1, carriage: true };\n }\n }\n return null;\n}\n//# sourceMappingURL=line.mjs.map","/**\n * Most browsers don't yet have async iterable support for ReadableStream,\n * and Node has a very different way of reading bytes from its \"ReadableStream\".\n *\n * This polyfill was pulled from https://github.com/MattiasBuelens/web-streams-polyfill/pull/122#issuecomment-1627354490\n */\nexport function ReadableStreamToAsyncIterable(stream) {\n if (stream[Symbol.asyncIterator])\n return stream;\n const reader = stream.getReader();\n return {\n async next() {\n try {\n const result = await reader.read();\n if (result?.done)\n reader.releaseLock(); // release lock when stream becomes closed\n return result;\n }\n catch (e) {\n reader.releaseLock(); // release lock when stream becomes errored\n throw e;\n }\n },\n async return() {\n const cancelPromise = reader.cancel();\n reader.releaseLock();\n await cancelPromise;\n return { done: true, value: undefined };\n },\n [Symbol.asyncIterator]() {\n return this;\n },\n };\n}\n//# sourceMappingURL=stream-utils.mjs.map","import { ReadableStream } from \"./_shims/index.mjs\";\nimport { OpenAIError } from \"./error.mjs\";\nimport { LineDecoder } from \"./internal/decoders/line.mjs\";\nimport { ReadableStreamToAsyncIterable } from \"./internal/stream-utils.mjs\";\nimport { APIError } from \"./error.mjs\";\nexport class Stream {\n constructor(iterator, controller) {\n this.iterator = iterator;\n this.controller = controller;\n }\n static fromSSEResponse(response, controller) {\n let consumed = false;\n async function* iterator() {\n if (consumed) {\n throw new Error('Cannot iterate over a consumed stream, use `.tee()` to split the stream.');\n }\n consumed = true;\n let done = false;\n try {\n for await (const sse of _iterSSEMessages(response, controller)) {\n if (done)\n continue;\n if (sse.data.startsWith('[DONE]')) {\n done = true;\n continue;\n }\n if (sse.event === null) {\n let data;\n try {\n data = JSON.parse(sse.data);\n }\n catch (e) {\n console.error(`Could not parse message into JSON:`, sse.data);\n console.error(`From chunk:`, sse.raw);\n throw e;\n }\n if (data && data.error) {\n throw new APIError(undefined, data.error, undefined, undefined);\n }\n yield data;\n }\n else {\n let data;\n try {\n data = JSON.parse(sse.data);\n }\n catch (e) {\n console.error(`Could not parse message into JSON:`, sse.data);\n console.error(`From chunk:`, sse.raw);\n throw e;\n }\n // TODO: Is this where the error should be thrown?\n if (sse.event == 'error') {\n throw new APIError(undefined, data.error, data.message, undefined);\n }\n yield { event: sse.event, data: data };\n }\n }\n done = true;\n }\n catch (e) {\n // If the user calls `stream.controller.abort()`, we should exit without throwing.\n if (e instanceof Error && e.name === 'AbortError')\n return;\n throw e;\n }\n finally {\n // If the user `break`s, abort the ongoing request.\n if (!done)\n controller.abort();\n }\n }\n return new Stream(iterator, controller);\n }\n /**\n * Generates a Stream from a newline-separated ReadableStream\n * where each item is a JSON value.\n */\n static fromReadableStream(readableStream, controller) {\n let consumed = false;\n async function* iterLines() {\n const lineDecoder = new LineDecoder();\n const iter = ReadableStreamToAsyncIterable(readableStream);\n for await (const chunk of iter) {\n for (const line of lineDecoder.decode(chunk)) {\n yield line;\n }\n }\n for (const line of lineDecoder.flush()) {\n yield line;\n }\n }\n async function* iterator() {\n if (consumed) {\n throw new Error('Cannot iterate over a consumed stream, use `.tee()` to split the stream.');\n }\n consumed = true;\n let done = false;\n try {\n for await (const line of iterLines()) {\n if (done)\n continue;\n if (line)\n yield JSON.parse(line);\n }\n done = true;\n }\n catch (e) {\n // If the user calls `stream.controller.abort()`, we should exit without throwing.\n if (e instanceof Error && e.name === 'AbortError')\n return;\n throw e;\n }\n finally {\n // If the user `break`s, abort the ongoing request.\n if (!done)\n controller.abort();\n }\n }\n return new Stream(iterator, controller);\n }\n [Symbol.asyncIterator]() {\n return this.iterator();\n }\n /**\n * Splits the stream into two streams which can be\n * independently read from at different speeds.\n */\n tee() {\n const left = [];\n const right = [];\n const iterator = this.iterator();\n const teeIterator = (queue) => {\n return {\n next: () => {\n if (queue.length === 0) {\n const result = iterator.next();\n left.push(result);\n right.push(result);\n }\n return queue.shift();\n },\n };\n };\n return [\n new Stream(() => teeIterator(left), this.controller),\n new Stream(() => teeIterator(right), this.controller),\n ];\n }\n /**\n * Converts this stream to a newline-separated ReadableStream of\n * JSON stringified values in the stream\n * which can be turned back into a Stream with `Stream.fromReadableStream()`.\n */\n toReadableStream() {\n const self = this;\n let iter;\n const encoder = new TextEncoder();\n return new ReadableStream({\n async start() {\n iter = self[Symbol.asyncIterator]();\n },\n async pull(ctrl) {\n try {\n const { value, done } = await iter.next();\n if (done)\n return ctrl.close();\n const bytes = encoder.encode(JSON.stringify(value) + '\\n');\n ctrl.enqueue(bytes);\n }\n catch (err) {\n ctrl.error(err);\n }\n },\n async cancel() {\n await iter.return?.();\n },\n });\n }\n}\nexport async function* _iterSSEMessages(response, controller) {\n if (!response.body) {\n controller.abort();\n throw new OpenAIError(`Attempted to iterate over a response with no body`);\n }\n const sseDecoder = new SSEDecoder();\n const lineDecoder = new LineDecoder();\n const iter = ReadableStreamToAsyncIterable(response.body);\n for await (const sseChunk of iterSSEChunks(iter)) {\n for (const line of lineDecoder.decode(sseChunk)) {\n const sse = sseDecoder.decode(line);\n if (sse)\n yield sse;\n }\n }\n for (const line of lineDecoder.flush()) {\n const sse = sseDecoder.decode(line);\n if (sse)\n yield sse;\n }\n}\n/**\n * Given an async iterable iterator, iterates over it and yields full\n * SSE chunks, i.e. yields when a double new-line is encountered.\n */\nasync function* iterSSEChunks(iterator) {\n let data = new Uint8Array();\n for await (const chunk of iterator) {\n if (chunk == null) {\n continue;\n }\n const binaryChunk = chunk instanceof ArrayBuffer ? new Uint8Array(chunk)\n : typeof chunk === 'string' ? new TextEncoder().encode(chunk)\n : chunk;\n let newData = new Uint8Array(data.length + binaryChunk.length);\n newData.set(data);\n newData.set(binaryChunk, data.length);\n data = newData;\n let patternIndex;\n while ((patternIndex = findDoubleNewlineIndex(data)) !== -1) {\n yield data.slice(0, patternIndex);\n data = data.slice(patternIndex);\n }\n }\n if (data.length > 0) {\n yield data;\n }\n}\nfunction findDoubleNewlineIndex(buffer) {\n // This function searches the buffer for the end patterns (\\r\\r, \\n\\n, \\r\\n\\r\\n)\n // and returns the index right after the first occurrence of any pattern,\n // or -1 if none of the patterns are found.\n const newline = 0x0a; // \\n\n const carriage = 0x0d; // \\r\n for (let i = 0; i < buffer.length - 2; i++) {\n if (buffer[i] === newline && buffer[i + 1] === newline) {\n // \\n\\n\n return i + 2;\n }\n if (buffer[i] === carriage && buffer[i + 1] === carriage) {\n // \\r\\r\n return i + 2;\n }\n if (buffer[i] === carriage &&\n buffer[i + 1] === newline &&\n i + 3 < buffer.length &&\n buffer[i + 2] === carriage &&\n buffer[i + 3] === newline) {\n // \\r\\n\\r\\n\n return i + 4;\n }\n }\n return -1;\n}\nclass SSEDecoder {\n constructor() {\n this.event = null;\n this.data = [];\n this.chunks = [];\n }\n decode(line) {\n if (line.endsWith('\\r')) {\n line = line.substring(0, line.length - 1);\n }\n if (!line) {\n // empty line and we didn't previously encounter any messages\n if (!this.event && !this.data.length)\n return null;\n const sse = {\n event: this.event,\n data: this.data.join('\\n'),\n raw: this.chunks,\n };\n this.event = null;\n this.data = [];\n this.chunks = [];\n return sse;\n }\n this.chunks.push(line);\n if (line.startsWith(':')) {\n return null;\n }\n let [fieldname, _, value] = partition(line, ':');\n if (value.startsWith(' ')) {\n value = value.substring(1);\n }\n if (fieldname === 'event') {\n this.event = value;\n }\n else if (fieldname === 'data') {\n this.data.push(value);\n }\n return null;\n }\n}\n/** This is an internal helper function that's just used for testing */\nexport function _decodeChunks(chunks, { flush } = { flush: false }) {\n const decoder = new LineDecoder();\n const lines = [];\n for (const chunk of chunks) {\n lines.push(...decoder.decode(chunk));\n }\n if (flush) {\n lines.push(...decoder.flush());\n }\n return lines;\n}\nfunction partition(str, delimiter) {\n const index = str.indexOf(delimiter);\n if (index !== -1) {\n return [str.substring(0, index), delimiter, str.substring(index + delimiter.length)];\n }\n return [str, '', ''];\n}\n//# sourceMappingURL=streaming.mjs.map","import { FormData, File, getMultipartRequestOptions, isFsReadStream, } from \"./_shims/index.mjs\";\nexport { fileFromPath } from \"./_shims/index.mjs\";\nexport const isResponseLike = (value) => value != null &&\n typeof value === 'object' &&\n typeof value.url === 'string' &&\n typeof value.blob === 'function';\nexport const isFileLike = (value) => value != null &&\n typeof value === 'object' &&\n typeof value.name === 'string' &&\n typeof value.lastModified === 'number' &&\n isBlobLike(value);\n/**\n * The BlobLike type omits arrayBuffer() because @types/node-fetch@^2.6.4 lacks it; but this check\n * adds the arrayBuffer() method type because it is available and used at runtime\n */\nexport const isBlobLike = (value) => value != null &&\n typeof value === 'object' &&\n typeof value.size === 'number' &&\n typeof value.type === 'string' &&\n typeof value.text === 'function' &&\n typeof value.slice === 'function' &&\n typeof value.arrayBuffer === 'function';\nexport const isUploadable = (value) => {\n return isFileLike(value) || isResponseLike(value) || isFsReadStream(value);\n};\n/**\n * Helper for creating a {@link File} to pass to an SDK upload method from a variety of different data formats\n * @param value the raw content of the file. Can be an {@link Uploadable}, {@link BlobLikePart}, or {@link AsyncIterable} of {@link BlobLikePart}s\n * @param {string=} name the name of the file. If omitted, toFile will try to determine a file name from bits if possible\n * @param {Object=} options additional properties\n * @param {string=} options.type the MIME type of the content\n * @param {number=} options.lastModified the last modified timestamp\n * @returns a {@link File} with the given properties\n */\nexport async function toFile(value, name, options) {\n // If it's a promise, resolve it.\n value = await value;\n // If we've been given a `File` we don't need to do anything\n if (isFileLike(value)) {\n return value;\n }\n if (isResponseLike(value)) {\n const blob = await value.blob();\n name || (name = new URL(value.url).pathname.split(/[\\\\/]/).pop() ?? 'unknown_file');\n // we need to convert the `Blob` into an array buffer because the `Blob` class\n // that `node-fetch` defines is incompatible with the web standard which results\n // in `new File` interpreting it as a string instead of binary data.\n const data = isBlobLike(blob) ? [(await blob.arrayBuffer())] : [blob];\n return new File(data, name, options);\n }\n const bits = await getBytes(value);\n name || (name = getName(value) ?? 'unknown_file');\n if (!options?.type) {\n const type = bits[0]?.type;\n if (typeof type === 'string') {\n options = { ...options, type };\n }\n }\n return new File(bits, name, options);\n}\nasync function getBytes(value) {\n let parts = [];\n if (typeof value === 'string' ||\n ArrayBuffer.isView(value) || // includes Uint8Array, Buffer, etc.\n value instanceof ArrayBuffer) {\n parts.push(value);\n }\n else if (isBlobLike(value)) {\n parts.push(await value.arrayBuffer());\n }\n else if (isAsyncIterableIterator(value) // includes Readable, ReadableStream, etc.\n ) {\n for await (const chunk of value) {\n parts.push(chunk); // TODO, consider validating?\n }\n }\n else {\n throw new Error(`Unexpected data type: ${typeof value}; constructor: ${value?.constructor\n ?.name}; props: ${propsForError(value)}`);\n }\n return parts;\n}\nfunction propsForError(value) {\n const props = Object.getOwnPropertyNames(value);\n return `[${props.map((p) => `\"${p}\"`).join(', ')}]`;\n}\nfunction getName(value) {\n return (getStringFromMaybeBuffer(value.name) ||\n getStringFromMaybeBuffer(value.filename) ||\n // For fs.ReadStream\n getStringFromMaybeBuffer(value.path)?.split(/[\\\\/]/).pop());\n}\nconst getStringFromMaybeBuffer = (x) => {\n if (typeof x === 'string')\n return x;\n if (typeof Buffer !== 'undefined' && x instanceof Buffer)\n return String(x);\n return undefined;\n};\nconst isAsyncIterableIterator = (value) => value != null && typeof value === 'object' && typeof value[Symbol.asyncIterator] === 'function';\nexport const isMultipartBody = (body) => body && typeof body === 'object' && body.body && body[Symbol.toStringTag] === 'MultipartBody';\n/**\n * Returns a multipart/form-data request if any part of the given request body contains a File / Blob value.\n * Otherwise returns the request as is.\n */\nexport const maybeMultipartFormRequestOptions = async (opts) => {\n if (!hasUploadableValue(opts.body))\n return opts;\n const form = await createForm(opts.body);\n return getMultipartRequestOptions(form, opts);\n};\nexport const multipartFormRequestOptions = async (opts) => {\n const form = await createForm(opts.body);\n return getMultipartRequestOptions(form, opts);\n};\nexport const createForm = async (body) => {\n const form = new FormData();\n await Promise.all(Object.entries(body || {}).map(([key, value]) => addFormValue(form, key, value)));\n return form;\n};\nconst hasUploadableValue = (value) => {\n if (isUploadable(value))\n return true;\n if (Array.isArray(value))\n return value.some(hasUploadableValue);\n if (value && typeof value === 'object') {\n for (const k in value) {\n if (hasUploadableValue(value[k]))\n return true;\n }\n }\n return false;\n};\nconst addFormValue = async (form, key, value) => {\n if (value === undefined)\n return;\n if (value == null) {\n throw new TypeError(`Received null for \"${key}\"; to pass null in FormData, you must use the string 'null'`);\n }\n // TODO: make nested formats configurable\n if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') {\n form.append(key, String(value));\n }\n else if (isUploadable(value)) {\n const file = await toFile(value);\n form.append(key, file);\n }\n else if (Array.isArray(value)) {\n await Promise.all(value.map((entry) => addFormValue(form, key + '[]', entry)));\n }\n else if (typeof value === 'object') {\n await Promise.all(Object.entries(value).map(([name, prop]) => addFormValue(form, `${key}[${name}]`, prop)));\n }\n else {\n throw new TypeError(`Invalid value given to form, expected a string, number, boolean, object, Array, File or Blob but got ${value} instead`);\n }\n};\n//# sourceMappingURL=uploads.mjs.map","var __classPrivateFieldSet = (this && this.__classPrivateFieldSet) || function (receiver, state, value, kind, f) {\n if (kind === \"m\") throw new TypeError(\"Private method is not writable\");\n if (kind === \"a\" && !f) throw new TypeError(\"Private accessor was defined without a setter\");\n if (typeof state === \"function\" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError(\"Cannot write private member to an object whose class did not declare it\");\n return (kind === \"a\" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;\n};\nvar __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (receiver, state, kind, f) {\n if (kind === \"a\" && !f) throw new TypeError(\"Private accessor was defined without a getter\");\n if (typeof state === \"function\" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError(\"Cannot read private member from an object whose class did not declare it\");\n return kind === \"m\" ? f : kind === \"a\" ? f.call(receiver) : f ? f.value : state.get(receiver);\n};\nvar _AbstractPage_client;\nimport { VERSION } from \"./version.mjs\";\nimport { Stream } from \"./streaming.mjs\";\nimport { OpenAIError, APIError, APIConnectionError, APIConnectionTimeoutError, APIUserAbortError, } from \"./error.mjs\";\nimport { kind as shimsKind, getDefaultAgent, fetch, } from \"./_shims/index.mjs\";\nimport { isBlobLike, isMultipartBody } from \"./uploads.mjs\";\nexport { maybeMultipartFormRequestOptions, multipartFormRequestOptions, createForm, } from \"./uploads.mjs\";\nasync function defaultParseResponse(props) {\n const { response } = props;\n if (props.options.stream) {\n debug('response', response.status, response.url, response.headers, response.body);\n // Note: there is an invariant here that isn't represented in the type system\n // that if you set `stream: true` the response type must also be `Stream`\n if (props.options.__streamClass) {\n return props.options.__streamClass.fromSSEResponse(response, props.controller);\n }\n return Stream.fromSSEResponse(response, props.controller);\n }\n // fetch refuses to read the body when the status code is 204.\n if (response.status === 204) {\n return null;\n }\n if (props.options.__binaryResponse) {\n return response;\n }\n const contentType = response.headers.get('content-type');\n const isJSON = contentType?.includes('application/json') || contentType?.includes('application/vnd.api+json');\n if (isJSON) {\n const json = await response.json();\n debug('response', response.status, response.url, response.headers, json);\n return _addRequestID(json, response);\n }\n const text = await response.text();\n debug('response', response.status, response.url, response.headers, text);\n // TODO handle blob, arraybuffer, other content types, etc.\n return text;\n}\nfunction _addRequestID(value, response) {\n if (!value || typeof value !== 'object' || Array.isArray(value)) {\n return value;\n }\n return Object.defineProperty(value, '_request_id', {\n value: response.headers.get('x-request-id'),\n enumerable: false,\n });\n}\n/**\n * A subclass of `Promise` providing additional helper methods\n * for interacting with the SDK.\n */\nexport class APIPromise extends Promise {\n constructor(responsePromise, parseResponse = defaultParseResponse) {\n super((resolve) => {\n // this is maybe a bit weird but this has to be a no-op to not implicitly\n // parse the response body; instead .then, .catch, .finally are overridden\n // to parse the response\n resolve(null);\n });\n this.responsePromise = responsePromise;\n this.parseResponse = parseResponse;\n }\n _thenUnwrap(transform) {\n return new APIPromise(this.responsePromise, async (props) => _addRequestID(transform(await this.parseResponse(props), props), props.response));\n }\n /**\n * Gets the raw `Response` instance instead of parsing the response\n * data.\n *\n * If you want to parse the response body but still get the `Response`\n * instance, you can use {@link withResponse()}.\n *\n * 👋 Getting the wrong TypeScript type for `Response`?\n * Try setting `\"moduleResolution\": \"NodeNext\"` if you can,\n * or add one of these imports before your first `import … from 'openai'`:\n * - `import 'openai/shims/node'` (if you're running on Node)\n * - `import 'openai/shims/web'` (otherwise)\n */\n asResponse() {\n return this.responsePromise.then((p) => p.response);\n }\n /**\n * Gets the parsed response data, the raw `Response` instance and the ID of the request,\n * returned via the X-Request-ID header which is useful for debugging requests and reporting\n * issues to OpenAI.\n *\n * If you just want to get the raw `Response` instance without parsing it,\n * you can use {@link asResponse()}.\n *\n *\n * 👋 Getting the wrong TypeScript type for `Response`?\n * Try setting `\"moduleResolution\": \"NodeNext\"` if you can,\n * or add one of these imports before your first `import … from 'openai'`:\n * - `import 'openai/shims/node'` (if you're running on Node)\n * - `import 'openai/shims/web'` (otherwise)\n */\n async withResponse() {\n const [data, response] = await Promise.all([this.parse(), this.asResponse()]);\n return { data, response, request_id: response.headers.get('x-request-id') };\n }\n parse() {\n if (!this.parsedPromise) {\n this.parsedPromise = this.responsePromise.then(this.parseResponse);\n }\n return this.parsedPromise;\n }\n then(onfulfilled, onrejected) {\n return this.parse().then(onfulfilled, onrejected);\n }\n catch(onrejected) {\n return this.parse().catch(onrejected);\n }\n finally(onfinally) {\n return this.parse().finally(onfinally);\n }\n}\nexport class APIClient {\n constructor({ baseURL, maxRetries = 2, timeout = 600000, // 10 minutes\n httpAgent, fetch: overriddenFetch, }) {\n this.baseURL = baseURL;\n this.maxRetries = validatePositiveInteger('maxRetries', maxRetries);\n this.timeout = validatePositiveInteger('timeout', timeout);\n this.httpAgent = httpAgent;\n this.fetch = overriddenFetch ?? fetch;\n }\n authHeaders(opts) {\n return {};\n }\n /**\n * Override this to add your own default headers, for example:\n *\n * {\n * ...super.defaultHeaders(),\n * Authorization: 'Bearer 123',\n * }\n */\n defaultHeaders(opts) {\n return {\n Accept: 'application/json',\n 'Content-Type': 'application/json',\n 'User-Agent': this.getUserAgent(),\n ...getPlatformHeaders(),\n ...this.authHeaders(opts),\n };\n }\n /**\n * Override this to add your own headers validation:\n */\n validateHeaders(headers, customHeaders) { }\n defaultIdempotencyKey() {\n return `stainless-node-retry-${uuid4()}`;\n }\n get(path, opts) {\n return this.methodRequest('get', path, opts);\n }\n post(path, opts) {\n return this.methodRequest('post', path, opts);\n }\n patch(path, opts) {\n return this.methodRequest('patch', path, opts);\n }\n put(path, opts) {\n return this.methodRequest('put', path, opts);\n }\n delete(path, opts) {\n return this.methodRequest('delete', path, opts);\n }\n methodRequest(method, path, opts) {\n return this.request(Promise.resolve(opts).then(async (opts) => {\n const body = opts && isBlobLike(opts?.body) ? new DataView(await opts.body.arrayBuffer())\n : opts?.body instanceof DataView ? opts.body\n : opts?.body instanceof ArrayBuffer ? new DataView(opts.body)\n : opts && ArrayBuffer.isView(opts?.body) ? new DataView(opts.body.buffer)\n : opts?.body;\n return { method, path, ...opts, body };\n }));\n }\n getAPIList(path, Page, opts) {\n return this.requestAPIList(Page, { method: 'get', path, ...opts });\n }\n calculateContentLength(body) {\n if (typeof body === 'string') {\n if (typeof Buffer !== 'undefined') {\n return Buffer.byteLength(body, 'utf8').toString();\n }\n if (typeof TextEncoder !== 'undefined') {\n const encoder = new TextEncoder();\n const encoded = encoder.encode(body);\n return encoded.length.toString();\n }\n }\n else if (ArrayBuffer.isView(body)) {\n return body.byteLength.toString();\n }\n return null;\n }\n buildRequest(options, { retryCount = 0 } = {}) {\n options = { ...options };\n const { method, path, query, headers: headers = {} } = options;\n const body = ArrayBuffer.isView(options.body) || (options.__binaryRequest && typeof options.body === 'string') ?\n options.body\n : isMultipartBody(options.body) ? options.body.body\n : options.body ? JSON.stringify(options.body, null, 2)\n : null;\n const contentLength = this.calculateContentLength(body);\n const url = this.buildURL(path, query);\n if ('timeout' in options)\n validatePositiveInteger('timeout', options.timeout);\n options.timeout = options.timeout ?? this.timeout;\n const httpAgent = options.httpAgent ?? this.httpAgent ?? getDefaultAgent(url);\n const minAgentTimeout = options.timeout + 1000;\n if (typeof httpAgent?.options?.timeout === 'number' &&\n minAgentTimeout > (httpAgent.options.timeout ?? 0)) {\n // Allow any given request to bump our agent active socket timeout.\n // This may seem strange, but leaking active sockets should be rare and not particularly problematic,\n // and without mutating agent we would need to create more of them.\n // This tradeoff optimizes for performance.\n httpAgent.options.timeout = minAgentTimeout;\n }\n if (this.idempotencyHeader && method !== 'get') {\n if (!options.idempotencyKey)\n options.idempotencyKey = this.defaultIdempotencyKey();\n headers[this.idempotencyHeader] = options.idempotencyKey;\n }\n const reqHeaders = this.buildHeaders({ options, headers, contentLength, retryCount });\n const req = {\n method,\n ...(body && { body: body }),\n headers: reqHeaders,\n ...(httpAgent && { agent: httpAgent }),\n // @ts-ignore node-fetch uses a custom AbortSignal type that is\n // not compatible with standard web types\n signal: options.signal ?? null,\n };\n return { req, url, timeout: options.timeout };\n }\n buildHeaders({ options, headers, contentLength, retryCount, }) {\n const reqHeaders = {};\n if (contentLength) {\n reqHeaders['content-length'] = contentLength;\n }\n const defaultHeaders = this.defaultHeaders(options);\n applyHeadersMut(reqHeaders, defaultHeaders);\n applyHeadersMut(reqHeaders, headers);\n // let builtin fetch set the Content-Type for multipart bodies\n if (isMultipartBody(options.body) && shimsKind !== 'node') {\n delete reqHeaders['content-type'];\n }\n // Don't set theses headers if they were already set or removed through default headers or by the caller.\n // We check `defaultHeaders` and `headers`, which can contain nulls, instead of `reqHeaders` to account\n // for the removal case.\n if (getHeader(defaultHeaders, 'x-stainless-retry-count') === undefined &&\n getHeader(headers, 'x-stainless-retry-count') === undefined) {\n reqHeaders['x-stainless-retry-count'] = String(retryCount);\n }\n if (getHeader(defaultHeaders, 'x-stainless-timeout') === undefined &&\n getHeader(headers, 'x-stainless-timeout') === undefined &&\n options.timeout) {\n reqHeaders['x-stainless-timeout'] = String(options.timeout);\n }\n this.validateHeaders(reqHeaders, headers);\n return reqHeaders;\n }\n /**\n * Used as a callback for mutating the given `FinalRequestOptions` object.\n */\n async prepareOptions(options) { }\n /**\n * Used as a callback for mutating the given `RequestInit` object.\n *\n * This is useful for cases where you want to add certain headers based off of\n * the request properties, e.g. `method` or `url`.\n */\n async prepareRequest(request, { url, options }) { }\n parseHeaders(headers) {\n return (!headers ? {}\n : Symbol.iterator in headers ?\n Object.fromEntries(Array.from(headers).map((header) => [...header]))\n : { ...headers });\n }\n makeStatusError(status, error, message, headers) {\n return APIError.generate(status, error, message, headers);\n }\n request(options, remainingRetries = null) {\n return new APIPromise(this.makeRequest(options, remainingRetries));\n }\n async makeRequest(optionsInput, retriesRemaining) {\n const options = await optionsInput;\n const maxRetries = options.maxRetries ?? this.maxRetries;\n if (retriesRemaining == null) {\n retriesRemaining = maxRetries;\n }\n await this.prepareOptions(options);\n const { req, url, timeout } = this.buildRequest(options, { retryCount: maxRetries - retriesRemaining });\n await this.prepareRequest(req, { url, options });\n debug('request', url, options, req.headers);\n if (options.signal?.aborted) {\n throw new APIUserAbortError();\n }\n const controller = new AbortController();\n const response = await this.fetchWithTimeout(url, req, timeout, controller).catch(castToError);\n if (response instanceof Error) {\n if (options.signal?.aborted) {\n throw new APIUserAbortError();\n }\n if (retriesRemaining) {\n return this.retryRequest(options, retriesRemaining);\n }\n if (response.name === 'AbortError') {\n throw new APIConnectionTimeoutError();\n }\n throw new APIConnectionError({ cause: response });\n }\n const responseHeaders = createResponseHeaders(response.headers);\n if (!response.ok) {\n if (retriesRemaining && this.shouldRetry(response)) {\n const retryMessage = `retrying, ${retriesRemaining} attempts remaining`;\n debug(`response (error; ${retryMessage})`, response.status, url, responseHeaders);\n return this.retryRequest(options, retriesRemaining, responseHeaders);\n }\n const errText = await response.text().catch((e) => castToError(e).message);\n const errJSON = safeJSON(errText);\n const errMessage = errJSON ? undefined : errText;\n const retryMessage = retriesRemaining ? `(error; no more retries left)` : `(error; not retryable)`;\n debug(`response (error; ${retryMessage})`, response.status, url, responseHeaders, errMessage);\n const err = this.makeStatusError(response.status, errJSON, errMessage, responseHeaders);\n throw err;\n }\n return { response, options, controller };\n }\n requestAPIList(Page, options) {\n const request = this.makeRequest(options, null);\n return new PagePromise(this, request, Page);\n }\n buildURL(path, query) {\n const url = isAbsoluteURL(path) ?\n new URL(path)\n : new URL(this.baseURL + (this.baseURL.endsWith('/') && path.startsWith('/') ? path.slice(1) : path));\n const defaultQuery = this.defaultQuery();\n if (!isEmptyObj(defaultQuery)) {\n query = { ...defaultQuery, ...query };\n }\n if (typeof query === 'object' && query && !Array.isArray(query)) {\n url.search = this.stringifyQuery(query);\n }\n return url.toString();\n }\n stringifyQuery(query) {\n return Object.entries(query)\n .filter(([_, value]) => typeof value !== 'undefined')\n .map(([key, value]) => {\n if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') {\n return `${encodeURIComponent(key)}=${encodeURIComponent(value)}`;\n }\n if (value === null) {\n return `${encodeURIComponent(key)}=`;\n }\n throw new OpenAIError(`Cannot stringify type ${typeof value}; Expected string, number, boolean, or null. If you need to pass nested query parameters, you can manually encode them, e.g. { query: { 'foo[key1]': value1, 'foo[key2]': value2 } }, and please open a GitHub issue requesting better support for your use case.`);\n })\n .join('&');\n }\n async fetchWithTimeout(url, init, ms, controller) {\n const { signal, ...options } = init || {};\n if (signal)\n signal.addEventListener('abort', () => controller.abort());\n const timeout = setTimeout(() => controller.abort(), ms);\n const fetchOptions = {\n signal: controller.signal,\n ...options,\n };\n if (fetchOptions.method) {\n // Custom methods like 'patch' need to be uppercased\n // See https://github.com/nodejs/undici/issues/2294\n fetchOptions.method = fetchOptions.method.toUpperCase();\n }\n return (\n // use undefined this binding; fetch errors if bound to something else in browser/cloudflare\n this.fetch.call(undefined, url, fetchOptions).finally(() => {\n clearTimeout(timeout);\n }));\n }\n shouldRetry(response) {\n // Note this is not a standard header.\n const shouldRetryHeader = response.headers.get('x-should-retry');\n // If the server explicitly says whether or not to retry, obey.\n if (shouldRetryHeader === 'true')\n return true;\n if (shouldRetryHeader === 'false')\n return false;\n // Retry on request timeouts.\n if (response.status === 408)\n return true;\n // Retry on lock timeouts.\n if (response.status === 409)\n return true;\n // Retry on rate limits.\n if (response.status === 429)\n return true;\n // Retry internal errors.\n if (response.status >= 500)\n return true;\n return false;\n }\n async retryRequest(options, retriesRemaining, responseHeaders) {\n let timeoutMillis;\n // Note the `retry-after-ms` header may not be standard, but is a good idea and we'd like proactive support for it.\n const retryAfterMillisHeader = responseHeaders?.['retry-after-ms'];\n if (retryAfterMillisHeader) {\n const timeoutMs = parseFloat(retryAfterMillisHeader);\n if (!Number.isNaN(timeoutMs)) {\n timeoutMillis = timeoutMs;\n }\n }\n // About the Retry-After header: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Retry-After\n const retryAfterHeader = responseHeaders?.['retry-after'];\n if (retryAfterHeader && !timeoutMillis) {\n const timeoutSeconds = parseFloat(retryAfterHeader);\n if (!Number.isNaN(timeoutSeconds)) {\n timeoutMillis = timeoutSeconds * 1000;\n }\n else {\n timeoutMillis = Date.parse(retryAfterHeader) - Date.now();\n }\n }\n // If the API asks us to wait a certain amount of time (and it's a reasonable amount),\n // just do what it says, but otherwise calculate a default\n if (!(timeoutMillis && 0 <= timeoutMillis && timeoutMillis < 60 * 1000)) {\n const maxRetries = options.maxRetries ?? this.maxRetries;\n timeoutMillis = this.calculateDefaultRetryTimeoutMillis(retriesRemaining, maxRetries);\n }\n await sleep(timeoutMillis);\n return this.makeRequest(options, retriesRemaining - 1);\n }\n calculateDefaultRetryTimeoutMillis(retriesRemaining, maxRetries) {\n const initialRetryDelay = 0.5;\n const maxRetryDelay = 8.0;\n const numRetries = maxRetries - retriesRemaining;\n // Apply exponential backoff, but not more than the max.\n const sleepSeconds = Math.min(initialRetryDelay * Math.pow(2, numRetries), maxRetryDelay);\n // Apply some jitter, take up to at most 25 percent of the retry time.\n const jitter = 1 - Math.random() * 0.25;\n return sleepSeconds * jitter * 1000;\n }\n getUserAgent() {\n return `${this.constructor.name}/JS ${VERSION}`;\n }\n}\nexport class AbstractPage {\n constructor(client, response, body, options) {\n _AbstractPage_client.set(this, void 0);\n __classPrivateFieldSet(this, _AbstractPage_client, client, \"f\");\n this.options = options;\n this.response = response;\n this.body = body;\n }\n hasNextPage() {\n const items = this.getPaginatedItems();\n if (!items.length)\n return false;\n return this.nextPageInfo() != null;\n }\n async getNextPage() {\n const nextInfo = this.nextPageInfo();\n if (!nextInfo) {\n throw new OpenAIError('No next page expected; please check `.hasNextPage()` before calling `.getNextPage()`.');\n }\n const nextOptions = { ...this.options };\n if ('params' in nextInfo && typeof nextOptions.query === 'object') {\n nextOptions.query = { ...nextOptions.query, ...nextInfo.params };\n }\n else if ('url' in nextInfo) {\n const params = [...Object.entries(nextOptions.query || {}), ...nextInfo.url.searchParams.entries()];\n for (const [key, value] of params) {\n nextInfo.url.searchParams.set(key, value);\n }\n nextOptions.query = undefined;\n nextOptions.path = nextInfo.url.toString();\n }\n return await __classPrivateFieldGet(this, _AbstractPage_client, \"f\").requestAPIList(this.constructor, nextOptions);\n }\n async *iterPages() {\n // eslint-disable-next-line @typescript-eslint/no-this-alias\n let page = this;\n yield page;\n while (page.hasNextPage()) {\n page = await page.getNextPage();\n yield page;\n }\n }\n async *[(_AbstractPage_client = new WeakMap(), Symbol.asyncIterator)]() {\n for await (const page of this.iterPages()) {\n for (const item of page.getPaginatedItems()) {\n yield item;\n }\n }\n }\n}\n/**\n * This subclass of Promise will resolve to an instantiated Page once the request completes.\n *\n * It also implements AsyncIterable to allow auto-paginating iteration on an unawaited list call, eg:\n *\n * for await (const item of client.items.list()) {\n * console.log(item)\n * }\n */\nexport class PagePromise extends APIPromise {\n constructor(client, request, Page) {\n super(request, async (props) => new Page(client, props.response, await defaultParseResponse(props), props.options));\n }\n /**\n * Allow auto-paginating iteration on an unawaited list call, eg:\n *\n * for await (const item of client.items.list()) {\n * console.log(item)\n * }\n */\n async *[Symbol.asyncIterator]() {\n const page = await this;\n for await (const item of page) {\n yield item;\n }\n }\n}\nexport const createResponseHeaders = (headers) => {\n return new Proxy(Object.fromEntries(\n // @ts-ignore\n headers.entries()), {\n get(target, name) {\n const key = name.toString();\n return target[key.toLowerCase()] || target[key];\n },\n });\n};\n// This is required so that we can determine if a given object matches the RequestOptions\n// type at runtime. While this requires duplication, it is enforced by the TypeScript\n// compiler such that any missing / extraneous keys will cause an error.\nconst requestOptionsKeys = {\n method: true,\n path: true,\n query: true,\n body: true,\n headers: true,\n maxRetries: true,\n stream: true,\n timeout: true,\n httpAgent: true,\n signal: true,\n idempotencyKey: true,\n __metadata: true,\n __binaryRequest: true,\n __binaryResponse: true,\n __streamClass: true,\n};\nexport const isRequestOptions = (obj) => {\n return (typeof obj === 'object' &&\n obj !== null &&\n !isEmptyObj(obj) &&\n Object.keys(obj).every((k) => hasOwn(requestOptionsKeys, k)));\n};\nconst getPlatformProperties = () => {\n if (typeof Deno !== 'undefined' && Deno.build != null) {\n return {\n 'X-Stainless-Lang': 'js',\n 'X-Stainless-Package-Version': VERSION,\n 'X-Stainless-OS': normalizePlatform(Deno.build.os),\n 'X-Stainless-Arch': normalizeArch(Deno.build.arch),\n 'X-Stainless-Runtime': 'deno',\n 'X-Stainless-Runtime-Version': typeof Deno.version === 'string' ? Deno.version : Deno.version?.deno ?? 'unknown',\n };\n }\n if (typeof EdgeRuntime !== 'undefined') {\n return {\n 'X-Stainless-Lang': 'js',\n 'X-Stainless-Package-Version': VERSION,\n 'X-Stainless-OS': 'Unknown',\n 'X-Stainless-Arch': `other:${EdgeRuntime}`,\n 'X-Stainless-Runtime': 'edge',\n 'X-Stainless-Runtime-Version': process.version,\n };\n }\n // Check if Node.js\n if (Object.prototype.toString.call(typeof process !== 'undefined' ? process : 0) === '[object process]') {\n return {\n 'X-Stainless-Lang': 'js',\n 'X-Stainless-Package-Version': VERSION,\n 'X-Stainless-OS': normalizePlatform(process.platform),\n 'X-Stainless-Arch': normalizeArch(process.arch),\n 'X-Stainless-Runtime': 'node',\n 'X-Stainless-Runtime-Version': process.version,\n };\n }\n const browserInfo = getBrowserInfo();\n if (browserInfo) {\n return {\n 'X-Stainless-Lang': 'js',\n 'X-Stainless-Package-Version': VERSION,\n 'X-Stainless-OS': 'Unknown',\n 'X-Stainless-Arch': 'unknown',\n 'X-Stainless-Runtime': `browser:${browserInfo.browser}`,\n 'X-Stainless-Runtime-Version': browserInfo.version,\n };\n }\n // TODO add support for Cloudflare workers, etc.\n return {\n 'X-Stainless-Lang': 'js',\n 'X-Stainless-Package-Version': VERSION,\n 'X-Stainless-OS': 'Unknown',\n 'X-Stainless-Arch': 'unknown',\n 'X-Stainless-Runtime': 'unknown',\n 'X-Stainless-Runtime-Version': 'unknown',\n };\n};\n// Note: modified from https://github.com/JS-DevTools/host-environment/blob/b1ab79ecde37db5d6e163c050e54fe7d287d7c92/src/isomorphic.browser.ts\nfunction getBrowserInfo() {\n if (typeof navigator === 'undefined' || !navigator) {\n return null;\n }\n // NOTE: The order matters here!\n const browserPatterns = [\n { key: 'edge', pattern: /Edge(?:\\W+(\\d+)\\.(\\d+)(?:\\.(\\d+))?)?/ },\n { key: 'ie', pattern: /MSIE(?:\\W+(\\d+)\\.(\\d+)(?:\\.(\\d+))?)?/ },\n { key: 'ie', pattern: /Trident(?:.*rv\\:(\\d+)\\.(\\d+)(?:\\.(\\d+))?)?/ },\n { key: 'chrome', pattern: /Chrome(?:\\W+(\\d+)\\.(\\d+)(?:\\.(\\d+))?)?/ },\n { key: 'firefox', pattern: /Firefox(?:\\W+(\\d+)\\.(\\d+)(?:\\.(\\d+))?)?/ },\n { key: 'safari', pattern: /(?:Version\\W+(\\d+)\\.(\\d+)(?:\\.(\\d+))?)?(?:\\W+Mobile\\S*)?\\W+Safari/ },\n ];\n // Find the FIRST matching browser\n for (const { key, pattern } of browserPatterns) {\n const match = pattern.exec(navigator.userAgent);\n if (match) {\n const major = match[1] || 0;\n const minor = match[2] || 0;\n const patch = match[3] || 0;\n return { browser: key, version: `${major}.${minor}.${patch}` };\n }\n }\n return null;\n}\nconst normalizeArch = (arch) => {\n // Node docs:\n // - https://nodejs.org/api/process.html#processarch\n // Deno docs:\n // - https://doc.deno.land/deno/stable/~/Deno.build\n if (arch === 'x32')\n return 'x32';\n if (arch === 'x86_64' || arch === 'x64')\n return 'x64';\n if (arch === 'arm')\n return 'arm';\n if (arch === 'aarch64' || arch === 'arm64')\n return 'arm64';\n if (arch)\n return `other:${arch}`;\n return 'unknown';\n};\nconst normalizePlatform = (platform) => {\n // Node platforms:\n // - https://nodejs.org/api/process.html#processplatform\n // Deno platforms:\n // - https://doc.deno.land/deno/stable/~/Deno.build\n // - https://github.com/denoland/deno/issues/14799\n platform = platform.toLowerCase();\n // NOTE: this iOS check is untested and may not work\n // Node does not work natively on IOS, there is a fork at\n // https://github.com/nodejs-mobile/nodejs-mobile\n // however it is unknown at the time of writing how to detect if it is running\n if (platform.includes('ios'))\n return 'iOS';\n if (platform === 'android')\n return 'Android';\n if (platform === 'darwin')\n return 'MacOS';\n if (platform === 'win32')\n return 'Windows';\n if (platform === 'freebsd')\n return 'FreeBSD';\n if (platform === 'openbsd')\n return 'OpenBSD';\n if (platform === 'linux')\n return 'Linux';\n if (platform)\n return `Other:${platform}`;\n return 'Unknown';\n};\nlet _platformHeaders;\nconst getPlatformHeaders = () => {\n return (_platformHeaders ?? (_platformHeaders = getPlatformProperties()));\n};\nexport const safeJSON = (text) => {\n try {\n return JSON.parse(text);\n }\n catch (err) {\n return undefined;\n }\n};\n// https://url.spec.whatwg.org/#url-scheme-string\nconst startsWithSchemeRegexp = /^[a-z][a-z0-9+.-]*:/i;\nconst isAbsoluteURL = (url) => {\n return startsWithSchemeRegexp.test(url);\n};\nexport const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));\nconst validatePositiveInteger = (name, n) => {\n if (typeof n !== 'number' || !Number.isInteger(n)) {\n throw new OpenAIError(`${name} must be an integer`);\n }\n if (n < 0) {\n throw new OpenAIError(`${name} must be a positive integer`);\n }\n return n;\n};\nexport const castToError = (err) => {\n if (err instanceof Error)\n return err;\n if (typeof err === 'object' && err !== null) {\n try {\n return new Error(JSON.stringify(err));\n }\n catch { }\n }\n return new Error(err);\n};\nexport const ensurePresent = (value) => {\n if (value == null)\n throw new OpenAIError(`Expected a value to be given but received ${value} instead.`);\n return value;\n};\n/**\n * Read an environment variable.\n *\n * Trims beginning and trailing whitespace.\n *\n * Will return undefined if the environment variable doesn't exist or cannot be accessed.\n */\nexport const readEnv = (env) => {\n if (typeof process !== 'undefined') {\n return process.env?.[env]?.trim() ?? undefined;\n }\n if (typeof Deno !== 'undefined') {\n return Deno.env?.get?.(env)?.trim();\n }\n return undefined;\n};\nexport const coerceInteger = (value) => {\n if (typeof value === 'number')\n return Math.round(value);\n if (typeof value === 'string')\n return parseInt(value, 10);\n throw new OpenAIError(`Could not coerce ${value} (type: ${typeof value}) into a number`);\n};\nexport const coerceFloat = (value) => {\n if (typeof value === 'number')\n return value;\n if (typeof value === 'string')\n return parseFloat(value);\n throw new OpenAIError(`Could not coerce ${value} (type: ${typeof value}) into a number`);\n};\nexport const coerceBoolean = (value) => {\n if (typeof value === 'boolean')\n return value;\n if (typeof value === 'string')\n return value === 'true';\n return Boolean(value);\n};\nexport const maybeCoerceInteger = (value) => {\n if (value === undefined) {\n return undefined;\n }\n return coerceInteger(value);\n};\nexport const maybeCoerceFloat = (value) => {\n if (value === undefined) {\n return undefined;\n }\n return coerceFloat(value);\n};\nexport const maybeCoerceBoolean = (value) => {\n if (value === undefined) {\n return undefined;\n }\n return coerceBoolean(value);\n};\n// https://stackoverflow.com/a/34491287\nexport function isEmptyObj(obj) {\n if (!obj)\n return true;\n for (const _k in obj)\n return false;\n return true;\n}\n// https://eslint.org/docs/latest/rules/no-prototype-builtins\nexport function hasOwn(obj, key) {\n return Object.prototype.hasOwnProperty.call(obj, key);\n}\n/**\n * Copies headers from \"newHeaders\" onto \"targetHeaders\",\n * using lower-case for all properties,\n * ignoring any keys with undefined values,\n * and deleting any keys with null values.\n */\nfunction applyHeadersMut(targetHeaders, newHeaders) {\n for (const k in newHeaders) {\n if (!hasOwn(newHeaders, k))\n continue;\n const lowerKey = k.toLowerCase();\n if (!lowerKey)\n continue;\n const val = newHeaders[k];\n if (val === null) {\n delete targetHeaders[lowerKey];\n }\n else if (val !== undefined) {\n targetHeaders[lowerKey] = val;\n }\n }\n}\nconst SENSITIVE_HEADERS = new Set(['authorization', 'api-key']);\nexport function debug(action, ...args) {\n if (typeof process !== 'undefined' && process?.env?.['DEBUG'] === 'true') {\n const modifiedArgs = args.map((arg) => {\n if (!arg) {\n return arg;\n }\n // Check for sensitive headers in request body 'headers' object\n if (arg['headers']) {\n // clone so we don't mutate\n const modifiedArg = { ...arg, headers: { ...arg['headers'] } };\n for (const header in arg['headers']) {\n if (SENSITIVE_HEADERS.has(header.toLowerCase())) {\n modifiedArg['headers'][header] = 'REDACTED';\n }\n }\n return modifiedArg;\n }\n let modifiedArg = null;\n // Check for sensitive headers in headers object\n for (const header in arg) {\n if (SENSITIVE_HEADERS.has(header.toLowerCase())) {\n // avoid making a copy until we need to\n modifiedArg ?? (modifiedArg = { ...arg });\n modifiedArg[header] = 'REDACTED';\n }\n }\n return modifiedArg ?? arg;\n });\n console.log(`OpenAI:DEBUG:${action}`, ...modifiedArgs);\n }\n}\n/**\n * https://stackoverflow.com/a/2117523\n */\nconst uuid4 = () => {\n return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, (c) => {\n const r = (Math.random() * 16) | 0;\n const v = c === 'x' ? r : (r & 0x3) | 0x8;\n return v.toString(16);\n });\n};\nexport const isRunningInBrowser = () => {\n return (\n // @ts-ignore\n typeof window !== 'undefined' &&\n // @ts-ignore\n typeof window.document !== 'undefined' &&\n // @ts-ignore\n typeof navigator !== 'undefined');\n};\nexport const isHeadersProtocol = (headers) => {\n return typeof headers?.get === 'function';\n};\nexport const getRequiredHeader = (headers, header) => {\n const foundHeader = getHeader(headers, header);\n if (foundHeader === undefined) {\n throw new Error(`Could not find ${header} header`);\n }\n return foundHeader;\n};\nexport const getHeader = (headers, header) => {\n const lowerCasedHeader = header.toLowerCase();\n if (isHeadersProtocol(headers)) {\n // to deal with the case where the header looks like Stainless-Event-Id\n const intercapsHeader = header[0]?.toUpperCase() +\n header.substring(1).replace(/([^\\w])(\\w)/g, (_m, g1, g2) => g1 + g2.toUpperCase());\n for (const key of [header, lowerCasedHeader, header.toUpperCase(), intercapsHeader]) {\n const value = headers.get(key);\n if (value) {\n return value;\n }\n }\n }\n for (const [key, value] of Object.entries(headers)) {\n if (key.toLowerCase() === lowerCasedHeader) {\n if (Array.isArray(value)) {\n if (value.length <= 1)\n return value[0];\n console.warn(`Received ${value.length} entries for the ${header} header, using the first entry.`);\n return value[0];\n }\n return value;\n }\n }\n return undefined;\n};\n/**\n * Encodes a string to Base64 format.\n */\nexport const toBase64 = (str) => {\n if (!str)\n return '';\n if (typeof Buffer !== 'undefined') {\n return Buffer.from(str).toString('base64');\n }\n if (typeof btoa !== 'undefined') {\n return btoa(str);\n }\n throw new OpenAIError('Cannot generate b64 string; Expected `Buffer` or `btoa` to be defined');\n};\nexport function isObj(obj) {\n return obj != null && typeof obj === 'object' && !Array.isArray(obj);\n}\n//# sourceMappingURL=core.mjs.map","// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.\nexport class APIResource {\n constructor(client) {\n this._client = client;\n }\n}\n//# sourceMappingURL=resource.mjs.map","// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.\nimport { APIResource } from \"../resource.mjs\";\nexport class Completions extends APIResource {\n create(body, options) {\n return this._client.post('/completions', { body, ...options, stream: body.stream ?? false });\n }\n}\n//# sourceMappingURL=completions.mjs.map","// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.\nimport { APIResource } from \"../../../resource.mjs\";\nimport { isRequestOptions } from \"../../../core.mjs\";\nimport { ChatCompletionStoreMessagesPage } from \"./completions.mjs\";\nexport class Messages extends APIResource {\n list(completionId, query = {}, options) {\n if (isRequestOptions(query)) {\n return this.list(completionId, {}, query);\n }\n return this._client.getAPIList(`/chat/completions/${completionId}/messages`, ChatCompletionStoreMessagesPage, { query, ...options });\n }\n}\nexport { ChatCompletionStoreMessagesPage };\n//# sourceMappingURL=messages.mjs.map","// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.\nimport { AbstractPage } from \"./core.mjs\";\n/**\n * Note: no pagination actually occurs yet, this is for forwards-compatibility.\n */\nexport class Page extends AbstractPage {\n constructor(client, response, body, options) {\n super(client, response, body, options);\n this.data = body.data || [];\n this.object = body.object;\n }\n getPaginatedItems() {\n return this.data ?? [];\n }\n // @deprecated Please use `nextPageInfo()` instead\n /**\n * This page represents a response that isn't actually paginated at the API level\n * so there will never be any next page params.\n */\n nextPageParams() {\n return null;\n }\n nextPageInfo() {\n return null;\n }\n}\nexport class CursorPage extends AbstractPage {\n constructor(client, response, body, options) {\n super(client, response, body, options);\n this.data = body.data || [];\n this.has_more = body.has_more || false;\n }\n getPaginatedItems() {\n return this.data ?? [];\n }\n hasNextPage() {\n if (this.has_more === false) {\n return false;\n }\n return super.hasNextPage();\n }\n // @deprecated Please use `nextPageInfo()` instead\n nextPageParams() {\n const info = this.nextPageInfo();\n if (!info)\n return null;\n if ('params' in info)\n return info.params;\n const params = Object.fromEntries(info.url.searchParams);\n if (!Object.keys(params).length)\n return null;\n return params;\n }\n nextPageInfo() {\n const data = this.getPaginatedItems();\n if (!data.length) {\n return null;\n }\n const id = data[data.length - 1]?.id;\n if (!id) {\n return null;\n }\n return { params: { after: id } };\n }\n}\n//# sourceMappingURL=pagination.mjs.map","// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.\nimport { APIResource } from \"../../../resource.mjs\";\nimport { isRequestOptions } from \"../../../core.mjs\";\nimport * as MessagesAPI from \"./messages.mjs\";\nimport { Messages } from \"./messages.mjs\";\nimport { CursorPage } from \"../../../pagination.mjs\";\nexport class Completions extends APIResource {\n constructor() {\n super(...arguments);\n this.messages = new MessagesAPI.Messages(this._client);\n }\n create(body, options) {\n return this._client.post('/chat/completions', { body, ...options, stream: body.stream ?? false });\n }\n /**\n * Get a stored chat completion. Only chat completions that have been created with\n * the `store` parameter set to `true` will be returned.\n */\n retrieve(completionId, options) {\n return this._client.get(`/chat/completions/${completionId}`, options);\n }\n /**\n * Modify a stored chat completion. Only chat completions that have been created\n * with the `store` parameter set to `true` can be modified. Currently, the only\n * supported modification is to update the `metadata` field.\n */\n update(completionId, body, options) {\n return this._client.post(`/chat/completions/${completionId}`, { body, ...options });\n }\n list(query = {}, options) {\n if (isRequestOptions(query)) {\n return this.list({}, query);\n }\n return this._client.getAPIList('/chat/completions', ChatCompletionsPage, { query, ...options });\n }\n /**\n * Delete a stored chat completion. Only chat completions that have been created\n * with the `store` parameter set to `true` can be deleted.\n */\n del(completionId, options) {\n return this._client.delete(`/chat/completions/${completionId}`, options);\n }\n}\nexport class ChatCompletionsPage extends CursorPage {\n}\nexport class ChatCompletionStoreMessagesPage extends CursorPage {\n}\nCompletions.ChatCompletionsPage = ChatCompletionsPage;\nCompletions.Messages = Messages;\n//# sourceMappingURL=completions.mjs.map","// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.\nimport { APIResource } from \"../../resource.mjs\";\nimport * as CompletionsAPI from \"./completions/completions.mjs\";\nimport { ChatCompletionsPage, Completions, } from \"./completions/completions.mjs\";\nexport class Chat extends APIResource {\n constructor() {\n super(...arguments);\n this.completions = new CompletionsAPI.Completions(this._client);\n }\n}\nChat.Completions = Completions;\nChat.ChatCompletionsPage = ChatCompletionsPage;\n//# sourceMappingURL=chat.mjs.map","// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.\nimport { APIResource } from \"../resource.mjs\";\nexport class Embeddings extends APIResource {\n /**\n * Creates an embedding vector representing the input text.\n */\n create(body, options) {\n return this._client.post('/embeddings', { body, ...options });\n }\n}\n//# sourceMappingURL=embeddings.mjs.map","// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.\nimport { APIResource } from \"../resource.mjs\";\nimport { isRequestOptions } from \"../core.mjs\";\nimport { sleep } from \"../core.mjs\";\nimport { APIConnectionTimeoutError } from \"../error.mjs\";\nimport * as Core from \"../core.mjs\";\nimport { CursorPage } from \"../pagination.mjs\";\nexport class Files extends APIResource {\n /**\n * Upload a file that can be used across various endpoints. Individual files can be\n * up to 512 MB, and the size of all files uploaded by one organization can be up\n * to 100 GB.\n *\n * The Assistants API supports files up to 2 million tokens and of specific file\n * types. See the\n * [Assistants Tools guide](https://platform.openai.com/docs/assistants/tools) for\n * details.\n *\n * The Fine-tuning API only supports `.jsonl` files. The input also has certain\n * required formats for fine-tuning\n * [chat](https://platform.openai.com/docs/api-reference/fine-tuning/chat-input) or\n * [completions](https://platform.openai.com/docs/api-reference/fine-tuning/completions-input)\n * models.\n *\n * The Batch API only supports `.jsonl` files up to 200 MB in size. The input also\n * has a specific required\n * [format](https://platform.openai.com/docs/api-reference/batch/request-input).\n *\n * Please [contact us](https://help.openai.com/) if you need to increase these\n * storage limits.\n */\n create(body, options) {\n return this._client.post('/files', Core.multipartFormRequestOptions({ body, ...options }));\n }\n /**\n * Returns information about a specific file.\n */\n retrieve(fileId, options) {\n return this._client.get(`/files/${fileId}`, options);\n }\n list(query = {}, options) {\n if (isRequestOptions(query)) {\n return this.list({}, query);\n }\n return this._client.getAPIList('/files', FileObjectsPage, { query, ...options });\n }\n /**\n * Delete a file.\n */\n del(fileId, options) {\n return this._client.delete(`/files/${fileId}`, options);\n }\n /**\n * Returns the contents of the specified file.\n */\n content(fileId, options) {\n return this._client.get(`/files/${fileId}/content`, {\n ...options,\n headers: { Accept: 'application/binary', ...options?.headers },\n __binaryResponse: true,\n });\n }\n /**\n * Returns the contents of the specified file.\n *\n * @deprecated The `.content()` method should be used instead\n */\n retrieveContent(fileId, options) {\n return this._client.get(`/files/${fileId}/content`, options);\n }\n /**\n * Waits for the given file to be processed, default timeout is 30 mins.\n */\n async waitForProcessing(id, { pollInterval = 5000, maxWait = 30 * 60 * 1000 } = {}) {\n const TERMINAL_STATES = new Set(['processed', 'error', 'deleted']);\n const start = Date.now();\n let file = await this.retrieve(id);\n while (!file.status || !TERMINAL_STATES.has(file.status)) {\n await sleep(pollInterval);\n file = await this.retrieve(id);\n if (Date.now() - start > maxWait) {\n throw new APIConnectionTimeoutError({\n message: `Giving up on waiting for file ${id} to finish processing after ${maxWait} milliseconds.`,\n });\n }\n }\n return file;\n }\n}\nexport class FileObjectsPage extends CursorPage {\n}\nFiles.FileObjectsPage = FileObjectsPage;\n//# sourceMappingURL=files.mjs.map","// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.\nimport { APIResource } from \"../resource.mjs\";\nimport * as Core from \"../core.mjs\";\nexport class Images extends APIResource {\n /**\n * Creates a variation of a given image.\n */\n createVariation(body, options) {\n return this._client.post('/images/variations', Core.multipartFormRequestOptions({ body, ...options }));\n }\n /**\n * Creates an edited or extended image given an original image and a prompt.\n */\n edit(body, options) {\n return this._client.post('/images/edits', Core.multipartFormRequestOptions({ body, ...options }));\n }\n /**\n * Creates an image given a prompt.\n */\n generate(body, options) {\n return this._client.post('/images/generations', { body, ...options });\n }\n}\n//# sourceMappingURL=images.mjs.map","// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.\nimport { APIResource } from \"../../resource.mjs\";\nexport class Speech extends APIResource {\n /**\n * Generates audio from the input text.\n */\n create(body, options) {\n return this._client.post('/audio/speech', {\n body,\n ...options,\n headers: { Accept: 'application/octet-stream', ...options?.headers },\n __binaryResponse: true,\n });\n }\n}\n//# sourceMappingURL=speech.mjs.map","// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.\nimport { APIResource } from \"../../resource.mjs\";\nimport * as Core from \"../../core.mjs\";\nexport class Transcriptions extends APIResource {\n create(body, options) {\n return this._client.post('/audio/transcriptions', Core.multipartFormRequestOptions({ body, ...options, __metadata: { model: body.model } }));\n }\n}\n//# sourceMappingURL=transcriptions.mjs.map","// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.\nimport { APIResource } from \"../../resource.mjs\";\nimport * as Core from \"../../core.mjs\";\nexport class Translations extends APIResource {\n create(body, options) {\n return this._client.post('/audio/translations', Core.multipartFormRequestOptions({ body, ...options, __metadata: { model: body.model } }));\n }\n}\n//# sourceMappingURL=translations.mjs.map","// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.\nimport { APIResource } from \"../../resource.mjs\";\nimport * as SpeechAPI from \"./speech.mjs\";\nimport { Speech } from \"./speech.mjs\";\nimport * as TranscriptionsAPI from \"./transcriptions.mjs\";\nimport { Transcriptions, } from \"./transcriptions.mjs\";\nimport * as TranslationsAPI from \"./translations.mjs\";\nimport { Translations, } from \"./translations.mjs\";\nexport class Audio extends APIResource {\n constructor() {\n super(...arguments);\n this.transcriptions = new TranscriptionsAPI.Transcriptions(this._client);\n this.translations = new TranslationsAPI.Translations(this._client);\n this.speech = new SpeechAPI.Speech(this._client);\n }\n}\nAudio.Transcriptions = Transcriptions;\nAudio.Translations = Translations;\nAudio.Speech = Speech;\n//# sourceMappingURL=audio.mjs.map","// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.\nimport { APIResource } from \"../resource.mjs\";\nexport class Moderations extends APIResource {\n /**\n * Classifies if text and/or image inputs are potentially harmful. Learn more in\n * the [moderation guide](https://platform.openai.com/docs/guides/moderation).\n */\n create(body, options) {\n return this._client.post('/moderations', { body, ...options });\n }\n}\n//# sourceMappingURL=moderations.mjs.map","// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.\nimport { APIResource } from \"../resource.mjs\";\nimport { Page } from \"../pagination.mjs\";\nexport class Models extends APIResource {\n /**\n * Retrieves a model instance, providing basic information about the model such as\n * the owner and permissioning.\n */\n retrieve(model, options) {\n return this._client.get(`/models/${model}`, options);\n }\n /**\n * Lists the currently available models, and provides basic information about each\n * one such as the owner and availability.\n */\n list(options) {\n return this._client.getAPIList('/models', ModelsPage, options);\n }\n /**\n * Delete a fine-tuned model. You must have the Owner role in your organization to\n * delete a model.\n */\n del(model, options) {\n return this._client.delete(`/models/${model}`, options);\n }\n}\n/**\n * Note: no pagination actually occurs yet, this is for forwards-compatibility.\n */\nexport class ModelsPage extends Page {\n}\nModels.ModelsPage = ModelsPage;\n//# sourceMappingURL=models.mjs.map","// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.\nimport { APIResource } from \"../../../resource.mjs\";\nimport { isRequestOptions } from \"../../../core.mjs\";\nimport { CursorPage } from \"../../../pagination.mjs\";\nexport class Checkpoints extends APIResource {\n list(fineTuningJobId, query = {}, options) {\n if (isRequestOptions(query)) {\n return this.list(fineTuningJobId, {}, query);\n }\n return this._client.getAPIList(`/fine_tuning/jobs/${fineTuningJobId}/checkpoints`, FineTuningJobCheckpointsPage, { query, ...options });\n }\n}\nexport class FineTuningJobCheckpointsPage extends CursorPage {\n}\nCheckpoints.FineTuningJobCheckpointsPage = FineTuningJobCheckpointsPage;\n//# sourceMappingURL=checkpoints.mjs.map","// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.\nimport { APIResource } from \"../../../resource.mjs\";\nimport { isRequestOptions } from \"../../../core.mjs\";\nimport * as CheckpointsAPI from \"./checkpoints.mjs\";\nimport { Checkpoints, FineTuningJobCheckpointsPage, } from \"./checkpoints.mjs\";\nimport { CursorPage } from \"../../../pagination.mjs\";\nexport class Jobs extends APIResource {\n constructor() {\n super(...arguments);\n this.checkpoints = new CheckpointsAPI.Checkpoints(this._client);\n }\n /**\n * Creates a fine-tuning job which begins the process of creating a new model from\n * a given dataset.\n *\n * Response includes details of the enqueued job including job status and the name\n * of the fine-tuned models once complete.\n *\n * [Learn more about fine-tuning](https://platform.openai.com/docs/guides/fine-tuning)\n */\n create(body, options) {\n return this._client.post('/fine_tuning/jobs', { body, ...options });\n }\n /**\n * Get info about a fine-tuning job.\n *\n * [Learn more about fine-tuning](https://platform.openai.com/docs/guides/fine-tuning)\n */\n retrieve(fineTuningJobId, options) {\n return this._client.get(`/fine_tuning/jobs/${fineTuningJobId}`, options);\n }\n list(query = {}, options) {\n if (isRequestOptions(query)) {\n return this.list({}, query);\n }\n return this._client.getAPIList('/fine_tuning/jobs', FineTuningJobsPage, { query, ...options });\n }\n /**\n * Immediately cancel a fine-tune job.\n */\n cancel(fineTuningJobId, options) {\n return this._client.post(`/fine_tuning/jobs/${fineTuningJobId}/cancel`, options);\n }\n listEvents(fineTuningJobId, query = {}, options) {\n if (isRequestOptions(query)) {\n return this.listEvents(fineTuningJobId, {}, query);\n }\n return this._client.getAPIList(`/fine_tuning/jobs/${fineTuningJobId}/events`, FineTuningJobEventsPage, {\n query,\n ...options,\n });\n }\n}\nexport class FineTuningJobsPage extends CursorPage {\n}\nexport class FineTuningJobEventsPage extends CursorPage {\n}\nJobs.FineTuningJobsPage = FineTuningJobsPage;\nJobs.FineTuningJobEventsPage = FineTuningJobEventsPage;\nJobs.Checkpoints = Checkpoints;\nJobs.FineTuningJobCheckpointsPage = FineTuningJobCheckpointsPage;\n//# sourceMappingURL=jobs.mjs.map","// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.\nimport { APIResource } from \"../../resource.mjs\";\nimport * as JobsAPI from \"./jobs/jobs.mjs\";\nimport { FineTuningJobEventsPage, FineTuningJobsPage, Jobs, } from \"./jobs/jobs.mjs\";\nexport class FineTuning extends APIResource {\n constructor() {\n super(...arguments);\n this.jobs = new JobsAPI.Jobs(this._client);\n }\n}\nFineTuning.Jobs = Jobs;\nFineTuning.FineTuningJobsPage = FineTuningJobsPage;\nFineTuning.FineTuningJobEventsPage = FineTuningJobEventsPage;\n//# sourceMappingURL=fine-tuning.mjs.map","// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.\nimport { APIResource } from \"../../resource.mjs\";\nimport { isRequestOptions } from \"../../core.mjs\";\nimport { CursorPage } from \"../../pagination.mjs\";\nexport class Assistants extends APIResource {\n /**\n * Create an assistant with a model and instructions.\n */\n create(body, options) {\n return this._client.post('/assistants', {\n body,\n ...options,\n headers: { 'OpenAI-Beta': 'assistants=v2', ...options?.headers },\n });\n }\n /**\n * Retrieves an assistant.\n */\n retrieve(assistantId, options) {\n return this._client.get(`/assistants/${assistantId}`, {\n ...options,\n headers: { 'OpenAI-Beta': 'assistants=v2', ...options?.headers },\n });\n }\n /**\n * Modifies an assistant.\n */\n update(assistantId, body, options) {\n return this._client.post(`/assistants/${assistantId}`, {\n body,\n ...options,\n headers: { 'OpenAI-Beta': 'assistants=v2', ...options?.headers },\n });\n }\n list(query = {}, options) {\n if (isRequestOptions(query)) {\n return this.list({}, query);\n }\n return this._client.getAPIList('/assistants', AssistantsPage, {\n query,\n ...options,\n headers: { 'OpenAI-Beta': 'assistants=v2', ...options?.headers },\n });\n }\n /**\n * Delete an assistant.\n */\n del(assistantId, options) {\n return this._client.delete(`/assistants/${assistantId}`, {\n ...options,\n headers: { 'OpenAI-Beta': 'assistants=v2', ...options?.headers },\n });\n }\n}\nexport class AssistantsPage extends CursorPage {\n}\nAssistants.AssistantsPage = AssistantsPage;\n//# sourceMappingURL=assistants.mjs.map","export function isRunnableFunctionWithParse(fn) {\n return typeof fn.parse === 'function';\n}\n/**\n * This is helper class for passing a `function` and `parse` where the `function`\n * argument type matches the `parse` return type.\n *\n * @deprecated - please use ParsingToolFunction instead.\n */\nexport class ParsingFunction {\n constructor(input) {\n this.function = input.function;\n this.parse = input.parse;\n this.parameters = input.parameters;\n this.description = input.description;\n this.name = input.name;\n }\n}\n/**\n * This is helper class for passing a `function` and `parse` where the `function`\n * argument type matches the `parse` return type.\n */\nexport class ParsingToolFunction {\n constructor(input) {\n this.type = 'function';\n this.function = input;\n }\n}\n//# sourceMappingURL=RunnableFunction.mjs.map","export const isAssistantMessage = (message) => {\n return message?.role === 'assistant';\n};\nexport const isFunctionMessage = (message) => {\n return message?.role === 'function';\n};\nexport const isToolMessage = (message) => {\n return message?.role === 'tool';\n};\nexport function isPresent(obj) {\n return obj != null;\n}\n//# sourceMappingURL=chatCompletionUtils.mjs.map","var __classPrivateFieldSet = (this && this.__classPrivateFieldSet) || function (receiver, state, value, kind, f) {\n if (kind === \"m\") throw new TypeError(\"Private method is not writable\");\n if (kind === \"a\" && !f) throw new TypeError(\"Private accessor was defined without a setter\");\n if (typeof state === \"function\" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError(\"Cannot write private member to an object whose class did not declare it\");\n return (kind === \"a\" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;\n};\nvar __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (receiver, state, kind, f) {\n if (kind === \"a\" && !f) throw new TypeError(\"Private accessor was defined without a getter\");\n if (typeof state === \"function\" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError(\"Cannot read private member from an object whose class did not declare it\");\n return kind === \"m\" ? f : kind === \"a\" ? f.call(receiver) : f ? f.value : state.get(receiver);\n};\nvar _EventStream_instances, _EventStream_connectedPromise, _EventStream_resolveConnectedPromise, _EventStream_rejectConnectedPromise, _EventStream_endPromise, _EventStream_resolveEndPromise, _EventStream_rejectEndPromise, _EventStream_listeners, _EventStream_ended, _EventStream_errored, _EventStream_aborted, _EventStream_catchingPromiseCreated, _EventStream_handleError;\nimport { APIUserAbortError, OpenAIError } from \"../error.mjs\";\nexport class EventStream {\n constructor() {\n _EventStream_instances.add(this);\n this.controller = new AbortController();\n _EventStream_connectedPromise.set(this, void 0);\n _EventStream_resolveConnectedPromise.set(this, () => { });\n _EventStream_rejectConnectedPromise.set(this, () => { });\n _EventStream_endPromise.set(this, void 0);\n _EventStream_resolveEndPromise.set(this, () => { });\n _EventStream_rejectEndPromise.set(this, () => { });\n _EventStream_listeners.set(this, {});\n _EventStream_ended.set(this, false);\n _EventStream_errored.set(this, false);\n _EventStream_aborted.set(this, false);\n _EventStream_catchingPromiseCreated.set(this, false);\n __classPrivateFieldSet(this, _EventStream_connectedPromise, new Promise((resolve, reject) => {\n __classPrivateFieldSet(this, _EventStream_resolveConnectedPromise, resolve, \"f\");\n __classPrivateFieldSet(this, _EventStream_rejectConnectedPromise, reject, \"f\");\n }), \"f\");\n __classPrivateFieldSet(this, _EventStream_endPromise, new Promise((resolve, reject) => {\n __classPrivateFieldSet(this, _EventStream_resolveEndPromise, resolve, \"f\");\n __classPrivateFieldSet(this, _EventStream_rejectEndPromise, reject, \"f\");\n }), \"f\");\n // Don't let these promises cause unhandled rejection errors.\n // we will manually cause an unhandled rejection error later\n // if the user hasn't registered any error listener or called\n // any promise-returning method.\n __classPrivateFieldGet(this, _EventStream_connectedPromise, \"f\").catch(() => { });\n __classPrivateFieldGet(this, _EventStream_endPromise, \"f\").catch(() => { });\n }\n _run(executor) {\n // Unfortunately if we call `executor()` immediately we get runtime errors about\n // references to `this` before the `super()` constructor call returns.\n setTimeout(() => {\n executor().then(() => {\n this._emitFinal();\n this._emit('end');\n }, __classPrivateFieldGet(this, _EventStream_instances, \"m\", _EventStream_handleError).bind(this));\n }, 0);\n }\n _connected() {\n if (this.ended)\n return;\n __classPrivateFieldGet(this, _EventStream_resolveConnectedPromise, \"f\").call(this);\n this._emit('connect');\n }\n get ended() {\n return __classPrivateFieldGet(this, _EventStream_ended, \"f\");\n }\n get errored() {\n return __classPrivateFieldGet(this, _EventStream_errored, \"f\");\n }\n get aborted() {\n return __classPrivateFieldGet(this, _EventStream_aborted, \"f\");\n }\n abort() {\n this.controller.abort();\n }\n /**\n * Adds the listener function to the end of the listeners array for the event.\n * No checks are made to see if the listener has already been added. Multiple calls passing\n * the same combination of event and listener will result in the listener being added, and\n * called, multiple times.\n * @returns this ChatCompletionStream, so that calls can be chained\n */\n on(event, listener) {\n const listeners = __classPrivateFieldGet(this, _EventStream_listeners, \"f\")[event] || (__classPrivateFieldGet(this, _EventStream_listeners, \"f\")[event] = []);\n listeners.push({ listener });\n return this;\n }\n /**\n * Removes the specified listener from the listener array for the event.\n * off() will remove, at most, one instance of a listener from the listener array. If any single\n * listener has been added multiple times to the listener array for the specified event, then\n * off() must be called multiple times to remove each instance.\n * @returns this ChatCompletionStream, so that calls can be chained\n */\n off(event, listener) {\n const listeners = __classPrivateFieldGet(this, _EventStream_listeners, \"f\")[event];\n if (!listeners)\n return this;\n const index = listeners.findIndex((l) => l.listener === listener);\n if (index >= 0)\n listeners.splice(index, 1);\n return this;\n }\n /**\n * Adds a one-time listener function for the event. The next time the event is triggered,\n * this listener is removed and then invoked.\n * @returns this ChatCompletionStream, so that calls can be chained\n */\n once(event, listener) {\n const listeners = __classPrivateFieldGet(this, _EventStream_listeners, \"f\")[event] || (__classPrivateFieldGet(this, _EventStream_listeners, \"f\")[event] = []);\n listeners.push({ listener, once: true });\n return this;\n }\n /**\n * This is similar to `.once()`, but returns a Promise that resolves the next time\n * the event is triggered, instead of calling a listener callback.\n * @returns a Promise that resolves the next time given event is triggered,\n * or rejects if an error is emitted. (If you request the 'error' event,\n * returns a promise that resolves with the error).\n *\n * Example:\n *\n * const message = await stream.emitted('message') // rejects if the stream errors\n */\n emitted(event) {\n return new Promise((resolve, reject) => {\n __classPrivateFieldSet(this, _EventStream_catchingPromiseCreated, true, \"f\");\n if (event !== 'error')\n this.once('error', reject);\n this.once(event, resolve);\n });\n }\n async done() {\n __classPrivateFieldSet(this, _EventStream_catchingPromiseCreated, true, \"f\");\n await __classPrivateFieldGet(this, _EventStream_endPromise, \"f\");\n }\n _emit(event, ...args) {\n // make sure we don't emit any events after end\n if (__classPrivateFieldGet(this, _EventStream_ended, \"f\")) {\n return;\n }\n if (event === 'end') {\n __classPrivateFieldSet(this, _EventStream_ended, true, \"f\");\n __classPrivateFieldGet(this, _EventStream_resolveEndPromise, \"f\").call(this);\n }\n const listeners = __classPrivateFieldGet(this, _EventStream_listeners, \"f\")[event];\n if (listeners) {\n __classPrivateFieldGet(this, _EventStream_listeners, \"f\")[event] = listeners.filter((l) => !l.once);\n listeners.forEach(({ listener }) => listener(...args));\n }\n if (event === 'abort') {\n const error = args[0];\n if (!__classPrivateFieldGet(this, _EventStream_catchingPromiseCreated, \"f\") && !listeners?.length) {\n Promise.reject(error);\n }\n __classPrivateFieldGet(this, _EventStream_rejectConnectedPromise, \"f\").call(this, error);\n __classPrivateFieldGet(this, _EventStream_rejectEndPromise, \"f\").call(this, error);\n this._emit('end');\n return;\n }\n if (event === 'error') {\n // NOTE: _emit('error', error) should only be called from #handleError().\n const error = args[0];\n if (!__classPrivateFieldGet(this, _EventStream_catchingPromiseCreated, \"f\") && !listeners?.length) {\n // Trigger an unhandled rejection if the user hasn't registered any error handlers.\n // If you are seeing stack traces here, make sure to handle errors via either:\n // - runner.on('error', () => ...)\n // - await runner.done()\n // - await runner.finalChatCompletion()\n // - etc.\n Promise.reject(error);\n }\n __classPrivateFieldGet(this, _EventStream_rejectConnectedPromise, \"f\").call(this, error);\n __classPrivateFieldGet(this, _EventStream_rejectEndPromise, \"f\").call(this, error);\n this._emit('end');\n }\n }\n _emitFinal() { }\n}\n_EventStream_connectedPromise = new WeakMap(), _EventStream_resolveConnectedPromise = new WeakMap(), _EventStream_rejectConnectedPromise = new WeakMap(), _EventStream_endPromise = new WeakMap(), _EventStream_resolveEndPromise = new WeakMap(), _EventStream_rejectEndPromise = new WeakMap(), _EventStream_listeners = new WeakMap(), _EventStream_ended = new WeakMap(), _EventStream_errored = new WeakMap(), _EventStream_aborted = new WeakMap(), _EventStream_catchingPromiseCreated = new WeakMap(), _EventStream_instances = new WeakSet(), _EventStream_handleError = function _EventStream_handleError(error) {\n __classPrivateFieldSet(this, _EventStream_errored, true, \"f\");\n if (error instanceof Error && error.name === 'AbortError') {\n error = new APIUserAbortError();\n }\n if (error instanceof APIUserAbortError) {\n __classPrivateFieldSet(this, _EventStream_aborted, true, \"f\");\n return this._emit('abort', error);\n }\n if (error instanceof OpenAIError) {\n return this._emit('error', error);\n }\n if (error instanceof Error) {\n const openAIError = new OpenAIError(error.message);\n // @ts-ignore\n openAIError.cause = error;\n return this._emit('error', openAIError);\n }\n return this._emit('error', new OpenAIError(String(error)));\n};\n//# sourceMappingURL=EventStream.mjs.map","import { ContentFilterFinishReasonError, LengthFinishReasonError, OpenAIError } from \"../error.mjs\";\nexport function makeParseableResponseFormat(response_format, parser) {\n const obj = { ...response_format };\n Object.defineProperties(obj, {\n $brand: {\n value: 'auto-parseable-response-format',\n enumerable: false,\n },\n $parseRaw: {\n value: parser,\n enumerable: false,\n },\n });\n return obj;\n}\nexport function isAutoParsableResponseFormat(response_format) {\n return response_format?.['$brand'] === 'auto-parseable-response-format';\n}\nexport function makeParseableTool(tool, { parser, callback, }) {\n const obj = { ...tool };\n Object.defineProperties(obj, {\n $brand: {\n value: 'auto-parseable-tool',\n enumerable: false,\n },\n $parseRaw: {\n value: parser,\n enumerable: false,\n },\n $callback: {\n value: callback,\n enumerable: false,\n },\n });\n return obj;\n}\nexport function isAutoParsableTool(tool) {\n return tool?.['$brand'] === 'auto-parseable-tool';\n}\nexport function maybeParseChatCompletion(completion, params) {\n if (!params || !hasAutoParseableInput(params)) {\n return {\n ...completion,\n choices: completion.choices.map((choice) => ({\n ...choice,\n message: { ...choice.message, parsed: null, tool_calls: choice.message.tool_calls ?? [] },\n })),\n };\n }\n return parseChatCompletion(completion, params);\n}\nexport function parseChatCompletion(completion, params) {\n const choices = completion.choices.map((choice) => {\n if (choice.finish_reason === 'length') {\n throw new LengthFinishReasonError();\n }\n if (choice.finish_reason === 'content_filter') {\n throw new ContentFilterFinishReasonError();\n }\n return {\n ...choice,\n message: {\n ...choice.message,\n tool_calls: choice.message.tool_calls?.map((toolCall) => parseToolCall(params, toolCall)) ?? [],\n parsed: choice.message.content && !choice.message.refusal ?\n parseResponseFormat(params, choice.message.content)\n : null,\n },\n };\n });\n return { ...completion, choices };\n}\nfunction parseResponseFormat(params, content) {\n if (params.response_format?.type !== 'json_schema') {\n return null;\n }\n if (params.response_format?.type === 'json_schema') {\n if ('$parseRaw' in params.response_format) {\n const response_format = params.response_format;\n return response_format.$parseRaw(content);\n }\n return JSON.parse(content);\n }\n return null;\n}\nfunction parseToolCall(params, toolCall) {\n const inputTool = params.tools?.find((inputTool) => inputTool.function?.name === toolCall.function.name);\n return {\n ...toolCall,\n function: {\n ...toolCall.function,\n parsed_arguments: isAutoParsableTool(inputTool) ? inputTool.$parseRaw(toolCall.function.arguments)\n : inputTool?.function.strict ? JSON.parse(toolCall.function.arguments)\n : null,\n },\n };\n}\nexport function shouldParseToolCall(params, toolCall) {\n if (!params) {\n return false;\n }\n const inputTool = params.tools?.find((inputTool) => inputTool.function?.name === toolCall.function.name);\n return isAutoParsableTool(inputTool) || inputTool?.function.strict || false;\n}\nexport function hasAutoParseableInput(params) {\n if (isAutoParsableResponseFormat(params.response_format)) {\n return true;\n }\n return (params.tools?.some((t) => isAutoParsableTool(t) || (t.type === 'function' && t.function.strict === true)) ?? false);\n}\nexport function validateInputTools(tools) {\n for (const tool of tools ?? []) {\n if (tool.type !== 'function') {\n throw new OpenAIError(`Currently only \\`function\\` tool types support auto-parsing; Received \\`${tool.type}\\``);\n }\n if (tool.function.strict !== true) {\n throw new OpenAIError(`The \\`${tool.function.name}\\` tool is not marked with \\`strict: true\\`. Only strict function tools can be auto-parsed`);\n }\n }\n}\n//# sourceMappingURL=parser.mjs.map","var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (receiver, state, kind, f) {\n if (kind === \"a\" && !f) throw new TypeError(\"Private accessor was defined without a getter\");\n if (typeof state === \"function\" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError(\"Cannot read private member from an object whose class did not declare it\");\n return kind === \"m\" ? f : kind === \"a\" ? f.call(receiver) : f ? f.value : state.get(receiver);\n};\nvar _AbstractChatCompletionRunner_instances, _AbstractChatCompletionRunner_getFinalContent, _AbstractChatCompletionRunner_getFinalMessage, _AbstractChatCompletionRunner_getFinalFunctionCall, _AbstractChatCompletionRunner_getFinalFunctionCallResult, _AbstractChatCompletionRunner_calculateTotalUsage, _AbstractChatCompletionRunner_validateParams, _AbstractChatCompletionRunner_stringifyFunctionCallResult;\nimport { OpenAIError } from \"../error.mjs\";\nimport { isRunnableFunctionWithParse, } from \"./RunnableFunction.mjs\";\nimport { isAssistantMessage, isFunctionMessage, isToolMessage } from \"./chatCompletionUtils.mjs\";\nimport { EventStream } from \"./EventStream.mjs\";\nimport { isAutoParsableTool, parseChatCompletion } from \"../lib/parser.mjs\";\nconst DEFAULT_MAX_CHAT_COMPLETIONS = 10;\nexport class AbstractChatCompletionRunner extends EventStream {\n constructor() {\n super(...arguments);\n _AbstractChatCompletionRunner_instances.add(this);\n this._chatCompletions = [];\n this.messages = [];\n }\n _addChatCompletion(chatCompletion) {\n this._chatCompletions.push(chatCompletion);\n this._emit('chatCompletion', chatCompletion);\n const message = chatCompletion.choices[0]?.message;\n if (message)\n this._addMessage(message);\n return chatCompletion;\n }\n _addMessage(message, emit = true) {\n if (!('content' in message))\n message.content = null;\n this.messages.push(message);\n if (emit) {\n this._emit('message', message);\n if ((isFunctionMessage(message) || isToolMessage(message)) && message.content) {\n // Note, this assumes that {role: 'tool', content: …} is always the result of a call of tool of type=function.\n this._emit('functionCallResult', message.content);\n }\n else if (isAssistantMessage(message) && message.function_call) {\n this._emit('functionCall', message.function_call);\n }\n else if (isAssistantMessage(message) && message.tool_calls) {\n for (const tool_call of message.tool_calls) {\n if (tool_call.type === 'function') {\n this._emit('functionCall', tool_call.function);\n }\n }\n }\n }\n }\n /**\n * @returns a promise that resolves with the final ChatCompletion, or rejects\n * if an error occurred or the stream ended prematurely without producing a ChatCompletion.\n */\n async finalChatCompletion() {\n await this.done();\n const completion = this._chatCompletions[this._chatCompletions.length - 1];\n if (!completion)\n throw new OpenAIError('stream ended without producing a ChatCompletion');\n return completion;\n }\n /**\n * @returns a promise that resolves with the content of the final ChatCompletionMessage, or rejects\n * if an error occurred or the stream ended prematurely without producing a ChatCompletionMessage.\n */\n async finalContent() {\n await this.done();\n return __classPrivateFieldGet(this, _AbstractChatCompletionRunner_instances, \"m\", _AbstractChatCompletionRunner_getFinalContent).call(this);\n }\n /**\n * @returns a promise that resolves with the the final assistant ChatCompletionMessage response,\n * or rejects if an error occurred or the stream ended prematurely without producing a ChatCompletionMessage.\n */\n async finalMessage() {\n await this.done();\n return __classPrivateFieldGet(this, _AbstractChatCompletionRunner_instances, \"m\", _AbstractChatCompletionRunner_getFinalMessage).call(this);\n }\n /**\n * @returns a promise that resolves with the content of the final FunctionCall, or rejects\n * if an error occurred or the stream ended prematurely without producing a ChatCompletionMessage.\n */\n async finalFunctionCall() {\n await this.done();\n return __classPrivateFieldGet(this, _AbstractChatCompletionRunner_instances, \"m\", _AbstractChatCompletionRunner_getFinalFunctionCall).call(this);\n }\n async finalFunctionCallResult() {\n await this.done();\n return __classPrivateFieldGet(this, _AbstractChatCompletionRunner_instances, \"m\", _AbstractChatCompletionRunner_getFinalFunctionCallResult).call(this);\n }\n async totalUsage() {\n await this.done();\n return __classPrivateFieldGet(this, _AbstractChatCompletionRunner_instances, \"m\", _AbstractChatCompletionRunner_calculateTotalUsage).call(this);\n }\n allChatCompletions() {\n return [...this._chatCompletions];\n }\n _emitFinal() {\n const completion = this._chatCompletions[this._chatCompletions.length - 1];\n if (completion)\n this._emit('finalChatCompletion', completion);\n const finalMessage = __classPrivateFieldGet(this, _AbstractChatCompletionRunner_instances, \"m\", _AbstractChatCompletionRunner_getFinalMessage).call(this);\n if (finalMessage)\n this._emit('finalMessage', finalMessage);\n const finalContent = __classPrivateFieldGet(this, _AbstractChatCompletionRunner_instances, \"m\", _AbstractChatCompletionRunner_getFinalContent).call(this);\n if (finalContent)\n this._emit('finalContent', finalContent);\n const finalFunctionCall = __classPrivateFieldGet(this, _AbstractChatCompletionRunner_instances, \"m\", _AbstractChatCompletionRunner_getFinalFunctionCall).call(this);\n if (finalFunctionCall)\n this._emit('finalFunctionCall', finalFunctionCall);\n const finalFunctionCallResult = __classPrivateFieldGet(this, _AbstractChatCompletionRunner_instances, \"m\", _AbstractChatCompletionRunner_getFinalFunctionCallResult).call(this);\n if (finalFunctionCallResult != null)\n this._emit('finalFunctionCallResult', finalFunctionCallResult);\n if (this._chatCompletions.some((c) => c.usage)) {\n this._emit('totalUsage', __classPrivateFieldGet(this, _AbstractChatCompletionRunner_instances, \"m\", _AbstractChatCompletionRunner_calculateTotalUsage).call(this));\n }\n }\n async _createChatCompletion(client, params, options) {\n const signal = options?.signal;\n if (signal) {\n if (signal.aborted)\n this.controller.abort();\n signal.addEventListener('abort', () => this.controller.abort());\n }\n __classPrivateFieldGet(this, _AbstractChatCompletionRunner_instances, \"m\", _AbstractChatCompletionRunner_validateParams).call(this, params);\n const chatCompletion = await client.chat.completions.create({ ...params, stream: false }, { ...options, signal: this.controller.signal });\n this._connected();\n return this._addChatCompletion(parseChatCompletion(chatCompletion, params));\n }\n async _runChatCompletion(client, params, options) {\n for (const message of params.messages) {\n this._addMessage(message, false);\n }\n return await this._createChatCompletion(client, params, options);\n }\n async _runFunctions(client, params, options) {\n const role = 'function';\n const { function_call = 'auto', stream, ...restParams } = params;\n const singleFunctionToCall = typeof function_call !== 'string' && function_call?.name;\n const { maxChatCompletions = DEFAULT_MAX_CHAT_COMPLETIONS } = options || {};\n const functionsByName = {};\n for (const f of params.functions) {\n functionsByName[f.name || f.function.name] = f;\n }\n const functions = params.functions.map((f) => ({\n name: f.name || f.function.name,\n parameters: f.parameters,\n description: f.description,\n }));\n for (const message of params.messages) {\n this._addMessage(message, false);\n }\n for (let i = 0; i < maxChatCompletions; ++i) {\n const chatCompletion = await this._createChatCompletion(client, {\n ...restParams,\n function_call,\n functions,\n messages: [...this.messages],\n }, options);\n const message = chatCompletion.choices[0]?.message;\n if (!message) {\n throw new OpenAIError(`missing message in ChatCompletion response`);\n }\n if (!message.function_call)\n return;\n const { name, arguments: args } = message.function_call;\n const fn = functionsByName[name];\n if (!fn) {\n const content = `Invalid function_call: ${JSON.stringify(name)}. Available options are: ${functions\n .map((f) => JSON.stringify(f.name))\n .join(', ')}. Please try again`;\n this._addMessage({ role, name, content });\n continue;\n }\n else if (singleFunctionToCall && singleFunctionToCall !== name) {\n const content = `Invalid function_call: ${JSON.stringify(name)}. ${JSON.stringify(singleFunctionToCall)} requested. Please try again`;\n this._addMessage({ role, name, content });\n continue;\n }\n let parsed;\n try {\n parsed = isRunnableFunctionWithParse(fn) ? await fn.parse(args) : args;\n }\n catch (error) {\n this._addMessage({\n role,\n name,\n content: error instanceof Error ? error.message : String(error),\n });\n continue;\n }\n // @ts-expect-error it can't rule out `never` type.\n const rawContent = await fn.function(parsed, this);\n const content = __classPrivateFieldGet(this, _AbstractChatCompletionRunner_instances, \"m\", _AbstractChatCompletionRunner_stringifyFunctionCallResult).call(this, rawContent);\n this._addMessage({ role, name, content });\n if (singleFunctionToCall)\n return;\n }\n }\n async _runTools(client, params, options) {\n const role = 'tool';\n const { tool_choice = 'auto', stream, ...restParams } = params;\n const singleFunctionToCall = typeof tool_choice !== 'string' && tool_choice?.function?.name;\n const { maxChatCompletions = DEFAULT_MAX_CHAT_COMPLETIONS } = options || {};\n // TODO(someday): clean this logic up\n const inputTools = params.tools.map((tool) => {\n if (isAutoParsableTool(tool)) {\n if (!tool.$callback) {\n throw new OpenAIError('Tool given to `.runTools()` that does not have an associated function');\n }\n return {\n type: 'function',\n function: {\n function: tool.$callback,\n name: tool.function.name,\n description: tool.function.description || '',\n parameters: tool.function.parameters,\n parse: tool.$parseRaw,\n strict: true,\n },\n };\n }\n return tool;\n });\n const functionsByName = {};\n for (const f of inputTools) {\n if (f.type === 'function') {\n functionsByName[f.function.name || f.function.function.name] = f.function;\n }\n }\n const tools = 'tools' in params ?\n inputTools.map((t) => t.type === 'function' ?\n {\n type: 'function',\n function: {\n name: t.function.name || t.function.function.name,\n parameters: t.function.parameters,\n description: t.function.description,\n strict: t.function.strict,\n },\n }\n : t)\n : undefined;\n for (const message of params.messages) {\n this._addMessage(message, false);\n }\n for (let i = 0; i < maxChatCompletions; ++i) {\n const chatCompletion = await this._createChatCompletion(client, {\n ...restParams,\n tool_choice,\n tools,\n messages: [...this.messages],\n }, options);\n const message = chatCompletion.choices[0]?.message;\n if (!message) {\n throw new OpenAIError(`missing message in ChatCompletion response`);\n }\n if (!message.tool_calls?.length) {\n return;\n }\n for (const tool_call of message.tool_calls) {\n if (tool_call.type !== 'function')\n continue;\n const tool_call_id = tool_call.id;\n const { name, arguments: args } = tool_call.function;\n const fn = functionsByName[name];\n if (!fn) {\n const content = `Invalid tool_call: ${JSON.stringify(name)}. Available options are: ${Object.keys(functionsByName)\n .map((name) => JSON.stringify(name))\n .join(', ')}. Please try again`;\n this._addMessage({ role, tool_call_id, content });\n continue;\n }\n else if (singleFunctionToCall && singleFunctionToCall !== name) {\n const content = `Invalid tool_call: ${JSON.stringify(name)}. ${JSON.stringify(singleFunctionToCall)} requested. Please try again`;\n this._addMessage({ role, tool_call_id, content });\n continue;\n }\n let parsed;\n try {\n parsed = isRunnableFunctionWithParse(fn) ? await fn.parse(args) : args;\n }\n catch (error) {\n const content = error instanceof Error ? error.message : String(error);\n this._addMessage({ role, tool_call_id, content });\n continue;\n }\n // @ts-expect-error it can't rule out `never` type.\n const rawContent = await fn.function(parsed, this);\n const content = __classPrivateFieldGet(this, _AbstractChatCompletionRunner_instances, \"m\", _AbstractChatCompletionRunner_stringifyFunctionCallResult).call(this, rawContent);\n this._addMessage({ role, tool_call_id, content });\n if (singleFunctionToCall) {\n return;\n }\n }\n }\n return;\n }\n}\n_AbstractChatCompletionRunner_instances = new WeakSet(), _AbstractChatCompletionRunner_getFinalContent = function _AbstractChatCompletionRunner_getFinalContent() {\n return __classPrivateFieldGet(this, _AbstractChatCompletionRunner_instances, \"m\", _AbstractChatCompletionRunner_getFinalMessage).call(this).content ?? null;\n}, _AbstractChatCompletionRunner_getFinalMessage = function _AbstractChatCompletionRunner_getFinalMessage() {\n let i = this.messages.length;\n while (i-- > 0) {\n const message = this.messages[i];\n if (isAssistantMessage(message)) {\n const { function_call, ...rest } = message;\n // TODO: support audio here\n const ret = {\n ...rest,\n content: message.content ?? null,\n refusal: message.refusal ?? null,\n };\n if (function_call) {\n ret.function_call = function_call;\n }\n return ret;\n }\n }\n throw new OpenAIError('stream ended without producing a ChatCompletionMessage with role=assistant');\n}, _AbstractChatCompletionRunner_getFinalFunctionCall = function _AbstractChatCompletionRunner_getFinalFunctionCall() {\n for (let i = this.messages.length - 1; i >= 0; i--) {\n const message = this.messages[i];\n if (isAssistantMessage(message) && message?.function_call) {\n return message.function_call;\n }\n if (isAssistantMessage(message) && message?.tool_calls?.length) {\n return message.tool_calls.at(-1)?.function;\n }\n }\n return;\n}, _AbstractChatCompletionRunner_getFinalFunctionCallResult = function _AbstractChatCompletionRunner_getFinalFunctionCallResult() {\n for (let i = this.messages.length - 1; i >= 0; i--) {\n const message = this.messages[i];\n if (isFunctionMessage(message) && message.content != null) {\n return message.content;\n }\n if (isToolMessage(message) &&\n message.content != null &&\n typeof message.content === 'string' &&\n this.messages.some((x) => x.role === 'assistant' &&\n x.tool_calls?.some((y) => y.type === 'function' && y.id === message.tool_call_id))) {\n return message.content;\n }\n }\n return;\n}, _AbstractChatCompletionRunner_calculateTotalUsage = function _AbstractChatCompletionRunner_calculateTotalUsage() {\n const total = {\n completion_tokens: 0,\n prompt_tokens: 0,\n total_tokens: 0,\n };\n for (const { usage } of this._chatCompletions) {\n if (usage) {\n total.completion_tokens += usage.completion_tokens;\n total.prompt_tokens += usage.prompt_tokens;\n total.total_tokens += usage.total_tokens;\n }\n }\n return total;\n}, _AbstractChatCompletionRunner_validateParams = function _AbstractChatCompletionRunner_validateParams(params) {\n if (params.n != null && params.n > 1) {\n throw new OpenAIError('ChatCompletion convenience helpers only support n=1 at this time. To use n>1, please use chat.completions.create() directly.');\n }\n}, _AbstractChatCompletionRunner_stringifyFunctionCallResult = function _AbstractChatCompletionRunner_stringifyFunctionCallResult(rawContent) {\n return (typeof rawContent === 'string' ? rawContent\n : rawContent === undefined ? 'undefined'\n : JSON.stringify(rawContent));\n};\n//# sourceMappingURL=AbstractChatCompletionRunner.mjs.map","import { AbstractChatCompletionRunner, } from \"./AbstractChatCompletionRunner.mjs\";\nimport { isAssistantMessage } from \"./chatCompletionUtils.mjs\";\nexport class ChatCompletionRunner extends AbstractChatCompletionRunner {\n /** @deprecated - please use `runTools` instead. */\n static runFunctions(client, params, options) {\n const runner = new ChatCompletionRunner();\n const opts = {\n ...options,\n headers: { ...options?.headers, 'X-Stainless-Helper-Method': 'runFunctions' },\n };\n runner._run(() => runner._runFunctions(client, params, opts));\n return runner;\n }\n static runTools(client, params, options) {\n const runner = new ChatCompletionRunner();\n const opts = {\n ...options,\n headers: { ...options?.headers, 'X-Stainless-Helper-Method': 'runTools' },\n };\n runner._run(() => runner._runTools(client, params, opts));\n return runner;\n }\n _addMessage(message, emit = true) {\n super._addMessage(message, emit);\n if (isAssistantMessage(message) && message.content) {\n this._emit('content', message.content);\n }\n }\n}\n//# sourceMappingURL=ChatCompletionRunner.mjs.map","const STR = 0b000000001;\nconst NUM = 0b000000010;\nconst ARR = 0b000000100;\nconst OBJ = 0b000001000;\nconst NULL = 0b000010000;\nconst BOOL = 0b000100000;\nconst NAN = 0b001000000;\nconst INFINITY = 0b010000000;\nconst MINUS_INFINITY = 0b100000000;\nconst INF = INFINITY | MINUS_INFINITY;\nconst SPECIAL = NULL | BOOL | INF | NAN;\nconst ATOM = STR | NUM | SPECIAL;\nconst COLLECTION = ARR | OBJ;\nconst ALL = ATOM | COLLECTION;\nconst Allow = {\n STR,\n NUM,\n ARR,\n OBJ,\n NULL,\n BOOL,\n NAN,\n INFINITY,\n MINUS_INFINITY,\n INF,\n SPECIAL,\n ATOM,\n COLLECTION,\n ALL,\n};\n// The JSON string segment was unable to be parsed completely\nclass PartialJSON extends Error {\n}\nclass MalformedJSON extends Error {\n}\n/**\n * Parse incomplete JSON\n * @param {string} jsonString Partial JSON to be parsed\n * @param {number} allowPartial Specify what types are allowed to be partial, see {@link Allow} for details\n * @returns The parsed JSON\n * @throws {PartialJSON} If the JSON is incomplete (related to the `allow` parameter)\n * @throws {MalformedJSON} If the JSON is malformed\n */\nfunction parseJSON(jsonString, allowPartial = Allow.ALL) {\n if (typeof jsonString !== 'string') {\n throw new TypeError(`expecting str, got ${typeof jsonString}`);\n }\n if (!jsonString.trim()) {\n throw new Error(`${jsonString} is empty`);\n }\n return _parseJSON(jsonString.trim(), allowPartial);\n}\nconst _parseJSON = (jsonString, allow) => {\n const length = jsonString.length;\n let index = 0;\n const markPartialJSON = (msg) => {\n throw new PartialJSON(`${msg} at position ${index}`);\n };\n const throwMalformedError = (msg) => {\n throw new MalformedJSON(`${msg} at position ${index}`);\n };\n const parseAny = () => {\n skipBlank();\n if (index >= length)\n markPartialJSON('Unexpected end of input');\n if (jsonString[index] === '\"')\n return parseStr();\n if (jsonString[index] === '{')\n return parseObj();\n if (jsonString[index] === '[')\n return parseArr();\n if (jsonString.substring(index, index + 4) === 'null' ||\n (Allow.NULL & allow && length - index < 4 && 'null'.startsWith(jsonString.substring(index)))) {\n index += 4;\n return null;\n }\n if (jsonString.substring(index, index + 4) === 'true' ||\n (Allow.BOOL & allow && length - index < 4 && 'true'.startsWith(jsonString.substring(index)))) {\n index += 4;\n return true;\n }\n if (jsonString.substring(index, index + 5) === 'false' ||\n (Allow.BOOL & allow && length - index < 5 && 'false'.startsWith(jsonString.substring(index)))) {\n index += 5;\n return false;\n }\n if (jsonString.substring(index, index + 8) === 'Infinity' ||\n (Allow.INFINITY & allow && length - index < 8 && 'Infinity'.startsWith(jsonString.substring(index)))) {\n index += 8;\n return Infinity;\n }\n if (jsonString.substring(index, index + 9) === '-Infinity' ||\n (Allow.MINUS_INFINITY & allow &&\n 1 < length - index &&\n length - index < 9 &&\n '-Infinity'.startsWith(jsonString.substring(index)))) {\n index += 9;\n return -Infinity;\n }\n if (jsonString.substring(index, index + 3) === 'NaN' ||\n (Allow.NAN & allow && length - index < 3 && 'NaN'.startsWith(jsonString.substring(index)))) {\n index += 3;\n return NaN;\n }\n return parseNum();\n };\n const parseStr = () => {\n const start = index;\n let escape = false;\n index++; // skip initial quote\n while (index < length && (jsonString[index] !== '\"' || (escape && jsonString[index - 1] === '\\\\'))) {\n escape = jsonString[index] === '\\\\' ? !escape : false;\n index++;\n }\n if (jsonString.charAt(index) == '\"') {\n try {\n return JSON.parse(jsonString.substring(start, ++index - Number(escape)));\n }\n catch (e) {\n throwMalformedError(String(e));\n }\n }\n else if (Allow.STR & allow) {\n try {\n return JSON.parse(jsonString.substring(start, index - Number(escape)) + '\"');\n }\n catch (e) {\n // SyntaxError: Invalid escape sequence\n return JSON.parse(jsonString.substring(start, jsonString.lastIndexOf('\\\\')) + '\"');\n }\n }\n markPartialJSON('Unterminated string literal');\n };\n const parseObj = () => {\n index++; // skip initial brace\n skipBlank();\n const obj = {};\n try {\n while (jsonString[index] !== '}') {\n skipBlank();\n if (index >= length && Allow.OBJ & allow)\n return obj;\n const key = parseStr();\n skipBlank();\n index++; // skip colon\n try {\n const value = parseAny();\n Object.defineProperty(obj, key, { value, writable: true, enumerable: true, configurable: true });\n }\n catch (e) {\n if (Allow.OBJ & allow)\n return obj;\n else\n throw e;\n }\n skipBlank();\n if (jsonString[index] === ',')\n index++; // skip comma\n }\n }\n catch (e) {\n if (Allow.OBJ & allow)\n return obj;\n else\n markPartialJSON(\"Expected '}' at end of object\");\n }\n index++; // skip final brace\n return obj;\n };\n const parseArr = () => {\n index++; // skip initial bracket\n const arr = [];\n try {\n while (jsonString[index] !== ']') {\n arr.push(parseAny());\n skipBlank();\n if (jsonString[index] === ',') {\n index++; // skip comma\n }\n }\n }\n catch (e) {\n if (Allow.ARR & allow) {\n return arr;\n }\n markPartialJSON(\"Expected ']' at end of array\");\n }\n index++; // skip final bracket\n return arr;\n };\n const parseNum = () => {\n if (index === 0) {\n if (jsonString === '-' && Allow.NUM & allow)\n markPartialJSON(\"Not sure what '-' is\");\n try {\n return JSON.parse(jsonString);\n }\n catch (e) {\n if (Allow.NUM & allow) {\n try {\n if ('.' === jsonString[jsonString.length - 1])\n return JSON.parse(jsonString.substring(0, jsonString.lastIndexOf('.')));\n return JSON.parse(jsonString.substring(0, jsonString.lastIndexOf('e')));\n }\n catch (e) { }\n }\n throwMalformedError(String(e));\n }\n }\n const start = index;\n if (jsonString[index] === '-')\n index++;\n while (jsonString[index] && !',]}'.includes(jsonString[index]))\n index++;\n if (index == length && !(Allow.NUM & allow))\n markPartialJSON('Unterminated number literal');\n try {\n return JSON.parse(jsonString.substring(start, index));\n }\n catch (e) {\n if (jsonString.substring(start, index) === '-' && Allow.NUM & allow)\n markPartialJSON(\"Not sure what '-' is\");\n try {\n return JSON.parse(jsonString.substring(start, jsonString.lastIndexOf('e')));\n }\n catch (e) {\n throwMalformedError(String(e));\n }\n }\n };\n const skipBlank = () => {\n while (index < length && ' \\n\\r\\t'.includes(jsonString[index])) {\n index++;\n }\n };\n return parseAny();\n};\n// using this function with malformed JSON is undefined behavior\nconst partialParse = (input) => parseJSON(input, Allow.ALL ^ Allow.NUM);\nexport { partialParse, PartialJSON, MalformedJSON };\n//# sourceMappingURL=parser.mjs.map","var __classPrivateFieldSet = (this && this.__classPrivateFieldSet) || function (receiver, state, value, kind, f) {\n if (kind === \"m\") throw new TypeError(\"Private method is not writable\");\n if (kind === \"a\" && !f) throw new TypeError(\"Private accessor was defined without a setter\");\n if (typeof state === \"function\" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError(\"Cannot write private member to an object whose class did not declare it\");\n return (kind === \"a\" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;\n};\nvar __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (receiver, state, kind, f) {\n if (kind === \"a\" && !f) throw new TypeError(\"Private accessor was defined without a getter\");\n if (typeof state === \"function\" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError(\"Cannot read private member from an object whose class did not declare it\");\n return kind === \"m\" ? f : kind === \"a\" ? f.call(receiver) : f ? f.value : state.get(receiver);\n};\nvar _ChatCompletionStream_instances, _ChatCompletionStream_params, _ChatCompletionStream_choiceEventStates, _ChatCompletionStream_currentChatCompletionSnapshot, _ChatCompletionStream_beginRequest, _ChatCompletionStream_getChoiceEventState, _ChatCompletionStream_addChunk, _ChatCompletionStream_emitToolCallDoneEvent, _ChatCompletionStream_emitContentDoneEvents, _ChatCompletionStream_endRequest, _ChatCompletionStream_getAutoParseableResponseFormat, _ChatCompletionStream_accumulateChatCompletion;\nimport { OpenAIError, APIUserAbortError, LengthFinishReasonError, ContentFilterFinishReasonError, } from \"../error.mjs\";\nimport { AbstractChatCompletionRunner, } from \"./AbstractChatCompletionRunner.mjs\";\nimport { Stream } from \"../streaming.mjs\";\nimport { hasAutoParseableInput, isAutoParsableResponseFormat, isAutoParsableTool, maybeParseChatCompletion, shouldParseToolCall, } from \"../lib/parser.mjs\";\nimport { partialParse } from \"../_vendor/partial-json-parser/parser.mjs\";\nexport class ChatCompletionStream extends AbstractChatCompletionRunner {\n constructor(params) {\n super();\n _ChatCompletionStream_instances.add(this);\n _ChatCompletionStream_params.set(this, void 0);\n _ChatCompletionStream_choiceEventStates.set(this, void 0);\n _ChatCompletionStream_currentChatCompletionSnapshot.set(this, void 0);\n __classPrivateFieldSet(this, _ChatCompletionStream_params, params, \"f\");\n __classPrivateFieldSet(this, _ChatCompletionStream_choiceEventStates, [], \"f\");\n }\n get currentChatCompletionSnapshot() {\n return __classPrivateFieldGet(this, _ChatCompletionStream_currentChatCompletionSnapshot, \"f\");\n }\n /**\n * Intended for use on the frontend, consuming a stream produced with\n * `.toReadableStream()` on the backend.\n *\n * Note that messages sent to the model do not appear in `.on('message')`\n * in this context.\n */\n static fromReadableStream(stream) {\n const runner = new ChatCompletionStream(null);\n runner._run(() => runner._fromReadableStream(stream));\n return runner;\n }\n static createChatCompletion(client, params, options) {\n const runner = new ChatCompletionStream(params);\n runner._run(() => runner._runChatCompletion(client, { ...params, stream: true }, { ...options, headers: { ...options?.headers, 'X-Stainless-Helper-Method': 'stream' } }));\n return runner;\n }\n async _createChatCompletion(client, params, options) {\n super._createChatCompletion;\n const signal = options?.signal;\n if (signal) {\n if (signal.aborted)\n this.controller.abort();\n signal.addEventListener('abort', () => this.controller.abort());\n }\n __classPrivateFieldGet(this, _ChatCompletionStream_instances, \"m\", _ChatCompletionStream_beginRequest).call(this);\n const stream = await client.chat.completions.create({ ...params, stream: true }, { ...options, signal: this.controller.signal });\n this._connected();\n for await (const chunk of stream) {\n __classPrivateFieldGet(this, _ChatCompletionStream_instances, \"m\", _ChatCompletionStream_addChunk).call(this, chunk);\n }\n if (stream.controller.signal?.aborted) {\n throw new APIUserAbortError();\n }\n return this._addChatCompletion(__classPrivateFieldGet(this, _ChatCompletionStream_instances, \"m\", _ChatCompletionStream_endRequest).call(this));\n }\n async _fromReadableStream(readableStream, options) {\n const signal = options?.signal;\n if (signal) {\n if (signal.aborted)\n this.controller.abort();\n signal.addEventListener('abort', () => this.controller.abort());\n }\n __classPrivateFieldGet(this, _ChatCompletionStream_instances, \"m\", _ChatCompletionStream_beginRequest).call(this);\n this._connected();\n const stream = Stream.fromReadableStream(readableStream, this.controller);\n let chatId;\n for await (const chunk of stream) {\n if (chatId && chatId !== chunk.id) {\n // A new request has been made.\n this._addChatCompletion(__classPrivateFieldGet(this, _ChatCompletionStream_instances, \"m\", _ChatCompletionStream_endRequest).call(this));\n }\n __classPrivateFieldGet(this, _ChatCompletionStream_instances, \"m\", _ChatCompletionStream_addChunk).call(this, chunk);\n chatId = chunk.id;\n }\n if (stream.controller.signal?.aborted) {\n throw new APIUserAbortError();\n }\n return this._addChatCompletion(__classPrivateFieldGet(this, _ChatCompletionStream_instances, \"m\", _ChatCompletionStream_endRequest).call(this));\n }\n [(_ChatCompletionStream_params = new WeakMap(), _ChatCompletionStream_choiceEventStates = new WeakMap(), _ChatCompletionStream_currentChatCompletionSnapshot = new WeakMap(), _ChatCompletionStream_instances = new WeakSet(), _ChatCompletionStream_beginRequest = function _ChatCompletionStream_beginRequest() {\n if (this.ended)\n return;\n __classPrivateFieldSet(this, _ChatCompletionStream_currentChatCompletionSnapshot, undefined, \"f\");\n }, _ChatCompletionStream_getChoiceEventState = function _ChatCompletionStream_getChoiceEventState(choice) {\n let state = __classPrivateFieldGet(this, _ChatCompletionStream_choiceEventStates, \"f\")[choice.index];\n if (state) {\n return state;\n }\n state = {\n content_done: false,\n refusal_done: false,\n logprobs_content_done: false,\n logprobs_refusal_done: false,\n done_tool_calls: new Set(),\n current_tool_call_index: null,\n };\n __classPrivateFieldGet(this, _ChatCompletionStream_choiceEventStates, \"f\")[choice.index] = state;\n return state;\n }, _ChatCompletionStream_addChunk = function _ChatCompletionStream_addChunk(chunk) {\n if (this.ended)\n return;\n const completion = __classPrivateFieldGet(this, _ChatCompletionStream_instances, \"m\", _ChatCompletionStream_accumulateChatCompletion).call(this, chunk);\n this._emit('chunk', chunk, completion);\n for (const choice of chunk.choices) {\n const choiceSnapshot = completion.choices[choice.index];\n if (choice.delta.content != null &&\n choiceSnapshot.message?.role === 'assistant' &&\n choiceSnapshot.message?.content) {\n this._emit('content', choice.delta.content, choiceSnapshot.message.content);\n this._emit('content.delta', {\n delta: choice.delta.content,\n snapshot: choiceSnapshot.message.content,\n parsed: choiceSnapshot.message.parsed,\n });\n }\n if (choice.delta.refusal != null &&\n choiceSnapshot.message?.role === 'assistant' &&\n choiceSnapshot.message?.refusal) {\n this._emit('refusal.delta', {\n delta: choice.delta.refusal,\n snapshot: choiceSnapshot.message.refusal,\n });\n }\n if (choice.logprobs?.content != null && choiceSnapshot.message?.role === 'assistant') {\n this._emit('logprobs.content.delta', {\n content: choice.logprobs?.content,\n snapshot: choiceSnapshot.logprobs?.content ?? [],\n });\n }\n if (choice.logprobs?.refusal != null && choiceSnapshot.message?.role === 'assistant') {\n this._emit('logprobs.refusal.delta', {\n refusal: choice.logprobs?.refusal,\n snapshot: choiceSnapshot.logprobs?.refusal ?? [],\n });\n }\n const state = __classPrivateFieldGet(this, _ChatCompletionStream_instances, \"m\", _ChatCompletionStream_getChoiceEventState).call(this, choiceSnapshot);\n if (choiceSnapshot.finish_reason) {\n __classPrivateFieldGet(this, _ChatCompletionStream_instances, \"m\", _ChatCompletionStream_emitContentDoneEvents).call(this, choiceSnapshot);\n if (state.current_tool_call_index != null) {\n __classPrivateFieldGet(this, _ChatCompletionStream_instances, \"m\", _ChatCompletionStream_emitToolCallDoneEvent).call(this, choiceSnapshot, state.current_tool_call_index);\n }\n }\n for (const toolCall of choice.delta.tool_calls ?? []) {\n if (state.current_tool_call_index !== toolCall.index) {\n __classPrivateFieldGet(this, _ChatCompletionStream_instances, \"m\", _ChatCompletionStream_emitContentDoneEvents).call(this, choiceSnapshot);\n // new tool call started, the previous one is done\n if (state.current_tool_call_index != null) {\n __classPrivateFieldGet(this, _ChatCompletionStream_instances, \"m\", _ChatCompletionStream_emitToolCallDoneEvent).call(this, choiceSnapshot, state.current_tool_call_index);\n }\n }\n state.current_tool_call_index = toolCall.index;\n }\n for (const toolCallDelta of choice.delta.tool_calls ?? []) {\n const toolCallSnapshot = choiceSnapshot.message.tool_calls?.[toolCallDelta.index];\n if (!toolCallSnapshot?.type) {\n continue;\n }\n if (toolCallSnapshot?.type === 'function') {\n this._emit('tool_calls.function.arguments.delta', {\n name: toolCallSnapshot.function?.name,\n index: toolCallDelta.index,\n arguments: toolCallSnapshot.function.arguments,\n parsed_arguments: toolCallSnapshot.function.parsed_arguments,\n arguments_delta: toolCallDelta.function?.arguments ?? '',\n });\n }\n else {\n assertNever(toolCallSnapshot?.type);\n }\n }\n }\n }, _ChatCompletionStream_emitToolCallDoneEvent = function _ChatCompletionStream_emitToolCallDoneEvent(choiceSnapshot, toolCallIndex) {\n const state = __classPrivateFieldGet(this, _ChatCompletionStream_instances, \"m\", _ChatCompletionStream_getChoiceEventState).call(this, choiceSnapshot);\n if (state.done_tool_calls.has(toolCallIndex)) {\n // we've already fired the done event\n return;\n }\n const toolCallSnapshot = choiceSnapshot.message.tool_calls?.[toolCallIndex];\n if (!toolCallSnapshot) {\n throw new Error('no tool call snapshot');\n }\n if (!toolCallSnapshot.type) {\n throw new Error('tool call snapshot missing `type`');\n }\n if (toolCallSnapshot.type === 'function') {\n const inputTool = __classPrivateFieldGet(this, _ChatCompletionStream_params, \"f\")?.tools?.find((tool) => tool.type === 'function' && tool.function.name === toolCallSnapshot.function.name);\n this._emit('tool_calls.function.arguments.done', {\n name: toolCallSnapshot.function.name,\n index: toolCallIndex,\n arguments: toolCallSnapshot.function.arguments,\n parsed_arguments: isAutoParsableTool(inputTool) ? inputTool.$parseRaw(toolCallSnapshot.function.arguments)\n : inputTool?.function.strict ? JSON.parse(toolCallSnapshot.function.arguments)\n : null,\n });\n }\n else {\n assertNever(toolCallSnapshot.type);\n }\n }, _ChatCompletionStream_emitContentDoneEvents = function _ChatCompletionStream_emitContentDoneEvents(choiceSnapshot) {\n const state = __classPrivateFieldGet(this, _ChatCompletionStream_instances, \"m\", _ChatCompletionStream_getChoiceEventState).call(this, choiceSnapshot);\n if (choiceSnapshot.message.content && !state.content_done) {\n state.content_done = true;\n const responseFormat = __classPrivateFieldGet(this, _ChatCompletionStream_instances, \"m\", _ChatCompletionStream_getAutoParseableResponseFormat).call(this);\n this._emit('content.done', {\n content: choiceSnapshot.message.content,\n parsed: responseFormat ? responseFormat.$parseRaw(choiceSnapshot.message.content) : null,\n });\n }\n if (choiceSnapshot.message.refusal && !state.refusal_done) {\n state.refusal_done = true;\n this._emit('refusal.done', { refusal: choiceSnapshot.message.refusal });\n }\n if (choiceSnapshot.logprobs?.content && !state.logprobs_content_done) {\n state.logprobs_content_done = true;\n this._emit('logprobs.content.done', { content: choiceSnapshot.logprobs.content });\n }\n if (choiceSnapshot.logprobs?.refusal && !state.logprobs_refusal_done) {\n state.logprobs_refusal_done = true;\n this._emit('logprobs.refusal.done', { refusal: choiceSnapshot.logprobs.refusal });\n }\n }, _ChatCompletionStream_endRequest = function _ChatCompletionStream_endRequest() {\n if (this.ended) {\n throw new OpenAIError(`stream has ended, this shouldn't happen`);\n }\n const snapshot = __classPrivateFieldGet(this, _ChatCompletionStream_currentChatCompletionSnapshot, \"f\");\n if (!snapshot) {\n throw new OpenAIError(`request ended without sending any chunks`);\n }\n __classPrivateFieldSet(this, _ChatCompletionStream_currentChatCompletionSnapshot, undefined, \"f\");\n __classPrivateFieldSet(this, _ChatCompletionStream_choiceEventStates, [], \"f\");\n return finalizeChatCompletion(snapshot, __classPrivateFieldGet(this, _ChatCompletionStream_params, \"f\"));\n }, _ChatCompletionStream_getAutoParseableResponseFormat = function _ChatCompletionStream_getAutoParseableResponseFormat() {\n const responseFormat = __classPrivateFieldGet(this, _ChatCompletionStream_params, \"f\")?.response_format;\n if (isAutoParsableResponseFormat(responseFormat)) {\n return responseFormat;\n }\n return null;\n }, _ChatCompletionStream_accumulateChatCompletion = function _ChatCompletionStream_accumulateChatCompletion(chunk) {\n var _a, _b, _c, _d;\n let snapshot = __classPrivateFieldGet(this, _ChatCompletionStream_currentChatCompletionSnapshot, \"f\");\n const { choices, ...rest } = chunk;\n if (!snapshot) {\n snapshot = __classPrivateFieldSet(this, _ChatCompletionStream_currentChatCompletionSnapshot, {\n ...rest,\n choices: [],\n }, \"f\");\n }\n else {\n Object.assign(snapshot, rest);\n }\n for (const { delta, finish_reason, index, logprobs = null, ...other } of chunk.choices) {\n let choice = snapshot.choices[index];\n if (!choice) {\n choice = snapshot.choices[index] = { finish_reason, index, message: {}, logprobs, ...other };\n }\n if (logprobs) {\n if (!choice.logprobs) {\n choice.logprobs = Object.assign({}, logprobs);\n }\n else {\n const { content, refusal, ...rest } = logprobs;\n assertIsEmpty(rest);\n Object.assign(choice.logprobs, rest);\n if (content) {\n (_a = choice.logprobs).content ?? (_a.content = []);\n choice.logprobs.content.push(...content);\n }\n if (refusal) {\n (_b = choice.logprobs).refusal ?? (_b.refusal = []);\n choice.logprobs.refusal.push(...refusal);\n }\n }\n }\n if (finish_reason) {\n choice.finish_reason = finish_reason;\n if (__classPrivateFieldGet(this, _ChatCompletionStream_params, \"f\") && hasAutoParseableInput(__classPrivateFieldGet(this, _ChatCompletionStream_params, \"f\"))) {\n if (finish_reason === 'length') {\n throw new LengthFinishReasonError();\n }\n if (finish_reason === 'content_filter') {\n throw new ContentFilterFinishReasonError();\n }\n }\n }\n Object.assign(choice, other);\n if (!delta)\n continue; // Shouldn't happen; just in case.\n const { content, refusal, function_call, role, tool_calls, ...rest } = delta;\n assertIsEmpty(rest);\n Object.assign(choice.message, rest);\n if (refusal) {\n choice.message.refusal = (choice.message.refusal || '') + refusal;\n }\n if (role)\n choice.message.role = role;\n if (function_call) {\n if (!choice.message.function_call) {\n choice.message.function_call = function_call;\n }\n else {\n if (function_call.name)\n choice.message.function_call.name = function_call.name;\n if (function_call.arguments) {\n (_c = choice.message.function_call).arguments ?? (_c.arguments = '');\n choice.message.function_call.arguments += function_call.arguments;\n }\n }\n }\n if (content) {\n choice.message.content = (choice.message.content || '') + content;\n if (!choice.message.refusal && __classPrivateFieldGet(this, _ChatCompletionStream_instances, \"m\", _ChatCompletionStream_getAutoParseableResponseFormat).call(this)) {\n choice.message.parsed = partialParse(choice.message.content);\n }\n }\n if (tool_calls) {\n if (!choice.message.tool_calls)\n choice.message.tool_calls = [];\n for (const { index, id, type, function: fn, ...rest } of tool_calls) {\n const tool_call = ((_d = choice.message.tool_calls)[index] ?? (_d[index] = {}));\n Object.assign(tool_call, rest);\n if (id)\n tool_call.id = id;\n if (type)\n tool_call.type = type;\n if (fn)\n tool_call.function ?? (tool_call.function = { name: fn.name ?? '', arguments: '' });\n if (fn?.name)\n tool_call.function.name = fn.name;\n if (fn?.arguments) {\n tool_call.function.arguments += fn.arguments;\n if (shouldParseToolCall(__classPrivateFieldGet(this, _ChatCompletionStream_params, \"f\"), tool_call)) {\n tool_call.function.parsed_arguments = partialParse(tool_call.function.arguments);\n }\n }\n }\n }\n }\n return snapshot;\n }, Symbol.asyncIterator)]() {\n const pushQueue = [];\n const readQueue = [];\n let done = false;\n this.on('chunk', (chunk) => {\n const reader = readQueue.shift();\n if (reader) {\n reader.resolve(chunk);\n }\n else {\n pushQueue.push(chunk);\n }\n });\n this.on('end', () => {\n done = true;\n for (const reader of readQueue) {\n reader.resolve(undefined);\n }\n readQueue.length = 0;\n });\n this.on('abort', (err) => {\n done = true;\n for (const reader of readQueue) {\n reader.reject(err);\n }\n readQueue.length = 0;\n });\n this.on('error', (err) => {\n done = true;\n for (const reader of readQueue) {\n reader.reject(err);\n }\n readQueue.length = 0;\n });\n return {\n next: async () => {\n if (!pushQueue.length) {\n if (done) {\n return { value: undefined, done: true };\n }\n return new Promise((resolve, reject) => readQueue.push({ resolve, reject })).then((chunk) => (chunk ? { value: chunk, done: false } : { value: undefined, done: true }));\n }\n const chunk = pushQueue.shift();\n return { value: chunk, done: false };\n },\n return: async () => {\n this.abort();\n return { value: undefined, done: true };\n },\n };\n }\n toReadableStream() {\n const stream = new Stream(this[Symbol.asyncIterator].bind(this), this.controller);\n return stream.toReadableStream();\n }\n}\nfunction finalizeChatCompletion(snapshot, params) {\n const { id, choices, created, model, system_fingerprint, ...rest } = snapshot;\n const completion = {\n ...rest,\n id,\n choices: choices.map(({ message, finish_reason, index, logprobs, ...choiceRest }) => {\n if (!finish_reason) {\n throw new OpenAIError(`missing finish_reason for choice ${index}`);\n }\n const { content = null, function_call, tool_calls, ...messageRest } = message;\n const role = message.role; // this is what we expect; in theory it could be different which would make our types a slight lie but would be fine.\n if (!role) {\n throw new OpenAIError(`missing role for choice ${index}`);\n }\n if (function_call) {\n const { arguments: args, name } = function_call;\n if (args == null) {\n throw new OpenAIError(`missing function_call.arguments for choice ${index}`);\n }\n if (!name) {\n throw new OpenAIError(`missing function_call.name for choice ${index}`);\n }\n return {\n ...choiceRest,\n message: {\n content,\n function_call: { arguments: args, name },\n role,\n refusal: message.refusal ?? null,\n },\n finish_reason,\n index,\n logprobs,\n };\n }\n if (tool_calls) {\n return {\n ...choiceRest,\n index,\n finish_reason,\n logprobs,\n message: {\n ...messageRest,\n role,\n content,\n refusal: message.refusal ?? null,\n tool_calls: tool_calls.map((tool_call, i) => {\n const { function: fn, type, id, ...toolRest } = tool_call;\n const { arguments: args, name, ...fnRest } = fn || {};\n if (id == null) {\n throw new OpenAIError(`missing choices[${index}].tool_calls[${i}].id\\n${str(snapshot)}`);\n }\n if (type == null) {\n throw new OpenAIError(`missing choices[${index}].tool_calls[${i}].type\\n${str(snapshot)}`);\n }\n if (name == null) {\n throw new OpenAIError(`missing choices[${index}].tool_calls[${i}].function.name\\n${str(snapshot)}`);\n }\n if (args == null) {\n throw new OpenAIError(`missing choices[${index}].tool_calls[${i}].function.arguments\\n${str(snapshot)}`);\n }\n return { ...toolRest, id, type, function: { ...fnRest, name, arguments: args } };\n }),\n },\n };\n }\n return {\n ...choiceRest,\n message: { ...messageRest, content, role, refusal: message.refusal ?? null },\n finish_reason,\n index,\n logprobs,\n };\n }),\n created,\n model,\n object: 'chat.completion',\n ...(system_fingerprint ? { system_fingerprint } : {}),\n };\n return maybeParseChatCompletion(completion, params);\n}\nfunction str(x) {\n return JSON.stringify(x);\n}\n/**\n * Ensures the given argument is an empty object, useful for\n * asserting that all known properties on an object have been\n * destructured.\n */\nfunction assertIsEmpty(obj) {\n return;\n}\nfunction assertNever(_x) { }\n//# sourceMappingURL=ChatCompletionStream.mjs.map","import { ChatCompletionStream } from \"./ChatCompletionStream.mjs\";\nexport class ChatCompletionStreamingRunner extends ChatCompletionStream {\n static fromReadableStream(stream) {\n const runner = new ChatCompletionStreamingRunner(null);\n runner._run(() => runner._fromReadableStream(stream));\n return runner;\n }\n /** @deprecated - please use `runTools` instead. */\n static runFunctions(client, params, options) {\n const runner = new ChatCompletionStreamingRunner(null);\n const opts = {\n ...options,\n headers: { ...options?.headers, 'X-Stainless-Helper-Method': 'runFunctions' },\n };\n runner._run(() => runner._runFunctions(client, params, opts));\n return runner;\n }\n static runTools(client, params, options) {\n const runner = new ChatCompletionStreamingRunner(\n // @ts-expect-error TODO these types are incompatible\n params);\n const opts = {\n ...options,\n headers: { ...options?.headers, 'X-Stainless-Helper-Method': 'runTools' },\n };\n runner._run(() => runner._runTools(client, params, opts));\n return runner;\n }\n}\n//# sourceMappingURL=ChatCompletionStreamingRunner.mjs.map","// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.\nimport { APIResource } from \"../../../resource.mjs\";\nimport { ChatCompletionRunner } from \"../../../lib/ChatCompletionRunner.mjs\";\nimport { ChatCompletionStreamingRunner, } from \"../../../lib/ChatCompletionStreamingRunner.mjs\";\nimport { ChatCompletionStream } from \"../../../lib/ChatCompletionStream.mjs\";\nimport { parseChatCompletion, validateInputTools } from \"../../../lib/parser.mjs\";\nexport { ChatCompletionStreamingRunner, } from \"../../../lib/ChatCompletionStreamingRunner.mjs\";\nexport { ParsingFunction, ParsingToolFunction, } from \"../../../lib/RunnableFunction.mjs\";\nexport { ChatCompletionStream } from \"../../../lib/ChatCompletionStream.mjs\";\nexport { ChatCompletionRunner, } from \"../../../lib/ChatCompletionRunner.mjs\";\nexport class Completions extends APIResource {\n parse(body, options) {\n validateInputTools(body.tools);\n return this._client.chat.completions\n .create(body, {\n ...options,\n headers: {\n ...options?.headers,\n 'X-Stainless-Helper-Method': 'beta.chat.completions.parse',\n },\n })\n ._thenUnwrap((completion) => parseChatCompletion(completion, body));\n }\n runFunctions(body, options) {\n if (body.stream) {\n return ChatCompletionStreamingRunner.runFunctions(this._client, body, options);\n }\n return ChatCompletionRunner.runFunctions(this._client, body, options);\n }\n runTools(body, options) {\n if (body.stream) {\n return ChatCompletionStreamingRunner.runTools(this._client, body, options);\n }\n return ChatCompletionRunner.runTools(this._client, body, options);\n }\n /**\n * Creates a chat completion stream\n */\n stream(body, options) {\n return ChatCompletionStream.createChatCompletion(this._client, body, options);\n }\n}\n//# sourceMappingURL=completions.mjs.map","// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.\nimport { APIResource } from \"../../../resource.mjs\";\nimport * as CompletionsAPI from \"./completions.mjs\";\nexport class Chat extends APIResource {\n constructor() {\n super(...arguments);\n this.completions = new CompletionsAPI.Completions(this._client);\n }\n}\n(function (Chat) {\n Chat.Completions = CompletionsAPI.Completions;\n})(Chat || (Chat = {}));\n//# sourceMappingURL=chat.mjs.map","// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.\nimport { APIResource } from \"../../../resource.mjs\";\nexport class Sessions extends APIResource {\n /**\n * Create an ephemeral API token for use in client-side applications with the\n * Realtime API. Can be configured with the same session parameters as the\n * `session.update` client event.\n *\n * It responds with a session object, plus a `client_secret` key which contains a\n * usable ephemeral API token that can be used to authenticate browser clients for\n * the Realtime API.\n */\n create(body, options) {\n return this._client.post('/realtime/sessions', {\n body,\n ...options,\n headers: { 'OpenAI-Beta': 'assistants=v2', ...options?.headers },\n });\n }\n}\n//# sourceMappingURL=sessions.mjs.map","// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.\nimport { APIResource } from \"../../../resource.mjs\";\nimport * as SessionsAPI from \"./sessions.mjs\";\nimport { Sessions, } from \"./sessions.mjs\";\nexport class Realtime extends APIResource {\n constructor() {\n super(...arguments);\n this.sessions = new SessionsAPI.Sessions(this._client);\n }\n}\nRealtime.Sessions = Sessions;\n//# sourceMappingURL=realtime.mjs.map","var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (receiver, state, kind, f) {\n if (kind === \"a\" && !f) throw new TypeError(\"Private accessor was defined without a getter\");\n if (typeof state === \"function\" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError(\"Cannot read private member from an object whose class did not declare it\");\n return kind === \"m\" ? f : kind === \"a\" ? f.call(receiver) : f ? f.value : state.get(receiver);\n};\nvar __classPrivateFieldSet = (this && this.__classPrivateFieldSet) || function (receiver, state, value, kind, f) {\n if (kind === \"m\") throw new TypeError(\"Private method is not writable\");\n if (kind === \"a\" && !f) throw new TypeError(\"Private accessor was defined without a setter\");\n if (typeof state === \"function\" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError(\"Cannot write private member to an object whose class did not declare it\");\n return (kind === \"a\" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;\n};\nvar _AssistantStream_instances, _AssistantStream_events, _AssistantStream_runStepSnapshots, _AssistantStream_messageSnapshots, _AssistantStream_messageSnapshot, _AssistantStream_finalRun, _AssistantStream_currentContentIndex, _AssistantStream_currentContent, _AssistantStream_currentToolCallIndex, _AssistantStream_currentToolCall, _AssistantStream_currentEvent, _AssistantStream_currentRunSnapshot, _AssistantStream_currentRunStepSnapshot, _AssistantStream_addEvent, _AssistantStream_endRequest, _AssistantStream_handleMessage, _AssistantStream_handleRunStep, _AssistantStream_handleEvent, _AssistantStream_accumulateRunStep, _AssistantStream_accumulateMessage, _AssistantStream_accumulateContent, _AssistantStream_handleRun;\nimport * as Core from \"../core.mjs\";\nimport { Stream } from \"../streaming.mjs\";\nimport { APIUserAbortError, OpenAIError } from \"../error.mjs\";\nimport { EventStream } from \"./EventStream.mjs\";\nexport class AssistantStream extends EventStream {\n constructor() {\n super(...arguments);\n _AssistantStream_instances.add(this);\n //Track all events in a single list for reference\n _AssistantStream_events.set(this, []);\n //Used to accumulate deltas\n //We are accumulating many types so the value here is not strict\n _AssistantStream_runStepSnapshots.set(this, {});\n _AssistantStream_messageSnapshots.set(this, {});\n _AssistantStream_messageSnapshot.set(this, void 0);\n _AssistantStream_finalRun.set(this, void 0);\n _AssistantStream_currentContentIndex.set(this, void 0);\n _AssistantStream_currentContent.set(this, void 0);\n _AssistantStream_currentToolCallIndex.set(this, void 0);\n _AssistantStream_currentToolCall.set(this, void 0);\n //For current snapshot methods\n _AssistantStream_currentEvent.set(this, void 0);\n _AssistantStream_currentRunSnapshot.set(this, void 0);\n _AssistantStream_currentRunStepSnapshot.set(this, void 0);\n }\n [(_AssistantStream_events = new WeakMap(), _AssistantStream_runStepSnapshots = new WeakMap(), _AssistantStream_messageSnapshots = new WeakMap(), _AssistantStream_messageSnapshot = new WeakMap(), _AssistantStream_finalRun = new WeakMap(), _AssistantStream_currentContentIndex = new WeakMap(), _AssistantStream_currentContent = new WeakMap(), _AssistantStream_currentToolCallIndex = new WeakMap(), _AssistantStream_currentToolCall = new WeakMap(), _AssistantStream_currentEvent = new WeakMap(), _AssistantStream_currentRunSnapshot = new WeakMap(), _AssistantStream_currentRunStepSnapshot = new WeakMap(), _AssistantStream_instances = new WeakSet(), Symbol.asyncIterator)]() {\n const pushQueue = [];\n const readQueue = [];\n let done = false;\n //Catch all for passing along all events\n this.on('event', (event) => {\n const reader = readQueue.shift();\n if (reader) {\n reader.resolve(event);\n }\n else {\n pushQueue.push(event);\n }\n });\n this.on('end', () => {\n done = true;\n for (const reader of readQueue) {\n reader.resolve(undefined);\n }\n readQueue.length = 0;\n });\n this.on('abort', (err) => {\n done = true;\n for (const reader of readQueue) {\n reader.reject(err);\n }\n readQueue.length = 0;\n });\n this.on('error', (err) => {\n done = true;\n for (const reader of readQueue) {\n reader.reject(err);\n }\n readQueue.length = 0;\n });\n return {\n next: async () => {\n if (!pushQueue.length) {\n if (done) {\n return { value: undefined, done: true };\n }\n return new Promise((resolve, reject) => readQueue.push({ resolve, reject })).then((chunk) => (chunk ? { value: chunk, done: false } : { value: undefined, done: true }));\n }\n const chunk = pushQueue.shift();\n return { value: chunk, done: false };\n },\n return: async () => {\n this.abort();\n return { value: undefined, done: true };\n },\n };\n }\n static fromReadableStream(stream) {\n const runner = new AssistantStream();\n runner._run(() => runner._fromReadableStream(stream));\n return runner;\n }\n async _fromReadableStream(readableStream, options) {\n const signal = options?.signal;\n if (signal) {\n if (signal.aborted)\n this.controller.abort();\n signal.addEventListener('abort', () => this.controller.abort());\n }\n this._connected();\n const stream = Stream.fromReadableStream(readableStream, this.controller);\n for await (const event of stream) {\n __classPrivateFieldGet(this, _AssistantStream_instances, \"m\", _AssistantStream_addEvent).call(this, event);\n }\n if (stream.controller.signal?.aborted) {\n throw new APIUserAbortError();\n }\n return this._addRun(__classPrivateFieldGet(this, _AssistantStream_instances, \"m\", _AssistantStream_endRequest).call(this));\n }\n toReadableStream() {\n const stream = new Stream(this[Symbol.asyncIterator].bind(this), this.controller);\n return stream.toReadableStream();\n }\n static createToolAssistantStream(threadId, runId, runs, params, options) {\n const runner = new AssistantStream();\n runner._run(() => runner._runToolAssistantStream(threadId, runId, runs, params, {\n ...options,\n headers: { ...options?.headers, 'X-Stainless-Helper-Method': 'stream' },\n }));\n return runner;\n }\n async _createToolAssistantStream(run, threadId, runId, params, options) {\n const signal = options?.signal;\n if (signal) {\n if (signal.aborted)\n this.controller.abort();\n signal.addEventListener('abort', () => this.controller.abort());\n }\n const body = { ...params, stream: true };\n const stream = await run.submitToolOutputs(threadId, runId, body, {\n ...options,\n signal: this.controller.signal,\n });\n this._connected();\n for await (const event of stream) {\n __classPrivateFieldGet(this, _AssistantStream_instances, \"m\", _AssistantStream_addEvent).call(this, event);\n }\n if (stream.controller.signal?.aborted) {\n throw new APIUserAbortError();\n }\n return this._addRun(__classPrivateFieldGet(this, _AssistantStream_instances, \"m\", _AssistantStream_endRequest).call(this));\n }\n static createThreadAssistantStream(params, thread, options) {\n const runner = new AssistantStream();\n runner._run(() => runner._threadAssistantStream(params, thread, {\n ...options,\n headers: { ...options?.headers, 'X-Stainless-Helper-Method': 'stream' },\n }));\n return runner;\n }\n static createAssistantStream(threadId, runs, params, options) {\n const runner = new AssistantStream();\n runner._run(() => runner._runAssistantStream(threadId, runs, params, {\n ...options,\n headers: { ...options?.headers, 'X-Stainless-Helper-Method': 'stream' },\n }));\n return runner;\n }\n currentEvent() {\n return __classPrivateFieldGet(this, _AssistantStream_currentEvent, \"f\");\n }\n currentRun() {\n return __classPrivateFieldGet(this, _AssistantStream_currentRunSnapshot, \"f\");\n }\n currentMessageSnapshot() {\n return __classPrivateFieldGet(this, _AssistantStream_messageSnapshot, \"f\");\n }\n currentRunStepSnapshot() {\n return __classPrivateFieldGet(this, _AssistantStream_currentRunStepSnapshot, \"f\");\n }\n async finalRunSteps() {\n await this.done();\n return Object.values(__classPrivateFieldGet(this, _AssistantStream_runStepSnapshots, \"f\"));\n }\n async finalMessages() {\n await this.done();\n return Object.values(__classPrivateFieldGet(this, _AssistantStream_messageSnapshots, \"f\"));\n }\n async finalRun() {\n await this.done();\n if (!__classPrivateFieldGet(this, _AssistantStream_finalRun, \"f\"))\n throw Error('Final run was not received.');\n return __classPrivateFieldGet(this, _AssistantStream_finalRun, \"f\");\n }\n async _createThreadAssistantStream(thread, params, options) {\n const signal = options?.signal;\n if (signal) {\n if (signal.aborted)\n this.controller.abort();\n signal.addEventListener('abort', () => this.controller.abort());\n }\n const body = { ...params, stream: true };\n const stream = await thread.createAndRun(body, { ...options, signal: this.controller.signal });\n this._connected();\n for await (const event of stream) {\n __classPrivateFieldGet(this, _AssistantStream_instances, \"m\", _AssistantStream_addEvent).call(this, event);\n }\n if (stream.controller.signal?.aborted) {\n throw new APIUserAbortError();\n }\n return this._addRun(__classPrivateFieldGet(this, _AssistantStream_instances, \"m\", _AssistantStream_endRequest).call(this));\n }\n async _createAssistantStream(run, threadId, params, options) {\n const signal = options?.signal;\n if (signal) {\n if (signal.aborted)\n this.controller.abort();\n signal.addEventListener('abort', () => this.controller.abort());\n }\n const body = { ...params, stream: true };\n const stream = await run.create(threadId, body, { ...options, signal: this.controller.signal });\n this._connected();\n for await (const event of stream) {\n __classPrivateFieldGet(this, _AssistantStream_instances, \"m\", _AssistantStream_addEvent).call(this, event);\n }\n if (stream.controller.signal?.aborted) {\n throw new APIUserAbortError();\n }\n return this._addRun(__classPrivateFieldGet(this, _AssistantStream_instances, \"m\", _AssistantStream_endRequest).call(this));\n }\n static accumulateDelta(acc, delta) {\n for (const [key, deltaValue] of Object.entries(delta)) {\n if (!acc.hasOwnProperty(key)) {\n acc[key] = deltaValue;\n continue;\n }\n let accValue = acc[key];\n if (accValue === null || accValue === undefined) {\n acc[key] = deltaValue;\n continue;\n }\n // We don't accumulate these special properties\n if (key === 'index' || key === 'type') {\n acc[key] = deltaValue;\n continue;\n }\n // Type-specific accumulation logic\n if (typeof accValue === 'string' && typeof deltaValue === 'string') {\n accValue += deltaValue;\n }\n else if (typeof accValue === 'number' && typeof deltaValue === 'number') {\n accValue += deltaValue;\n }\n else if (Core.isObj(accValue) && Core.isObj(deltaValue)) {\n accValue = this.accumulateDelta(accValue, deltaValue);\n }\n else if (Array.isArray(accValue) && Array.isArray(deltaValue)) {\n if (accValue.every((x) => typeof x === 'string' || typeof x === 'number')) {\n accValue.push(...deltaValue); // Use spread syntax for efficient addition\n continue;\n }\n for (const deltaEntry of deltaValue) {\n if (!Core.isObj(deltaEntry)) {\n throw new Error(`Expected array delta entry to be an object but got: ${deltaEntry}`);\n }\n const index = deltaEntry['index'];\n if (index == null) {\n console.error(deltaEntry);\n throw new Error('Expected array delta entry to have an `index` property');\n }\n if (typeof index !== 'number') {\n throw new Error(`Expected array delta entry \\`index\\` property to be a number but got ${index}`);\n }\n const accEntry = accValue[index];\n if (accEntry == null) {\n accValue.push(deltaEntry);\n }\n else {\n accValue[index] = this.accumulateDelta(accEntry, deltaEntry);\n }\n }\n continue;\n }\n else {\n throw Error(`Unhandled record type: ${key}, deltaValue: ${deltaValue}, accValue: ${accValue}`);\n }\n acc[key] = accValue;\n }\n return acc;\n }\n _addRun(run) {\n return run;\n }\n async _threadAssistantStream(params, thread, options) {\n return await this._createThreadAssistantStream(thread, params, options);\n }\n async _runAssistantStream(threadId, runs, params, options) {\n return await this._createAssistantStream(runs, threadId, params, options);\n }\n async _runToolAssistantStream(threadId, runId, runs, params, options) {\n return await this._createToolAssistantStream(runs, threadId, runId, params, options);\n }\n}\n_AssistantStream_addEvent = function _AssistantStream_addEvent(event) {\n if (this.ended)\n return;\n __classPrivateFieldSet(this, _AssistantStream_currentEvent, event, \"f\");\n __classPrivateFieldGet(this, _AssistantStream_instances, \"m\", _AssistantStream_handleEvent).call(this, event);\n switch (event.event) {\n case 'thread.created':\n //No action on this event.\n break;\n case 'thread.run.created':\n case 'thread.run.queued':\n case 'thread.run.in_progress':\n case 'thread.run.requires_action':\n case 'thread.run.completed':\n case 'thread.run.incomplete':\n case 'thread.run.failed':\n case 'thread.run.cancelling':\n case 'thread.run.cancelled':\n case 'thread.run.expired':\n __classPrivateFieldGet(this, _AssistantStream_instances, \"m\", _AssistantStream_handleRun).call(this, event);\n break;\n case 'thread.run.step.created':\n case 'thread.run.step.in_progress':\n case 'thread.run.step.delta':\n case 'thread.run.step.completed':\n case 'thread.run.step.failed':\n case 'thread.run.step.cancelled':\n case 'thread.run.step.expired':\n __classPrivateFieldGet(this, _AssistantStream_instances, \"m\", _AssistantStream_handleRunStep).call(this, event);\n break;\n case 'thread.message.created':\n case 'thread.message.in_progress':\n case 'thread.message.delta':\n case 'thread.message.completed':\n case 'thread.message.incomplete':\n __classPrivateFieldGet(this, _AssistantStream_instances, \"m\", _AssistantStream_handleMessage).call(this, event);\n break;\n case 'error':\n //This is included for completeness, but errors are processed in the SSE event processing so this should not occur\n throw new Error('Encountered an error event in event processing - errors should be processed earlier');\n default:\n assertNever(event);\n }\n}, _AssistantStream_endRequest = function _AssistantStream_endRequest() {\n if (this.ended) {\n throw new OpenAIError(`stream has ended, this shouldn't happen`);\n }\n if (!__classPrivateFieldGet(this, _AssistantStream_finalRun, \"f\"))\n throw Error('Final run has not been received');\n return __classPrivateFieldGet(this, _AssistantStream_finalRun, \"f\");\n}, _AssistantStream_handleMessage = function _AssistantStream_handleMessage(event) {\n const [accumulatedMessage, newContent] = __classPrivateFieldGet(this, _AssistantStream_instances, \"m\", _AssistantStream_accumulateMessage).call(this, event, __classPrivateFieldGet(this, _AssistantStream_messageSnapshot, \"f\"));\n __classPrivateFieldSet(this, _AssistantStream_messageSnapshot, accumulatedMessage, \"f\");\n __classPrivateFieldGet(this, _AssistantStream_messageSnapshots, \"f\")[accumulatedMessage.id] = accumulatedMessage;\n for (const content of newContent) {\n const snapshotContent = accumulatedMessage.content[content.index];\n if (snapshotContent?.type == 'text') {\n this._emit('textCreated', snapshotContent.text);\n }\n }\n switch (event.event) {\n case 'thread.message.created':\n this._emit('messageCreated', event.data);\n break;\n case 'thread.message.in_progress':\n break;\n case 'thread.message.delta':\n this._emit('messageDelta', event.data.delta, accumulatedMessage);\n if (event.data.delta.content) {\n for (const content of event.data.delta.content) {\n //If it is text delta, emit a text delta event\n if (content.type == 'text' && content.text) {\n let textDelta = content.text;\n let snapshot = accumulatedMessage.content[content.index];\n if (snapshot && snapshot.type == 'text') {\n this._emit('textDelta', textDelta, snapshot.text);\n }\n else {\n throw Error('The snapshot associated with this text delta is not text or missing');\n }\n }\n if (content.index != __classPrivateFieldGet(this, _AssistantStream_currentContentIndex, \"f\")) {\n //See if we have in progress content\n if (__classPrivateFieldGet(this, _AssistantStream_currentContent, \"f\")) {\n switch (__classPrivateFieldGet(this, _AssistantStream_currentContent, \"f\").type) {\n case 'text':\n this._emit('textDone', __classPrivateFieldGet(this, _AssistantStream_currentContent, \"f\").text, __classPrivateFieldGet(this, _AssistantStream_messageSnapshot, \"f\"));\n break;\n case 'image_file':\n this._emit('imageFileDone', __classPrivateFieldGet(this, _AssistantStream_currentContent, \"f\").image_file, __classPrivateFieldGet(this, _AssistantStream_messageSnapshot, \"f\"));\n break;\n }\n }\n __classPrivateFieldSet(this, _AssistantStream_currentContentIndex, content.index, \"f\");\n }\n __classPrivateFieldSet(this, _AssistantStream_currentContent, accumulatedMessage.content[content.index], \"f\");\n }\n }\n break;\n case 'thread.message.completed':\n case 'thread.message.incomplete':\n //We emit the latest content we were working on on completion (including incomplete)\n if (__classPrivateFieldGet(this, _AssistantStream_currentContentIndex, \"f\") !== undefined) {\n const currentContent = event.data.content[__classPrivateFieldGet(this, _AssistantStream_currentContentIndex, \"f\")];\n if (currentContent) {\n switch (currentContent.type) {\n case 'image_file':\n this._emit('imageFileDone', currentContent.image_file, __classPrivateFieldGet(this, _AssistantStream_messageSnapshot, \"f\"));\n break;\n case 'text':\n this._emit('textDone', currentContent.text, __classPrivateFieldGet(this, _AssistantStream_messageSnapshot, \"f\"));\n break;\n }\n }\n }\n if (__classPrivateFieldGet(this, _AssistantStream_messageSnapshot, \"f\")) {\n this._emit('messageDone', event.data);\n }\n __classPrivateFieldSet(this, _AssistantStream_messageSnapshot, undefined, \"f\");\n }\n}, _AssistantStream_handleRunStep = function _AssistantStream_handleRunStep(event) {\n const accumulatedRunStep = __classPrivateFieldGet(this, _AssistantStream_instances, \"m\", _AssistantStream_accumulateRunStep).call(this, event);\n __classPrivateFieldSet(this, _AssistantStream_currentRunStepSnapshot, accumulatedRunStep, \"f\");\n switch (event.event) {\n case 'thread.run.step.created':\n this._emit('runStepCreated', event.data);\n break;\n case 'thread.run.step.delta':\n const delta = event.data.delta;\n if (delta.step_details &&\n delta.step_details.type == 'tool_calls' &&\n delta.step_details.tool_calls &&\n accumulatedRunStep.step_details.type == 'tool_calls') {\n for (const toolCall of delta.step_details.tool_calls) {\n if (toolCall.index == __classPrivateFieldGet(this, _AssistantStream_currentToolCallIndex, \"f\")) {\n this._emit('toolCallDelta', toolCall, accumulatedRunStep.step_details.tool_calls[toolCall.index]);\n }\n else {\n if (__classPrivateFieldGet(this, _AssistantStream_currentToolCall, \"f\")) {\n this._emit('toolCallDone', __classPrivateFieldGet(this, _AssistantStream_currentToolCall, \"f\"));\n }\n __classPrivateFieldSet(this, _AssistantStream_currentToolCallIndex, toolCall.index, \"f\");\n __classPrivateFieldSet(this, _AssistantStream_currentToolCall, accumulatedRunStep.step_details.tool_calls[toolCall.index], \"f\");\n if (__classPrivateFieldGet(this, _AssistantStream_currentToolCall, \"f\"))\n this._emit('toolCallCreated', __classPrivateFieldGet(this, _AssistantStream_currentToolCall, \"f\"));\n }\n }\n }\n this._emit('runStepDelta', event.data.delta, accumulatedRunStep);\n break;\n case 'thread.run.step.completed':\n case 'thread.run.step.failed':\n case 'thread.run.step.cancelled':\n case 'thread.run.step.expired':\n __classPrivateFieldSet(this, _AssistantStream_currentRunStepSnapshot, undefined, \"f\");\n const details = event.data.step_details;\n if (details.type == 'tool_calls') {\n if (__classPrivateFieldGet(this, _AssistantStream_currentToolCall, \"f\")) {\n this._emit('toolCallDone', __classPrivateFieldGet(this, _AssistantStream_currentToolCall, \"f\"));\n __classPrivateFieldSet(this, _AssistantStream_currentToolCall, undefined, \"f\");\n }\n }\n this._emit('runStepDone', event.data, accumulatedRunStep);\n break;\n case 'thread.run.step.in_progress':\n break;\n }\n}, _AssistantStream_handleEvent = function _AssistantStream_handleEvent(event) {\n __classPrivateFieldGet(this, _AssistantStream_events, \"f\").push(event);\n this._emit('event', event);\n}, _AssistantStream_accumulateRunStep = function _AssistantStream_accumulateRunStep(event) {\n switch (event.event) {\n case 'thread.run.step.created':\n __classPrivateFieldGet(this, _AssistantStream_runStepSnapshots, \"f\")[event.data.id] = event.data;\n return event.data;\n case 'thread.run.step.delta':\n let snapshot = __classPrivateFieldGet(this, _AssistantStream_runStepSnapshots, \"f\")[event.data.id];\n if (!snapshot) {\n throw Error('Received a RunStepDelta before creation of a snapshot');\n }\n let data = event.data;\n if (data.delta) {\n const accumulated = AssistantStream.accumulateDelta(snapshot, data.delta);\n __classPrivateFieldGet(this, _AssistantStream_runStepSnapshots, \"f\")[event.data.id] = accumulated;\n }\n return __classPrivateFieldGet(this, _AssistantStream_runStepSnapshots, \"f\")[event.data.id];\n case 'thread.run.step.completed':\n case 'thread.run.step.failed':\n case 'thread.run.step.cancelled':\n case 'thread.run.step.expired':\n case 'thread.run.step.in_progress':\n __classPrivateFieldGet(this, _AssistantStream_runStepSnapshots, \"f\")[event.data.id] = event.data;\n break;\n }\n if (__classPrivateFieldGet(this, _AssistantStream_runStepSnapshots, \"f\")[event.data.id])\n return __classPrivateFieldGet(this, _AssistantStream_runStepSnapshots, \"f\")[event.data.id];\n throw new Error('No snapshot available');\n}, _AssistantStream_accumulateMessage = function _AssistantStream_accumulateMessage(event, snapshot) {\n let newContent = [];\n switch (event.event) {\n case 'thread.message.created':\n //On creation the snapshot is just the initial message\n return [event.data, newContent];\n case 'thread.message.delta':\n if (!snapshot) {\n throw Error('Received a delta with no existing snapshot (there should be one from message creation)');\n }\n let data = event.data;\n //If this delta does not have content, nothing to process\n if (data.delta.content) {\n for (const contentElement of data.delta.content) {\n if (contentElement.index in snapshot.content) {\n let currentContent = snapshot.content[contentElement.index];\n snapshot.content[contentElement.index] = __classPrivateFieldGet(this, _AssistantStream_instances, \"m\", _AssistantStream_accumulateContent).call(this, contentElement, currentContent);\n }\n else {\n snapshot.content[contentElement.index] = contentElement;\n // This is a new element\n newContent.push(contentElement);\n }\n }\n }\n return [snapshot, newContent];\n case 'thread.message.in_progress':\n case 'thread.message.completed':\n case 'thread.message.incomplete':\n //No changes on other thread events\n if (snapshot) {\n return [snapshot, newContent];\n }\n else {\n throw Error('Received thread message event with no existing snapshot');\n }\n }\n throw Error('Tried to accumulate a non-message event');\n}, _AssistantStream_accumulateContent = function _AssistantStream_accumulateContent(contentElement, currentContent) {\n return AssistantStream.accumulateDelta(currentContent, contentElement);\n}, _AssistantStream_handleRun = function _AssistantStream_handleRun(event) {\n __classPrivateFieldSet(this, _AssistantStream_currentRunSnapshot, event.data, \"f\");\n switch (event.event) {\n case 'thread.run.created':\n break;\n case 'thread.run.queued':\n break;\n case 'thread.run.in_progress':\n break;\n case 'thread.run.requires_action':\n case 'thread.run.cancelled':\n case 'thread.run.failed':\n case 'thread.run.completed':\n case 'thread.run.expired':\n __classPrivateFieldSet(this, _AssistantStream_finalRun, event.data, \"f\");\n if (__classPrivateFieldGet(this, _AssistantStream_currentToolCall, \"f\")) {\n this._emit('toolCallDone', __classPrivateFieldGet(this, _AssistantStream_currentToolCall, \"f\"));\n __classPrivateFieldSet(this, _AssistantStream_currentToolCall, undefined, \"f\");\n }\n break;\n case 'thread.run.cancelling':\n break;\n }\n};\nfunction assertNever(_x) { }\n//# sourceMappingURL=AssistantStream.mjs.map","// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.\nvar _a;\nimport * as qs from \"./internal/qs/index.mjs\";\nimport * as Core from \"./core.mjs\";\nimport * as Errors from \"./error.mjs\";\nimport * as Pagination from \"./pagination.mjs\";\nimport * as Uploads from \"./uploads.mjs\";\nimport * as API from \"./resources/index.mjs\";\nimport { Batches, BatchesPage, } from \"./resources/batches.mjs\";\nimport { Completions, } from \"./resources/completions.mjs\";\nimport { Embeddings, } from \"./resources/embeddings.mjs\";\nimport { FileObjectsPage, Files, } from \"./resources/files.mjs\";\nimport { Images, } from \"./resources/images.mjs\";\nimport { Models, ModelsPage } from \"./resources/models.mjs\";\nimport { Moderations, } from \"./resources/moderations.mjs\";\nimport { Audio } from \"./resources/audio/audio.mjs\";\nimport { Beta } from \"./resources/beta/beta.mjs\";\nimport { Chat } from \"./resources/chat/chat.mjs\";\nimport { FineTuning } from \"./resources/fine-tuning/fine-tuning.mjs\";\nimport { Uploads as UploadsAPIUploads, } from \"./resources/uploads/uploads.mjs\";\nimport { ChatCompletionsPage, } from \"./resources/chat/completions/completions.mjs\";\n/**\n * API Client for interfacing with the OpenAI API.\n */\nexport class OpenAI extends Core.APIClient {\n /**\n * API Client for interfacing with the OpenAI API.\n *\n * @param {string | undefined} [opts.apiKey=process.env['OPENAI_API_KEY'] ?? undefined]\n * @param {string | null | undefined} [opts.organization=process.env['OPENAI_ORG_ID'] ?? null]\n * @param {string | null | undefined} [opts.project=process.env['OPENAI_PROJECT_ID'] ?? null]\n * @param {string} [opts.baseURL=process.env['OPENAI_BASE_URL'] ?? https://api.openai.com/v1] - Override the default base URL for the API.\n * @param {number} [opts.timeout=10 minutes] - The maximum amount of time (in milliseconds) the client will wait for a response before timing out.\n * @param {number} [opts.httpAgent] - An HTTP agent used to manage HTTP(s) connections.\n * @param {Core.Fetch} [opts.fetch] - Specify a custom `fetch` function implementation.\n * @param {number} [opts.maxRetries=2] - The maximum number of times the client will retry a request.\n * @param {Core.Headers} opts.defaultHeaders - Default headers to include with every request to the API.\n * @param {Core.DefaultQuery} opts.defaultQuery - Default query parameters to include with every request to the API.\n * @param {boolean} [opts.dangerouslyAllowBrowser=false] - By default, client-side use of this library is not allowed, as it risks exposing your secret API credentials to attackers.\n */\n constructor({ baseURL = Core.readEnv('OPENAI_BASE_URL'), apiKey = Core.readEnv('OPENAI_API_KEY'), organization = Core.readEnv('OPENAI_ORG_ID') ?? null, project = Core.readEnv('OPENAI_PROJECT_ID') ?? null, ...opts } = {}) {\n if (apiKey === undefined) {\n throw new Errors.OpenAIError(\"The OPENAI_API_KEY environment variable is missing or empty; either provide it, or instantiate the OpenAI client with an apiKey option, like new OpenAI({ apiKey: 'My API Key' }).\");\n }\n const options = {\n apiKey,\n organization,\n project,\n ...opts,\n baseURL: baseURL || `https://api.openai.com/v1`,\n };\n if (!options.dangerouslyAllowBrowser && Core.isRunningInBrowser()) {\n throw new Errors.OpenAIError(\"It looks like you're running in a browser-like environment.\\n\\nThis is disabled by default, as it risks exposing your secret API credentials to attackers.\\nIf you understand the risks and have appropriate mitigations in place,\\nyou can set the `dangerouslyAllowBrowser` option to `true`, e.g.,\\n\\nnew OpenAI({ apiKey, dangerouslyAllowBrowser: true });\\n\\nhttps://help.openai.com/en/articles/5112595-best-practices-for-api-key-safety\\n\");\n }\n super({\n baseURL: options.baseURL,\n timeout: options.timeout ?? 600000 /* 10 minutes */,\n httpAgent: options.httpAgent,\n maxRetries: options.maxRetries,\n fetch: options.fetch,\n });\n this.completions = new API.Completions(this);\n this.chat = new API.Chat(this);\n this.embeddings = new API.Embeddings(this);\n this.files = new API.Files(this);\n this.images = new API.Images(this);\n this.audio = new API.Audio(this);\n this.moderations = new API.Moderations(this);\n this.models = new API.Models(this);\n this.fineTuning = new API.FineTuning(this);\n this.beta = new API.Beta(this);\n this.batches = new API.Batches(this);\n this.uploads = new API.Uploads(this);\n this._options = options;\n this.apiKey = apiKey;\n this.organization = organization;\n this.project = project;\n }\n defaultQuery() {\n return this._options.defaultQuery;\n }\n defaultHeaders(opts) {\n return {\n ...super.defaultHeaders(opts),\n 'OpenAI-Organization': this.organization,\n 'OpenAI-Project': this.project,\n ...this._options.defaultHeaders,\n };\n }\n authHeaders(opts) {\n return { Authorization: `Bearer ${this.apiKey}` };\n }\n stringifyQuery(query) {\n return qs.stringify(query, { arrayFormat: 'brackets' });\n }\n}\n_a = OpenAI;\nOpenAI.OpenAI = _a;\nOpenAI.DEFAULT_TIMEOUT = 600000; // 10 minutes\nOpenAI.OpenAIError = Errors.OpenAIError;\nOpenAI.APIError = Errors.APIError;\nOpenAI.APIConnectionError = Errors.APIConnectionError;\nOpenAI.APIConnectionTimeoutError = Errors.APIConnectionTimeoutError;\nOpenAI.APIUserAbortError = Errors.APIUserAbortError;\nOpenAI.NotFoundError = Errors.NotFoundError;\nOpenAI.ConflictError = Errors.ConflictError;\nOpenAI.RateLimitError = Errors.RateLimitError;\nOpenAI.BadRequestError = Errors.BadRequestError;\nOpenAI.AuthenticationError = Errors.AuthenticationError;\nOpenAI.InternalServerError = Errors.InternalServerError;\nOpenAI.PermissionDeniedError = Errors.PermissionDeniedError;\nOpenAI.UnprocessableEntityError = Errors.UnprocessableEntityError;\nOpenAI.toFile = Uploads.toFile;\nOpenAI.fileFromPath = Uploads.fileFromPath;\nOpenAI.Completions = Completions;\nOpenAI.Chat = Chat;\nOpenAI.ChatCompletionsPage = ChatCompletionsPage;\nOpenAI.Embeddings = Embeddings;\nOpenAI.Files = Files;\nOpenAI.FileObjectsPage = FileObjectsPage;\nOpenAI.Images = Images;\nOpenAI.Audio = Audio;\nOpenAI.Moderations = Moderations;\nOpenAI.Models = Models;\nOpenAI.ModelsPage = ModelsPage;\nOpenAI.FineTuning = FineTuning;\nOpenAI.Beta = Beta;\nOpenAI.Batches = Batches;\nOpenAI.BatchesPage = BatchesPage;\nOpenAI.Uploads = UploadsAPIUploads;\n/** API Client for interfacing with the Azure OpenAI API. */\nexport class AzureOpenAI extends OpenAI {\n /**\n * API Client for interfacing with the Azure OpenAI API.\n *\n * @param {string | undefined} [opts.apiVersion=process.env['OPENAI_API_VERSION'] ?? undefined]\n * @param {string | undefined} [opts.endpoint=process.env['AZURE_OPENAI_ENDPOINT'] ?? undefined] - Your Azure endpoint, including the resource, e.g. `https://example-resource.azure.openai.com/`\n * @param {string | undefined} [opts.apiKey=process.env['AZURE_OPENAI_API_KEY'] ?? undefined]\n * @param {string | undefined} opts.deployment - A model deployment, if given, sets the base client URL to include `/deployments/{deployment}`.\n * @param {string | null | undefined} [opts.organization=process.env['OPENAI_ORG_ID'] ?? null]\n * @param {string} [opts.baseURL=process.env['OPENAI_BASE_URL']] - Sets the base URL for the API, e.g. `https://example-resource.azure.openai.com/openai/`.\n * @param {number} [opts.timeout=10 minutes] - The maximum amount of time (in milliseconds) the client will wait for a response before timing out.\n * @param {number} [opts.httpAgent] - An HTTP agent used to manage HTTP(s) connections.\n * @param {Core.Fetch} [opts.fetch] - Specify a custom `fetch` function implementation.\n * @param {number} [opts.maxRetries=2] - The maximum number of times the client will retry a request.\n * @param {Core.Headers} opts.defaultHeaders - Default headers to include with every request to the API.\n * @param {Core.DefaultQuery} opts.defaultQuery - Default query parameters to include with every request to the API.\n * @param {boolean} [opts.dangerouslyAllowBrowser=false] - By default, client-side use of this library is not allowed, as it risks exposing your secret API credentials to attackers.\n */\n constructor({ baseURL = Core.readEnv('OPENAI_BASE_URL'), apiKey = Core.readEnv('AZURE_OPENAI_API_KEY'), apiVersion = Core.readEnv('OPENAI_API_VERSION'), endpoint, deployment, azureADTokenProvider, dangerouslyAllowBrowser, ...opts } = {}) {\n if (!apiVersion) {\n throw new Errors.OpenAIError(\"The OPENAI_API_VERSION environment variable is missing or empty; either provide it, or instantiate the AzureOpenAI client with an apiVersion option, like new AzureOpenAI({ apiVersion: 'My API Version' }).\");\n }\n if (typeof azureADTokenProvider === 'function') {\n dangerouslyAllowBrowser = true;\n }\n if (!azureADTokenProvider && !apiKey) {\n throw new Errors.OpenAIError('Missing credentials. Please pass one of `apiKey` and `azureADTokenProvider`, or set the `AZURE_OPENAI_API_KEY` environment variable.');\n }\n if (azureADTokenProvider && apiKey) {\n throw new Errors.OpenAIError('The `apiKey` and `azureADTokenProvider` arguments are mutually exclusive; only one can be passed at a time.');\n }\n // define a sentinel value to avoid any typing issues\n apiKey ?? (apiKey = API_KEY_SENTINEL);\n opts.defaultQuery = { ...opts.defaultQuery, 'api-version': apiVersion };\n if (!baseURL) {\n if (!endpoint) {\n endpoint = process.env['AZURE_OPENAI_ENDPOINT'];\n }\n if (!endpoint) {\n throw new Errors.OpenAIError('Must provide one of the `baseURL` or `endpoint` arguments, or the `AZURE_OPENAI_ENDPOINT` environment variable');\n }\n baseURL = `${endpoint}/openai`;\n }\n else {\n if (endpoint) {\n throw new Errors.OpenAIError('baseURL and endpoint are mutually exclusive');\n }\n }\n super({\n apiKey,\n baseURL,\n ...opts,\n ...(dangerouslyAllowBrowser !== undefined ? { dangerouslyAllowBrowser } : {}),\n });\n this.apiVersion = '';\n this._azureADTokenProvider = azureADTokenProvider;\n this.apiVersion = apiVersion;\n this.deploymentName = deployment;\n }\n buildRequest(options, props = {}) {\n if (_deployments_endpoints.has(options.path) && options.method === 'post' && options.body !== undefined) {\n if (!Core.isObj(options.body)) {\n throw new Error('Expected request body to be an object');\n }\n const model = this.deploymentName || options.body['model'] || options.__metadata?.['model'];\n if (model !== undefined && !this.baseURL.includes('/deployments')) {\n options.path = `/deployments/${model}${options.path}`;\n }\n }\n return super.buildRequest(options, props);\n }\n async _getAzureADToken() {\n if (typeof this._azureADTokenProvider === 'function') {\n const token = await this._azureADTokenProvider();\n if (!token || typeof token !== 'string') {\n throw new Errors.OpenAIError(`Expected 'azureADTokenProvider' argument to return a string but it returned ${token}`);\n }\n return token;\n }\n return undefined;\n }\n authHeaders(opts) {\n return {};\n }\n async prepareOptions(opts) {\n /**\n * The user should provide a bearer token provider if they want\n * to use Azure AD authentication. The user shouldn't set the\n * Authorization header manually because the header is overwritten\n * with the Azure AD token if a bearer token provider is provided.\n */\n if (opts.headers?.['api-key']) {\n return super.prepareOptions(opts);\n }\n const token = await this._getAzureADToken();\n opts.headers ?? (opts.headers = {});\n if (token) {\n opts.headers['Authorization'] = `Bearer ${token}`;\n }\n else if (this.apiKey !== API_KEY_SENTINEL) {\n opts.headers['api-key'] = this.apiKey;\n }\n else {\n throw new Errors.OpenAIError('Unable to handle auth');\n }\n return super.prepareOptions(opts);\n }\n}\nconst _deployments_endpoints = new Set([\n '/completions',\n '/chat/completions',\n '/embeddings',\n '/audio/transcriptions',\n '/audio/translations',\n '/audio/speech',\n '/images/generations',\n]);\nconst API_KEY_SENTINEL = '';\nexport { toFile, fileFromPath } from \"./uploads.mjs\";\nexport { OpenAIError, APIError, APIConnectionError, APIConnectionTimeoutError, APIUserAbortError, NotFoundError, ConflictError, RateLimitError, BadRequestError, AuthenticationError, InternalServerError, PermissionDeniedError, UnprocessableEntityError, } from \"./error.mjs\";\nexport default OpenAI;\n//# sourceMappingURL=index.mjs.map","// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.\nimport { APIResource } from \"../../../resource.mjs\";\nimport { isRequestOptions } from \"../../../core.mjs\";\nimport { CursorPage } from \"../../../pagination.mjs\";\nexport class Messages extends APIResource {\n /**\n * Create a message.\n */\n create(threadId, body, options) {\n return this._client.post(`/threads/${threadId}/messages`, {\n body,\n ...options,\n headers: { 'OpenAI-Beta': 'assistants=v2', ...options?.headers },\n });\n }\n /**\n * Retrieve a message.\n */\n retrieve(threadId, messageId, options) {\n return this._client.get(`/threads/${threadId}/messages/${messageId}`, {\n ...options,\n headers: { 'OpenAI-Beta': 'assistants=v2', ...options?.headers },\n });\n }\n /**\n * Modifies a message.\n */\n update(threadId, messageId, body, options) {\n return this._client.post(`/threads/${threadId}/messages/${messageId}`, {\n body,\n ...options,\n headers: { 'OpenAI-Beta': 'assistants=v2', ...options?.headers },\n });\n }\n list(threadId, query = {}, options) {\n if (isRequestOptions(query)) {\n return this.list(threadId, {}, query);\n }\n return this._client.getAPIList(`/threads/${threadId}/messages`, MessagesPage, {\n query,\n ...options,\n headers: { 'OpenAI-Beta': 'assistants=v2', ...options?.headers },\n });\n }\n /**\n * Deletes a message.\n */\n del(threadId, messageId, options) {\n return this._client.delete(`/threads/${threadId}/messages/${messageId}`, {\n ...options,\n headers: { 'OpenAI-Beta': 'assistants=v2', ...options?.headers },\n });\n }\n}\nexport class MessagesPage extends CursorPage {\n}\nMessages.MessagesPage = MessagesPage;\n//# sourceMappingURL=messages.mjs.map","// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.\nimport { APIResource } from \"../../../../resource.mjs\";\nimport { isRequestOptions } from \"../../../../core.mjs\";\nimport { CursorPage } from \"../../../../pagination.mjs\";\nexport class Steps extends APIResource {\n retrieve(threadId, runId, stepId, query = {}, options) {\n if (isRequestOptions(query)) {\n return this.retrieve(threadId, runId, stepId, {}, query);\n }\n return this._client.get(`/threads/${threadId}/runs/${runId}/steps/${stepId}`, {\n query,\n ...options,\n headers: { 'OpenAI-Beta': 'assistants=v2', ...options?.headers },\n });\n }\n list(threadId, runId, query = {}, options) {\n if (isRequestOptions(query)) {\n return this.list(threadId, runId, {}, query);\n }\n return this._client.getAPIList(`/threads/${threadId}/runs/${runId}/steps`, RunStepsPage, {\n query,\n ...options,\n headers: { 'OpenAI-Beta': 'assistants=v2', ...options?.headers },\n });\n }\n}\nexport class RunStepsPage extends CursorPage {\n}\nSteps.RunStepsPage = RunStepsPage;\n//# sourceMappingURL=steps.mjs.map","// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.\nimport { APIResource } from \"../../../../resource.mjs\";\nimport { isRequestOptions } from \"../../../../core.mjs\";\nimport { AssistantStream } from \"../../../../lib/AssistantStream.mjs\";\nimport { sleep } from \"../../../../core.mjs\";\nimport * as StepsAPI from \"./steps.mjs\";\nimport { RunStepsPage, Steps, } from \"./steps.mjs\";\nimport { CursorPage } from \"../../../../pagination.mjs\";\nexport class Runs extends APIResource {\n constructor() {\n super(...arguments);\n this.steps = new StepsAPI.Steps(this._client);\n }\n create(threadId, params, options) {\n const { include, ...body } = params;\n return this._client.post(`/threads/${threadId}/runs`, {\n query: { include },\n body,\n ...options,\n headers: { 'OpenAI-Beta': 'assistants=v2', ...options?.headers },\n stream: params.stream ?? false,\n });\n }\n /**\n * Retrieves a run.\n */\n retrieve(threadId, runId, options) {\n return this._client.get(`/threads/${threadId}/runs/${runId}`, {\n ...options,\n headers: { 'OpenAI-Beta': 'assistants=v2', ...options?.headers },\n });\n }\n /**\n * Modifies a run.\n */\n update(threadId, runId, body, options) {\n return this._client.post(`/threads/${threadId}/runs/${runId}`, {\n body,\n ...options,\n headers: { 'OpenAI-Beta': 'assistants=v2', ...options?.headers },\n });\n }\n list(threadId, query = {}, options) {\n if (isRequestOptions(query)) {\n return this.list(threadId, {}, query);\n }\n return this._client.getAPIList(`/threads/${threadId}/runs`, RunsPage, {\n query,\n ...options,\n headers: { 'OpenAI-Beta': 'assistants=v2', ...options?.headers },\n });\n }\n /**\n * Cancels a run that is `in_progress`.\n */\n cancel(threadId, runId, options) {\n return this._client.post(`/threads/${threadId}/runs/${runId}/cancel`, {\n ...options,\n headers: { 'OpenAI-Beta': 'assistants=v2', ...options?.headers },\n });\n }\n /**\n * A helper to create a run an poll for a terminal state. More information on Run\n * lifecycles can be found here:\n * https://platform.openai.com/docs/assistants/how-it-works/runs-and-run-steps\n */\n async createAndPoll(threadId, body, options) {\n const run = await this.create(threadId, body, options);\n return await this.poll(threadId, run.id, options);\n }\n /**\n * Create a Run stream\n *\n * @deprecated use `stream` instead\n */\n createAndStream(threadId, body, options) {\n return AssistantStream.createAssistantStream(threadId, this._client.beta.threads.runs, body, options);\n }\n /**\n * A helper to poll a run status until it reaches a terminal state. More\n * information on Run lifecycles can be found here:\n * https://platform.openai.com/docs/assistants/how-it-works/runs-and-run-steps\n */\n async poll(threadId, runId, options) {\n const headers = { ...options?.headers, 'X-Stainless-Poll-Helper': 'true' };\n if (options?.pollIntervalMs) {\n headers['X-Stainless-Custom-Poll-Interval'] = options.pollIntervalMs.toString();\n }\n while (true) {\n const { data: run, response } = await this.retrieve(threadId, runId, {\n ...options,\n headers: { ...options?.headers, ...headers },\n }).withResponse();\n switch (run.status) {\n //If we are in any sort of intermediate state we poll\n case 'queued':\n case 'in_progress':\n case 'cancelling':\n let sleepInterval = 5000;\n if (options?.pollIntervalMs) {\n sleepInterval = options.pollIntervalMs;\n }\n else {\n const headerInterval = response.headers.get('openai-poll-after-ms');\n if (headerInterval) {\n const headerIntervalMs = parseInt(headerInterval);\n if (!isNaN(headerIntervalMs)) {\n sleepInterval = headerIntervalMs;\n }\n }\n }\n await sleep(sleepInterval);\n break;\n //We return the run in any terminal state.\n case 'requires_action':\n case 'incomplete':\n case 'cancelled':\n case 'completed':\n case 'failed':\n case 'expired':\n return run;\n }\n }\n }\n /**\n * Create a Run stream\n */\n stream(threadId, body, options) {\n return AssistantStream.createAssistantStream(threadId, this._client.beta.threads.runs, body, options);\n }\n submitToolOutputs(threadId, runId, body, options) {\n return this._client.post(`/threads/${threadId}/runs/${runId}/submit_tool_outputs`, {\n body,\n ...options,\n headers: { 'OpenAI-Beta': 'assistants=v2', ...options?.headers },\n stream: body.stream ?? false,\n });\n }\n /**\n * A helper to submit a tool output to a run and poll for a terminal run state.\n * More information on Run lifecycles can be found here:\n * https://platform.openai.com/docs/assistants/how-it-works/runs-and-run-steps\n */\n async submitToolOutputsAndPoll(threadId, runId, body, options) {\n const run = await this.submitToolOutputs(threadId, runId, body, options);\n return await this.poll(threadId, run.id, options);\n }\n /**\n * Submit the tool outputs from a previous run and stream the run to a terminal\n * state. More information on Run lifecycles can be found here:\n * https://platform.openai.com/docs/assistants/how-it-works/runs-and-run-steps\n */\n submitToolOutputsStream(threadId, runId, body, options) {\n return AssistantStream.createToolAssistantStream(threadId, runId, this._client.beta.threads.runs, body, options);\n }\n}\nexport class RunsPage extends CursorPage {\n}\nRuns.RunsPage = RunsPage;\nRuns.Steps = Steps;\nRuns.RunStepsPage = RunStepsPage;\n//# sourceMappingURL=runs.mjs.map","// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.\nimport { APIResource } from \"../../../resource.mjs\";\nimport { isRequestOptions } from \"../../../core.mjs\";\nimport { AssistantStream } from \"../../../lib/AssistantStream.mjs\";\nimport * as MessagesAPI from \"./messages.mjs\";\nimport { Messages, MessagesPage, } from \"./messages.mjs\";\nimport * as RunsAPI from \"./runs/runs.mjs\";\nimport { Runs, RunsPage, } from \"./runs/runs.mjs\";\nexport class Threads extends APIResource {\n constructor() {\n super(...arguments);\n this.runs = new RunsAPI.Runs(this._client);\n this.messages = new MessagesAPI.Messages(this._client);\n }\n create(body = {}, options) {\n if (isRequestOptions(body)) {\n return this.create({}, body);\n }\n return this._client.post('/threads', {\n body,\n ...options,\n headers: { 'OpenAI-Beta': 'assistants=v2', ...options?.headers },\n });\n }\n /**\n * Retrieves a thread.\n */\n retrieve(threadId, options) {\n return this._client.get(`/threads/${threadId}`, {\n ...options,\n headers: { 'OpenAI-Beta': 'assistants=v2', ...options?.headers },\n });\n }\n /**\n * Modifies a thread.\n */\n update(threadId, body, options) {\n return this._client.post(`/threads/${threadId}`, {\n body,\n ...options,\n headers: { 'OpenAI-Beta': 'assistants=v2', ...options?.headers },\n });\n }\n /**\n * Delete a thread.\n */\n del(threadId, options) {\n return this._client.delete(`/threads/${threadId}`, {\n ...options,\n headers: { 'OpenAI-Beta': 'assistants=v2', ...options?.headers },\n });\n }\n createAndRun(body, options) {\n return this._client.post('/threads/runs', {\n body,\n ...options,\n headers: { 'OpenAI-Beta': 'assistants=v2', ...options?.headers },\n stream: body.stream ?? false,\n });\n }\n /**\n * A helper to create a thread, start a run and then poll for a terminal state.\n * More information on Run lifecycles can be found here:\n * https://platform.openai.com/docs/assistants/how-it-works/runs-and-run-steps\n */\n async createAndRunPoll(body, options) {\n const run = await this.createAndRun(body, options);\n return await this.runs.poll(run.thread_id, run.id, options);\n }\n /**\n * Create a thread and stream the run back\n */\n createAndRunStream(body, options) {\n return AssistantStream.createThreadAssistantStream(body, this._client.beta.threads, options);\n }\n}\nThreads.Runs = Runs;\nThreads.RunsPage = RunsPage;\nThreads.Messages = Messages;\nThreads.MessagesPage = MessagesPage;\n//# sourceMappingURL=threads.mjs.map","// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.\nimport { APIResource } from \"../../../resource.mjs\";\nimport { sleep, isRequestOptions } from \"../../../core.mjs\";\nimport { CursorPage } from \"../../../pagination.mjs\";\nexport class Files extends APIResource {\n /**\n * Create a vector store file by attaching a\n * [File](https://platform.openai.com/docs/api-reference/files) to a\n * [vector store](https://platform.openai.com/docs/api-reference/vector-stores/object).\n */\n create(vectorStoreId, body, options) {\n return this._client.post(`/vector_stores/${vectorStoreId}/files`, {\n body,\n ...options,\n headers: { 'OpenAI-Beta': 'assistants=v2', ...options?.headers },\n });\n }\n /**\n * Retrieves a vector store file.\n */\n retrieve(vectorStoreId, fileId, options) {\n return this._client.get(`/vector_stores/${vectorStoreId}/files/${fileId}`, {\n ...options,\n headers: { 'OpenAI-Beta': 'assistants=v2', ...options?.headers },\n });\n }\n list(vectorStoreId, query = {}, options) {\n if (isRequestOptions(query)) {\n return this.list(vectorStoreId, {}, query);\n }\n return this._client.getAPIList(`/vector_stores/${vectorStoreId}/files`, VectorStoreFilesPage, {\n query,\n ...options,\n headers: { 'OpenAI-Beta': 'assistants=v2', ...options?.headers },\n });\n }\n /**\n * Delete a vector store file. This will remove the file from the vector store but\n * the file itself will not be deleted. To delete the file, use the\n * [delete file](https://platform.openai.com/docs/api-reference/files/delete)\n * endpoint.\n */\n del(vectorStoreId, fileId, options) {\n return this._client.delete(`/vector_stores/${vectorStoreId}/files/${fileId}`, {\n ...options,\n headers: { 'OpenAI-Beta': 'assistants=v2', ...options?.headers },\n });\n }\n /**\n * Attach a file to the given vector store and wait for it to be processed.\n */\n async createAndPoll(vectorStoreId, body, options) {\n const file = await this.create(vectorStoreId, body, options);\n return await this.poll(vectorStoreId, file.id, options);\n }\n /**\n * Wait for the vector store file to finish processing.\n *\n * Note: this will return even if the file failed to process, you need to check\n * file.last_error and file.status to handle these cases\n */\n async poll(vectorStoreId, fileId, options) {\n const headers = { ...options?.headers, 'X-Stainless-Poll-Helper': 'true' };\n if (options?.pollIntervalMs) {\n headers['X-Stainless-Custom-Poll-Interval'] = options.pollIntervalMs.toString();\n }\n while (true) {\n const fileResponse = await this.retrieve(vectorStoreId, fileId, {\n ...options,\n headers,\n }).withResponse();\n const file = fileResponse.data;\n switch (file.status) {\n case 'in_progress':\n let sleepInterval = 5000;\n if (options?.pollIntervalMs) {\n sleepInterval = options.pollIntervalMs;\n }\n else {\n const headerInterval = fileResponse.response.headers.get('openai-poll-after-ms');\n if (headerInterval) {\n const headerIntervalMs = parseInt(headerInterval);\n if (!isNaN(headerIntervalMs)) {\n sleepInterval = headerIntervalMs;\n }\n }\n }\n await sleep(sleepInterval);\n break;\n case 'failed':\n case 'completed':\n return file;\n }\n }\n }\n /**\n * Upload a file to the `files` API and then attach it to the given vector store.\n *\n * Note the file will be asynchronously processed (you can use the alternative\n * polling helper method to wait for processing to complete).\n */\n async upload(vectorStoreId, file, options) {\n const fileInfo = await this._client.files.create({ file: file, purpose: 'assistants' }, options);\n return this.create(vectorStoreId, { file_id: fileInfo.id }, options);\n }\n /**\n * Add a file to a vector store and poll until processing is complete.\n */\n async uploadAndPoll(vectorStoreId, file, options) {\n const fileInfo = await this.upload(vectorStoreId, file, options);\n return await this.poll(vectorStoreId, fileInfo.id, options);\n }\n}\nexport class VectorStoreFilesPage extends CursorPage {\n}\nFiles.VectorStoreFilesPage = VectorStoreFilesPage;\n//# sourceMappingURL=files.mjs.map","// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.\nimport { APIResource } from \"../../../resource.mjs\";\nimport { isRequestOptions } from \"../../../core.mjs\";\nimport { sleep } from \"../../../core.mjs\";\nimport { allSettledWithThrow } from \"../../../lib/Util.mjs\";\nimport { VectorStoreFilesPage } from \"./files.mjs\";\nexport class FileBatches extends APIResource {\n /**\n * Create a vector store file batch.\n */\n create(vectorStoreId, body, options) {\n return this._client.post(`/vector_stores/${vectorStoreId}/file_batches`, {\n body,\n ...options,\n headers: { 'OpenAI-Beta': 'assistants=v2', ...options?.headers },\n });\n }\n /**\n * Retrieves a vector store file batch.\n */\n retrieve(vectorStoreId, batchId, options) {\n return this._client.get(`/vector_stores/${vectorStoreId}/file_batches/${batchId}`, {\n ...options,\n headers: { 'OpenAI-Beta': 'assistants=v2', ...options?.headers },\n });\n }\n /**\n * Cancel a vector store file batch. This attempts to cancel the processing of\n * files in this batch as soon as possible.\n */\n cancel(vectorStoreId, batchId, options) {\n return this._client.post(`/vector_stores/${vectorStoreId}/file_batches/${batchId}/cancel`, {\n ...options,\n headers: { 'OpenAI-Beta': 'assistants=v2', ...options?.headers },\n });\n }\n /**\n * Create a vector store batch and poll until all files have been processed.\n */\n async createAndPoll(vectorStoreId, body, options) {\n const batch = await this.create(vectorStoreId, body);\n return await this.poll(vectorStoreId, batch.id, options);\n }\n listFiles(vectorStoreId, batchId, query = {}, options) {\n if (isRequestOptions(query)) {\n return this.listFiles(vectorStoreId, batchId, {}, query);\n }\n return this._client.getAPIList(`/vector_stores/${vectorStoreId}/file_batches/${batchId}/files`, VectorStoreFilesPage, { query, ...options, headers: { 'OpenAI-Beta': 'assistants=v2', ...options?.headers } });\n }\n /**\n * Wait for the given file batch to be processed.\n *\n * Note: this will return even if one of the files failed to process, you need to\n * check batch.file_counts.failed_count to handle this case.\n */\n async poll(vectorStoreId, batchId, options) {\n const headers = { ...options?.headers, 'X-Stainless-Poll-Helper': 'true' };\n if (options?.pollIntervalMs) {\n headers['X-Stainless-Custom-Poll-Interval'] = options.pollIntervalMs.toString();\n }\n while (true) {\n const { data: batch, response } = await this.retrieve(vectorStoreId, batchId, {\n ...options,\n headers,\n }).withResponse();\n switch (batch.status) {\n case 'in_progress':\n let sleepInterval = 5000;\n if (options?.pollIntervalMs) {\n sleepInterval = options.pollIntervalMs;\n }\n else {\n const headerInterval = response.headers.get('openai-poll-after-ms');\n if (headerInterval) {\n const headerIntervalMs = parseInt(headerInterval);\n if (!isNaN(headerIntervalMs)) {\n sleepInterval = headerIntervalMs;\n }\n }\n }\n await sleep(sleepInterval);\n break;\n case 'failed':\n case 'cancelled':\n case 'completed':\n return batch;\n }\n }\n }\n /**\n * Uploads the given files concurrently and then creates a vector store file batch.\n *\n * The concurrency limit is configurable using the `maxConcurrency` parameter.\n */\n async uploadAndPoll(vectorStoreId, { files, fileIds = [] }, options) {\n if (files == null || files.length == 0) {\n throw new Error(`No \\`files\\` provided to process. If you've already uploaded files you should use \\`.createAndPoll()\\` instead`);\n }\n const configuredConcurrency = options?.maxConcurrency ?? 5;\n // We cap the number of workers at the number of files (so we don't start any unnecessary workers)\n const concurrencyLimit = Math.min(configuredConcurrency, files.length);\n const client = this._client;\n const fileIterator = files.values();\n const allFileIds = [...fileIds];\n // This code is based on this design. The libraries don't accommodate our environment limits.\n // https://stackoverflow.com/questions/40639432/what-is-the-best-way-to-limit-concurrency-when-using-es6s-promise-all\n async function processFiles(iterator) {\n for (let item of iterator) {\n const fileObj = await client.files.create({ file: item, purpose: 'assistants' }, options);\n allFileIds.push(fileObj.id);\n }\n }\n // Start workers to process results\n const workers = Array(concurrencyLimit).fill(fileIterator).map(processFiles);\n // Wait for all processing to complete.\n await allSettledWithThrow(workers);\n return await this.createAndPoll(vectorStoreId, {\n file_ids: allFileIds,\n });\n }\n}\nexport { VectorStoreFilesPage };\n//# sourceMappingURL=file-batches.mjs.map","/**\n * Like `Promise.allSettled()` but throws an error if any promises are rejected.\n */\nexport const allSettledWithThrow = async (promises) => {\n const results = await Promise.allSettled(promises);\n const rejected = results.filter((result) => result.status === 'rejected');\n if (rejected.length) {\n for (const result of rejected) {\n console.error(result.reason);\n }\n throw new Error(`${rejected.length} promise(s) failed - see the above errors`);\n }\n // Note: TS was complaining about using `.filter().map()` here for some reason\n const values = [];\n for (const result of results) {\n if (result.status === 'fulfilled') {\n values.push(result.value);\n }\n }\n return values;\n};\n//# sourceMappingURL=Util.mjs.map","// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.\nimport { APIResource } from \"../../../resource.mjs\";\nimport { isRequestOptions } from \"../../../core.mjs\";\nimport * as FileBatchesAPI from \"./file-batches.mjs\";\nimport { FileBatches, } from \"./file-batches.mjs\";\nimport * as FilesAPI from \"./files.mjs\";\nimport { Files, VectorStoreFilesPage, } from \"./files.mjs\";\nimport { CursorPage } from \"../../../pagination.mjs\";\nexport class VectorStores extends APIResource {\n constructor() {\n super(...arguments);\n this.files = new FilesAPI.Files(this._client);\n this.fileBatches = new FileBatchesAPI.FileBatches(this._client);\n }\n /**\n * Create a vector store.\n */\n create(body, options) {\n return this._client.post('/vector_stores', {\n body,\n ...options,\n headers: { 'OpenAI-Beta': 'assistants=v2', ...options?.headers },\n });\n }\n /**\n * Retrieves a vector store.\n */\n retrieve(vectorStoreId, options) {\n return this._client.get(`/vector_stores/${vectorStoreId}`, {\n ...options,\n headers: { 'OpenAI-Beta': 'assistants=v2', ...options?.headers },\n });\n }\n /**\n * Modifies a vector store.\n */\n update(vectorStoreId, body, options) {\n return this._client.post(`/vector_stores/${vectorStoreId}`, {\n body,\n ...options,\n headers: { 'OpenAI-Beta': 'assistants=v2', ...options?.headers },\n });\n }\n list(query = {}, options) {\n if (isRequestOptions(query)) {\n return this.list({}, query);\n }\n return this._client.getAPIList('/vector_stores', VectorStoresPage, {\n query,\n ...options,\n headers: { 'OpenAI-Beta': 'assistants=v2', ...options?.headers },\n });\n }\n /**\n * Delete a vector store.\n */\n del(vectorStoreId, options) {\n return this._client.delete(`/vector_stores/${vectorStoreId}`, {\n ...options,\n headers: { 'OpenAI-Beta': 'assistants=v2', ...options?.headers },\n });\n }\n}\nexport class VectorStoresPage extends CursorPage {\n}\nVectorStores.VectorStoresPage = VectorStoresPage;\nVectorStores.Files = Files;\nVectorStores.VectorStoreFilesPage = VectorStoreFilesPage;\nVectorStores.FileBatches = FileBatches;\n//# sourceMappingURL=vector-stores.mjs.map","// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.\nimport { APIResource } from \"../../resource.mjs\";\nimport * as AssistantsAPI from \"./assistants.mjs\";\nimport * as ChatAPI from \"./chat/chat.mjs\";\nimport { Assistants, AssistantsPage, } from \"./assistants.mjs\";\nimport * as RealtimeAPI from \"./realtime/realtime.mjs\";\nimport { Realtime } from \"./realtime/realtime.mjs\";\nimport * as ThreadsAPI from \"./threads/threads.mjs\";\nimport { Threads, } from \"./threads/threads.mjs\";\nimport * as VectorStoresAPI from \"./vector-stores/vector-stores.mjs\";\nimport { VectorStores, VectorStoresPage, } from \"./vector-stores/vector-stores.mjs\";\nimport { Chat } from \"./chat/chat.mjs\";\nexport class Beta extends APIResource {\n constructor() {\n super(...arguments);\n this.realtime = new RealtimeAPI.Realtime(this._client);\n this.vectorStores = new VectorStoresAPI.VectorStores(this._client);\n this.chat = new ChatAPI.Chat(this._client);\n this.assistants = new AssistantsAPI.Assistants(this._client);\n this.threads = new ThreadsAPI.Threads(this._client);\n }\n}\nBeta.Realtime = Realtime;\nBeta.VectorStores = VectorStores;\nBeta.VectorStoresPage = VectorStoresPage;\nBeta.Assistants = Assistants;\nBeta.AssistantsPage = AssistantsPage;\nBeta.Threads = Threads;\n//# sourceMappingURL=beta.mjs.map","// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.\nimport { APIResource } from \"../resource.mjs\";\nimport { isRequestOptions } from \"../core.mjs\";\nimport { CursorPage } from \"../pagination.mjs\";\nexport class Batches extends APIResource {\n /**\n * Creates and executes a batch from an uploaded file of requests\n */\n create(body, options) {\n return this._client.post('/batches', { body, ...options });\n }\n /**\n * Retrieves a batch.\n */\n retrieve(batchId, options) {\n return this._client.get(`/batches/${batchId}`, options);\n }\n list(query = {}, options) {\n if (isRequestOptions(query)) {\n return this.list({}, query);\n }\n return this._client.getAPIList('/batches', BatchesPage, { query, ...options });\n }\n /**\n * Cancels an in-progress batch. The batch will be in status `cancelling` for up to\n * 10 minutes, before changing to `cancelled`, where it will have partial results\n * (if any) available in the output file.\n */\n cancel(batchId, options) {\n return this._client.post(`/batches/${batchId}/cancel`, options);\n }\n}\nexport class BatchesPage extends CursorPage {\n}\nBatches.BatchesPage = BatchesPage;\n//# sourceMappingURL=batches.mjs.map","// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.\nimport { APIResource } from \"../../resource.mjs\";\nimport * as Core from \"../../core.mjs\";\nexport class Parts extends APIResource {\n /**\n * Adds a\n * [Part](https://platform.openai.com/docs/api-reference/uploads/part-object) to an\n * [Upload](https://platform.openai.com/docs/api-reference/uploads/object) object.\n * A Part represents a chunk of bytes from the file you are trying to upload.\n *\n * Each Part can be at most 64 MB, and you can add Parts until you hit the Upload\n * maximum of 8 GB.\n *\n * It is possible to add multiple Parts in parallel. You can decide the intended\n * order of the Parts when you\n * [complete the Upload](https://platform.openai.com/docs/api-reference/uploads/complete).\n */\n create(uploadId, body, options) {\n return this._client.post(`/uploads/${uploadId}/parts`, Core.multipartFormRequestOptions({ body, ...options }));\n }\n}\n//# sourceMappingURL=parts.mjs.map","// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.\nimport { APIResource } from \"../../resource.mjs\";\nimport * as PartsAPI from \"./parts.mjs\";\nimport { Parts } from \"./parts.mjs\";\nexport class Uploads extends APIResource {\n constructor() {\n super(...arguments);\n this.parts = new PartsAPI.Parts(this._client);\n }\n /**\n * Creates an intermediate\n * [Upload](https://platform.openai.com/docs/api-reference/uploads/object) object\n * that you can add\n * [Parts](https://platform.openai.com/docs/api-reference/uploads/part-object) to.\n * Currently, an Upload can accept at most 8 GB in total and expires after an hour\n * after you create it.\n *\n * Once you complete the Upload, we will create a\n * [File](https://platform.openai.com/docs/api-reference/files/object) object that\n * contains all the parts you uploaded. This File is usable in the rest of our\n * platform as a regular File object.\n *\n * For certain `purpose`s, the correct `mime_type` must be specified. Please refer\n * to documentation for the supported MIME types for your use case:\n *\n * - [Assistants](https://platform.openai.com/docs/assistants/tools/file-search#supported-files)\n *\n * For guidance on the proper filename extensions for each purpose, please follow\n * the documentation on\n * [creating a File](https://platform.openai.com/docs/api-reference/files/create).\n */\n create(body, options) {\n return this._client.post('/uploads', { body, ...options });\n }\n /**\n * Cancels the Upload. No Parts may be added after an Upload is cancelled.\n */\n cancel(uploadId, options) {\n return this._client.post(`/uploads/${uploadId}/cancel`, options);\n }\n /**\n * Completes the\n * [Upload](https://platform.openai.com/docs/api-reference/uploads/object).\n *\n * Within the returned Upload object, there is a nested\n * [File](https://platform.openai.com/docs/api-reference/files/object) object that\n * is ready to use in the rest of the platform.\n *\n * You can specify the order of the Parts by passing in an ordered list of the Part\n * IDs.\n *\n * The number of bytes uploaded upon completion must match the number of bytes\n * initially specified when creating the Upload object. No Parts may be added after\n * an Upload is completed.\n */\n complete(uploadId, body, options) {\n return this._client.post(`/uploads/${uploadId}/complete`, { body, ...options });\n }\n}\nUploads.Parts = Parts;\n//# sourceMappingURL=uploads.mjs.map","/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * @fileoverview Firebase constants. Some of these (@defines) can be overridden at compile-time.\r\n */\r\nconst CONSTANTS = {\r\n /**\r\n * @define {boolean} Whether this is the client Node.js SDK.\r\n */\r\n NODE_CLIENT: false,\r\n /**\r\n * @define {boolean} Whether this is the Admin Node.js SDK.\r\n */\r\n NODE_ADMIN: false,\r\n /**\r\n * Firebase SDK Version\r\n */\r\n SDK_VERSION: '${JSCORE_VERSION}'\r\n};\n\n/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Throws an error if the provided assertion is falsy\r\n */\r\nconst assert = function (assertion, message) {\r\n if (!assertion) {\r\n throw assertionError(message);\r\n }\r\n};\r\n/**\r\n * Returns an Error object suitable for throwing.\r\n */\r\nconst assertionError = function (message) {\r\n return new Error('Firebase Database (' +\r\n CONSTANTS.SDK_VERSION +\r\n ') INTERNAL ASSERT FAILED: ' +\r\n message);\r\n};\n\n/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nconst stringToByteArray$1 = function (str) {\r\n // TODO(user): Use native implementations if/when available\r\n const out = [];\r\n let p = 0;\r\n for (let i = 0; i < str.length; i++) {\r\n let c = str.charCodeAt(i);\r\n if (c < 128) {\r\n out[p++] = c;\r\n }\r\n else if (c < 2048) {\r\n out[p++] = (c >> 6) | 192;\r\n out[p++] = (c & 63) | 128;\r\n }\r\n else if ((c & 0xfc00) === 0xd800 &&\r\n i + 1 < str.length &&\r\n (str.charCodeAt(i + 1) & 0xfc00) === 0xdc00) {\r\n // Surrogate Pair\r\n c = 0x10000 + ((c & 0x03ff) << 10) + (str.charCodeAt(++i) & 0x03ff);\r\n out[p++] = (c >> 18) | 240;\r\n out[p++] = ((c >> 12) & 63) | 128;\r\n out[p++] = ((c >> 6) & 63) | 128;\r\n out[p++] = (c & 63) | 128;\r\n }\r\n else {\r\n out[p++] = (c >> 12) | 224;\r\n out[p++] = ((c >> 6) & 63) | 128;\r\n out[p++] = (c & 63) | 128;\r\n }\r\n }\r\n return out;\r\n};\r\n/**\r\n * Turns an array of numbers into the string given by the concatenation of the\r\n * characters to which the numbers correspond.\r\n * @param bytes Array of numbers representing characters.\r\n * @return Stringification of the array.\r\n */\r\nconst byteArrayToString = function (bytes) {\r\n // TODO(user): Use native implementations if/when available\r\n const out = [];\r\n let pos = 0, c = 0;\r\n while (pos < bytes.length) {\r\n const c1 = bytes[pos++];\r\n if (c1 < 128) {\r\n out[c++] = String.fromCharCode(c1);\r\n }\r\n else if (c1 > 191 && c1 < 224) {\r\n const c2 = bytes[pos++];\r\n out[c++] = String.fromCharCode(((c1 & 31) << 6) | (c2 & 63));\r\n }\r\n else if (c1 > 239 && c1 < 365) {\r\n // Surrogate Pair\r\n const c2 = bytes[pos++];\r\n const c3 = bytes[pos++];\r\n const c4 = bytes[pos++];\r\n const u = (((c1 & 7) << 18) | ((c2 & 63) << 12) | ((c3 & 63) << 6) | (c4 & 63)) -\r\n 0x10000;\r\n out[c++] = String.fromCharCode(0xd800 + (u >> 10));\r\n out[c++] = String.fromCharCode(0xdc00 + (u & 1023));\r\n }\r\n else {\r\n const c2 = bytes[pos++];\r\n const c3 = bytes[pos++];\r\n out[c++] = String.fromCharCode(((c1 & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));\r\n }\r\n }\r\n return out.join('');\r\n};\r\n// We define it as an object literal instead of a class because a class compiled down to es5 can't\r\n// be treeshaked. https://github.com/rollup/rollup/issues/1691\r\n// Static lookup maps, lazily populated by init_()\r\nconst base64 = {\r\n /**\r\n * Maps bytes to characters.\r\n */\r\n byteToCharMap_: null,\r\n /**\r\n * Maps characters to bytes.\r\n */\r\n charToByteMap_: null,\r\n /**\r\n * Maps bytes to websafe characters.\r\n * @private\r\n */\r\n byteToCharMapWebSafe_: null,\r\n /**\r\n * Maps websafe characters to bytes.\r\n * @private\r\n */\r\n charToByteMapWebSafe_: null,\r\n /**\r\n * Our default alphabet, shared between\r\n * ENCODED_VALS and ENCODED_VALS_WEBSAFE\r\n */\r\n ENCODED_VALS_BASE: 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' + 'abcdefghijklmnopqrstuvwxyz' + '0123456789',\r\n /**\r\n * Our default alphabet. Value 64 (=) is special; it means \"nothing.\"\r\n */\r\n get ENCODED_VALS() {\r\n return this.ENCODED_VALS_BASE + '+/=';\r\n },\r\n /**\r\n * Our websafe alphabet.\r\n */\r\n get ENCODED_VALS_WEBSAFE() {\r\n return this.ENCODED_VALS_BASE + '-_.';\r\n },\r\n /**\r\n * Whether this browser supports the atob and btoa functions. This extension\r\n * started at Mozilla but is now implemented by many browsers. We use the\r\n * ASSUME_* variables to avoid pulling in the full useragent detection library\r\n * but still allowing the standard per-browser compilations.\r\n *\r\n */\r\n HAS_NATIVE_SUPPORT: typeof atob === 'function',\r\n /**\r\n * Base64-encode an array of bytes.\r\n *\r\n * @param input An array of bytes (numbers with\r\n * value in [0, 255]) to encode.\r\n * @param webSafe Boolean indicating we should use the\r\n * alternative alphabet.\r\n * @return The base64 encoded string.\r\n */\r\n encodeByteArray(input, webSafe) {\r\n if (!Array.isArray(input)) {\r\n throw Error('encodeByteArray takes an array as a parameter');\r\n }\r\n this.init_();\r\n const byteToCharMap = webSafe\r\n ? this.byteToCharMapWebSafe_\r\n : this.byteToCharMap_;\r\n const output = [];\r\n for (let i = 0; i < input.length; i += 3) {\r\n const byte1 = input[i];\r\n const haveByte2 = i + 1 < input.length;\r\n const byte2 = haveByte2 ? input[i + 1] : 0;\r\n const haveByte3 = i + 2 < input.length;\r\n const byte3 = haveByte3 ? input[i + 2] : 0;\r\n const outByte1 = byte1 >> 2;\r\n const outByte2 = ((byte1 & 0x03) << 4) | (byte2 >> 4);\r\n let outByte3 = ((byte2 & 0x0f) << 2) | (byte3 >> 6);\r\n let outByte4 = byte3 & 0x3f;\r\n if (!haveByte3) {\r\n outByte4 = 64;\r\n if (!haveByte2) {\r\n outByte3 = 64;\r\n }\r\n }\r\n output.push(byteToCharMap[outByte1], byteToCharMap[outByte2], byteToCharMap[outByte3], byteToCharMap[outByte4]);\r\n }\r\n return output.join('');\r\n },\r\n /**\r\n * Base64-encode a string.\r\n *\r\n * @param input A string to encode.\r\n * @param webSafe If true, we should use the\r\n * alternative alphabet.\r\n * @return The base64 encoded string.\r\n */\r\n encodeString(input, webSafe) {\r\n // Shortcut for Mozilla browsers that implement\r\n // a native base64 encoder in the form of \"btoa/atob\"\r\n if (this.HAS_NATIVE_SUPPORT && !webSafe) {\r\n return btoa(input);\r\n }\r\n return this.encodeByteArray(stringToByteArray$1(input), webSafe);\r\n },\r\n /**\r\n * Base64-decode a string.\r\n *\r\n * @param input to decode.\r\n * @param webSafe True if we should use the\r\n * alternative alphabet.\r\n * @return string representing the decoded value.\r\n */\r\n decodeString(input, webSafe) {\r\n // Shortcut for Mozilla browsers that implement\r\n // a native base64 encoder in the form of \"btoa/atob\"\r\n if (this.HAS_NATIVE_SUPPORT && !webSafe) {\r\n return atob(input);\r\n }\r\n return byteArrayToString(this.decodeStringToByteArray(input, webSafe));\r\n },\r\n /**\r\n * Base64-decode a string.\r\n *\r\n * In base-64 decoding, groups of four characters are converted into three\r\n * bytes. If the encoder did not apply padding, the input length may not\r\n * be a multiple of 4.\r\n *\r\n * In this case, the last group will have fewer than 4 characters, and\r\n * padding will be inferred. If the group has one or two characters, it decodes\r\n * to one byte. If the group has three characters, it decodes to two bytes.\r\n *\r\n * @param input Input to decode.\r\n * @param webSafe True if we should use the web-safe alphabet.\r\n * @return bytes representing the decoded value.\r\n */\r\n decodeStringToByteArray(input, webSafe) {\r\n this.init_();\r\n const charToByteMap = webSafe\r\n ? this.charToByteMapWebSafe_\r\n : this.charToByteMap_;\r\n const output = [];\r\n for (let i = 0; i < input.length;) {\r\n const byte1 = charToByteMap[input.charAt(i++)];\r\n const haveByte2 = i < input.length;\r\n const byte2 = haveByte2 ? charToByteMap[input.charAt(i)] : 0;\r\n ++i;\r\n const haveByte3 = i < input.length;\r\n const byte3 = haveByte3 ? charToByteMap[input.charAt(i)] : 64;\r\n ++i;\r\n const haveByte4 = i < input.length;\r\n const byte4 = haveByte4 ? charToByteMap[input.charAt(i)] : 64;\r\n ++i;\r\n if (byte1 == null || byte2 == null || byte3 == null || byte4 == null) {\r\n throw new DecodeBase64StringError();\r\n }\r\n const outByte1 = (byte1 << 2) | (byte2 >> 4);\r\n output.push(outByte1);\r\n if (byte3 !== 64) {\r\n const outByte2 = ((byte2 << 4) & 0xf0) | (byte3 >> 2);\r\n output.push(outByte2);\r\n if (byte4 !== 64) {\r\n const outByte3 = ((byte3 << 6) & 0xc0) | byte4;\r\n output.push(outByte3);\r\n }\r\n }\r\n }\r\n return output;\r\n },\r\n /**\r\n * Lazy static initialization function. Called before\r\n * accessing any of the static map variables.\r\n * @private\r\n */\r\n init_() {\r\n if (!this.byteToCharMap_) {\r\n this.byteToCharMap_ = {};\r\n this.charToByteMap_ = {};\r\n this.byteToCharMapWebSafe_ = {};\r\n this.charToByteMapWebSafe_ = {};\r\n // We want quick mappings back and forth, so we precompute two maps.\r\n for (let i = 0; i < this.ENCODED_VALS.length; i++) {\r\n this.byteToCharMap_[i] = this.ENCODED_VALS.charAt(i);\r\n this.charToByteMap_[this.byteToCharMap_[i]] = i;\r\n this.byteToCharMapWebSafe_[i] = this.ENCODED_VALS_WEBSAFE.charAt(i);\r\n this.charToByteMapWebSafe_[this.byteToCharMapWebSafe_[i]] = i;\r\n // Be forgiving when decoding and correctly decode both encodings.\r\n if (i >= this.ENCODED_VALS_BASE.length) {\r\n this.charToByteMap_[this.ENCODED_VALS_WEBSAFE.charAt(i)] = i;\r\n this.charToByteMapWebSafe_[this.ENCODED_VALS.charAt(i)] = i;\r\n }\r\n }\r\n }\r\n }\r\n};\r\n/**\r\n * An error encountered while decoding base64 string.\r\n */\r\nclass DecodeBase64StringError extends Error {\r\n constructor() {\r\n super(...arguments);\r\n this.name = 'DecodeBase64StringError';\r\n }\r\n}\r\n/**\r\n * URL-safe base64 encoding\r\n */\r\nconst base64Encode = function (str) {\r\n const utf8Bytes = stringToByteArray$1(str);\r\n return base64.encodeByteArray(utf8Bytes, true);\r\n};\r\n/**\r\n * URL-safe base64 encoding (without \".\" padding in the end).\r\n * e.g. Used in JSON Web Token (JWT) parts.\r\n */\r\nconst base64urlEncodeWithoutPadding = function (str) {\r\n // Use base64url encoding and remove padding in the end (dot characters).\r\n return base64Encode(str).replace(/\\./g, '');\r\n};\r\n/**\r\n * URL-safe base64 decoding\r\n *\r\n * NOTE: DO NOT use the global atob() function - it does NOT support the\r\n * base64Url variant encoding.\r\n *\r\n * @param str To be decoded\r\n * @return Decoded result, if possible\r\n */\r\nconst base64Decode = function (str) {\r\n try {\r\n return base64.decodeString(str, true);\r\n }\r\n catch (e) {\r\n console.error('base64Decode failed: ', e);\r\n }\r\n return null;\r\n};\n\n/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Do a deep-copy of basic JavaScript Objects or Arrays.\r\n */\r\nfunction deepCopy(value) {\r\n return deepExtend(undefined, value);\r\n}\r\n/**\r\n * Copy properties from source to target (recursively allows extension\r\n * of Objects and Arrays). Scalar values in the target are over-written.\r\n * If target is undefined, an object of the appropriate type will be created\r\n * (and returned).\r\n *\r\n * We recursively copy all child properties of plain Objects in the source- so\r\n * that namespace- like dictionaries are merged.\r\n *\r\n * Note that the target can be a function, in which case the properties in\r\n * the source Object are copied onto it as static properties of the Function.\r\n *\r\n * Note: we don't merge __proto__ to prevent prototype pollution\r\n */\r\nfunction deepExtend(target, source) {\r\n if (!(source instanceof Object)) {\r\n return source;\r\n }\r\n switch (source.constructor) {\r\n case Date:\r\n // Treat Dates like scalars; if the target date object had any child\r\n // properties - they will be lost!\r\n const dateValue = source;\r\n return new Date(dateValue.getTime());\r\n case Object:\r\n if (target === undefined) {\r\n target = {};\r\n }\r\n break;\r\n case Array:\r\n // Always copy the array source and overwrite the target.\r\n target = [];\r\n break;\r\n default:\r\n // Not a plain Object - treat it as a scalar.\r\n return source;\r\n }\r\n for (const prop in source) {\r\n // use isValidKey to guard against prototype pollution. See https://snyk.io/vuln/SNYK-JS-LODASH-450202\r\n if (!source.hasOwnProperty(prop) || !isValidKey(prop)) {\r\n continue;\r\n }\r\n target[prop] = deepExtend(target[prop], source[prop]);\r\n }\r\n return target;\r\n}\r\nfunction isValidKey(key) {\r\n return key !== '__proto__';\r\n}\n\n/**\r\n * @license\r\n * Copyright 2022 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Polyfill for `globalThis` object.\r\n * @returns the `globalThis` object for the given environment.\r\n * @public\r\n */\r\nfunction getGlobal() {\r\n if (typeof self !== 'undefined') {\r\n return self;\r\n }\r\n if (typeof window !== 'undefined') {\r\n return window;\r\n }\r\n if (typeof global !== 'undefined') {\r\n return global;\r\n }\r\n throw new Error('Unable to locate global object.');\r\n}\n\n/**\r\n * @license\r\n * Copyright 2022 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nconst getDefaultsFromGlobal = () => getGlobal().__FIREBASE_DEFAULTS__;\r\n/**\r\n * Attempt to read defaults from a JSON string provided to\r\n * process(.)env(.)__FIREBASE_DEFAULTS__ or a JSON file whose path is in\r\n * process(.)env(.)__FIREBASE_DEFAULTS_PATH__\r\n * The dots are in parens because certain compilers (Vite?) cannot\r\n * handle seeing that variable in comments.\r\n * See https://github.com/firebase/firebase-js-sdk/issues/6838\r\n */\r\nconst getDefaultsFromEnvVariable = () => {\r\n if (typeof process === 'undefined' || typeof process.env === 'undefined') {\r\n return;\r\n }\r\n const defaultsJsonString = process.env.__FIREBASE_DEFAULTS__;\r\n if (defaultsJsonString) {\r\n return JSON.parse(defaultsJsonString);\r\n }\r\n};\r\nconst getDefaultsFromCookie = () => {\r\n if (typeof document === 'undefined') {\r\n return;\r\n }\r\n let match;\r\n try {\r\n match = document.cookie.match(/__FIREBASE_DEFAULTS__=([^;]+)/);\r\n }\r\n catch (e) {\r\n // Some environments such as Angular Universal SSR have a\r\n // `document` object but error on accessing `document.cookie`.\r\n return;\r\n }\r\n const decoded = match && base64Decode(match[1]);\r\n return decoded && JSON.parse(decoded);\r\n};\r\n/**\r\n * Get the __FIREBASE_DEFAULTS__ object. It checks in order:\r\n * (1) if such an object exists as a property of `globalThis`\r\n * (2) if such an object was provided on a shell environment variable\r\n * (3) if such an object exists in a cookie\r\n * @public\r\n */\r\nconst getDefaults = () => {\r\n try {\r\n return (getDefaultsFromGlobal() ||\r\n getDefaultsFromEnvVariable() ||\r\n getDefaultsFromCookie());\r\n }\r\n catch (e) {\r\n /**\r\n * Catch-all for being unable to get __FIREBASE_DEFAULTS__ due\r\n * to any environment case we have not accounted for. Log to\r\n * info instead of swallowing so we can find these unknown cases\r\n * and add paths for them if needed.\r\n */\r\n console.info(`Unable to get __FIREBASE_DEFAULTS__ due to: ${e}`);\r\n return;\r\n }\r\n};\r\n/**\r\n * Returns emulator host stored in the __FIREBASE_DEFAULTS__ object\r\n * for the given product.\r\n * @returns a URL host formatted like `127.0.0.1:9999` or `[::1]:4000` if available\r\n * @public\r\n */\r\nconst getDefaultEmulatorHost = (productName) => { var _a, _b; return (_b = (_a = getDefaults()) === null || _a === void 0 ? void 0 : _a.emulatorHosts) === null || _b === void 0 ? void 0 : _b[productName]; };\r\n/**\r\n * Returns emulator hostname and port stored in the __FIREBASE_DEFAULTS__ object\r\n * for the given product.\r\n * @returns a pair of hostname and port like `[\"::1\", 4000]` if available\r\n * @public\r\n */\r\nconst getDefaultEmulatorHostnameAndPort = (productName) => {\r\n const host = getDefaultEmulatorHost(productName);\r\n if (!host) {\r\n return undefined;\r\n }\r\n const separatorIndex = host.lastIndexOf(':'); // Finding the last since IPv6 addr also has colons.\r\n if (separatorIndex <= 0 || separatorIndex + 1 === host.length) {\r\n throw new Error(`Invalid host ${host} with no separate hostname and port!`);\r\n }\r\n // eslint-disable-next-line no-restricted-globals\r\n const port = parseInt(host.substring(separatorIndex + 1), 10);\r\n if (host[0] === '[') {\r\n // Bracket-quoted `[ipv6addr]:port` => return \"ipv6addr\" (without brackets).\r\n return [host.substring(1, separatorIndex - 1), port];\r\n }\r\n else {\r\n return [host.substring(0, separatorIndex), port];\r\n }\r\n};\r\n/**\r\n * Returns Firebase app config stored in the __FIREBASE_DEFAULTS__ object.\r\n * @public\r\n */\r\nconst getDefaultAppConfig = () => { var _a; return (_a = getDefaults()) === null || _a === void 0 ? void 0 : _a.config; };\r\n/**\r\n * Returns an experimental setting on the __FIREBASE_DEFAULTS__ object (properties\r\n * prefixed by \"_\")\r\n * @public\r\n */\r\nconst getExperimentalSetting = (name) => { var _a; return (_a = getDefaults()) === null || _a === void 0 ? void 0 : _a[`_${name}`]; };\n\n/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nclass Deferred {\r\n constructor() {\r\n this.reject = () => { };\r\n this.resolve = () => { };\r\n this.promise = new Promise((resolve, reject) => {\r\n this.resolve = resolve;\r\n this.reject = reject;\r\n });\r\n }\r\n /**\r\n * Our API internals are not promiseified and cannot because our callback APIs have subtle expectations around\r\n * invoking promises inline, which Promises are forbidden to do. This method accepts an optional node-style callback\r\n * and returns a node-style callback which will resolve or reject the Deferred's promise.\r\n */\r\n wrapCallback(callback) {\r\n return (error, value) => {\r\n if (error) {\r\n this.reject(error);\r\n }\r\n else {\r\n this.resolve(value);\r\n }\r\n if (typeof callback === 'function') {\r\n // Attaching noop handler just in case developer wasn't expecting\r\n // promises\r\n this.promise.catch(() => { });\r\n // Some of our callbacks don't expect a value and our own tests\r\n // assert that the parameter length is 1\r\n if (callback.length === 1) {\r\n callback(error);\r\n }\r\n else {\r\n callback(error, value);\r\n }\r\n }\r\n };\r\n }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2021 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nfunction createMockUserToken(token, projectId) {\r\n if (token.uid) {\r\n throw new Error('The \"uid\" field is no longer supported by mockUserToken. Please use \"sub\" instead for Firebase Auth User ID.');\r\n }\r\n // Unsecured JWTs use \"none\" as the algorithm.\r\n const header = {\r\n alg: 'none',\r\n type: 'JWT'\r\n };\r\n const project = projectId || 'demo-project';\r\n const iat = token.iat || 0;\r\n const sub = token.sub || token.user_id;\r\n if (!sub) {\r\n throw new Error(\"mockUserToken must contain 'sub' or 'user_id' field!\");\r\n }\r\n const payload = Object.assign({ \r\n // Set all required fields to decent defaults\r\n iss: `https://securetoken.google.com/${project}`, aud: project, iat, exp: iat + 3600, auth_time: iat, sub, user_id: sub, firebase: {\r\n sign_in_provider: 'custom',\r\n identities: {}\r\n } }, token);\r\n // Unsecured JWTs use the empty string as a signature.\r\n const signature = '';\r\n return [\r\n base64urlEncodeWithoutPadding(JSON.stringify(header)),\r\n base64urlEncodeWithoutPadding(JSON.stringify(payload)),\r\n signature\r\n ].join('.');\r\n}\n\n/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Returns navigator.userAgent string or '' if it's not defined.\r\n * @return user agent string\r\n */\r\nfunction getUA() {\r\n if (typeof navigator !== 'undefined' &&\r\n typeof navigator['userAgent'] === 'string') {\r\n return navigator['userAgent'];\r\n }\r\n else {\r\n return '';\r\n }\r\n}\r\n/**\r\n * Detect Cordova / PhoneGap / Ionic frameworks on a mobile device.\r\n *\r\n * Deliberately does not rely on checking `file://` URLs (as this fails PhoneGap\r\n * in the Ripple emulator) nor Cordova `onDeviceReady`, which would normally\r\n * wait for a callback.\r\n */\r\nfunction isMobileCordova() {\r\n return (typeof window !== 'undefined' &&\r\n // @ts-ignore Setting up an broadly applicable index signature for Window\r\n // just to deal with this case would probably be a bad idea.\r\n !!(window['cordova'] || window['phonegap'] || window['PhoneGap']) &&\r\n /ios|iphone|ipod|ipad|android|blackberry|iemobile/i.test(getUA()));\r\n}\r\n/**\r\n * Detect Node.js.\r\n *\r\n * @return true if Node.js environment is detected or specified.\r\n */\r\n// Node detection logic from: https://github.com/iliakan/detect-node/\r\nfunction isNode() {\r\n var _a;\r\n const forceEnvironment = (_a = getDefaults()) === null || _a === void 0 ? void 0 : _a.forceEnvironment;\r\n if (forceEnvironment === 'node') {\r\n return true;\r\n }\r\n else if (forceEnvironment === 'browser') {\r\n return false;\r\n }\r\n try {\r\n return (Object.prototype.toString.call(global.process) === '[object process]');\r\n }\r\n catch (e) {\r\n return false;\r\n }\r\n}\r\n/**\r\n * Detect Browser Environment\r\n */\r\nfunction isBrowser() {\r\n return typeof self === 'object' && self.self === self;\r\n}\r\nfunction isBrowserExtension() {\r\n const runtime = typeof chrome === 'object'\r\n ? chrome.runtime\r\n : typeof browser === 'object'\r\n ? browser.runtime\r\n : undefined;\r\n return typeof runtime === 'object' && runtime.id !== undefined;\r\n}\r\n/**\r\n * Detect React Native.\r\n *\r\n * @return true if ReactNative environment is detected.\r\n */\r\nfunction isReactNative() {\r\n return (typeof navigator === 'object' && navigator['product'] === 'ReactNative');\r\n}\r\n/** Detects Electron apps. */\r\nfunction isElectron() {\r\n return getUA().indexOf('Electron/') >= 0;\r\n}\r\n/** Detects Internet Explorer. */\r\nfunction isIE() {\r\n const ua = getUA();\r\n return ua.indexOf('MSIE ') >= 0 || ua.indexOf('Trident/') >= 0;\r\n}\r\n/** Detects Universal Windows Platform apps. */\r\nfunction isUWP() {\r\n return getUA().indexOf('MSAppHost/') >= 0;\r\n}\r\n/**\r\n * Detect whether the current SDK build is the Node version.\r\n *\r\n * @return true if it's the Node SDK build.\r\n */\r\nfunction isNodeSdk() {\r\n return CONSTANTS.NODE_CLIENT === true || CONSTANTS.NODE_ADMIN === true;\r\n}\r\n/** Returns true if we are running in Safari. */\r\nfunction isSafari() {\r\n return (!isNode() &&\r\n navigator.userAgent.includes('Safari') &&\r\n !navigator.userAgent.includes('Chrome'));\r\n}\r\n/**\r\n * This method checks if indexedDB is supported by current browser/service worker context\r\n * @return true if indexedDB is supported by current browser/service worker context\r\n */\r\nfunction isIndexedDBAvailable() {\r\n try {\r\n return typeof indexedDB === 'object';\r\n }\r\n catch (e) {\r\n return false;\r\n }\r\n}\r\n/**\r\n * This method validates browser/sw context for indexedDB by opening a dummy indexedDB database and reject\r\n * if errors occur during the database open operation.\r\n *\r\n * @throws exception if current browser/sw context can't run idb.open (ex: Safari iframe, Firefox\r\n * private browsing)\r\n */\r\nfunction validateIndexedDBOpenable() {\r\n return new Promise((resolve, reject) => {\r\n try {\r\n let preExist = true;\r\n const DB_CHECK_NAME = 'validate-browser-context-for-indexeddb-analytics-module';\r\n const request = self.indexedDB.open(DB_CHECK_NAME);\r\n request.onsuccess = () => {\r\n request.result.close();\r\n // delete database only when it doesn't pre-exist\r\n if (!preExist) {\r\n self.indexedDB.deleteDatabase(DB_CHECK_NAME);\r\n }\r\n resolve(true);\r\n };\r\n request.onupgradeneeded = () => {\r\n preExist = false;\r\n };\r\n request.onerror = () => {\r\n var _a;\r\n reject(((_a = request.error) === null || _a === void 0 ? void 0 : _a.message) || '');\r\n };\r\n }\r\n catch (error) {\r\n reject(error);\r\n }\r\n });\r\n}\r\n/**\r\n *\r\n * This method checks whether cookie is enabled within current browser\r\n * @return true if cookie is enabled within current browser\r\n */\r\nfunction areCookiesEnabled() {\r\n if (typeof navigator === 'undefined' || !navigator.cookieEnabled) {\r\n return false;\r\n }\r\n return true;\r\n}\n\n/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * @fileoverview Standardized Firebase Error.\r\n *\r\n * Usage:\r\n *\r\n * // Typescript string literals for type-safe codes\r\n * type Err =\r\n * 'unknown' |\r\n * 'object-not-found'\r\n * ;\r\n *\r\n * // Closure enum for type-safe error codes\r\n * // at-enum {string}\r\n * var Err = {\r\n * UNKNOWN: 'unknown',\r\n * OBJECT_NOT_FOUND: 'object-not-found',\r\n * }\r\n *\r\n * let errors: Map = {\r\n * 'generic-error': \"Unknown error\",\r\n * 'file-not-found': \"Could not find file: {$file}\",\r\n * };\r\n *\r\n * // Type-safe function - must pass a valid error code as param.\r\n * let error = new ErrorFactory('service', 'Service', errors);\r\n *\r\n * ...\r\n * throw error.create(Err.GENERIC);\r\n * ...\r\n * throw error.create(Err.FILE_NOT_FOUND, {'file': fileName});\r\n * ...\r\n * // Service: Could not file file: foo.txt (service/file-not-found).\r\n *\r\n * catch (e) {\r\n * assert(e.message === \"Could not find file: foo.txt.\");\r\n * if ((e as FirebaseError)?.code === 'service/file-not-found') {\r\n * console.log(\"Could not read file: \" + e['file']);\r\n * }\r\n * }\r\n */\r\nconst ERROR_NAME = 'FirebaseError';\r\n// Based on code from:\r\n// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error#Custom_Error_Types\r\nclass FirebaseError extends Error {\r\n constructor(\r\n /** The error code for this error. */\r\n code, message, \r\n /** Custom data for this error. */\r\n customData) {\r\n super(message);\r\n this.code = code;\r\n this.customData = customData;\r\n /** The custom name for all FirebaseErrors. */\r\n this.name = ERROR_NAME;\r\n // Fix For ES5\r\n // https://github.com/Microsoft/TypeScript-wiki/blob/master/Breaking-Changes.md#extending-built-ins-like-error-array-and-map-may-no-longer-work\r\n Object.setPrototypeOf(this, FirebaseError.prototype);\r\n // Maintains proper stack trace for where our error was thrown.\r\n // Only available on V8.\r\n if (Error.captureStackTrace) {\r\n Error.captureStackTrace(this, ErrorFactory.prototype.create);\r\n }\r\n }\r\n}\r\nclass ErrorFactory {\r\n constructor(service, serviceName, errors) {\r\n this.service = service;\r\n this.serviceName = serviceName;\r\n this.errors = errors;\r\n }\r\n create(code, ...data) {\r\n const customData = data[0] || {};\r\n const fullCode = `${this.service}/${code}`;\r\n const template = this.errors[code];\r\n const message = template ? replaceTemplate(template, customData) : 'Error';\r\n // Service Name: Error message (service/code).\r\n const fullMessage = `${this.serviceName}: ${message} (${fullCode}).`;\r\n const error = new FirebaseError(fullCode, fullMessage, customData);\r\n return error;\r\n }\r\n}\r\nfunction replaceTemplate(template, data) {\r\n return template.replace(PATTERN, (_, key) => {\r\n const value = data[key];\r\n return value != null ? String(value) : `<${key}?>`;\r\n });\r\n}\r\nconst PATTERN = /\\{\\$([^}]+)}/g;\n\n/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Evaluates a JSON string into a javascript object.\r\n *\r\n * @param {string} str A string containing JSON.\r\n * @return {*} The javascript object representing the specified JSON.\r\n */\r\nfunction jsonEval(str) {\r\n return JSON.parse(str);\r\n}\r\n/**\r\n * Returns JSON representing a javascript object.\r\n * @param {*} data Javascript object to be stringified.\r\n * @return {string} The JSON contents of the object.\r\n */\r\nfunction stringify(data) {\r\n return JSON.stringify(data);\r\n}\n\n/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Decodes a Firebase auth. token into constituent parts.\r\n *\r\n * Notes:\r\n * - May return with invalid / incomplete claims if there's no native base64 decoding support.\r\n * - Doesn't check if the token is actually valid.\r\n */\r\nconst decode = function (token) {\r\n let header = {}, claims = {}, data = {}, signature = '';\r\n try {\r\n const parts = token.split('.');\r\n header = jsonEval(base64Decode(parts[0]) || '');\r\n claims = jsonEval(base64Decode(parts[1]) || '');\r\n signature = parts[2];\r\n data = claims['d'] || {};\r\n delete claims['d'];\r\n }\r\n catch (e) { }\r\n return {\r\n header,\r\n claims,\r\n data,\r\n signature\r\n };\r\n};\r\n/**\r\n * Decodes a Firebase auth. token and checks the validity of its time-based claims. Will return true if the\r\n * token is within the time window authorized by the 'nbf' (not-before) and 'iat' (issued-at) claims.\r\n *\r\n * Notes:\r\n * - May return a false negative if there's no native base64 decoding support.\r\n * - Doesn't check if the token is actually valid.\r\n */\r\nconst isValidTimestamp = function (token) {\r\n const claims = decode(token).claims;\r\n const now = Math.floor(new Date().getTime() / 1000);\r\n let validSince = 0, validUntil = 0;\r\n if (typeof claims === 'object') {\r\n if (claims.hasOwnProperty('nbf')) {\r\n validSince = claims['nbf'];\r\n }\r\n else if (claims.hasOwnProperty('iat')) {\r\n validSince = claims['iat'];\r\n }\r\n if (claims.hasOwnProperty('exp')) {\r\n validUntil = claims['exp'];\r\n }\r\n else {\r\n // token will expire after 24h by default\r\n validUntil = validSince + 86400;\r\n }\r\n }\r\n return (!!now &&\r\n !!validSince &&\r\n !!validUntil &&\r\n now >= validSince &&\r\n now <= validUntil);\r\n};\r\n/**\r\n * Decodes a Firebase auth. token and returns its issued at time if valid, null otherwise.\r\n *\r\n * Notes:\r\n * - May return null if there's no native base64 decoding support.\r\n * - Doesn't check if the token is actually valid.\r\n */\r\nconst issuedAtTime = function (token) {\r\n const claims = decode(token).claims;\r\n if (typeof claims === 'object' && claims.hasOwnProperty('iat')) {\r\n return claims['iat'];\r\n }\r\n return null;\r\n};\r\n/**\r\n * Decodes a Firebase auth. token and checks the validity of its format. Expects a valid issued-at time.\r\n *\r\n * Notes:\r\n * - May return a false negative if there's no native base64 decoding support.\r\n * - Doesn't check if the token is actually valid.\r\n */\r\nconst isValidFormat = function (token) {\r\n const decoded = decode(token), claims = decoded.claims;\r\n return !!claims && typeof claims === 'object' && claims.hasOwnProperty('iat');\r\n};\r\n/**\r\n * Attempts to peer into an auth token and determine if it's an admin auth token by looking at the claims portion.\r\n *\r\n * Notes:\r\n * - May return a false negative if there's no native base64 decoding support.\r\n * - Doesn't check if the token is actually valid.\r\n */\r\nconst isAdmin = function (token) {\r\n const claims = decode(token).claims;\r\n return typeof claims === 'object' && claims['admin'] === true;\r\n};\n\n/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nfunction contains(obj, key) {\r\n return Object.prototype.hasOwnProperty.call(obj, key);\r\n}\r\nfunction safeGet(obj, key) {\r\n if (Object.prototype.hasOwnProperty.call(obj, key)) {\r\n return obj[key];\r\n }\r\n else {\r\n return undefined;\r\n }\r\n}\r\nfunction isEmpty(obj) {\r\n for (const key in obj) {\r\n if (Object.prototype.hasOwnProperty.call(obj, key)) {\r\n return false;\r\n }\r\n }\r\n return true;\r\n}\r\nfunction map(obj, fn, contextObj) {\r\n const res = {};\r\n for (const key in obj) {\r\n if (Object.prototype.hasOwnProperty.call(obj, key)) {\r\n res[key] = fn.call(contextObj, obj[key], key, obj);\r\n }\r\n }\r\n return res;\r\n}\r\n/**\r\n * Deep equal two objects. Support Arrays and Objects.\r\n */\r\nfunction deepEqual(a, b) {\r\n if (a === b) {\r\n return true;\r\n }\r\n const aKeys = Object.keys(a);\r\n const bKeys = Object.keys(b);\r\n for (const k of aKeys) {\r\n if (!bKeys.includes(k)) {\r\n return false;\r\n }\r\n const aProp = a[k];\r\n const bProp = b[k];\r\n if (isObject(aProp) && isObject(bProp)) {\r\n if (!deepEqual(aProp, bProp)) {\r\n return false;\r\n }\r\n }\r\n else if (aProp !== bProp) {\r\n return false;\r\n }\r\n }\r\n for (const k of bKeys) {\r\n if (!aKeys.includes(k)) {\r\n return false;\r\n }\r\n }\r\n return true;\r\n}\r\nfunction isObject(thing) {\r\n return thing !== null && typeof thing === 'object';\r\n}\n\n/**\r\n * @license\r\n * Copyright 2022 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Rejects if the given promise doesn't resolve in timeInMS milliseconds.\r\n * @internal\r\n */\r\nfunction promiseWithTimeout(promise, timeInMS = 2000) {\r\n const deferredPromise = new Deferred();\r\n setTimeout(() => deferredPromise.reject('timeout!'), timeInMS);\r\n promise.then(deferredPromise.resolve, deferredPromise.reject);\r\n return deferredPromise.promise;\r\n}\n\n/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Returns a querystring-formatted string (e.g. &arg=val&arg2=val2) from a\r\n * params object (e.g. {arg: 'val', arg2: 'val2'})\r\n * Note: You must prepend it with ? when adding it to a URL.\r\n */\r\nfunction querystring(querystringParams) {\r\n const params = [];\r\n for (const [key, value] of Object.entries(querystringParams)) {\r\n if (Array.isArray(value)) {\r\n value.forEach(arrayVal => {\r\n params.push(encodeURIComponent(key) + '=' + encodeURIComponent(arrayVal));\r\n });\r\n }\r\n else {\r\n params.push(encodeURIComponent(key) + '=' + encodeURIComponent(value));\r\n }\r\n }\r\n return params.length ? '&' + params.join('&') : '';\r\n}\r\n/**\r\n * Decodes a querystring (e.g. ?arg=val&arg2=val2) into a params object\r\n * (e.g. {arg: 'val', arg2: 'val2'})\r\n */\r\nfunction querystringDecode(querystring) {\r\n const obj = {};\r\n const tokens = querystring.replace(/^\\?/, '').split('&');\r\n tokens.forEach(token => {\r\n if (token) {\r\n const [key, value] = token.split('=');\r\n obj[decodeURIComponent(key)] = decodeURIComponent(value);\r\n }\r\n });\r\n return obj;\r\n}\r\n/**\r\n * Extract the query string part of a URL, including the leading question mark (if present).\r\n */\r\nfunction extractQuerystring(url) {\r\n const queryStart = url.indexOf('?');\r\n if (!queryStart) {\r\n return '';\r\n }\r\n const fragmentStart = url.indexOf('#', queryStart);\r\n return url.substring(queryStart, fragmentStart > 0 ? fragmentStart : undefined);\r\n}\n\n/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * @fileoverview SHA-1 cryptographic hash.\r\n * Variable names follow the notation in FIPS PUB 180-3:\r\n * http://csrc.nist.gov/publications/fips/fips180-3/fips180-3_final.pdf.\r\n *\r\n * Usage:\r\n * var sha1 = new sha1();\r\n * sha1.update(bytes);\r\n * var hash = sha1.digest();\r\n *\r\n * Performance:\r\n * Chrome 23: ~400 Mbit/s\r\n * Firefox 16: ~250 Mbit/s\r\n *\r\n */\r\n/**\r\n * SHA-1 cryptographic hash constructor.\r\n *\r\n * The properties declared here are discussed in the above algorithm document.\r\n * @constructor\r\n * @final\r\n * @struct\r\n */\r\nclass Sha1 {\r\n constructor() {\r\n /**\r\n * Holds the previous values of accumulated variables a-e in the compress_\r\n * function.\r\n * @private\r\n */\r\n this.chain_ = [];\r\n /**\r\n * A buffer holding the partially computed hash result.\r\n * @private\r\n */\r\n this.buf_ = [];\r\n /**\r\n * An array of 80 bytes, each a part of the message to be hashed. Referred to\r\n * as the message schedule in the docs.\r\n * @private\r\n */\r\n this.W_ = [];\r\n /**\r\n * Contains data needed to pad messages less than 64 bytes.\r\n * @private\r\n */\r\n this.pad_ = [];\r\n /**\r\n * @private {number}\r\n */\r\n this.inbuf_ = 0;\r\n /**\r\n * @private {number}\r\n */\r\n this.total_ = 0;\r\n this.blockSize = 512 / 8;\r\n this.pad_[0] = 128;\r\n for (let i = 1; i < this.blockSize; ++i) {\r\n this.pad_[i] = 0;\r\n }\r\n this.reset();\r\n }\r\n reset() {\r\n this.chain_[0] = 0x67452301;\r\n this.chain_[1] = 0xefcdab89;\r\n this.chain_[2] = 0x98badcfe;\r\n this.chain_[3] = 0x10325476;\r\n this.chain_[4] = 0xc3d2e1f0;\r\n this.inbuf_ = 0;\r\n this.total_ = 0;\r\n }\r\n /**\r\n * Internal compress helper function.\r\n * @param buf Block to compress.\r\n * @param offset Offset of the block in the buffer.\r\n * @private\r\n */\r\n compress_(buf, offset) {\r\n if (!offset) {\r\n offset = 0;\r\n }\r\n const W = this.W_;\r\n // get 16 big endian words\r\n if (typeof buf === 'string') {\r\n for (let i = 0; i < 16; i++) {\r\n // TODO(user): [bug 8140122] Recent versions of Safari for Mac OS and iOS\r\n // have a bug that turns the post-increment ++ operator into pre-increment\r\n // during JIT compilation. We have code that depends heavily on SHA-1 for\r\n // correctness and which is affected by this bug, so I've removed all uses\r\n // of post-increment ++ in which the result value is used. We can revert\r\n // this change once the Safari bug\r\n // (https://bugs.webkit.org/show_bug.cgi?id=109036) has been fixed and\r\n // most clients have been updated.\r\n W[i] =\r\n (buf.charCodeAt(offset) << 24) |\r\n (buf.charCodeAt(offset + 1) << 16) |\r\n (buf.charCodeAt(offset + 2) << 8) |\r\n buf.charCodeAt(offset + 3);\r\n offset += 4;\r\n }\r\n }\r\n else {\r\n for (let i = 0; i < 16; i++) {\r\n W[i] =\r\n (buf[offset] << 24) |\r\n (buf[offset + 1] << 16) |\r\n (buf[offset + 2] << 8) |\r\n buf[offset + 3];\r\n offset += 4;\r\n }\r\n }\r\n // expand to 80 words\r\n for (let i = 16; i < 80; i++) {\r\n const t = W[i - 3] ^ W[i - 8] ^ W[i - 14] ^ W[i - 16];\r\n W[i] = ((t << 1) | (t >>> 31)) & 0xffffffff;\r\n }\r\n let a = this.chain_[0];\r\n let b = this.chain_[1];\r\n let c = this.chain_[2];\r\n let d = this.chain_[3];\r\n let e = this.chain_[4];\r\n let f, k;\r\n // TODO(user): Try to unroll this loop to speed up the computation.\r\n for (let i = 0; i < 80; i++) {\r\n if (i < 40) {\r\n if (i < 20) {\r\n f = d ^ (b & (c ^ d));\r\n k = 0x5a827999;\r\n }\r\n else {\r\n f = b ^ c ^ d;\r\n k = 0x6ed9eba1;\r\n }\r\n }\r\n else {\r\n if (i < 60) {\r\n f = (b & c) | (d & (b | c));\r\n k = 0x8f1bbcdc;\r\n }\r\n else {\r\n f = b ^ c ^ d;\r\n k = 0xca62c1d6;\r\n }\r\n }\r\n const t = (((a << 5) | (a >>> 27)) + f + e + k + W[i]) & 0xffffffff;\r\n e = d;\r\n d = c;\r\n c = ((b << 30) | (b >>> 2)) & 0xffffffff;\r\n b = a;\r\n a = t;\r\n }\r\n this.chain_[0] = (this.chain_[0] + a) & 0xffffffff;\r\n this.chain_[1] = (this.chain_[1] + b) & 0xffffffff;\r\n this.chain_[2] = (this.chain_[2] + c) & 0xffffffff;\r\n this.chain_[3] = (this.chain_[3] + d) & 0xffffffff;\r\n this.chain_[4] = (this.chain_[4] + e) & 0xffffffff;\r\n }\r\n update(bytes, length) {\r\n // TODO(johnlenz): tighten the function signature and remove this check\r\n if (bytes == null) {\r\n return;\r\n }\r\n if (length === undefined) {\r\n length = bytes.length;\r\n }\r\n const lengthMinusBlock = length - this.blockSize;\r\n let n = 0;\r\n // Using local instead of member variables gives ~5% speedup on Firefox 16.\r\n const buf = this.buf_;\r\n let inbuf = this.inbuf_;\r\n // The outer while loop should execute at most twice.\r\n while (n < length) {\r\n // When we have no data in the block to top up, we can directly process the\r\n // input buffer (assuming it contains sufficient data). This gives ~25%\r\n // speedup on Chrome 23 and ~15% speedup on Firefox 16, but requires that\r\n // the data is provided in large chunks (or in multiples of 64 bytes).\r\n if (inbuf === 0) {\r\n while (n <= lengthMinusBlock) {\r\n this.compress_(bytes, n);\r\n n += this.blockSize;\r\n }\r\n }\r\n if (typeof bytes === 'string') {\r\n while (n < length) {\r\n buf[inbuf] = bytes.charCodeAt(n);\r\n ++inbuf;\r\n ++n;\r\n if (inbuf === this.blockSize) {\r\n this.compress_(buf);\r\n inbuf = 0;\r\n // Jump to the outer loop so we use the full-block optimization.\r\n break;\r\n }\r\n }\r\n }\r\n else {\r\n while (n < length) {\r\n buf[inbuf] = bytes[n];\r\n ++inbuf;\r\n ++n;\r\n if (inbuf === this.blockSize) {\r\n this.compress_(buf);\r\n inbuf = 0;\r\n // Jump to the outer loop so we use the full-block optimization.\r\n break;\r\n }\r\n }\r\n }\r\n }\r\n this.inbuf_ = inbuf;\r\n this.total_ += length;\r\n }\r\n /** @override */\r\n digest() {\r\n const digest = [];\r\n let totalBits = this.total_ * 8;\r\n // Add pad 0x80 0x00*.\r\n if (this.inbuf_ < 56) {\r\n this.update(this.pad_, 56 - this.inbuf_);\r\n }\r\n else {\r\n this.update(this.pad_, this.blockSize - (this.inbuf_ - 56));\r\n }\r\n // Add # bits.\r\n for (let i = this.blockSize - 1; i >= 56; i--) {\r\n this.buf_[i] = totalBits & 255;\r\n totalBits /= 256; // Don't use bit-shifting here!\r\n }\r\n this.compress_(this.buf_);\r\n let n = 0;\r\n for (let i = 0; i < 5; i++) {\r\n for (let j = 24; j >= 0; j -= 8) {\r\n digest[n] = (this.chain_[i] >> j) & 255;\r\n ++n;\r\n }\r\n }\r\n return digest;\r\n }\r\n}\n\n/**\r\n * Helper to make a Subscribe function (just like Promise helps make a\r\n * Thenable).\r\n *\r\n * @param executor Function which can make calls to a single Observer\r\n * as a proxy.\r\n * @param onNoObservers Callback when count of Observers goes to zero.\r\n */\r\nfunction createSubscribe(executor, onNoObservers) {\r\n const proxy = new ObserverProxy(executor, onNoObservers);\r\n return proxy.subscribe.bind(proxy);\r\n}\r\n/**\r\n * Implement fan-out for any number of Observers attached via a subscribe\r\n * function.\r\n */\r\nclass ObserverProxy {\r\n /**\r\n * @param executor Function which can make calls to a single Observer\r\n * as a proxy.\r\n * @param onNoObservers Callback when count of Observers goes to zero.\r\n */\r\n constructor(executor, onNoObservers) {\r\n this.observers = [];\r\n this.unsubscribes = [];\r\n this.observerCount = 0;\r\n // Micro-task scheduling by calling task.then().\r\n this.task = Promise.resolve();\r\n this.finalized = false;\r\n this.onNoObservers = onNoObservers;\r\n // Call the executor asynchronously so subscribers that are called\r\n // synchronously after the creation of the subscribe function\r\n // can still receive the very first value generated in the executor.\r\n this.task\r\n .then(() => {\r\n executor(this);\r\n })\r\n .catch(e => {\r\n this.error(e);\r\n });\r\n }\r\n next(value) {\r\n this.forEachObserver((observer) => {\r\n observer.next(value);\r\n });\r\n }\r\n error(error) {\r\n this.forEachObserver((observer) => {\r\n observer.error(error);\r\n });\r\n this.close(error);\r\n }\r\n complete() {\r\n this.forEachObserver((observer) => {\r\n observer.complete();\r\n });\r\n this.close();\r\n }\r\n /**\r\n * Subscribe function that can be used to add an Observer to the fan-out list.\r\n *\r\n * - We require that no event is sent to a subscriber sychronously to their\r\n * call to subscribe().\r\n */\r\n subscribe(nextOrObserver, error, complete) {\r\n let observer;\r\n if (nextOrObserver === undefined &&\r\n error === undefined &&\r\n complete === undefined) {\r\n throw new Error('Missing Observer.');\r\n }\r\n // Assemble an Observer object when passed as callback functions.\r\n if (implementsAnyMethods(nextOrObserver, [\r\n 'next',\r\n 'error',\r\n 'complete'\r\n ])) {\r\n observer = nextOrObserver;\r\n }\r\n else {\r\n observer = {\r\n next: nextOrObserver,\r\n error,\r\n complete\r\n };\r\n }\r\n if (observer.next === undefined) {\r\n observer.next = noop;\r\n }\r\n if (observer.error === undefined) {\r\n observer.error = noop;\r\n }\r\n if (observer.complete === undefined) {\r\n observer.complete = noop;\r\n }\r\n const unsub = this.unsubscribeOne.bind(this, this.observers.length);\r\n // Attempt to subscribe to a terminated Observable - we\r\n // just respond to the Observer with the final error or complete\r\n // event.\r\n if (this.finalized) {\r\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\r\n this.task.then(() => {\r\n try {\r\n if (this.finalError) {\r\n observer.error(this.finalError);\r\n }\r\n else {\r\n observer.complete();\r\n }\r\n }\r\n catch (e) {\r\n // nothing\r\n }\r\n return;\r\n });\r\n }\r\n this.observers.push(observer);\r\n return unsub;\r\n }\r\n // Unsubscribe is synchronous - we guarantee that no events are sent to\r\n // any unsubscribed Observer.\r\n unsubscribeOne(i) {\r\n if (this.observers === undefined || this.observers[i] === undefined) {\r\n return;\r\n }\r\n delete this.observers[i];\r\n this.observerCount -= 1;\r\n if (this.observerCount === 0 && this.onNoObservers !== undefined) {\r\n this.onNoObservers(this);\r\n }\r\n }\r\n forEachObserver(fn) {\r\n if (this.finalized) {\r\n // Already closed by previous event....just eat the additional values.\r\n return;\r\n }\r\n // Since sendOne calls asynchronously - there is no chance that\r\n // this.observers will become undefined.\r\n for (let i = 0; i < this.observers.length; i++) {\r\n this.sendOne(i, fn);\r\n }\r\n }\r\n // Call the Observer via one of it's callback function. We are careful to\r\n // confirm that the observe has not been unsubscribed since this asynchronous\r\n // function had been queued.\r\n sendOne(i, fn) {\r\n // Execute the callback asynchronously\r\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\r\n this.task.then(() => {\r\n if (this.observers !== undefined && this.observers[i] !== undefined) {\r\n try {\r\n fn(this.observers[i]);\r\n }\r\n catch (e) {\r\n // Ignore exceptions raised in Observers or missing methods of an\r\n // Observer.\r\n // Log error to console. b/31404806\r\n if (typeof console !== 'undefined' && console.error) {\r\n console.error(e);\r\n }\r\n }\r\n }\r\n });\r\n }\r\n close(err) {\r\n if (this.finalized) {\r\n return;\r\n }\r\n this.finalized = true;\r\n if (err !== undefined) {\r\n this.finalError = err;\r\n }\r\n // Proxy is no longer needed - garbage collect references\r\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\r\n this.task.then(() => {\r\n this.observers = undefined;\r\n this.onNoObservers = undefined;\r\n });\r\n }\r\n}\r\n/** Turn synchronous function into one called asynchronously. */\r\n// eslint-disable-next-line @typescript-eslint/ban-types\r\nfunction async(fn, onError) {\r\n return (...args) => {\r\n Promise.resolve(true)\r\n .then(() => {\r\n fn(...args);\r\n })\r\n .catch((error) => {\r\n if (onError) {\r\n onError(error);\r\n }\r\n });\r\n };\r\n}\r\n/**\r\n * Return true if the object passed in implements any of the named methods.\r\n */\r\nfunction implementsAnyMethods(obj, methods) {\r\n if (typeof obj !== 'object' || obj === null) {\r\n return false;\r\n }\r\n for (const method of methods) {\r\n if (method in obj && typeof obj[method] === 'function') {\r\n return true;\r\n }\r\n }\r\n return false;\r\n}\r\nfunction noop() {\r\n // do nothing\r\n}\n\n/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Check to make sure the appropriate number of arguments are provided for a public function.\r\n * Throws an error if it fails.\r\n *\r\n * @param fnName The function name\r\n * @param minCount The minimum number of arguments to allow for the function call\r\n * @param maxCount The maximum number of argument to allow for the function call\r\n * @param argCount The actual number of arguments provided.\r\n */\r\nconst validateArgCount = function (fnName, minCount, maxCount, argCount) {\r\n let argError;\r\n if (argCount < minCount) {\r\n argError = 'at least ' + minCount;\r\n }\r\n else if (argCount > maxCount) {\r\n argError = maxCount === 0 ? 'none' : 'no more than ' + maxCount;\r\n }\r\n if (argError) {\r\n const error = fnName +\r\n ' failed: Was called with ' +\r\n argCount +\r\n (argCount === 1 ? ' argument.' : ' arguments.') +\r\n ' Expects ' +\r\n argError +\r\n '.';\r\n throw new Error(error);\r\n }\r\n};\r\n/**\r\n * Generates a string to prefix an error message about failed argument validation\r\n *\r\n * @param fnName The function name\r\n * @param argName The name of the argument\r\n * @return The prefix to add to the error thrown for validation.\r\n */\r\nfunction errorPrefix(fnName, argName) {\r\n return `${fnName} failed: ${argName} argument `;\r\n}\r\n/**\r\n * @param fnName\r\n * @param argumentNumber\r\n * @param namespace\r\n * @param optional\r\n */\r\nfunction validateNamespace(fnName, namespace, optional) {\r\n if (optional && !namespace) {\r\n return;\r\n }\r\n if (typeof namespace !== 'string') {\r\n //TODO: I should do more validation here. We only allow certain chars in namespaces.\r\n throw new Error(errorPrefix(fnName, 'namespace') + 'must be a valid firebase namespace.');\r\n }\r\n}\r\nfunction validateCallback(fnName, argumentName, \r\n// eslint-disable-next-line @typescript-eslint/ban-types\r\ncallback, optional) {\r\n if (optional && !callback) {\r\n return;\r\n }\r\n if (typeof callback !== 'function') {\r\n throw new Error(errorPrefix(fnName, argumentName) + 'must be a valid function.');\r\n }\r\n}\r\nfunction validateContextObject(fnName, argumentName, context, optional) {\r\n if (optional && !context) {\r\n return;\r\n }\r\n if (typeof context !== 'object' || context === null) {\r\n throw new Error(errorPrefix(fnName, argumentName) + 'must be a valid context object.');\r\n }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n// Code originally came from goog.crypt.stringToUtf8ByteArray, but for some reason they\r\n// automatically replaced '\\r\\n' with '\\n', and they didn't handle surrogate pairs,\r\n// so it's been modified.\r\n// Note that not all Unicode characters appear as single characters in JavaScript strings.\r\n// fromCharCode returns the UTF-16 encoding of a character - so some Unicode characters\r\n// use 2 characters in Javascript. All 4-byte UTF-8 characters begin with a first\r\n// character in the range 0xD800 - 0xDBFF (the first character of a so-called surrogate\r\n// pair).\r\n// See http://www.ecma-international.org/ecma-262/5.1/#sec-15.1.3\r\n/**\r\n * @param {string} str\r\n * @return {Array}\r\n */\r\nconst stringToByteArray = function (str) {\r\n const out = [];\r\n let p = 0;\r\n for (let i = 0; i < str.length; i++) {\r\n let c = str.charCodeAt(i);\r\n // Is this the lead surrogate in a surrogate pair?\r\n if (c >= 0xd800 && c <= 0xdbff) {\r\n const high = c - 0xd800; // the high 10 bits.\r\n i++;\r\n assert(i < str.length, 'Surrogate pair missing trail surrogate.');\r\n const low = str.charCodeAt(i) - 0xdc00; // the low 10 bits.\r\n c = 0x10000 + (high << 10) + low;\r\n }\r\n if (c < 128) {\r\n out[p++] = c;\r\n }\r\n else if (c < 2048) {\r\n out[p++] = (c >> 6) | 192;\r\n out[p++] = (c & 63) | 128;\r\n }\r\n else if (c < 65536) {\r\n out[p++] = (c >> 12) | 224;\r\n out[p++] = ((c >> 6) & 63) | 128;\r\n out[p++] = (c & 63) | 128;\r\n }\r\n else {\r\n out[p++] = (c >> 18) | 240;\r\n out[p++] = ((c >> 12) & 63) | 128;\r\n out[p++] = ((c >> 6) & 63) | 128;\r\n out[p++] = (c & 63) | 128;\r\n }\r\n }\r\n return out;\r\n};\r\n/**\r\n * Calculate length without actually converting; useful for doing cheaper validation.\r\n * @param {string} str\r\n * @return {number}\r\n */\r\nconst stringLength = function (str) {\r\n let p = 0;\r\n for (let i = 0; i < str.length; i++) {\r\n const c = str.charCodeAt(i);\r\n if (c < 128) {\r\n p++;\r\n }\r\n else if (c < 2048) {\r\n p += 2;\r\n }\r\n else if (c >= 0xd800 && c <= 0xdbff) {\r\n // Lead surrogate of a surrogate pair. The pair together will take 4 bytes to represent.\r\n p += 4;\r\n i++; // skip trail surrogate.\r\n }\r\n else {\r\n p += 3;\r\n }\r\n }\r\n return p;\r\n};\n\n/**\r\n * @license\r\n * Copyright 2022 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Copied from https://stackoverflow.com/a/2117523\r\n * Generates a new uuid.\r\n * @public\r\n */\r\nconst uuidv4 = function () {\r\n return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, c => {\r\n const r = (Math.random() * 16) | 0, v = c === 'x' ? r : (r & 0x3) | 0x8;\r\n return v.toString(16);\r\n });\r\n};\n\n/**\r\n * @license\r\n * Copyright 2019 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * The amount of milliseconds to exponentially increase.\r\n */\r\nconst DEFAULT_INTERVAL_MILLIS = 1000;\r\n/**\r\n * The factor to backoff by.\r\n * Should be a number greater than 1.\r\n */\r\nconst DEFAULT_BACKOFF_FACTOR = 2;\r\n/**\r\n * The maximum milliseconds to increase to.\r\n *\r\n *

Visible for testing\r\n */\r\nconst MAX_VALUE_MILLIS = 4 * 60 * 60 * 1000; // Four hours, like iOS and Android.\r\n/**\r\n * The percentage of backoff time to randomize by.\r\n * See\r\n * http://go/safe-client-behavior#step-1-determine-the-appropriate-retry-interval-to-handle-spike-traffic\r\n * for context.\r\n *\r\n *

Visible for testing\r\n */\r\nconst RANDOM_FACTOR = 0.5;\r\n/**\r\n * Based on the backoff method from\r\n * https://github.com/google/closure-library/blob/master/closure/goog/math/exponentialbackoff.js.\r\n * Extracted here so we don't need to pass metadata and a stateful ExponentialBackoff object around.\r\n */\r\nfunction calculateBackoffMillis(backoffCount, intervalMillis = DEFAULT_INTERVAL_MILLIS, backoffFactor = DEFAULT_BACKOFF_FACTOR) {\r\n // Calculates an exponentially increasing value.\r\n // Deviation: calculates value from count and a constant interval, so we only need to save value\r\n // and count to restore state.\r\n const currBaseValue = intervalMillis * Math.pow(backoffFactor, backoffCount);\r\n // A random \"fuzz\" to avoid waves of retries.\r\n // Deviation: randomFactor is required.\r\n const randomWait = Math.round(\r\n // A fraction of the backoff value to add/subtract.\r\n // Deviation: changes multiplication order to improve readability.\r\n RANDOM_FACTOR *\r\n currBaseValue *\r\n // A random float (rounded to int by Math.round above) in the range [-1, 1]. Determines\r\n // if we add or subtract.\r\n (Math.random() - 0.5) *\r\n 2);\r\n // Limits backoff to max to avoid effectively permanent backoff.\r\n return Math.min(MAX_VALUE_MILLIS, currBaseValue + randomWait);\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Provide English ordinal letters after a number\r\n */\r\nfunction ordinal(i) {\r\n if (!Number.isFinite(i)) {\r\n return `${i}`;\r\n }\r\n return i + indicator(i);\r\n}\r\nfunction indicator(i) {\r\n i = Math.abs(i);\r\n const cent = i % 100;\r\n if (cent >= 10 && cent <= 20) {\r\n return 'th';\r\n }\r\n const dec = i % 10;\r\n if (dec === 1) {\r\n return 'st';\r\n }\r\n if (dec === 2) {\r\n return 'nd';\r\n }\r\n if (dec === 3) {\r\n return 'rd';\r\n }\r\n return 'th';\r\n}\n\n/**\r\n * @license\r\n * Copyright 2021 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nfunction getModularInstance(service) {\r\n if (service && service._delegate) {\r\n return service._delegate;\r\n }\r\n else {\r\n return service;\r\n }\r\n}\n\nexport { CONSTANTS, DecodeBase64StringError, Deferred, ErrorFactory, FirebaseError, MAX_VALUE_MILLIS, RANDOM_FACTOR, Sha1, areCookiesEnabled, assert, assertionError, async, base64, base64Decode, base64Encode, base64urlEncodeWithoutPadding, calculateBackoffMillis, contains, createMockUserToken, createSubscribe, decode, deepCopy, deepEqual, deepExtend, errorPrefix, extractQuerystring, getDefaultAppConfig, getDefaultEmulatorHost, getDefaultEmulatorHostnameAndPort, getDefaults, getExperimentalSetting, getGlobal, getModularInstance, getUA, isAdmin, isBrowser, isBrowserExtension, isElectron, isEmpty, isIE, isIndexedDBAvailable, isMobileCordova, isNode, isNodeSdk, isReactNative, isSafari, isUWP, isValidFormat, isValidTimestamp, issuedAtTime, jsonEval, map, ordinal, promiseWithTimeout, querystring, querystringDecode, safeGet, stringLength, stringToByteArray, stringify, uuidv4, validateArgCount, validateCallback, validateContextObject, validateIndexedDBOpenable, validateNamespace };\n//# sourceMappingURL=index.esm2017.js.map\n","import { Deferred } from '@firebase/util';\n\n/**\r\n * Component for service name T, e.g. `auth`, `auth-internal`\r\n */\r\nclass Component {\r\n /**\r\n *\r\n * @param name The public service name, e.g. app, auth, firestore, database\r\n * @param instanceFactory Service factory responsible for creating the public interface\r\n * @param type whether the service provided by the component is public or private\r\n */\r\n constructor(name, instanceFactory, type) {\r\n this.name = name;\r\n this.instanceFactory = instanceFactory;\r\n this.type = type;\r\n this.multipleInstances = false;\r\n /**\r\n * Properties to be added to the service namespace\r\n */\r\n this.serviceProps = {};\r\n this.instantiationMode = \"LAZY\" /* InstantiationMode.LAZY */;\r\n this.onInstanceCreated = null;\r\n }\r\n setInstantiationMode(mode) {\r\n this.instantiationMode = mode;\r\n return this;\r\n }\r\n setMultipleInstances(multipleInstances) {\r\n this.multipleInstances = multipleInstances;\r\n return this;\r\n }\r\n setServiceProps(props) {\r\n this.serviceProps = props;\r\n return this;\r\n }\r\n setInstanceCreatedCallback(callback) {\r\n this.onInstanceCreated = callback;\r\n return this;\r\n }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2019 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nconst DEFAULT_ENTRY_NAME = '[DEFAULT]';\n\n/**\r\n * @license\r\n * Copyright 2019 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Provider for instance for service name T, e.g. 'auth', 'auth-internal'\r\n * NameServiceMapping[T] is an alias for the type of the instance\r\n */\r\nclass Provider {\r\n constructor(name, container) {\r\n this.name = name;\r\n this.container = container;\r\n this.component = null;\r\n this.instances = new Map();\r\n this.instancesDeferred = new Map();\r\n this.instancesOptions = new Map();\r\n this.onInitCallbacks = new Map();\r\n }\r\n /**\r\n * @param identifier A provider can provide mulitple instances of a service\r\n * if this.component.multipleInstances is true.\r\n */\r\n get(identifier) {\r\n // if multipleInstances is not supported, use the default name\r\n const normalizedIdentifier = this.normalizeInstanceIdentifier(identifier);\r\n if (!this.instancesDeferred.has(normalizedIdentifier)) {\r\n const deferred = new Deferred();\r\n this.instancesDeferred.set(normalizedIdentifier, deferred);\r\n if (this.isInitialized(normalizedIdentifier) ||\r\n this.shouldAutoInitialize()) {\r\n // initialize the service if it can be auto-initialized\r\n try {\r\n const instance = this.getOrInitializeService({\r\n instanceIdentifier: normalizedIdentifier\r\n });\r\n if (instance) {\r\n deferred.resolve(instance);\r\n }\r\n }\r\n catch (e) {\r\n // when the instance factory throws an exception during get(), it should not cause\r\n // a fatal error. We just return the unresolved promise in this case.\r\n }\r\n }\r\n }\r\n return this.instancesDeferred.get(normalizedIdentifier).promise;\r\n }\r\n getImmediate(options) {\r\n var _a;\r\n // if multipleInstances is not supported, use the default name\r\n const normalizedIdentifier = this.normalizeInstanceIdentifier(options === null || options === void 0 ? void 0 : options.identifier);\r\n const optional = (_a = options === null || options === void 0 ? void 0 : options.optional) !== null && _a !== void 0 ? _a : false;\r\n if (this.isInitialized(normalizedIdentifier) ||\r\n this.shouldAutoInitialize()) {\r\n try {\r\n return this.getOrInitializeService({\r\n instanceIdentifier: normalizedIdentifier\r\n });\r\n }\r\n catch (e) {\r\n if (optional) {\r\n return null;\r\n }\r\n else {\r\n throw e;\r\n }\r\n }\r\n }\r\n else {\r\n // In case a component is not initialized and should/can not be auto-initialized at the moment, return null if the optional flag is set, or throw\r\n if (optional) {\r\n return null;\r\n }\r\n else {\r\n throw Error(`Service ${this.name} is not available`);\r\n }\r\n }\r\n }\r\n getComponent() {\r\n return this.component;\r\n }\r\n setComponent(component) {\r\n if (component.name !== this.name) {\r\n throw Error(`Mismatching Component ${component.name} for Provider ${this.name}.`);\r\n }\r\n if (this.component) {\r\n throw Error(`Component for ${this.name} has already been provided`);\r\n }\r\n this.component = component;\r\n // return early without attempting to initialize the component if the component requires explicit initialization (calling `Provider.initialize()`)\r\n if (!this.shouldAutoInitialize()) {\r\n return;\r\n }\r\n // if the service is eager, initialize the default instance\r\n if (isComponentEager(component)) {\r\n try {\r\n this.getOrInitializeService({ instanceIdentifier: DEFAULT_ENTRY_NAME });\r\n }\r\n catch (e) {\r\n // when the instance factory for an eager Component throws an exception during the eager\r\n // initialization, it should not cause a fatal error.\r\n // TODO: Investigate if we need to make it configurable, because some component may want to cause\r\n // a fatal error in this case?\r\n }\r\n }\r\n // Create service instances for the pending promises and resolve them\r\n // NOTE: if this.multipleInstances is false, only the default instance will be created\r\n // and all promises with resolve with it regardless of the identifier.\r\n for (const [instanceIdentifier, instanceDeferred] of this.instancesDeferred.entries()) {\r\n const normalizedIdentifier = this.normalizeInstanceIdentifier(instanceIdentifier);\r\n try {\r\n // `getOrInitializeService()` should always return a valid instance since a component is guaranteed. use ! to make typescript happy.\r\n const instance = this.getOrInitializeService({\r\n instanceIdentifier: normalizedIdentifier\r\n });\r\n instanceDeferred.resolve(instance);\r\n }\r\n catch (e) {\r\n // when the instance factory throws an exception, it should not cause\r\n // a fatal error. We just leave the promise unresolved.\r\n }\r\n }\r\n }\r\n clearInstance(identifier = DEFAULT_ENTRY_NAME) {\r\n this.instancesDeferred.delete(identifier);\r\n this.instancesOptions.delete(identifier);\r\n this.instances.delete(identifier);\r\n }\r\n // app.delete() will call this method on every provider to delete the services\r\n // TODO: should we mark the provider as deleted?\r\n async delete() {\r\n const services = Array.from(this.instances.values());\r\n await Promise.all([\r\n ...services\r\n .filter(service => 'INTERNAL' in service) // legacy services\r\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\r\n .map(service => service.INTERNAL.delete()),\r\n ...services\r\n .filter(service => '_delete' in service) // modularized services\r\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\r\n .map(service => service._delete())\r\n ]);\r\n }\r\n isComponentSet() {\r\n return this.component != null;\r\n }\r\n isInitialized(identifier = DEFAULT_ENTRY_NAME) {\r\n return this.instances.has(identifier);\r\n }\r\n getOptions(identifier = DEFAULT_ENTRY_NAME) {\r\n return this.instancesOptions.get(identifier) || {};\r\n }\r\n initialize(opts = {}) {\r\n const { options = {} } = opts;\r\n const normalizedIdentifier = this.normalizeInstanceIdentifier(opts.instanceIdentifier);\r\n if (this.isInitialized(normalizedIdentifier)) {\r\n throw Error(`${this.name}(${normalizedIdentifier}) has already been initialized`);\r\n }\r\n if (!this.isComponentSet()) {\r\n throw Error(`Component ${this.name} has not been registered yet`);\r\n }\r\n const instance = this.getOrInitializeService({\r\n instanceIdentifier: normalizedIdentifier,\r\n options\r\n });\r\n // resolve any pending promise waiting for the service instance\r\n for (const [instanceIdentifier, instanceDeferred] of this.instancesDeferred.entries()) {\r\n const normalizedDeferredIdentifier = this.normalizeInstanceIdentifier(instanceIdentifier);\r\n if (normalizedIdentifier === normalizedDeferredIdentifier) {\r\n instanceDeferred.resolve(instance);\r\n }\r\n }\r\n return instance;\r\n }\r\n /**\r\n *\r\n * @param callback - a function that will be invoked after the provider has been initialized by calling provider.initialize().\r\n * The function is invoked SYNCHRONOUSLY, so it should not execute any longrunning tasks in order to not block the program.\r\n *\r\n * @param identifier An optional instance identifier\r\n * @returns a function to unregister the callback\r\n */\r\n onInit(callback, identifier) {\r\n var _a;\r\n const normalizedIdentifier = this.normalizeInstanceIdentifier(identifier);\r\n const existingCallbacks = (_a = this.onInitCallbacks.get(normalizedIdentifier)) !== null && _a !== void 0 ? _a : new Set();\r\n existingCallbacks.add(callback);\r\n this.onInitCallbacks.set(normalizedIdentifier, existingCallbacks);\r\n const existingInstance = this.instances.get(normalizedIdentifier);\r\n if (existingInstance) {\r\n callback(existingInstance, normalizedIdentifier);\r\n }\r\n return () => {\r\n existingCallbacks.delete(callback);\r\n };\r\n }\r\n /**\r\n * Invoke onInit callbacks synchronously\r\n * @param instance the service instance`\r\n */\r\n invokeOnInitCallbacks(instance, identifier) {\r\n const callbacks = this.onInitCallbacks.get(identifier);\r\n if (!callbacks) {\r\n return;\r\n }\r\n for (const callback of callbacks) {\r\n try {\r\n callback(instance, identifier);\r\n }\r\n catch (_a) {\r\n // ignore errors in the onInit callback\r\n }\r\n }\r\n }\r\n getOrInitializeService({ instanceIdentifier, options = {} }) {\r\n let instance = this.instances.get(instanceIdentifier);\r\n if (!instance && this.component) {\r\n instance = this.component.instanceFactory(this.container, {\r\n instanceIdentifier: normalizeIdentifierForFactory(instanceIdentifier),\r\n options\r\n });\r\n this.instances.set(instanceIdentifier, instance);\r\n this.instancesOptions.set(instanceIdentifier, options);\r\n /**\r\n * Invoke onInit listeners.\r\n * Note this.component.onInstanceCreated is different, which is used by the component creator,\r\n * while onInit listeners are registered by consumers of the provider.\r\n */\r\n this.invokeOnInitCallbacks(instance, instanceIdentifier);\r\n /**\r\n * Order is important\r\n * onInstanceCreated() should be called after this.instances.set(instanceIdentifier, instance); which\r\n * makes `isInitialized()` return true.\r\n */\r\n if (this.component.onInstanceCreated) {\r\n try {\r\n this.component.onInstanceCreated(this.container, instanceIdentifier, instance);\r\n }\r\n catch (_a) {\r\n // ignore errors in the onInstanceCreatedCallback\r\n }\r\n }\r\n }\r\n return instance || null;\r\n }\r\n normalizeInstanceIdentifier(identifier = DEFAULT_ENTRY_NAME) {\r\n if (this.component) {\r\n return this.component.multipleInstances ? identifier : DEFAULT_ENTRY_NAME;\r\n }\r\n else {\r\n return identifier; // assume multiple instances are supported before the component is provided.\r\n }\r\n }\r\n shouldAutoInitialize() {\r\n return (!!this.component &&\r\n this.component.instantiationMode !== \"EXPLICIT\" /* InstantiationMode.EXPLICIT */);\r\n }\r\n}\r\n// undefined should be passed to the service factory for the default instance\r\nfunction normalizeIdentifierForFactory(identifier) {\r\n return identifier === DEFAULT_ENTRY_NAME ? undefined : identifier;\r\n}\r\nfunction isComponentEager(component) {\r\n return component.instantiationMode === \"EAGER\" /* InstantiationMode.EAGER */;\r\n}\n\n/**\r\n * @license\r\n * Copyright 2019 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * ComponentContainer that provides Providers for service name T, e.g. `auth`, `auth-internal`\r\n */\r\nclass ComponentContainer {\r\n constructor(name) {\r\n this.name = name;\r\n this.providers = new Map();\r\n }\r\n /**\r\n *\r\n * @param component Component being added\r\n * @param overwrite When a component with the same name has already been registered,\r\n * if overwrite is true: overwrite the existing component with the new component and create a new\r\n * provider with the new component. It can be useful in tests where you want to use different mocks\r\n * for different tests.\r\n * if overwrite is false: throw an exception\r\n */\r\n addComponent(component) {\r\n const provider = this.getProvider(component.name);\r\n if (provider.isComponentSet()) {\r\n throw new Error(`Component ${component.name} has already been registered with ${this.name}`);\r\n }\r\n provider.setComponent(component);\r\n }\r\n addOrOverwriteComponent(component) {\r\n const provider = this.getProvider(component.name);\r\n if (provider.isComponentSet()) {\r\n // delete the existing provider from the container, so we can register the new component\r\n this.providers.delete(component.name);\r\n }\r\n this.addComponent(component);\r\n }\r\n /**\r\n * getProvider provides a type safe interface where it can only be called with a field name\r\n * present in NameServiceMapping interface.\r\n *\r\n * Firebase SDKs providing services should extend NameServiceMapping interface to register\r\n * themselves.\r\n */\r\n getProvider(name) {\r\n if (this.providers.has(name)) {\r\n return this.providers.get(name);\r\n }\r\n // create a Provider for a service that hasn't registered with Firebase\r\n const provider = new Provider(name, this);\r\n this.providers.set(name, provider);\r\n return provider;\r\n }\r\n getProviders() {\r\n return Array.from(this.providers.values());\r\n }\r\n}\n\nexport { Component, ComponentContainer, Provider };\n//# sourceMappingURL=index.esm2017.js.map\n","/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * A container for all of the Logger instances\r\n */\r\nconst instances = [];\r\n/**\r\n * The JS SDK supports 5 log levels and also allows a user the ability to\r\n * silence the logs altogether.\r\n *\r\n * The order is a follows:\r\n * DEBUG < VERBOSE < INFO < WARN < ERROR\r\n *\r\n * All of the log types above the current log level will be captured (i.e. if\r\n * you set the log level to `INFO`, errors will still be logged, but `DEBUG` and\r\n * `VERBOSE` logs will not)\r\n */\r\nvar LogLevel;\r\n(function (LogLevel) {\r\n LogLevel[LogLevel[\"DEBUG\"] = 0] = \"DEBUG\";\r\n LogLevel[LogLevel[\"VERBOSE\"] = 1] = \"VERBOSE\";\r\n LogLevel[LogLevel[\"INFO\"] = 2] = \"INFO\";\r\n LogLevel[LogLevel[\"WARN\"] = 3] = \"WARN\";\r\n LogLevel[LogLevel[\"ERROR\"] = 4] = \"ERROR\";\r\n LogLevel[LogLevel[\"SILENT\"] = 5] = \"SILENT\";\r\n})(LogLevel || (LogLevel = {}));\r\nconst levelStringToEnum = {\r\n 'debug': LogLevel.DEBUG,\r\n 'verbose': LogLevel.VERBOSE,\r\n 'info': LogLevel.INFO,\r\n 'warn': LogLevel.WARN,\r\n 'error': LogLevel.ERROR,\r\n 'silent': LogLevel.SILENT\r\n};\r\n/**\r\n * The default log level\r\n */\r\nconst defaultLogLevel = LogLevel.INFO;\r\n/**\r\n * By default, `console.debug` is not displayed in the developer console (in\r\n * chrome). To avoid forcing users to have to opt-in to these logs twice\r\n * (i.e. once for firebase, and once in the console), we are sending `DEBUG`\r\n * logs to the `console.log` function.\r\n */\r\nconst ConsoleMethod = {\r\n [LogLevel.DEBUG]: 'log',\r\n [LogLevel.VERBOSE]: 'log',\r\n [LogLevel.INFO]: 'info',\r\n [LogLevel.WARN]: 'warn',\r\n [LogLevel.ERROR]: 'error'\r\n};\r\n/**\r\n * The default log handler will forward DEBUG, VERBOSE, INFO, WARN, and ERROR\r\n * messages on to their corresponding console counterparts (if the log method\r\n * is supported by the current log level)\r\n */\r\nconst defaultLogHandler = (instance, logType, ...args) => {\r\n if (logType < instance.logLevel) {\r\n return;\r\n }\r\n const now = new Date().toISOString();\r\n const method = ConsoleMethod[logType];\r\n if (method) {\r\n console[method](`[${now}] ${instance.name}:`, ...args);\r\n }\r\n else {\r\n throw new Error(`Attempted to log a message with an invalid logType (value: ${logType})`);\r\n }\r\n};\r\nclass Logger {\r\n /**\r\n * Gives you an instance of a Logger to capture messages according to\r\n * Firebase's logging scheme.\r\n *\r\n * @param name The name that the logs will be associated with\r\n */\r\n constructor(name) {\r\n this.name = name;\r\n /**\r\n * The log level of the given Logger instance.\r\n */\r\n this._logLevel = defaultLogLevel;\r\n /**\r\n * The main (internal) log handler for the Logger instance.\r\n * Can be set to a new function in internal package code but not by user.\r\n */\r\n this._logHandler = defaultLogHandler;\r\n /**\r\n * The optional, additional, user-defined log handler for the Logger instance.\r\n */\r\n this._userLogHandler = null;\r\n /**\r\n * Capture the current instance for later use\r\n */\r\n instances.push(this);\r\n }\r\n get logLevel() {\r\n return this._logLevel;\r\n }\r\n set logLevel(val) {\r\n if (!(val in LogLevel)) {\r\n throw new TypeError(`Invalid value \"${val}\" assigned to \\`logLevel\\``);\r\n }\r\n this._logLevel = val;\r\n }\r\n // Workaround for setter/getter having to be the same type.\r\n setLogLevel(val) {\r\n this._logLevel = typeof val === 'string' ? levelStringToEnum[val] : val;\r\n }\r\n get logHandler() {\r\n return this._logHandler;\r\n }\r\n set logHandler(val) {\r\n if (typeof val !== 'function') {\r\n throw new TypeError('Value assigned to `logHandler` must be a function');\r\n }\r\n this._logHandler = val;\r\n }\r\n get userLogHandler() {\r\n return this._userLogHandler;\r\n }\r\n set userLogHandler(val) {\r\n this._userLogHandler = val;\r\n }\r\n /**\r\n * The functions below are all based on the `console` interface\r\n */\r\n debug(...args) {\r\n this._userLogHandler && this._userLogHandler(this, LogLevel.DEBUG, ...args);\r\n this._logHandler(this, LogLevel.DEBUG, ...args);\r\n }\r\n log(...args) {\r\n this._userLogHandler &&\r\n this._userLogHandler(this, LogLevel.VERBOSE, ...args);\r\n this._logHandler(this, LogLevel.VERBOSE, ...args);\r\n }\r\n info(...args) {\r\n this._userLogHandler && this._userLogHandler(this, LogLevel.INFO, ...args);\r\n this._logHandler(this, LogLevel.INFO, ...args);\r\n }\r\n warn(...args) {\r\n this._userLogHandler && this._userLogHandler(this, LogLevel.WARN, ...args);\r\n this._logHandler(this, LogLevel.WARN, ...args);\r\n }\r\n error(...args) {\r\n this._userLogHandler && this._userLogHandler(this, LogLevel.ERROR, ...args);\r\n this._logHandler(this, LogLevel.ERROR, ...args);\r\n }\r\n}\r\nfunction setLogLevel(level) {\r\n instances.forEach(inst => {\r\n inst.setLogLevel(level);\r\n });\r\n}\r\nfunction setUserLogHandler(logCallback, options) {\r\n for (const instance of instances) {\r\n let customLogLevel = null;\r\n if (options && options.level) {\r\n customLogLevel = levelStringToEnum[options.level];\r\n }\r\n if (logCallback === null) {\r\n instance.userLogHandler = null;\r\n }\r\n else {\r\n instance.userLogHandler = (instance, level, ...args) => {\r\n const message = args\r\n .map(arg => {\r\n if (arg == null) {\r\n return null;\r\n }\r\n else if (typeof arg === 'string') {\r\n return arg;\r\n }\r\n else if (typeof arg === 'number' || typeof arg === 'boolean') {\r\n return arg.toString();\r\n }\r\n else if (arg instanceof Error) {\r\n return arg.message;\r\n }\r\n else {\r\n try {\r\n return JSON.stringify(arg);\r\n }\r\n catch (ignored) {\r\n return null;\r\n }\r\n }\r\n })\r\n .filter(arg => arg)\r\n .join(' ');\r\n if (level >= (customLogLevel !== null && customLogLevel !== void 0 ? customLogLevel : instance.logLevel)) {\r\n logCallback({\r\n level: LogLevel[level].toLowerCase(),\r\n message,\r\n args,\r\n type: instance.name\r\n });\r\n }\r\n };\r\n }\r\n }\r\n}\n\nexport { LogLevel, Logger, setLogLevel, setUserLogHandler };\n//# sourceMappingURL=index.esm2017.js.map\n","const instanceOfAny = (object, constructors) => constructors.some((c) => object instanceof c);\n\nlet idbProxyableTypes;\nlet cursorAdvanceMethods;\n// This is a function to prevent it throwing up in node environments.\nfunction getIdbProxyableTypes() {\n return (idbProxyableTypes ||\n (idbProxyableTypes = [\n IDBDatabase,\n IDBObjectStore,\n IDBIndex,\n IDBCursor,\n IDBTransaction,\n ]));\n}\n// This is a function to prevent it throwing up in node environments.\nfunction getCursorAdvanceMethods() {\n return (cursorAdvanceMethods ||\n (cursorAdvanceMethods = [\n IDBCursor.prototype.advance,\n IDBCursor.prototype.continue,\n IDBCursor.prototype.continuePrimaryKey,\n ]));\n}\nconst cursorRequestMap = new WeakMap();\nconst transactionDoneMap = new WeakMap();\nconst transactionStoreNamesMap = new WeakMap();\nconst transformCache = new WeakMap();\nconst reverseTransformCache = new WeakMap();\nfunction promisifyRequest(request) {\n const promise = new Promise((resolve, reject) => {\n const unlisten = () => {\n request.removeEventListener('success', success);\n request.removeEventListener('error', error);\n };\n const success = () => {\n resolve(wrap(request.result));\n unlisten();\n };\n const error = () => {\n reject(request.error);\n unlisten();\n };\n request.addEventListener('success', success);\n request.addEventListener('error', error);\n });\n promise\n .then((value) => {\n // Since cursoring reuses the IDBRequest (*sigh*), we cache it for later retrieval\n // (see wrapFunction).\n if (value instanceof IDBCursor) {\n cursorRequestMap.set(value, request);\n }\n // Catching to avoid \"Uncaught Promise exceptions\"\n })\n .catch(() => { });\n // This mapping exists in reverseTransformCache but doesn't doesn't exist in transformCache. This\n // is because we create many promises from a single IDBRequest.\n reverseTransformCache.set(promise, request);\n return promise;\n}\nfunction cacheDonePromiseForTransaction(tx) {\n // Early bail if we've already created a done promise for this transaction.\n if (transactionDoneMap.has(tx))\n return;\n const done = new Promise((resolve, reject) => {\n const unlisten = () => {\n tx.removeEventListener('complete', complete);\n tx.removeEventListener('error', error);\n tx.removeEventListener('abort', error);\n };\n const complete = () => {\n resolve();\n unlisten();\n };\n const error = () => {\n reject(tx.error || new DOMException('AbortError', 'AbortError'));\n unlisten();\n };\n tx.addEventListener('complete', complete);\n tx.addEventListener('error', error);\n tx.addEventListener('abort', error);\n });\n // Cache it for later retrieval.\n transactionDoneMap.set(tx, done);\n}\nlet idbProxyTraps = {\n get(target, prop, receiver) {\n if (target instanceof IDBTransaction) {\n // Special handling for transaction.done.\n if (prop === 'done')\n return transactionDoneMap.get(target);\n // Polyfill for objectStoreNames because of Edge.\n if (prop === 'objectStoreNames') {\n return target.objectStoreNames || transactionStoreNamesMap.get(target);\n }\n // Make tx.store return the only store in the transaction, or undefined if there are many.\n if (prop === 'store') {\n return receiver.objectStoreNames[1]\n ? undefined\n : receiver.objectStore(receiver.objectStoreNames[0]);\n }\n }\n // Else transform whatever we get back.\n return wrap(target[prop]);\n },\n set(target, prop, value) {\n target[prop] = value;\n return true;\n },\n has(target, prop) {\n if (target instanceof IDBTransaction &&\n (prop === 'done' || prop === 'store')) {\n return true;\n }\n return prop in target;\n },\n};\nfunction replaceTraps(callback) {\n idbProxyTraps = callback(idbProxyTraps);\n}\nfunction wrapFunction(func) {\n // Due to expected object equality (which is enforced by the caching in `wrap`), we\n // only create one new func per func.\n // Edge doesn't support objectStoreNames (booo), so we polyfill it here.\n if (func === IDBDatabase.prototype.transaction &&\n !('objectStoreNames' in IDBTransaction.prototype)) {\n return function (storeNames, ...args) {\n const tx = func.call(unwrap(this), storeNames, ...args);\n transactionStoreNamesMap.set(tx, storeNames.sort ? storeNames.sort() : [storeNames]);\n return wrap(tx);\n };\n }\n // Cursor methods are special, as the behaviour is a little more different to standard IDB. In\n // IDB, you advance the cursor and wait for a new 'success' on the IDBRequest that gave you the\n // cursor. It's kinda like a promise that can resolve with many values. That doesn't make sense\n // with real promises, so each advance methods returns a new promise for the cursor object, or\n // undefined if the end of the cursor has been reached.\n if (getCursorAdvanceMethods().includes(func)) {\n return function (...args) {\n // Calling the original function with the proxy as 'this' causes ILLEGAL INVOCATION, so we use\n // the original object.\n func.apply(unwrap(this), args);\n return wrap(cursorRequestMap.get(this));\n };\n }\n return function (...args) {\n // Calling the original function with the proxy as 'this' causes ILLEGAL INVOCATION, so we use\n // the original object.\n return wrap(func.apply(unwrap(this), args));\n };\n}\nfunction transformCachableValue(value) {\n if (typeof value === 'function')\n return wrapFunction(value);\n // This doesn't return, it just creates a 'done' promise for the transaction,\n // which is later returned for transaction.done (see idbObjectHandler).\n if (value instanceof IDBTransaction)\n cacheDonePromiseForTransaction(value);\n if (instanceOfAny(value, getIdbProxyableTypes()))\n return new Proxy(value, idbProxyTraps);\n // Return the same value back if we're not going to transform it.\n return value;\n}\nfunction wrap(value) {\n // We sometimes generate multiple promises from a single IDBRequest (eg when cursoring), because\n // IDB is weird and a single IDBRequest can yield many responses, so these can't be cached.\n if (value instanceof IDBRequest)\n return promisifyRequest(value);\n // If we've already transformed this value before, reuse the transformed value.\n // This is faster, but it also provides object equality.\n if (transformCache.has(value))\n return transformCache.get(value);\n const newValue = transformCachableValue(value);\n // Not all types are transformed.\n // These may be primitive types, so they can't be WeakMap keys.\n if (newValue !== value) {\n transformCache.set(value, newValue);\n reverseTransformCache.set(newValue, value);\n }\n return newValue;\n}\nconst unwrap = (value) => reverseTransformCache.get(value);\n\nexport { reverseTransformCache as a, instanceOfAny as i, replaceTraps as r, unwrap as u, wrap as w };\n","import { w as wrap, r as replaceTraps } from './wrap-idb-value.js';\nexport { u as unwrap, w as wrap } from './wrap-idb-value.js';\n\n/**\n * Open a database.\n *\n * @param name Name of the database.\n * @param version Schema version.\n * @param callbacks Additional callbacks.\n */\nfunction openDB(name, version, { blocked, upgrade, blocking, terminated } = {}) {\n const request = indexedDB.open(name, version);\n const openPromise = wrap(request);\n if (upgrade) {\n request.addEventListener('upgradeneeded', (event) => {\n upgrade(wrap(request.result), event.oldVersion, event.newVersion, wrap(request.transaction), event);\n });\n }\n if (blocked) {\n request.addEventListener('blocked', (event) => blocked(\n // Casting due to https://github.com/microsoft/TypeScript-DOM-lib-generator/pull/1405\n event.oldVersion, event.newVersion, event));\n }\n openPromise\n .then((db) => {\n if (terminated)\n db.addEventListener('close', () => terminated());\n if (blocking) {\n db.addEventListener('versionchange', (event) => blocking(event.oldVersion, event.newVersion, event));\n }\n })\n .catch(() => { });\n return openPromise;\n}\n/**\n * Delete a database.\n *\n * @param name Name of the database.\n */\nfunction deleteDB(name, { blocked } = {}) {\n const request = indexedDB.deleteDatabase(name);\n if (blocked) {\n request.addEventListener('blocked', (event) => blocked(\n // Casting due to https://github.com/microsoft/TypeScript-DOM-lib-generator/pull/1405\n event.oldVersion, event));\n }\n return wrap(request).then(() => undefined);\n}\n\nconst readMethods = ['get', 'getKey', 'getAll', 'getAllKeys', 'count'];\nconst writeMethods = ['put', 'add', 'delete', 'clear'];\nconst cachedMethods = new Map();\nfunction getMethod(target, prop) {\n if (!(target instanceof IDBDatabase &&\n !(prop in target) &&\n typeof prop === 'string')) {\n return;\n }\n if (cachedMethods.get(prop))\n return cachedMethods.get(prop);\n const targetFuncName = prop.replace(/FromIndex$/, '');\n const useIndex = prop !== targetFuncName;\n const isWrite = writeMethods.includes(targetFuncName);\n if (\n // Bail if the target doesn't exist on the target. Eg, getAll isn't in Edge.\n !(targetFuncName in (useIndex ? IDBIndex : IDBObjectStore).prototype) ||\n !(isWrite || readMethods.includes(targetFuncName))) {\n return;\n }\n const method = async function (storeName, ...args) {\n // isWrite ? 'readwrite' : undefined gzipps better, but fails in Edge :(\n const tx = this.transaction(storeName, isWrite ? 'readwrite' : 'readonly');\n let target = tx.store;\n if (useIndex)\n target = target.index(args.shift());\n // Must reject if op rejects.\n // If it's a write operation, must reject if tx.done rejects.\n // Must reject with op rejection first.\n // Must resolve with op value.\n // Must handle both promises (no unhandled rejections)\n return (await Promise.all([\n target[targetFuncName](...args),\n isWrite && tx.done,\n ]))[0];\n };\n cachedMethods.set(prop, method);\n return method;\n}\nreplaceTraps((oldTraps) => ({\n ...oldTraps,\n get: (target, prop, receiver) => getMethod(target, prop) || oldTraps.get(target, prop, receiver),\n has: (target, prop) => !!getMethod(target, prop) || oldTraps.has(target, prop),\n}));\n\nexport { deleteDB, openDB };\n","import { Component, ComponentContainer } from '@firebase/component';\nimport { Logger, setUserLogHandler, setLogLevel as setLogLevel$1 } from '@firebase/logger';\nimport { ErrorFactory, getDefaultAppConfig, deepEqual, FirebaseError, base64urlEncodeWithoutPadding, isIndexedDBAvailable, validateIndexedDBOpenable } from '@firebase/util';\nexport { FirebaseError } from '@firebase/util';\nimport { openDB } from 'idb';\n\n/**\r\n * @license\r\n * Copyright 2019 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nclass PlatformLoggerServiceImpl {\r\n constructor(container) {\r\n this.container = container;\r\n }\r\n // In initial implementation, this will be called by installations on\r\n // auth token refresh, and installations will send this string.\r\n getPlatformInfoString() {\r\n const providers = this.container.getProviders();\r\n // Loop through providers and get library/version pairs from any that are\r\n // version components.\r\n return providers\r\n .map(provider => {\r\n if (isVersionServiceProvider(provider)) {\r\n const service = provider.getImmediate();\r\n return `${service.library}/${service.version}`;\r\n }\r\n else {\r\n return null;\r\n }\r\n })\r\n .filter(logString => logString)\r\n .join(' ');\r\n }\r\n}\r\n/**\r\n *\r\n * @param provider check if this provider provides a VersionService\r\n *\r\n * NOTE: Using Provider<'app-version'> is a hack to indicate that the provider\r\n * provides VersionService. The provider is not necessarily a 'app-version'\r\n * provider.\r\n */\r\nfunction isVersionServiceProvider(provider) {\r\n const component = provider.getComponent();\r\n return (component === null || component === void 0 ? void 0 : component.type) === \"VERSION\" /* ComponentType.VERSION */;\r\n}\n\nconst name$o = \"@firebase/app\";\nconst version$1 = \"0.9.13\";\n\n/**\r\n * @license\r\n * Copyright 2019 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nconst logger = new Logger('@firebase/app');\n\nconst name$n = \"@firebase/app-compat\";\n\nconst name$m = \"@firebase/analytics-compat\";\n\nconst name$l = \"@firebase/analytics\";\n\nconst name$k = \"@firebase/app-check-compat\";\n\nconst name$j = \"@firebase/app-check\";\n\nconst name$i = \"@firebase/auth\";\n\nconst name$h = \"@firebase/auth-compat\";\n\nconst name$g = \"@firebase/database\";\n\nconst name$f = \"@firebase/database-compat\";\n\nconst name$e = \"@firebase/functions\";\n\nconst name$d = \"@firebase/functions-compat\";\n\nconst name$c = \"@firebase/installations\";\n\nconst name$b = \"@firebase/installations-compat\";\n\nconst name$a = \"@firebase/messaging\";\n\nconst name$9 = \"@firebase/messaging-compat\";\n\nconst name$8 = \"@firebase/performance\";\n\nconst name$7 = \"@firebase/performance-compat\";\n\nconst name$6 = \"@firebase/remote-config\";\n\nconst name$5 = \"@firebase/remote-config-compat\";\n\nconst name$4 = \"@firebase/storage\";\n\nconst name$3 = \"@firebase/storage-compat\";\n\nconst name$2 = \"@firebase/firestore\";\n\nconst name$1 = \"@firebase/firestore-compat\";\n\nconst name = \"firebase\";\nconst version = \"9.23.0\";\n\n/**\r\n * @license\r\n * Copyright 2019 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * The default app name\r\n *\r\n * @internal\r\n */\r\nconst DEFAULT_ENTRY_NAME = '[DEFAULT]';\r\nconst PLATFORM_LOG_STRING = {\r\n [name$o]: 'fire-core',\r\n [name$n]: 'fire-core-compat',\r\n [name$l]: 'fire-analytics',\r\n [name$m]: 'fire-analytics-compat',\r\n [name$j]: 'fire-app-check',\r\n [name$k]: 'fire-app-check-compat',\r\n [name$i]: 'fire-auth',\r\n [name$h]: 'fire-auth-compat',\r\n [name$g]: 'fire-rtdb',\r\n [name$f]: 'fire-rtdb-compat',\r\n [name$e]: 'fire-fn',\r\n [name$d]: 'fire-fn-compat',\r\n [name$c]: 'fire-iid',\r\n [name$b]: 'fire-iid-compat',\r\n [name$a]: 'fire-fcm',\r\n [name$9]: 'fire-fcm-compat',\r\n [name$8]: 'fire-perf',\r\n [name$7]: 'fire-perf-compat',\r\n [name$6]: 'fire-rc',\r\n [name$5]: 'fire-rc-compat',\r\n [name$4]: 'fire-gcs',\r\n [name$3]: 'fire-gcs-compat',\r\n [name$2]: 'fire-fst',\r\n [name$1]: 'fire-fst-compat',\r\n 'fire-js': 'fire-js',\r\n [name]: 'fire-js-all'\r\n};\n\n/**\r\n * @license\r\n * Copyright 2019 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * @internal\r\n */\r\nconst _apps = new Map();\r\n/**\r\n * Registered components.\r\n *\r\n * @internal\r\n */\r\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\r\nconst _components = new Map();\r\n/**\r\n * @param component - the component being added to this app's container\r\n *\r\n * @internal\r\n */\r\nfunction _addComponent(app, component) {\r\n try {\r\n app.container.addComponent(component);\r\n }\r\n catch (e) {\r\n logger.debug(`Component ${component.name} failed to register with FirebaseApp ${app.name}`, e);\r\n }\r\n}\r\n/**\r\n *\r\n * @internal\r\n */\r\nfunction _addOrOverwriteComponent(app, component) {\r\n app.container.addOrOverwriteComponent(component);\r\n}\r\n/**\r\n *\r\n * @param component - the component to register\r\n * @returns whether or not the component is registered successfully\r\n *\r\n * @internal\r\n */\r\nfunction _registerComponent(component) {\r\n const componentName = component.name;\r\n if (_components.has(componentName)) {\r\n logger.debug(`There were multiple attempts to register component ${componentName}.`);\r\n return false;\r\n }\r\n _components.set(componentName, component);\r\n // add the component to existing app instances\r\n for (const app of _apps.values()) {\r\n _addComponent(app, component);\r\n }\r\n return true;\r\n}\r\n/**\r\n *\r\n * @param app - FirebaseApp instance\r\n * @param name - service name\r\n *\r\n * @returns the provider for the service with the matching name\r\n *\r\n * @internal\r\n */\r\nfunction _getProvider(app, name) {\r\n const heartbeatController = app.container\r\n .getProvider('heartbeat')\r\n .getImmediate({ optional: true });\r\n if (heartbeatController) {\r\n void heartbeatController.triggerHeartbeat();\r\n }\r\n return app.container.getProvider(name);\r\n}\r\n/**\r\n *\r\n * @param app - FirebaseApp instance\r\n * @param name - service name\r\n * @param instanceIdentifier - service instance identifier in case the service supports multiple instances\r\n *\r\n * @internal\r\n */\r\nfunction _removeServiceInstance(app, name, instanceIdentifier = DEFAULT_ENTRY_NAME) {\r\n _getProvider(app, name).clearInstance(instanceIdentifier);\r\n}\r\n/**\r\n * Test only\r\n *\r\n * @internal\r\n */\r\nfunction _clearComponents() {\r\n _components.clear();\r\n}\n\n/**\r\n * @license\r\n * Copyright 2019 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nconst ERRORS = {\r\n [\"no-app\" /* AppError.NO_APP */]: \"No Firebase App '{$appName}' has been created - \" +\r\n 'call initializeApp() first',\r\n [\"bad-app-name\" /* AppError.BAD_APP_NAME */]: \"Illegal App name: '{$appName}\",\r\n [\"duplicate-app\" /* AppError.DUPLICATE_APP */]: \"Firebase App named '{$appName}' already exists with different options or config\",\r\n [\"app-deleted\" /* AppError.APP_DELETED */]: \"Firebase App named '{$appName}' already deleted\",\r\n [\"no-options\" /* AppError.NO_OPTIONS */]: 'Need to provide options, when not being deployed to hosting via source.',\r\n [\"invalid-app-argument\" /* AppError.INVALID_APP_ARGUMENT */]: 'firebase.{$appName}() takes either no argument or a ' +\r\n 'Firebase App instance.',\r\n [\"invalid-log-argument\" /* AppError.INVALID_LOG_ARGUMENT */]: 'First argument to `onLog` must be null or a function.',\r\n [\"idb-open\" /* AppError.IDB_OPEN */]: 'Error thrown when opening IndexedDB. Original error: {$originalErrorMessage}.',\r\n [\"idb-get\" /* AppError.IDB_GET */]: 'Error thrown when reading from IndexedDB. Original error: {$originalErrorMessage}.',\r\n [\"idb-set\" /* AppError.IDB_WRITE */]: 'Error thrown when writing to IndexedDB. Original error: {$originalErrorMessage}.',\r\n [\"idb-delete\" /* AppError.IDB_DELETE */]: 'Error thrown when deleting from IndexedDB. Original error: {$originalErrorMessage}.'\r\n};\r\nconst ERROR_FACTORY = new ErrorFactory('app', 'Firebase', ERRORS);\n\n/**\r\n * @license\r\n * Copyright 2019 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nclass FirebaseAppImpl {\r\n constructor(options, config, container) {\r\n this._isDeleted = false;\r\n this._options = Object.assign({}, options);\r\n this._config = Object.assign({}, config);\r\n this._name = config.name;\r\n this._automaticDataCollectionEnabled =\r\n config.automaticDataCollectionEnabled;\r\n this._container = container;\r\n this.container.addComponent(new Component('app', () => this, \"PUBLIC\" /* ComponentType.PUBLIC */));\r\n }\r\n get automaticDataCollectionEnabled() {\r\n this.checkDestroyed();\r\n return this._automaticDataCollectionEnabled;\r\n }\r\n set automaticDataCollectionEnabled(val) {\r\n this.checkDestroyed();\r\n this._automaticDataCollectionEnabled = val;\r\n }\r\n get name() {\r\n this.checkDestroyed();\r\n return this._name;\r\n }\r\n get options() {\r\n this.checkDestroyed();\r\n return this._options;\r\n }\r\n get config() {\r\n this.checkDestroyed();\r\n return this._config;\r\n }\r\n get container() {\r\n return this._container;\r\n }\r\n get isDeleted() {\r\n return this._isDeleted;\r\n }\r\n set isDeleted(val) {\r\n this._isDeleted = val;\r\n }\r\n /**\r\n * This function will throw an Error if the App has already been deleted -\r\n * use before performing API actions on the App.\r\n */\r\n checkDestroyed() {\r\n if (this.isDeleted) {\r\n throw ERROR_FACTORY.create(\"app-deleted\" /* AppError.APP_DELETED */, { appName: this._name });\r\n }\r\n }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2019 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * The current SDK version.\r\n *\r\n * @public\r\n */\r\nconst SDK_VERSION = version;\r\nfunction initializeApp(_options, rawConfig = {}) {\r\n let options = _options;\r\n if (typeof rawConfig !== 'object') {\r\n const name = rawConfig;\r\n rawConfig = { name };\r\n }\r\n const config = Object.assign({ name: DEFAULT_ENTRY_NAME, automaticDataCollectionEnabled: false }, rawConfig);\r\n const name = config.name;\r\n if (typeof name !== 'string' || !name) {\r\n throw ERROR_FACTORY.create(\"bad-app-name\" /* AppError.BAD_APP_NAME */, {\r\n appName: String(name)\r\n });\r\n }\r\n options || (options = getDefaultAppConfig());\r\n if (!options) {\r\n throw ERROR_FACTORY.create(\"no-options\" /* AppError.NO_OPTIONS */);\r\n }\r\n const existingApp = _apps.get(name);\r\n if (existingApp) {\r\n // return the existing app if options and config deep equal the ones in the existing app.\r\n if (deepEqual(options, existingApp.options) &&\r\n deepEqual(config, existingApp.config)) {\r\n return existingApp;\r\n }\r\n else {\r\n throw ERROR_FACTORY.create(\"duplicate-app\" /* AppError.DUPLICATE_APP */, { appName: name });\r\n }\r\n }\r\n const container = new ComponentContainer(name);\r\n for (const component of _components.values()) {\r\n container.addComponent(component);\r\n }\r\n const newApp = new FirebaseAppImpl(options, config, container);\r\n _apps.set(name, newApp);\r\n return newApp;\r\n}\r\n/**\r\n * Retrieves a {@link @firebase/app#FirebaseApp} instance.\r\n *\r\n * When called with no arguments, the default app is returned. When an app name\r\n * is provided, the app corresponding to that name is returned.\r\n *\r\n * An exception is thrown if the app being retrieved has not yet been\r\n * initialized.\r\n *\r\n * @example\r\n * ```javascript\r\n * // Return the default app\r\n * const app = getApp();\r\n * ```\r\n *\r\n * @example\r\n * ```javascript\r\n * // Return a named app\r\n * const otherApp = getApp(\"otherApp\");\r\n * ```\r\n *\r\n * @param name - Optional name of the app to return. If no name is\r\n * provided, the default is `\"[DEFAULT]\"`.\r\n *\r\n * @returns The app corresponding to the provided app name.\r\n * If no app name is provided, the default app is returned.\r\n *\r\n * @public\r\n */\r\nfunction getApp(name = DEFAULT_ENTRY_NAME) {\r\n const app = _apps.get(name);\r\n if (!app && name === DEFAULT_ENTRY_NAME && getDefaultAppConfig()) {\r\n return initializeApp();\r\n }\r\n if (!app) {\r\n throw ERROR_FACTORY.create(\"no-app\" /* AppError.NO_APP */, { appName: name });\r\n }\r\n return app;\r\n}\r\n/**\r\n * A (read-only) array of all initialized apps.\r\n * @public\r\n */\r\nfunction getApps() {\r\n return Array.from(_apps.values());\r\n}\r\n/**\r\n * Renders this app unusable and frees the resources of all associated\r\n * services.\r\n *\r\n * @example\r\n * ```javascript\r\n * deleteApp(app)\r\n * .then(function() {\r\n * console.log(\"App deleted successfully\");\r\n * })\r\n * .catch(function(error) {\r\n * console.log(\"Error deleting app:\", error);\r\n * });\r\n * ```\r\n *\r\n * @public\r\n */\r\nasync function deleteApp(app) {\r\n const name = app.name;\r\n if (_apps.has(name)) {\r\n _apps.delete(name);\r\n await Promise.all(app.container\r\n .getProviders()\r\n .map(provider => provider.delete()));\r\n app.isDeleted = true;\r\n }\r\n}\r\n/**\r\n * Registers a library's name and version for platform logging purposes.\r\n * @param library - Name of 1p or 3p library (e.g. firestore, angularfire)\r\n * @param version - Current version of that library.\r\n * @param variant - Bundle variant, e.g., node, rn, etc.\r\n *\r\n * @public\r\n */\r\nfunction registerVersion(libraryKeyOrName, version, variant) {\r\n var _a;\r\n // TODO: We can use this check to whitelist strings when/if we set up\r\n // a good whitelist system.\r\n let library = (_a = PLATFORM_LOG_STRING[libraryKeyOrName]) !== null && _a !== void 0 ? _a : libraryKeyOrName;\r\n if (variant) {\r\n library += `-${variant}`;\r\n }\r\n const libraryMismatch = library.match(/\\s|\\//);\r\n const versionMismatch = version.match(/\\s|\\//);\r\n if (libraryMismatch || versionMismatch) {\r\n const warning = [\r\n `Unable to register library \"${library}\" with version \"${version}\":`\r\n ];\r\n if (libraryMismatch) {\r\n warning.push(`library name \"${library}\" contains illegal characters (whitespace or \"/\")`);\r\n }\r\n if (libraryMismatch && versionMismatch) {\r\n warning.push('and');\r\n }\r\n if (versionMismatch) {\r\n warning.push(`version name \"${version}\" contains illegal characters (whitespace or \"/\")`);\r\n }\r\n logger.warn(warning.join(' '));\r\n return;\r\n }\r\n _registerComponent(new Component(`${library}-version`, () => ({ library, version }), \"VERSION\" /* ComponentType.VERSION */));\r\n}\r\n/**\r\n * Sets log handler for all Firebase SDKs.\r\n * @param logCallback - An optional custom log handler that executes user code whenever\r\n * the Firebase SDK makes a logging call.\r\n *\r\n * @public\r\n */\r\nfunction onLog(logCallback, options) {\r\n if (logCallback !== null && typeof logCallback !== 'function') {\r\n throw ERROR_FACTORY.create(\"invalid-log-argument\" /* AppError.INVALID_LOG_ARGUMENT */);\r\n }\r\n setUserLogHandler(logCallback, options);\r\n}\r\n/**\r\n * Sets log level for all Firebase SDKs.\r\n *\r\n * All of the log types above the current log level are captured (i.e. if\r\n * you set the log level to `info`, errors are logged, but `debug` and\r\n * `verbose` logs are not).\r\n *\r\n * @public\r\n */\r\nfunction setLogLevel(logLevel) {\r\n setLogLevel$1(logLevel);\r\n}\n\n/**\r\n * @license\r\n * Copyright 2021 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nconst DB_NAME = 'firebase-heartbeat-database';\r\nconst DB_VERSION = 1;\r\nconst STORE_NAME = 'firebase-heartbeat-store';\r\nlet dbPromise = null;\r\nfunction getDbPromise() {\r\n if (!dbPromise) {\r\n dbPromise = openDB(DB_NAME, DB_VERSION, {\r\n upgrade: (db, oldVersion) => {\r\n // We don't use 'break' in this switch statement, the fall-through\r\n // behavior is what we want, because if there are multiple versions between\r\n // the old version and the current version, we want ALL the migrations\r\n // that correspond to those versions to run, not only the last one.\r\n // eslint-disable-next-line default-case\r\n switch (oldVersion) {\r\n case 0:\r\n db.createObjectStore(STORE_NAME);\r\n }\r\n }\r\n }).catch(e => {\r\n throw ERROR_FACTORY.create(\"idb-open\" /* AppError.IDB_OPEN */, {\r\n originalErrorMessage: e.message\r\n });\r\n });\r\n }\r\n return dbPromise;\r\n}\r\nasync function readHeartbeatsFromIndexedDB(app) {\r\n try {\r\n const db = await getDbPromise();\r\n const result = await db\r\n .transaction(STORE_NAME)\r\n .objectStore(STORE_NAME)\r\n .get(computeKey(app));\r\n return result;\r\n }\r\n catch (e) {\r\n if (e instanceof FirebaseError) {\r\n logger.warn(e.message);\r\n }\r\n else {\r\n const idbGetError = ERROR_FACTORY.create(\"idb-get\" /* AppError.IDB_GET */, {\r\n originalErrorMessage: e === null || e === void 0 ? void 0 : e.message\r\n });\r\n logger.warn(idbGetError.message);\r\n }\r\n }\r\n}\r\nasync function writeHeartbeatsToIndexedDB(app, heartbeatObject) {\r\n try {\r\n const db = await getDbPromise();\r\n const tx = db.transaction(STORE_NAME, 'readwrite');\r\n const objectStore = tx.objectStore(STORE_NAME);\r\n await objectStore.put(heartbeatObject, computeKey(app));\r\n await tx.done;\r\n }\r\n catch (e) {\r\n if (e instanceof FirebaseError) {\r\n logger.warn(e.message);\r\n }\r\n else {\r\n const idbGetError = ERROR_FACTORY.create(\"idb-set\" /* AppError.IDB_WRITE */, {\r\n originalErrorMessage: e === null || e === void 0 ? void 0 : e.message\r\n });\r\n logger.warn(idbGetError.message);\r\n }\r\n }\r\n}\r\nfunction computeKey(app) {\r\n return `${app.name}!${app.options.appId}`;\r\n}\n\n/**\r\n * @license\r\n * Copyright 2021 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nconst MAX_HEADER_BYTES = 1024;\r\n// 30 days\r\nconst STORED_HEARTBEAT_RETENTION_MAX_MILLIS = 30 * 24 * 60 * 60 * 1000;\r\nclass HeartbeatServiceImpl {\r\n constructor(container) {\r\n this.container = container;\r\n /**\r\n * In-memory cache for heartbeats, used by getHeartbeatsHeader() to generate\r\n * the header string.\r\n * Stores one record per date. This will be consolidated into the standard\r\n * format of one record per user agent string before being sent as a header.\r\n * Populated from indexedDB when the controller is instantiated and should\r\n * be kept in sync with indexedDB.\r\n * Leave public for easier testing.\r\n */\r\n this._heartbeatsCache = null;\r\n const app = this.container.getProvider('app').getImmediate();\r\n this._storage = new HeartbeatStorageImpl(app);\r\n this._heartbeatsCachePromise = this._storage.read().then(result => {\r\n this._heartbeatsCache = result;\r\n return result;\r\n });\r\n }\r\n /**\r\n * Called to report a heartbeat. The function will generate\r\n * a HeartbeatsByUserAgent object, update heartbeatsCache, and persist it\r\n * to IndexedDB.\r\n * Note that we only store one heartbeat per day. So if a heartbeat for today is\r\n * already logged, subsequent calls to this function in the same day will be ignored.\r\n */\r\n async triggerHeartbeat() {\r\n const platformLogger = this.container\r\n .getProvider('platform-logger')\r\n .getImmediate();\r\n // This is the \"Firebase user agent\" string from the platform logger\r\n // service, not the browser user agent.\r\n const agent = platformLogger.getPlatformInfoString();\r\n const date = getUTCDateString();\r\n if (this._heartbeatsCache === null) {\r\n this._heartbeatsCache = await this._heartbeatsCachePromise;\r\n }\r\n // Do not store a heartbeat if one is already stored for this day\r\n // or if a header has already been sent today.\r\n if (this._heartbeatsCache.lastSentHeartbeatDate === date ||\r\n this._heartbeatsCache.heartbeats.some(singleDateHeartbeat => singleDateHeartbeat.date === date)) {\r\n return;\r\n }\r\n else {\r\n // There is no entry for this date. Create one.\r\n this._heartbeatsCache.heartbeats.push({ date, agent });\r\n }\r\n // Remove entries older than 30 days.\r\n this._heartbeatsCache.heartbeats = this._heartbeatsCache.heartbeats.filter(singleDateHeartbeat => {\r\n const hbTimestamp = new Date(singleDateHeartbeat.date).valueOf();\r\n const now = Date.now();\r\n return now - hbTimestamp <= STORED_HEARTBEAT_RETENTION_MAX_MILLIS;\r\n });\r\n return this._storage.overwrite(this._heartbeatsCache);\r\n }\r\n /**\r\n * Returns a base64 encoded string which can be attached to the heartbeat-specific header directly.\r\n * It also clears all heartbeats from memory as well as in IndexedDB.\r\n *\r\n * NOTE: Consuming product SDKs should not send the header if this method\r\n * returns an empty string.\r\n */\r\n async getHeartbeatsHeader() {\r\n if (this._heartbeatsCache === null) {\r\n await this._heartbeatsCachePromise;\r\n }\r\n // If it's still null or the array is empty, there is no data to send.\r\n if (this._heartbeatsCache === null ||\r\n this._heartbeatsCache.heartbeats.length === 0) {\r\n return '';\r\n }\r\n const date = getUTCDateString();\r\n // Extract as many heartbeats from the cache as will fit under the size limit.\r\n const { heartbeatsToSend, unsentEntries } = extractHeartbeatsForHeader(this._heartbeatsCache.heartbeats);\r\n const headerString = base64urlEncodeWithoutPadding(JSON.stringify({ version: 2, heartbeats: heartbeatsToSend }));\r\n // Store last sent date to prevent another being logged/sent for the same day.\r\n this._heartbeatsCache.lastSentHeartbeatDate = date;\r\n if (unsentEntries.length > 0) {\r\n // Store any unsent entries if they exist.\r\n this._heartbeatsCache.heartbeats = unsentEntries;\r\n // This seems more likely than emptying the array (below) to lead to some odd state\r\n // since the cache isn't empty and this will be called again on the next request,\r\n // and is probably safest if we await it.\r\n await this._storage.overwrite(this._heartbeatsCache);\r\n }\r\n else {\r\n this._heartbeatsCache.heartbeats = [];\r\n // Do not wait for this, to reduce latency.\r\n void this._storage.overwrite(this._heartbeatsCache);\r\n }\r\n return headerString;\r\n }\r\n}\r\nfunction getUTCDateString() {\r\n const today = new Date();\r\n // Returns date format 'YYYY-MM-DD'\r\n return today.toISOString().substring(0, 10);\r\n}\r\nfunction extractHeartbeatsForHeader(heartbeatsCache, maxSize = MAX_HEADER_BYTES) {\r\n // Heartbeats grouped by user agent in the standard format to be sent in\r\n // the header.\r\n const heartbeatsToSend = [];\r\n // Single date format heartbeats that are not sent.\r\n let unsentEntries = heartbeatsCache.slice();\r\n for (const singleDateHeartbeat of heartbeatsCache) {\r\n // Look for an existing entry with the same user agent.\r\n const heartbeatEntry = heartbeatsToSend.find(hb => hb.agent === singleDateHeartbeat.agent);\r\n if (!heartbeatEntry) {\r\n // If no entry for this user agent exists, create one.\r\n heartbeatsToSend.push({\r\n agent: singleDateHeartbeat.agent,\r\n dates: [singleDateHeartbeat.date]\r\n });\r\n if (countBytes(heartbeatsToSend) > maxSize) {\r\n // If the header would exceed max size, remove the added heartbeat\r\n // entry and stop adding to the header.\r\n heartbeatsToSend.pop();\r\n break;\r\n }\r\n }\r\n else {\r\n heartbeatEntry.dates.push(singleDateHeartbeat.date);\r\n // If the header would exceed max size, remove the added date\r\n // and stop adding to the header.\r\n if (countBytes(heartbeatsToSend) > maxSize) {\r\n heartbeatEntry.dates.pop();\r\n break;\r\n }\r\n }\r\n // Pop unsent entry from queue. (Skipped if adding the entry exceeded\r\n // quota and the loop breaks early.)\r\n unsentEntries = unsentEntries.slice(1);\r\n }\r\n return {\r\n heartbeatsToSend,\r\n unsentEntries\r\n };\r\n}\r\nclass HeartbeatStorageImpl {\r\n constructor(app) {\r\n this.app = app;\r\n this._canUseIndexedDBPromise = this.runIndexedDBEnvironmentCheck();\r\n }\r\n async runIndexedDBEnvironmentCheck() {\r\n if (!isIndexedDBAvailable()) {\r\n return false;\r\n }\r\n else {\r\n return validateIndexedDBOpenable()\r\n .then(() => true)\r\n .catch(() => false);\r\n }\r\n }\r\n /**\r\n * Read all heartbeats.\r\n */\r\n async read() {\r\n const canUseIndexedDB = await this._canUseIndexedDBPromise;\r\n if (!canUseIndexedDB) {\r\n return { heartbeats: [] };\r\n }\r\n else {\r\n const idbHeartbeatObject = await readHeartbeatsFromIndexedDB(this.app);\r\n return idbHeartbeatObject || { heartbeats: [] };\r\n }\r\n }\r\n // overwrite the storage with the provided heartbeats\r\n async overwrite(heartbeatsObject) {\r\n var _a;\r\n const canUseIndexedDB = await this._canUseIndexedDBPromise;\r\n if (!canUseIndexedDB) {\r\n return;\r\n }\r\n else {\r\n const existingHeartbeatsObject = await this.read();\r\n return writeHeartbeatsToIndexedDB(this.app, {\r\n lastSentHeartbeatDate: (_a = heartbeatsObject.lastSentHeartbeatDate) !== null && _a !== void 0 ? _a : existingHeartbeatsObject.lastSentHeartbeatDate,\r\n heartbeats: heartbeatsObject.heartbeats\r\n });\r\n }\r\n }\r\n // add heartbeats\r\n async add(heartbeatsObject) {\r\n var _a;\r\n const canUseIndexedDB = await this._canUseIndexedDBPromise;\r\n if (!canUseIndexedDB) {\r\n return;\r\n }\r\n else {\r\n const existingHeartbeatsObject = await this.read();\r\n return writeHeartbeatsToIndexedDB(this.app, {\r\n lastSentHeartbeatDate: (_a = heartbeatsObject.lastSentHeartbeatDate) !== null && _a !== void 0 ? _a : existingHeartbeatsObject.lastSentHeartbeatDate,\r\n heartbeats: [\r\n ...existingHeartbeatsObject.heartbeats,\r\n ...heartbeatsObject.heartbeats\r\n ]\r\n });\r\n }\r\n }\r\n}\r\n/**\r\n * Calculate bytes of a HeartbeatsByUserAgent array after being wrapped\r\n * in a platform logging header JSON object, stringified, and converted\r\n * to base 64.\r\n */\r\nfunction countBytes(heartbeatsCache) {\r\n // base64 has a restricted set of characters, all of which should be 1 byte.\r\n return base64urlEncodeWithoutPadding(\r\n // heartbeatsCache wrapper properties\r\n JSON.stringify({ version: 2, heartbeats: heartbeatsCache })).length;\r\n}\n\n/**\r\n * @license\r\n * Copyright 2019 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nfunction registerCoreComponents(variant) {\r\n _registerComponent(new Component('platform-logger', container => new PlatformLoggerServiceImpl(container), \"PRIVATE\" /* ComponentType.PRIVATE */));\r\n _registerComponent(new Component('heartbeat', container => new HeartbeatServiceImpl(container), \"PRIVATE\" /* ComponentType.PRIVATE */));\r\n // Register `app` package.\r\n registerVersion(name$o, version$1, variant);\r\n // BUILD_TARGET will be replaced by values like esm5, esm2017, cjs5, etc during the compilation\r\n registerVersion(name$o, version$1, 'esm2017');\r\n // Register platform SDK identifier (no version).\r\n registerVersion('fire-js', '');\r\n}\n\n/**\r\n * Firebase App\r\n *\r\n * @remarks This package coordinates the communication between the different Firebase components\r\n * @packageDocumentation\r\n */\r\nregisterCoreComponents('');\n\nexport { SDK_VERSION, DEFAULT_ENTRY_NAME as _DEFAULT_ENTRY_NAME, _addComponent, _addOrOverwriteComponent, _apps, _clearComponents, _components, _getProvider, _registerComponent, _removeServiceInstance, deleteApp, getApp, getApps, initializeApp, onLog, registerVersion, setLogLevel };\n//# sourceMappingURL=index.esm2017.js.map\n","/******************************************************************************\nCopyright (c) Microsoft Corporation.\n\nPermission to use, copy, modify, and/or distribute this software for any\npurpose with or without fee is hereby granted.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH\nREGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY\nAND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,\nINDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM\nLOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR\nOTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR\nPERFORMANCE OF THIS SOFTWARE.\n***************************************************************************** */\n/* global Reflect, Promise, SuppressedError, Symbol */\n\nvar extendStatics = function(d, b) {\n extendStatics = Object.setPrototypeOf ||\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\n function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };\n return extendStatics(d, b);\n};\n\nexport function __extends(d, b) {\n if (typeof b !== \"function\" && b !== null)\n throw new TypeError(\"Class extends value \" + String(b) + \" is not a constructor or null\");\n extendStatics(d, b);\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n}\n\nexport var __assign = function() {\n __assign = Object.assign || function __assign(t) {\n for (var s, i = 1, n = arguments.length; i < n; i++) {\n s = arguments[i];\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];\n }\n return t;\n }\n return __assign.apply(this, arguments);\n}\n\nexport function __rest(s, e) {\n var t = {};\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)\n t[p] = s[p];\n if (s != null && typeof Object.getOwnPropertySymbols === \"function\")\n for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {\n if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))\n t[p[i]] = s[p[i]];\n }\n return t;\n}\n\nexport function __decorate(decorators, target, key, desc) {\n var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;\n if (typeof Reflect === \"object\" && typeof Reflect.decorate === \"function\") r = Reflect.decorate(decorators, target, key, desc);\n else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;\n return c > 3 && r && Object.defineProperty(target, key, r), r;\n}\n\nexport function __param(paramIndex, decorator) {\n return function (target, key) { decorator(target, key, paramIndex); }\n}\n\nexport function __esDecorate(ctor, descriptorIn, decorators, contextIn, initializers, extraInitializers) {\n function accept(f) { if (f !== void 0 && typeof f !== \"function\") throw new TypeError(\"Function expected\"); return f; }\n var kind = contextIn.kind, key = kind === \"getter\" ? \"get\" : kind === \"setter\" ? \"set\" : \"value\";\n var target = !descriptorIn && ctor ? contextIn[\"static\"] ? ctor : ctor.prototype : null;\n var descriptor = descriptorIn || (target ? Object.getOwnPropertyDescriptor(target, contextIn.name) : {});\n var _, done = false;\n for (var i = decorators.length - 1; i >= 0; i--) {\n var context = {};\n for (var p in contextIn) context[p] = p === \"access\" ? {} : contextIn[p];\n for (var p in contextIn.access) context.access[p] = contextIn.access[p];\n context.addInitializer = function (f) { if (done) throw new TypeError(\"Cannot add initializers after decoration has completed\"); extraInitializers.push(accept(f || null)); };\n var result = (0, decorators[i])(kind === \"accessor\" ? { get: descriptor.get, set: descriptor.set } : descriptor[key], context);\n if (kind === \"accessor\") {\n if (result === void 0) continue;\n if (result === null || typeof result !== \"object\") throw new TypeError(\"Object expected\");\n if (_ = accept(result.get)) descriptor.get = _;\n if (_ = accept(result.set)) descriptor.set = _;\n if (_ = accept(result.init)) initializers.unshift(_);\n }\n else if (_ = accept(result)) {\n if (kind === \"field\") initializers.unshift(_);\n else descriptor[key] = _;\n }\n }\n if (target) Object.defineProperty(target, contextIn.name, descriptor);\n done = true;\n};\n\nexport function __runInitializers(thisArg, initializers, value) {\n var useValue = arguments.length > 2;\n for (var i = 0; i < initializers.length; i++) {\n value = useValue ? initializers[i].call(thisArg, value) : initializers[i].call(thisArg);\n }\n return useValue ? value : void 0;\n};\n\nexport function __propKey(x) {\n return typeof x === \"symbol\" ? x : \"\".concat(x);\n};\n\nexport function __setFunctionName(f, name, prefix) {\n if (typeof name === \"symbol\") name = name.description ? \"[\".concat(name.description, \"]\") : \"\";\n return Object.defineProperty(f, \"name\", { configurable: true, value: prefix ? \"\".concat(prefix, \" \", name) : name });\n};\n\nexport function __metadata(metadataKey, metadataValue) {\n if (typeof Reflect === \"object\" && typeof Reflect.metadata === \"function\") return Reflect.metadata(metadataKey, metadataValue);\n}\n\nexport function __awaiter(thisArg, _arguments, P, generator) {\n function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }\n return new (P || (P = Promise))(function (resolve, reject) {\n function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\n function rejected(value) { try { step(generator[\"throw\"](value)); } catch (e) { reject(e); } }\n function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }\n step((generator = generator.apply(thisArg, _arguments || [])).next());\n });\n}\n\nexport function __generator(thisArg, body) {\n var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;\n return g = { next: verb(0), \"throw\": verb(1), \"return\": verb(2) }, typeof Symbol === \"function\" && (g[Symbol.iterator] = function() { return this; }), g;\n function verb(n) { return function (v) { return step([n, v]); }; }\n function step(op) {\n if (f) throw new TypeError(\"Generator is already executing.\");\n while (g && (g = 0, op[0] && (_ = 0)), _) try {\n 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;\n if (y = 0, t) op = [op[0] & 2, t.value];\n switch (op[0]) {\n case 0: case 1: t = op; break;\n case 4: _.label++; return { value: op[1], done: false };\n case 5: _.label++; y = op[1]; op = [0]; continue;\n case 7: op = _.ops.pop(); _.trys.pop(); continue;\n default:\n if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }\n if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }\n if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }\n if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }\n if (t[2]) _.ops.pop();\n _.trys.pop(); continue;\n }\n op = body.call(thisArg, _);\n } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }\n if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };\n }\n}\n\nexport var __createBinding = Object.create ? (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n var desc = Object.getOwnPropertyDescriptor(m, k);\n if (!desc || (\"get\" in desc ? !m.__esModule : desc.writable || desc.configurable)) {\n desc = { enumerable: true, get: function() { return m[k]; } };\n }\n Object.defineProperty(o, k2, desc);\n}) : (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n o[k2] = m[k];\n});\n\nexport function __exportStar(m, o) {\n for (var p in m) if (p !== \"default\" && !Object.prototype.hasOwnProperty.call(o, p)) __createBinding(o, m, p);\n}\n\nexport function __values(o) {\n var s = typeof Symbol === \"function\" && Symbol.iterator, m = s && o[s], i = 0;\n if (m) return m.call(o);\n if (o && typeof o.length === \"number\") return {\n next: function () {\n if (o && i >= o.length) o = void 0;\n return { value: o && o[i++], done: !o };\n }\n };\n throw new TypeError(s ? \"Object is not iterable.\" : \"Symbol.iterator is not defined.\");\n}\n\nexport function __read(o, n) {\n var m = typeof Symbol === \"function\" && o[Symbol.iterator];\n if (!m) return o;\n var i = m.call(o), r, ar = [], e;\n try {\n while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);\n }\n catch (error) { e = { error: error }; }\n finally {\n try {\n if (r && !r.done && (m = i[\"return\"])) m.call(i);\n }\n finally { if (e) throw e.error; }\n }\n return ar;\n}\n\n/** @deprecated */\nexport function __spread() {\n for (var ar = [], i = 0; i < arguments.length; i++)\n ar = ar.concat(__read(arguments[i]));\n return ar;\n}\n\n/** @deprecated */\nexport function __spreadArrays() {\n for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length;\n for (var r = Array(s), k = 0, i = 0; i < il; i++)\n for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++)\n r[k] = a[j];\n return r;\n}\n\nexport function __spreadArray(to, from, pack) {\n if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {\n if (ar || !(i in from)) {\n if (!ar) ar = Array.prototype.slice.call(from, 0, i);\n ar[i] = from[i];\n }\n }\n return to.concat(ar || Array.prototype.slice.call(from));\n}\n\nexport function __await(v) {\n return this instanceof __await ? (this.v = v, this) : new __await(v);\n}\n\nexport function __asyncGenerator(thisArg, _arguments, generator) {\n if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\n var g = generator.apply(thisArg, _arguments || []), i, q = [];\n return i = {}, verb(\"next\"), verb(\"throw\"), verb(\"return\"), i[Symbol.asyncIterator] = function () { return this; }, i;\n 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); }); }; }\n function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } }\n function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); }\n function fulfill(value) { resume(\"next\", value); }\n function reject(value) { resume(\"throw\", value); }\n function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); }\n}\n\nexport function __asyncDelegator(o) {\n var i, p;\n return i = {}, verb(\"next\"), verb(\"throw\", function (e) { throw e; }), verb(\"return\"), i[Symbol.iterator] = function () { return this; }, i;\n function verb(n, f) { i[n] = o[n] ? function (v) { return (p = !p) ? { value: __await(o[n](v)), done: false } : f ? f(v) : v; } : f; }\n}\n\nexport function __asyncValues(o) {\n if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\n var m = o[Symbol.asyncIterator], i;\n 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);\n 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); }); }; }\n function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); }\n}\n\nexport function __makeTemplateObject(cooked, raw) {\n if (Object.defineProperty) { Object.defineProperty(cooked, \"raw\", { value: raw }); } else { cooked.raw = raw; }\n return cooked;\n};\n\nvar __setModuleDefault = Object.create ? (function(o, v) {\n Object.defineProperty(o, \"default\", { enumerable: true, value: v });\n}) : function(o, v) {\n o[\"default\"] = v;\n};\n\nexport function __importStar(mod) {\n if (mod && mod.__esModule) return mod;\n var result = {};\n if (mod != null) for (var k in mod) if (k !== \"default\" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);\n __setModuleDefault(result, mod);\n return result;\n}\n\nexport function __importDefault(mod) {\n return (mod && mod.__esModule) ? mod : { default: mod };\n}\n\nexport function __classPrivateFieldGet(receiver, state, kind, f) {\n if (kind === \"a\" && !f) throw new TypeError(\"Private accessor was defined without a getter\");\n if (typeof state === \"function\" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError(\"Cannot read private member from an object whose class did not declare it\");\n return kind === \"m\" ? f : kind === \"a\" ? f.call(receiver) : f ? f.value : state.get(receiver);\n}\n\nexport function __classPrivateFieldSet(receiver, state, value, kind, f) {\n if (kind === \"m\") throw new TypeError(\"Private method is not writable\");\n if (kind === \"a\" && !f) throw new TypeError(\"Private accessor was defined without a setter\");\n if (typeof state === \"function\" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError(\"Cannot write private member to an object whose class did not declare it\");\n return (kind === \"a\" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;\n}\n\nexport function __classPrivateFieldIn(state, receiver) {\n if (receiver === null || (typeof receiver !== \"object\" && typeof receiver !== \"function\")) throw new TypeError(\"Cannot use 'in' operator on non-object\");\n return typeof state === \"function\" ? receiver === state : state.has(receiver);\n}\n\nexport function __addDisposableResource(env, value, async) {\n if (value !== null && value !== void 0) {\n if (typeof value !== \"object\" && typeof value !== \"function\") throw new TypeError(\"Object expected.\");\n var dispose;\n if (async) {\n if (!Symbol.asyncDispose) throw new TypeError(\"Symbol.asyncDispose is not defined.\");\n dispose = value[Symbol.asyncDispose];\n }\n if (dispose === void 0) {\n if (!Symbol.dispose) throw new TypeError(\"Symbol.dispose is not defined.\");\n dispose = value[Symbol.dispose];\n }\n if (typeof dispose !== \"function\") throw new TypeError(\"Object not disposable.\");\n env.stack.push({ value: value, dispose: dispose, async: async });\n }\n else if (async) {\n env.stack.push({ async: true });\n }\n return value;\n}\n\nvar _SuppressedError = typeof SuppressedError === \"function\" ? SuppressedError : function (error, suppressed, message) {\n var e = new Error(message);\n return e.name = \"SuppressedError\", e.error = error, e.suppressed = suppressed, e;\n};\n\nexport function __disposeResources(env) {\n function fail(e) {\n env.error = env.hasError ? new _SuppressedError(e, env.error, \"An error was suppressed during disposal.\") : e;\n env.hasError = true;\n }\n function next() {\n while (env.stack.length) {\n var rec = env.stack.pop();\n try {\n var result = rec.dispose && rec.dispose.call(rec.value);\n if (rec.async) return Promise.resolve(result).then(next, function(e) { fail(e); return next(); });\n }\n catch (e) {\n fail(e);\n }\n }\n if (env.hasError) throw env.error;\n }\n return next();\n}\n\nexport default {\n __extends,\n __assign,\n __rest,\n __decorate,\n __param,\n __metadata,\n __awaiter,\n __generator,\n __createBinding,\n __exportStar,\n __values,\n __read,\n __spread,\n __spreadArrays,\n __spreadArray,\n __await,\n __asyncGenerator,\n __asyncDelegator,\n __asyncValues,\n __makeTemplateObject,\n __importStar,\n __importDefault,\n __classPrivateFieldGet,\n __classPrivateFieldSet,\n __classPrivateFieldIn,\n __addDisposableResource,\n __disposeResources,\n};\n","import { registerVersion } from '@firebase/app';\nexport * from '@firebase/app';\n\nvar name = \"firebase\";\nvar version = \"9.23.0\";\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nregisterVersion(name, version, 'app');\n//# sourceMappingURL=index.esm.js.map\n","import { ErrorFactory, isBrowserExtension, isMobileCordova, isReactNative, FirebaseError, querystring, getModularInstance, base64Decode, getUA, isIE, createSubscribe, deepEqual, querystringDecode, extractQuerystring, isEmpty, getExperimentalSetting, getDefaultEmulatorHost } from '@firebase/util';\nimport { SDK_VERSION, _getProvider, _registerComponent, registerVersion, getApp } from '@firebase/app';\nimport { __rest } from 'tslib';\nimport { Logger, LogLevel } from '@firebase/logger';\nimport { Component } from '@firebase/component';\n\n/**\r\n * @license\r\n * Copyright 2021 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * An enum of factors that may be used for multifactor authentication.\r\n *\r\n * @public\r\n */\r\nconst FactorId = {\r\n /** Phone as second factor */\r\n PHONE: 'phone',\r\n TOTP: 'totp'\r\n};\r\n/**\r\n * Enumeration of supported providers.\r\n *\r\n * @public\r\n */\r\nconst ProviderId = {\r\n /** Facebook provider ID */\r\n FACEBOOK: 'facebook.com',\r\n /** GitHub provider ID */\r\n GITHUB: 'github.com',\r\n /** Google provider ID */\r\n GOOGLE: 'google.com',\r\n /** Password provider */\r\n PASSWORD: 'password',\r\n /** Phone provider */\r\n PHONE: 'phone',\r\n /** Twitter provider ID */\r\n TWITTER: 'twitter.com'\r\n};\r\n/**\r\n * Enumeration of supported sign-in methods.\r\n *\r\n * @public\r\n */\r\nconst SignInMethod = {\r\n /** Email link sign in method */\r\n EMAIL_LINK: 'emailLink',\r\n /** Email/password sign in method */\r\n EMAIL_PASSWORD: 'password',\r\n /** Facebook sign in method */\r\n FACEBOOK: 'facebook.com',\r\n /** GitHub sign in method */\r\n GITHUB: 'github.com',\r\n /** Google sign in method */\r\n GOOGLE: 'google.com',\r\n /** Phone sign in method */\r\n PHONE: 'phone',\r\n /** Twitter sign in method */\r\n TWITTER: 'twitter.com'\r\n};\r\n/**\r\n * Enumeration of supported operation types.\r\n *\r\n * @public\r\n */\r\nconst OperationType = {\r\n /** Operation involving linking an additional provider to an already signed-in user. */\r\n LINK: 'link',\r\n /** Operation involving using a provider to reauthenticate an already signed-in user. */\r\n REAUTHENTICATE: 'reauthenticate',\r\n /** Operation involving signing in a user. */\r\n SIGN_IN: 'signIn'\r\n};\r\n/**\r\n * An enumeration of the possible email action types.\r\n *\r\n * @public\r\n */\r\nconst ActionCodeOperation = {\r\n /** The email link sign-in action. */\r\n EMAIL_SIGNIN: 'EMAIL_SIGNIN',\r\n /** The password reset action. */\r\n PASSWORD_RESET: 'PASSWORD_RESET',\r\n /** The email revocation action. */\r\n RECOVER_EMAIL: 'RECOVER_EMAIL',\r\n /** The revert second factor addition email action. */\r\n REVERT_SECOND_FACTOR_ADDITION: 'REVERT_SECOND_FACTOR_ADDITION',\r\n /** The revert second factor addition email action. */\r\n VERIFY_AND_CHANGE_EMAIL: 'VERIFY_AND_CHANGE_EMAIL',\r\n /** The email verification action. */\r\n VERIFY_EMAIL: 'VERIFY_EMAIL'\r\n};\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nfunction _debugErrorMap() {\r\n return {\r\n [\"admin-restricted-operation\" /* AuthErrorCode.ADMIN_ONLY_OPERATION */]: 'This operation is restricted to administrators only.',\r\n [\"argument-error\" /* AuthErrorCode.ARGUMENT_ERROR */]: '',\r\n [\"app-not-authorized\" /* AuthErrorCode.APP_NOT_AUTHORIZED */]: \"This app, identified by the domain where it's hosted, is not \" +\r\n 'authorized to use Firebase Authentication with the provided API key. ' +\r\n 'Review your key configuration in the Google API console.',\r\n [\"app-not-installed\" /* AuthErrorCode.APP_NOT_INSTALLED */]: 'The requested mobile application corresponding to the identifier (' +\r\n 'Android package name or iOS bundle ID) provided is not installed on ' +\r\n 'this device.',\r\n [\"captcha-check-failed\" /* AuthErrorCode.CAPTCHA_CHECK_FAILED */]: 'The reCAPTCHA response token provided is either invalid, expired, ' +\r\n 'already used or the domain associated with it does not match the list ' +\r\n 'of whitelisted domains.',\r\n [\"code-expired\" /* AuthErrorCode.CODE_EXPIRED */]: 'The SMS code has expired. Please re-send the verification code to try ' +\r\n 'again.',\r\n [\"cordova-not-ready\" /* AuthErrorCode.CORDOVA_NOT_READY */]: 'Cordova framework is not ready.',\r\n [\"cors-unsupported\" /* AuthErrorCode.CORS_UNSUPPORTED */]: 'This browser is not supported.',\r\n [\"credential-already-in-use\" /* AuthErrorCode.CREDENTIAL_ALREADY_IN_USE */]: 'This credential is already associated with a different user account.',\r\n [\"custom-token-mismatch\" /* AuthErrorCode.CREDENTIAL_MISMATCH */]: 'The custom token corresponds to a different audience.',\r\n [\"requires-recent-login\" /* AuthErrorCode.CREDENTIAL_TOO_OLD_LOGIN_AGAIN */]: 'This operation is sensitive and requires recent authentication. Log in ' +\r\n 'again before retrying this request.',\r\n [\"dependent-sdk-initialized-before-auth\" /* AuthErrorCode.DEPENDENT_SDK_INIT_BEFORE_AUTH */]: 'Another Firebase SDK was initialized and is trying to use Auth before Auth is ' +\r\n 'initialized. Please be sure to call `initializeAuth` or `getAuth` before ' +\r\n 'starting any other Firebase SDK.',\r\n [\"dynamic-link-not-activated\" /* AuthErrorCode.DYNAMIC_LINK_NOT_ACTIVATED */]: 'Please activate Dynamic Links in the Firebase Console and agree to the terms and ' +\r\n 'conditions.',\r\n [\"email-change-needs-verification\" /* AuthErrorCode.EMAIL_CHANGE_NEEDS_VERIFICATION */]: 'Multi-factor users must always have a verified email.',\r\n [\"email-already-in-use\" /* AuthErrorCode.EMAIL_EXISTS */]: 'The email address is already in use by another account.',\r\n [\"emulator-config-failed\" /* AuthErrorCode.EMULATOR_CONFIG_FAILED */]: 'Auth instance has already been used to make a network call. Auth can ' +\r\n 'no longer be configured to use the emulator. Try calling ' +\r\n '\"connectAuthEmulator()\" sooner.',\r\n [\"expired-action-code\" /* AuthErrorCode.EXPIRED_OOB_CODE */]: 'The action code has expired.',\r\n [\"cancelled-popup-request\" /* AuthErrorCode.EXPIRED_POPUP_REQUEST */]: 'This operation has been cancelled due to another conflicting popup being opened.',\r\n [\"internal-error\" /* AuthErrorCode.INTERNAL_ERROR */]: 'An internal AuthError has occurred.',\r\n [\"invalid-app-credential\" /* AuthErrorCode.INVALID_APP_CREDENTIAL */]: 'The phone verification request contains an invalid application verifier.' +\r\n ' The reCAPTCHA token response is either invalid or expired.',\r\n [\"invalid-app-id\" /* AuthErrorCode.INVALID_APP_ID */]: 'The mobile app identifier is not registed for the current project.',\r\n [\"invalid-user-token\" /* AuthErrorCode.INVALID_AUTH */]: \"This user's credential isn't valid for this project. This can happen \" +\r\n \"if the user's token has been tampered with, or if the user isn't for \" +\r\n 'the project associated with this API key.',\r\n [\"invalid-auth-event\" /* AuthErrorCode.INVALID_AUTH_EVENT */]: 'An internal AuthError has occurred.',\r\n [\"invalid-verification-code\" /* AuthErrorCode.INVALID_CODE */]: 'The SMS verification code used to create the phone auth credential is ' +\r\n 'invalid. Please resend the verification code sms and be sure to use the ' +\r\n 'verification code provided by the user.',\r\n [\"invalid-continue-uri\" /* AuthErrorCode.INVALID_CONTINUE_URI */]: 'The continue URL provided in the request is invalid.',\r\n [\"invalid-cordova-configuration\" /* AuthErrorCode.INVALID_CORDOVA_CONFIGURATION */]: 'The following Cordova plugins must be installed to enable OAuth sign-in: ' +\r\n 'cordova-plugin-buildinfo, cordova-universal-links-plugin, ' +\r\n 'cordova-plugin-browsertab, cordova-plugin-inappbrowser and ' +\r\n 'cordova-plugin-customurlscheme.',\r\n [\"invalid-custom-token\" /* AuthErrorCode.INVALID_CUSTOM_TOKEN */]: 'The custom token format is incorrect. Please check the documentation.',\r\n [\"invalid-dynamic-link-domain\" /* AuthErrorCode.INVALID_DYNAMIC_LINK_DOMAIN */]: 'The provided dynamic link domain is not configured or authorized for the current project.',\r\n [\"invalid-email\" /* AuthErrorCode.INVALID_EMAIL */]: 'The email address is badly formatted.',\r\n [\"invalid-emulator-scheme\" /* AuthErrorCode.INVALID_EMULATOR_SCHEME */]: 'Emulator URL must start with a valid scheme (http:// or https://).',\r\n [\"invalid-api-key\" /* AuthErrorCode.INVALID_API_KEY */]: 'Your API key is invalid, please check you have copied it correctly.',\r\n [\"invalid-cert-hash\" /* AuthErrorCode.INVALID_CERT_HASH */]: 'The SHA-1 certificate hash provided is invalid.',\r\n [\"invalid-credential\" /* AuthErrorCode.INVALID_IDP_RESPONSE */]: 'The supplied auth credential is malformed or has expired.',\r\n [\"invalid-message-payload\" /* AuthErrorCode.INVALID_MESSAGE_PAYLOAD */]: 'The email template corresponding to this action contains invalid characters in its message. ' +\r\n 'Please fix by going to the Auth email templates section in the Firebase Console.',\r\n [\"invalid-multi-factor-session\" /* AuthErrorCode.INVALID_MFA_SESSION */]: 'The request does not contain a valid proof of first factor successful sign-in.',\r\n [\"invalid-oauth-provider\" /* AuthErrorCode.INVALID_OAUTH_PROVIDER */]: 'EmailAuthProvider is not supported for this operation. This operation ' +\r\n 'only supports OAuth providers.',\r\n [\"invalid-oauth-client-id\" /* AuthErrorCode.INVALID_OAUTH_CLIENT_ID */]: 'The OAuth client ID provided is either invalid or does not match the ' +\r\n 'specified API key.',\r\n [\"unauthorized-domain\" /* AuthErrorCode.INVALID_ORIGIN */]: 'This domain is not authorized for OAuth operations for your Firebase ' +\r\n 'project. Edit the list of authorized domains from the Firebase console.',\r\n [\"invalid-action-code\" /* AuthErrorCode.INVALID_OOB_CODE */]: 'The action code is invalid. This can happen if the code is malformed, ' +\r\n 'expired, or has already been used.',\r\n [\"wrong-password\" /* AuthErrorCode.INVALID_PASSWORD */]: 'The password is invalid or the user does not have a password.',\r\n [\"invalid-persistence-type\" /* AuthErrorCode.INVALID_PERSISTENCE */]: 'The specified persistence type is invalid. It can only be local, session or none.',\r\n [\"invalid-phone-number\" /* AuthErrorCode.INVALID_PHONE_NUMBER */]: 'The format of the phone number provided is incorrect. Please enter the ' +\r\n 'phone number in a format that can be parsed into E.164 format. E.164 ' +\r\n 'phone numbers are written in the format [+][country code][subscriber ' +\r\n 'number including area code].',\r\n [\"invalid-provider-id\" /* AuthErrorCode.INVALID_PROVIDER_ID */]: 'The specified provider ID is invalid.',\r\n [\"invalid-recipient-email\" /* AuthErrorCode.INVALID_RECIPIENT_EMAIL */]: 'The email corresponding to this action failed to send as the provided ' +\r\n 'recipient email address is invalid.',\r\n [\"invalid-sender\" /* AuthErrorCode.INVALID_SENDER */]: 'The email template corresponding to this action contains an invalid sender email or name. ' +\r\n 'Please fix by going to the Auth email templates section in the Firebase Console.',\r\n [\"invalid-verification-id\" /* AuthErrorCode.INVALID_SESSION_INFO */]: 'The verification ID used to create the phone auth credential is invalid.',\r\n [\"invalid-tenant-id\" /* AuthErrorCode.INVALID_TENANT_ID */]: \"The Auth instance's tenant ID is invalid.\",\r\n [\"login-blocked\" /* AuthErrorCode.LOGIN_BLOCKED */]: 'Login blocked by user-provided method: {$originalMessage}',\r\n [\"missing-android-pkg-name\" /* AuthErrorCode.MISSING_ANDROID_PACKAGE_NAME */]: 'An Android Package Name must be provided if the Android App is required to be installed.',\r\n [\"auth-domain-config-required\" /* AuthErrorCode.MISSING_AUTH_DOMAIN */]: 'Be sure to include authDomain when calling firebase.initializeApp(), ' +\r\n 'by following the instructions in the Firebase console.',\r\n [\"missing-app-credential\" /* AuthErrorCode.MISSING_APP_CREDENTIAL */]: 'The phone verification request is missing an application verifier ' +\r\n 'assertion. A reCAPTCHA response token needs to be provided.',\r\n [\"missing-verification-code\" /* AuthErrorCode.MISSING_CODE */]: 'The phone auth credential was created with an empty SMS verification code.',\r\n [\"missing-continue-uri\" /* AuthErrorCode.MISSING_CONTINUE_URI */]: 'A continue URL must be provided in the request.',\r\n [\"missing-iframe-start\" /* AuthErrorCode.MISSING_IFRAME_START */]: 'An internal AuthError has occurred.',\r\n [\"missing-ios-bundle-id\" /* AuthErrorCode.MISSING_IOS_BUNDLE_ID */]: 'An iOS Bundle ID must be provided if an App Store ID is provided.',\r\n [\"missing-or-invalid-nonce\" /* AuthErrorCode.MISSING_OR_INVALID_NONCE */]: 'The request does not contain a valid nonce. This can occur if the ' +\r\n 'SHA-256 hash of the provided raw nonce does not match the hashed nonce ' +\r\n 'in the ID token payload.',\r\n [\"missing-password\" /* AuthErrorCode.MISSING_PASSWORD */]: 'A non-empty password must be provided',\r\n [\"missing-multi-factor-info\" /* AuthErrorCode.MISSING_MFA_INFO */]: 'No second factor identifier is provided.',\r\n [\"missing-multi-factor-session\" /* AuthErrorCode.MISSING_MFA_SESSION */]: 'The request is missing proof of first factor successful sign-in.',\r\n [\"missing-phone-number\" /* AuthErrorCode.MISSING_PHONE_NUMBER */]: 'To send verification codes, provide a phone number for the recipient.',\r\n [\"missing-verification-id\" /* AuthErrorCode.MISSING_SESSION_INFO */]: 'The phone auth credential was created with an empty verification ID.',\r\n [\"app-deleted\" /* AuthErrorCode.MODULE_DESTROYED */]: 'This instance of FirebaseApp has been deleted.',\r\n [\"multi-factor-info-not-found\" /* AuthErrorCode.MFA_INFO_NOT_FOUND */]: 'The user does not have a second factor matching the identifier provided.',\r\n [\"multi-factor-auth-required\" /* AuthErrorCode.MFA_REQUIRED */]: 'Proof of ownership of a second factor is required to complete sign-in.',\r\n [\"account-exists-with-different-credential\" /* AuthErrorCode.NEED_CONFIRMATION */]: 'An account already exists with the same email address but different ' +\r\n 'sign-in credentials. Sign in using a provider associated with this ' +\r\n 'email address.',\r\n [\"network-request-failed\" /* AuthErrorCode.NETWORK_REQUEST_FAILED */]: 'A network AuthError (such as timeout, interrupted connection or unreachable host) has occurred.',\r\n [\"no-auth-event\" /* AuthErrorCode.NO_AUTH_EVENT */]: 'An internal AuthError has occurred.',\r\n [\"no-such-provider\" /* AuthErrorCode.NO_SUCH_PROVIDER */]: 'User was not linked to an account with the given provider.',\r\n [\"null-user\" /* AuthErrorCode.NULL_USER */]: 'A null user object was provided as the argument for an operation which ' +\r\n 'requires a non-null user object.',\r\n [\"operation-not-allowed\" /* AuthErrorCode.OPERATION_NOT_ALLOWED */]: 'The given sign-in provider is disabled for this Firebase project. ' +\r\n 'Enable it in the Firebase console, under the sign-in method tab of the ' +\r\n 'Auth section.',\r\n [\"operation-not-supported-in-this-environment\" /* AuthErrorCode.OPERATION_NOT_SUPPORTED */]: 'This operation is not supported in the environment this application is ' +\r\n 'running on. \"location.protocol\" must be http, https or chrome-extension' +\r\n ' and web storage must be enabled.',\r\n [\"popup-blocked\" /* AuthErrorCode.POPUP_BLOCKED */]: 'Unable to establish a connection with the popup. It may have been blocked by the browser.',\r\n [\"popup-closed-by-user\" /* AuthErrorCode.POPUP_CLOSED_BY_USER */]: 'The popup has been closed by the user before finalizing the operation.',\r\n [\"provider-already-linked\" /* AuthErrorCode.PROVIDER_ALREADY_LINKED */]: 'User can only be linked to one identity for the given provider.',\r\n [\"quota-exceeded\" /* AuthErrorCode.QUOTA_EXCEEDED */]: \"The project's quota for this operation has been exceeded.\",\r\n [\"redirect-cancelled-by-user\" /* AuthErrorCode.REDIRECT_CANCELLED_BY_USER */]: 'The redirect operation has been cancelled by the user before finalizing.',\r\n [\"redirect-operation-pending\" /* AuthErrorCode.REDIRECT_OPERATION_PENDING */]: 'A redirect sign-in operation is already pending.',\r\n [\"rejected-credential\" /* AuthErrorCode.REJECTED_CREDENTIAL */]: 'The request contains malformed or mismatching credentials.',\r\n [\"second-factor-already-in-use\" /* AuthErrorCode.SECOND_FACTOR_ALREADY_ENROLLED */]: 'The second factor is already enrolled on this account.',\r\n [\"maximum-second-factor-count-exceeded\" /* AuthErrorCode.SECOND_FACTOR_LIMIT_EXCEEDED */]: 'The maximum allowed number of second factors on a user has been exceeded.',\r\n [\"tenant-id-mismatch\" /* AuthErrorCode.TENANT_ID_MISMATCH */]: \"The provided tenant ID does not match the Auth instance's tenant ID\",\r\n [\"timeout\" /* AuthErrorCode.TIMEOUT */]: 'The operation has timed out.',\r\n [\"user-token-expired\" /* AuthErrorCode.TOKEN_EXPIRED */]: \"The user's credential is no longer valid. The user must sign in again.\",\r\n [\"too-many-requests\" /* AuthErrorCode.TOO_MANY_ATTEMPTS_TRY_LATER */]: 'We have blocked all requests from this device due to unusual activity. ' +\r\n 'Try again later.',\r\n [\"unauthorized-continue-uri\" /* AuthErrorCode.UNAUTHORIZED_DOMAIN */]: 'The domain of the continue URL is not whitelisted. Please whitelist ' +\r\n 'the domain in the Firebase console.',\r\n [\"unsupported-first-factor\" /* AuthErrorCode.UNSUPPORTED_FIRST_FACTOR */]: 'Enrolling a second factor or signing in with a multi-factor account requires sign-in with a supported first factor.',\r\n [\"unsupported-persistence-type\" /* AuthErrorCode.UNSUPPORTED_PERSISTENCE */]: 'The current environment does not support the specified persistence type.',\r\n [\"unsupported-tenant-operation\" /* AuthErrorCode.UNSUPPORTED_TENANT_OPERATION */]: 'This operation is not supported in a multi-tenant context.',\r\n [\"unverified-email\" /* AuthErrorCode.UNVERIFIED_EMAIL */]: 'The operation requires a verified email.',\r\n [\"user-cancelled\" /* AuthErrorCode.USER_CANCELLED */]: 'The user did not grant your application the permissions it requested.',\r\n [\"user-not-found\" /* AuthErrorCode.USER_DELETED */]: 'There is no user record corresponding to this identifier. The user may ' +\r\n 'have been deleted.',\r\n [\"user-disabled\" /* AuthErrorCode.USER_DISABLED */]: 'The user account has been disabled by an administrator.',\r\n [\"user-mismatch\" /* AuthErrorCode.USER_MISMATCH */]: 'The supplied credentials do not correspond to the previously signed in user.',\r\n [\"user-signed-out\" /* AuthErrorCode.USER_SIGNED_OUT */]: '',\r\n [\"weak-password\" /* AuthErrorCode.WEAK_PASSWORD */]: 'The password must be 6 characters long or more.',\r\n [\"web-storage-unsupported\" /* AuthErrorCode.WEB_STORAGE_UNSUPPORTED */]: 'This browser is not supported or 3rd party cookies and data may be disabled.',\r\n [\"already-initialized\" /* AuthErrorCode.ALREADY_INITIALIZED */]: 'initializeAuth() has already been called with ' +\r\n 'different options. To avoid this error, call initializeAuth() with the ' +\r\n 'same options as when it was originally called, or call getAuth() to return the' +\r\n ' already initialized instance.',\r\n [\"missing-recaptcha-token\" /* AuthErrorCode.MISSING_RECAPTCHA_TOKEN */]: 'The reCAPTCHA token is missing when sending request to the backend.',\r\n [\"invalid-recaptcha-token\" /* AuthErrorCode.INVALID_RECAPTCHA_TOKEN */]: 'The reCAPTCHA token is invalid when sending request to the backend.',\r\n [\"invalid-recaptcha-action\" /* AuthErrorCode.INVALID_RECAPTCHA_ACTION */]: 'The reCAPTCHA action is invalid when sending request to the backend.',\r\n [\"recaptcha-not-enabled\" /* AuthErrorCode.RECAPTCHA_NOT_ENABLED */]: 'reCAPTCHA Enterprise integration is not enabled for this project.',\r\n [\"missing-client-type\" /* AuthErrorCode.MISSING_CLIENT_TYPE */]: 'The reCAPTCHA client type is missing when sending request to the backend.',\r\n [\"missing-recaptcha-version\" /* AuthErrorCode.MISSING_RECAPTCHA_VERSION */]: 'The reCAPTCHA version is missing when sending request to the backend.',\r\n [\"invalid-req-type\" /* AuthErrorCode.INVALID_REQ_TYPE */]: 'Invalid request parameters.',\r\n [\"invalid-recaptcha-version\" /* AuthErrorCode.INVALID_RECAPTCHA_VERSION */]: 'The reCAPTCHA version is invalid when sending request to the backend.'\r\n };\r\n}\r\nfunction _prodErrorMap() {\r\n // We will include this one message in the prod error map since by the very\r\n // nature of this error, developers will never be able to see the message\r\n // using the debugErrorMap (which is installed during auth initialization).\r\n return {\r\n [\"dependent-sdk-initialized-before-auth\" /* AuthErrorCode.DEPENDENT_SDK_INIT_BEFORE_AUTH */]: 'Another Firebase SDK was initialized and is trying to use Auth before Auth is ' +\r\n 'initialized. Please be sure to call `initializeAuth` or `getAuth` before ' +\r\n 'starting any other Firebase SDK.'\r\n };\r\n}\r\n/**\r\n * A verbose error map with detailed descriptions for most error codes.\r\n *\r\n * See discussion at {@link AuthErrorMap}\r\n *\r\n * @public\r\n */\r\nconst debugErrorMap = _debugErrorMap;\r\n/**\r\n * A minimal error map with all verbose error messages stripped.\r\n *\r\n * See discussion at {@link AuthErrorMap}\r\n *\r\n * @public\r\n */\r\nconst prodErrorMap = _prodErrorMap;\r\nconst _DEFAULT_AUTH_ERROR_FACTORY = new ErrorFactory('auth', 'Firebase', _prodErrorMap());\r\n/**\r\n * A map of potential `Auth` error codes, for easier comparison with errors\r\n * thrown by the SDK.\r\n *\r\n * @remarks\r\n * Note that you can't tree-shake individual keys\r\n * in the map, so by using the map you might substantially increase your\r\n * bundle size.\r\n *\r\n * @public\r\n */\r\nconst AUTH_ERROR_CODES_MAP_DO_NOT_USE_INTERNALLY = {\r\n ADMIN_ONLY_OPERATION: 'auth/admin-restricted-operation',\r\n ARGUMENT_ERROR: 'auth/argument-error',\r\n APP_NOT_AUTHORIZED: 'auth/app-not-authorized',\r\n APP_NOT_INSTALLED: 'auth/app-not-installed',\r\n CAPTCHA_CHECK_FAILED: 'auth/captcha-check-failed',\r\n CODE_EXPIRED: 'auth/code-expired',\r\n CORDOVA_NOT_READY: 'auth/cordova-not-ready',\r\n CORS_UNSUPPORTED: 'auth/cors-unsupported',\r\n CREDENTIAL_ALREADY_IN_USE: 'auth/credential-already-in-use',\r\n CREDENTIAL_MISMATCH: 'auth/custom-token-mismatch',\r\n CREDENTIAL_TOO_OLD_LOGIN_AGAIN: 'auth/requires-recent-login',\r\n DEPENDENT_SDK_INIT_BEFORE_AUTH: 'auth/dependent-sdk-initialized-before-auth',\r\n DYNAMIC_LINK_NOT_ACTIVATED: 'auth/dynamic-link-not-activated',\r\n EMAIL_CHANGE_NEEDS_VERIFICATION: 'auth/email-change-needs-verification',\r\n EMAIL_EXISTS: 'auth/email-already-in-use',\r\n EMULATOR_CONFIG_FAILED: 'auth/emulator-config-failed',\r\n EXPIRED_OOB_CODE: 'auth/expired-action-code',\r\n EXPIRED_POPUP_REQUEST: 'auth/cancelled-popup-request',\r\n INTERNAL_ERROR: 'auth/internal-error',\r\n INVALID_API_KEY: 'auth/invalid-api-key',\r\n INVALID_APP_CREDENTIAL: 'auth/invalid-app-credential',\r\n INVALID_APP_ID: 'auth/invalid-app-id',\r\n INVALID_AUTH: 'auth/invalid-user-token',\r\n INVALID_AUTH_EVENT: 'auth/invalid-auth-event',\r\n INVALID_CERT_HASH: 'auth/invalid-cert-hash',\r\n INVALID_CODE: 'auth/invalid-verification-code',\r\n INVALID_CONTINUE_URI: 'auth/invalid-continue-uri',\r\n INVALID_CORDOVA_CONFIGURATION: 'auth/invalid-cordova-configuration',\r\n INVALID_CUSTOM_TOKEN: 'auth/invalid-custom-token',\r\n INVALID_DYNAMIC_LINK_DOMAIN: 'auth/invalid-dynamic-link-domain',\r\n INVALID_EMAIL: 'auth/invalid-email',\r\n INVALID_EMULATOR_SCHEME: 'auth/invalid-emulator-scheme',\r\n INVALID_IDP_RESPONSE: 'auth/invalid-credential',\r\n INVALID_MESSAGE_PAYLOAD: 'auth/invalid-message-payload',\r\n INVALID_MFA_SESSION: 'auth/invalid-multi-factor-session',\r\n INVALID_OAUTH_CLIENT_ID: 'auth/invalid-oauth-client-id',\r\n INVALID_OAUTH_PROVIDER: 'auth/invalid-oauth-provider',\r\n INVALID_OOB_CODE: 'auth/invalid-action-code',\r\n INVALID_ORIGIN: 'auth/unauthorized-domain',\r\n INVALID_PASSWORD: 'auth/wrong-password',\r\n INVALID_PERSISTENCE: 'auth/invalid-persistence-type',\r\n INVALID_PHONE_NUMBER: 'auth/invalid-phone-number',\r\n INVALID_PROVIDER_ID: 'auth/invalid-provider-id',\r\n INVALID_RECIPIENT_EMAIL: 'auth/invalid-recipient-email',\r\n INVALID_SENDER: 'auth/invalid-sender',\r\n INVALID_SESSION_INFO: 'auth/invalid-verification-id',\r\n INVALID_TENANT_ID: 'auth/invalid-tenant-id',\r\n MFA_INFO_NOT_FOUND: 'auth/multi-factor-info-not-found',\r\n MFA_REQUIRED: 'auth/multi-factor-auth-required',\r\n MISSING_ANDROID_PACKAGE_NAME: 'auth/missing-android-pkg-name',\r\n MISSING_APP_CREDENTIAL: 'auth/missing-app-credential',\r\n MISSING_AUTH_DOMAIN: 'auth/auth-domain-config-required',\r\n MISSING_CODE: 'auth/missing-verification-code',\r\n MISSING_CONTINUE_URI: 'auth/missing-continue-uri',\r\n MISSING_IFRAME_START: 'auth/missing-iframe-start',\r\n MISSING_IOS_BUNDLE_ID: 'auth/missing-ios-bundle-id',\r\n MISSING_OR_INVALID_NONCE: 'auth/missing-or-invalid-nonce',\r\n MISSING_MFA_INFO: 'auth/missing-multi-factor-info',\r\n MISSING_MFA_SESSION: 'auth/missing-multi-factor-session',\r\n MISSING_PHONE_NUMBER: 'auth/missing-phone-number',\r\n MISSING_SESSION_INFO: 'auth/missing-verification-id',\r\n MODULE_DESTROYED: 'auth/app-deleted',\r\n NEED_CONFIRMATION: 'auth/account-exists-with-different-credential',\r\n NETWORK_REQUEST_FAILED: 'auth/network-request-failed',\r\n NULL_USER: 'auth/null-user',\r\n NO_AUTH_EVENT: 'auth/no-auth-event',\r\n NO_SUCH_PROVIDER: 'auth/no-such-provider',\r\n OPERATION_NOT_ALLOWED: 'auth/operation-not-allowed',\r\n OPERATION_NOT_SUPPORTED: 'auth/operation-not-supported-in-this-environment',\r\n POPUP_BLOCKED: 'auth/popup-blocked',\r\n POPUP_CLOSED_BY_USER: 'auth/popup-closed-by-user',\r\n PROVIDER_ALREADY_LINKED: 'auth/provider-already-linked',\r\n QUOTA_EXCEEDED: 'auth/quota-exceeded',\r\n REDIRECT_CANCELLED_BY_USER: 'auth/redirect-cancelled-by-user',\r\n REDIRECT_OPERATION_PENDING: 'auth/redirect-operation-pending',\r\n REJECTED_CREDENTIAL: 'auth/rejected-credential',\r\n SECOND_FACTOR_ALREADY_ENROLLED: 'auth/second-factor-already-in-use',\r\n SECOND_FACTOR_LIMIT_EXCEEDED: 'auth/maximum-second-factor-count-exceeded',\r\n TENANT_ID_MISMATCH: 'auth/tenant-id-mismatch',\r\n TIMEOUT: 'auth/timeout',\r\n TOKEN_EXPIRED: 'auth/user-token-expired',\r\n TOO_MANY_ATTEMPTS_TRY_LATER: 'auth/too-many-requests',\r\n UNAUTHORIZED_DOMAIN: 'auth/unauthorized-continue-uri',\r\n UNSUPPORTED_FIRST_FACTOR: 'auth/unsupported-first-factor',\r\n UNSUPPORTED_PERSISTENCE: 'auth/unsupported-persistence-type',\r\n UNSUPPORTED_TENANT_OPERATION: 'auth/unsupported-tenant-operation',\r\n UNVERIFIED_EMAIL: 'auth/unverified-email',\r\n USER_CANCELLED: 'auth/user-cancelled',\r\n USER_DELETED: 'auth/user-not-found',\r\n USER_DISABLED: 'auth/user-disabled',\r\n USER_MISMATCH: 'auth/user-mismatch',\r\n USER_SIGNED_OUT: 'auth/user-signed-out',\r\n WEAK_PASSWORD: 'auth/weak-password',\r\n WEB_STORAGE_UNSUPPORTED: 'auth/web-storage-unsupported',\r\n ALREADY_INITIALIZED: 'auth/already-initialized',\r\n RECAPTCHA_NOT_ENABLED: 'auth/recaptcha-not-enabled',\r\n MISSING_RECAPTCHA_TOKEN: 'auth/missing-recaptcha-token',\r\n INVALID_RECAPTCHA_TOKEN: 'auth/invalid-recaptcha-token',\r\n INVALID_RECAPTCHA_ACTION: 'auth/invalid-recaptcha-action',\r\n MISSING_CLIENT_TYPE: 'auth/missing-client-type',\r\n MISSING_RECAPTCHA_VERSION: 'auth/missing-recaptcha-version',\r\n INVALID_RECAPTCHA_VERSION: 'auth/invalid-recaptcha-version',\r\n INVALID_REQ_TYPE: 'auth/invalid-req-type'\r\n};\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nconst logClient = new Logger('@firebase/auth');\r\nfunction _logWarn(msg, ...args) {\r\n if (logClient.logLevel <= LogLevel.WARN) {\r\n logClient.warn(`Auth (${SDK_VERSION}): ${msg}`, ...args);\r\n }\r\n}\r\nfunction _logError(msg, ...args) {\r\n if (logClient.logLevel <= LogLevel.ERROR) {\r\n logClient.error(`Auth (${SDK_VERSION}): ${msg}`, ...args);\r\n }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nfunction _fail(authOrCode, ...rest) {\r\n throw createErrorInternal(authOrCode, ...rest);\r\n}\r\nfunction _createError(authOrCode, ...rest) {\r\n return createErrorInternal(authOrCode, ...rest);\r\n}\r\nfunction _errorWithCustomMessage(auth, code, message) {\r\n const errorMap = Object.assign(Object.assign({}, prodErrorMap()), { [code]: message });\r\n const factory = new ErrorFactory('auth', 'Firebase', errorMap);\r\n return factory.create(code, {\r\n appName: auth.name\r\n });\r\n}\r\nfunction _assertInstanceOf(auth, object, instance) {\r\n const constructorInstance = instance;\r\n if (!(object instanceof constructorInstance)) {\r\n if (constructorInstance.name !== object.constructor.name) {\r\n _fail(auth, \"argument-error\" /* AuthErrorCode.ARGUMENT_ERROR */);\r\n }\r\n throw _errorWithCustomMessage(auth, \"argument-error\" /* AuthErrorCode.ARGUMENT_ERROR */, `Type of ${object.constructor.name} does not match expected instance.` +\r\n `Did you pass a reference from a different Auth SDK?`);\r\n }\r\n}\r\nfunction createErrorInternal(authOrCode, ...rest) {\r\n if (typeof authOrCode !== 'string') {\r\n const code = rest[0];\r\n const fullParams = [...rest.slice(1)];\r\n if (fullParams[0]) {\r\n fullParams[0].appName = authOrCode.name;\r\n }\r\n return authOrCode._errorFactory.create(code, ...fullParams);\r\n }\r\n return _DEFAULT_AUTH_ERROR_FACTORY.create(authOrCode, ...rest);\r\n}\r\nfunction _assert(assertion, authOrCode, ...rest) {\r\n if (!assertion) {\r\n throw createErrorInternal(authOrCode, ...rest);\r\n }\r\n}\r\n/**\r\n * Unconditionally fails, throwing an internal error with the given message.\r\n *\r\n * @param failure type of failure encountered\r\n * @throws Error\r\n */\r\nfunction debugFail(failure) {\r\n // Log the failure in addition to throw an exception, just in case the\r\n // exception is swallowed.\r\n const message = `INTERNAL ASSERTION FAILED: ` + failure;\r\n _logError(message);\r\n // NOTE: We don't use FirebaseError here because these are internal failures\r\n // that cannot be handled by the user. (Also it would create a circular\r\n // dependency between the error and assert modules which doesn't work.)\r\n throw new Error(message);\r\n}\r\n/**\r\n * Fails if the given assertion condition is false, throwing an Error with the\r\n * given message if it did.\r\n *\r\n * @param assertion\r\n * @param message\r\n */\r\nfunction debugAssert(assertion, message) {\r\n if (!assertion) {\r\n debugFail(message);\r\n }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nfunction _getCurrentUrl() {\r\n var _a;\r\n return (typeof self !== 'undefined' && ((_a = self.location) === null || _a === void 0 ? void 0 : _a.href)) || '';\r\n}\r\nfunction _isHttpOrHttps() {\r\n return _getCurrentScheme() === 'http:' || _getCurrentScheme() === 'https:';\r\n}\r\nfunction _getCurrentScheme() {\r\n var _a;\r\n return (typeof self !== 'undefined' && ((_a = self.location) === null || _a === void 0 ? void 0 : _a.protocol)) || null;\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Determine whether the browser is working online\r\n */\r\nfunction _isOnline() {\r\n if (typeof navigator !== 'undefined' &&\r\n navigator &&\r\n 'onLine' in navigator &&\r\n typeof navigator.onLine === 'boolean' &&\r\n // Apply only for traditional web apps and Chrome extensions.\r\n // This is especially true for Cordova apps which have unreliable\r\n // navigator.onLine behavior unless cordova-plugin-network-information is\r\n // installed which overwrites the native navigator.onLine value and\r\n // defines navigator.connection.\r\n (_isHttpOrHttps() || isBrowserExtension() || 'connection' in navigator)) {\r\n return navigator.onLine;\r\n }\r\n // If we can't determine the state, assume it is online.\r\n return true;\r\n}\r\nfunction _getUserLanguage() {\r\n if (typeof navigator === 'undefined') {\r\n return null;\r\n }\r\n const navigatorLanguage = navigator;\r\n return (\r\n // Most reliable, but only supported in Chrome/Firefox.\r\n (navigatorLanguage.languages && navigatorLanguage.languages[0]) ||\r\n // Supported in most browsers, but returns the language of the browser\r\n // UI, not the language set in browser settings.\r\n navigatorLanguage.language ||\r\n // Couldn't determine language.\r\n null);\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * A structure to help pick between a range of long and short delay durations\r\n * depending on the current environment. In general, the long delay is used for\r\n * mobile environments whereas short delays are used for desktop environments.\r\n */\r\nclass Delay {\r\n constructor(shortDelay, longDelay) {\r\n this.shortDelay = shortDelay;\r\n this.longDelay = longDelay;\r\n // Internal error when improperly initialized.\r\n debugAssert(longDelay > shortDelay, 'Short delay should be less than long delay!');\r\n this.isMobile = isMobileCordova() || isReactNative();\r\n }\r\n get() {\r\n if (!_isOnline()) {\r\n // Pick the shorter timeout.\r\n return Math.min(5000 /* DelayMin.OFFLINE */, this.shortDelay);\r\n }\r\n // If running in a mobile environment, return the long delay, otherwise\r\n // return the short delay.\r\n // This could be improved in the future to dynamically change based on other\r\n // variables instead of just reading the current environment.\r\n return this.isMobile ? this.longDelay : this.shortDelay;\r\n }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nfunction _emulatorUrl(config, path) {\r\n debugAssert(config.emulator, 'Emulator should always be set here');\r\n const { url } = config.emulator;\r\n if (!path) {\r\n return url;\r\n }\r\n return `${url}${path.startsWith('/') ? path.slice(1) : path}`;\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nclass FetchProvider {\r\n static initialize(fetchImpl, headersImpl, responseImpl) {\r\n this.fetchImpl = fetchImpl;\r\n if (headersImpl) {\r\n this.headersImpl = headersImpl;\r\n }\r\n if (responseImpl) {\r\n this.responseImpl = responseImpl;\r\n }\r\n }\r\n static fetch() {\r\n if (this.fetchImpl) {\r\n return this.fetchImpl;\r\n }\r\n if (typeof self !== 'undefined' && 'fetch' in self) {\r\n return self.fetch;\r\n }\r\n debugFail('Could not find fetch implementation, make sure you call FetchProvider.initialize() with an appropriate polyfill');\r\n }\r\n static headers() {\r\n if (this.headersImpl) {\r\n return this.headersImpl;\r\n }\r\n if (typeof self !== 'undefined' && 'Headers' in self) {\r\n return self.Headers;\r\n }\r\n debugFail('Could not find Headers implementation, make sure you call FetchProvider.initialize() with an appropriate polyfill');\r\n }\r\n static response() {\r\n if (this.responseImpl) {\r\n return this.responseImpl;\r\n }\r\n if (typeof self !== 'undefined' && 'Response' in self) {\r\n return self.Response;\r\n }\r\n debugFail('Could not find Response implementation, make sure you call FetchProvider.initialize() with an appropriate polyfill');\r\n }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Map from errors returned by the server to errors to developer visible errors\r\n */\r\nconst SERVER_ERROR_MAP = {\r\n // Custom token errors.\r\n [\"CREDENTIAL_MISMATCH\" /* ServerError.CREDENTIAL_MISMATCH */]: \"custom-token-mismatch\" /* AuthErrorCode.CREDENTIAL_MISMATCH */,\r\n // This can only happen if the SDK sends a bad request.\r\n [\"MISSING_CUSTOM_TOKEN\" /* ServerError.MISSING_CUSTOM_TOKEN */]: \"internal-error\" /* AuthErrorCode.INTERNAL_ERROR */,\r\n // Create Auth URI errors.\r\n [\"INVALID_IDENTIFIER\" /* ServerError.INVALID_IDENTIFIER */]: \"invalid-email\" /* AuthErrorCode.INVALID_EMAIL */,\r\n // This can only happen if the SDK sends a bad request.\r\n [\"MISSING_CONTINUE_URI\" /* ServerError.MISSING_CONTINUE_URI */]: \"internal-error\" /* AuthErrorCode.INTERNAL_ERROR */,\r\n // Sign in with email and password errors (some apply to sign up too).\r\n [\"INVALID_PASSWORD\" /* ServerError.INVALID_PASSWORD */]: \"wrong-password\" /* AuthErrorCode.INVALID_PASSWORD */,\r\n // This can only happen if the SDK sends a bad request.\r\n [\"MISSING_PASSWORD\" /* ServerError.MISSING_PASSWORD */]: \"missing-password\" /* AuthErrorCode.MISSING_PASSWORD */,\r\n // Sign up with email and password errors.\r\n [\"EMAIL_EXISTS\" /* ServerError.EMAIL_EXISTS */]: \"email-already-in-use\" /* AuthErrorCode.EMAIL_EXISTS */,\r\n [\"PASSWORD_LOGIN_DISABLED\" /* ServerError.PASSWORD_LOGIN_DISABLED */]: \"operation-not-allowed\" /* AuthErrorCode.OPERATION_NOT_ALLOWED */,\r\n // Verify assertion for sign in with credential errors:\r\n [\"INVALID_IDP_RESPONSE\" /* ServerError.INVALID_IDP_RESPONSE */]: \"invalid-credential\" /* AuthErrorCode.INVALID_IDP_RESPONSE */,\r\n [\"INVALID_PENDING_TOKEN\" /* ServerError.INVALID_PENDING_TOKEN */]: \"invalid-credential\" /* AuthErrorCode.INVALID_IDP_RESPONSE */,\r\n [\"FEDERATED_USER_ID_ALREADY_LINKED\" /* ServerError.FEDERATED_USER_ID_ALREADY_LINKED */]: \"credential-already-in-use\" /* AuthErrorCode.CREDENTIAL_ALREADY_IN_USE */,\r\n // This can only happen if the SDK sends a bad request.\r\n [\"MISSING_REQ_TYPE\" /* ServerError.MISSING_REQ_TYPE */]: \"internal-error\" /* AuthErrorCode.INTERNAL_ERROR */,\r\n // Send Password reset email errors:\r\n [\"EMAIL_NOT_FOUND\" /* ServerError.EMAIL_NOT_FOUND */]: \"user-not-found\" /* AuthErrorCode.USER_DELETED */,\r\n [\"RESET_PASSWORD_EXCEED_LIMIT\" /* ServerError.RESET_PASSWORD_EXCEED_LIMIT */]: \"too-many-requests\" /* AuthErrorCode.TOO_MANY_ATTEMPTS_TRY_LATER */,\r\n [\"EXPIRED_OOB_CODE\" /* ServerError.EXPIRED_OOB_CODE */]: \"expired-action-code\" /* AuthErrorCode.EXPIRED_OOB_CODE */,\r\n [\"INVALID_OOB_CODE\" /* ServerError.INVALID_OOB_CODE */]: \"invalid-action-code\" /* AuthErrorCode.INVALID_OOB_CODE */,\r\n // This can only happen if the SDK sends a bad request.\r\n [\"MISSING_OOB_CODE\" /* ServerError.MISSING_OOB_CODE */]: \"internal-error\" /* AuthErrorCode.INTERNAL_ERROR */,\r\n // Operations that require ID token in request:\r\n [\"CREDENTIAL_TOO_OLD_LOGIN_AGAIN\" /* ServerError.CREDENTIAL_TOO_OLD_LOGIN_AGAIN */]: \"requires-recent-login\" /* AuthErrorCode.CREDENTIAL_TOO_OLD_LOGIN_AGAIN */,\r\n [\"INVALID_ID_TOKEN\" /* ServerError.INVALID_ID_TOKEN */]: \"invalid-user-token\" /* AuthErrorCode.INVALID_AUTH */,\r\n [\"TOKEN_EXPIRED\" /* ServerError.TOKEN_EXPIRED */]: \"user-token-expired\" /* AuthErrorCode.TOKEN_EXPIRED */,\r\n [\"USER_NOT_FOUND\" /* ServerError.USER_NOT_FOUND */]: \"user-token-expired\" /* AuthErrorCode.TOKEN_EXPIRED */,\r\n // Other errors.\r\n [\"TOO_MANY_ATTEMPTS_TRY_LATER\" /* ServerError.TOO_MANY_ATTEMPTS_TRY_LATER */]: \"too-many-requests\" /* AuthErrorCode.TOO_MANY_ATTEMPTS_TRY_LATER */,\r\n // Phone Auth related errors.\r\n [\"INVALID_CODE\" /* ServerError.INVALID_CODE */]: \"invalid-verification-code\" /* AuthErrorCode.INVALID_CODE */,\r\n [\"INVALID_SESSION_INFO\" /* ServerError.INVALID_SESSION_INFO */]: \"invalid-verification-id\" /* AuthErrorCode.INVALID_SESSION_INFO */,\r\n [\"INVALID_TEMPORARY_PROOF\" /* ServerError.INVALID_TEMPORARY_PROOF */]: \"invalid-credential\" /* AuthErrorCode.INVALID_IDP_RESPONSE */,\r\n [\"MISSING_SESSION_INFO\" /* ServerError.MISSING_SESSION_INFO */]: \"missing-verification-id\" /* AuthErrorCode.MISSING_SESSION_INFO */,\r\n [\"SESSION_EXPIRED\" /* ServerError.SESSION_EXPIRED */]: \"code-expired\" /* AuthErrorCode.CODE_EXPIRED */,\r\n // Other action code errors when additional settings passed.\r\n // MISSING_CONTINUE_URI is getting mapped to INTERNAL_ERROR above.\r\n // This is OK as this error will be caught by client side validation.\r\n [\"MISSING_ANDROID_PACKAGE_NAME\" /* ServerError.MISSING_ANDROID_PACKAGE_NAME */]: \"missing-android-pkg-name\" /* AuthErrorCode.MISSING_ANDROID_PACKAGE_NAME */,\r\n [\"UNAUTHORIZED_DOMAIN\" /* ServerError.UNAUTHORIZED_DOMAIN */]: \"unauthorized-continue-uri\" /* AuthErrorCode.UNAUTHORIZED_DOMAIN */,\r\n // getProjectConfig errors when clientId is passed.\r\n [\"INVALID_OAUTH_CLIENT_ID\" /* ServerError.INVALID_OAUTH_CLIENT_ID */]: \"invalid-oauth-client-id\" /* AuthErrorCode.INVALID_OAUTH_CLIENT_ID */,\r\n // User actions (sign-up or deletion) disabled errors.\r\n [\"ADMIN_ONLY_OPERATION\" /* ServerError.ADMIN_ONLY_OPERATION */]: \"admin-restricted-operation\" /* AuthErrorCode.ADMIN_ONLY_OPERATION */,\r\n // Multi factor related errors.\r\n [\"INVALID_MFA_PENDING_CREDENTIAL\" /* ServerError.INVALID_MFA_PENDING_CREDENTIAL */]: \"invalid-multi-factor-session\" /* AuthErrorCode.INVALID_MFA_SESSION */,\r\n [\"MFA_ENROLLMENT_NOT_FOUND\" /* ServerError.MFA_ENROLLMENT_NOT_FOUND */]: \"multi-factor-info-not-found\" /* AuthErrorCode.MFA_INFO_NOT_FOUND */,\r\n [\"MISSING_MFA_ENROLLMENT_ID\" /* ServerError.MISSING_MFA_ENROLLMENT_ID */]: \"missing-multi-factor-info\" /* AuthErrorCode.MISSING_MFA_INFO */,\r\n [\"MISSING_MFA_PENDING_CREDENTIAL\" /* ServerError.MISSING_MFA_PENDING_CREDENTIAL */]: \"missing-multi-factor-session\" /* AuthErrorCode.MISSING_MFA_SESSION */,\r\n [\"SECOND_FACTOR_EXISTS\" /* ServerError.SECOND_FACTOR_EXISTS */]: \"second-factor-already-in-use\" /* AuthErrorCode.SECOND_FACTOR_ALREADY_ENROLLED */,\r\n [\"SECOND_FACTOR_LIMIT_EXCEEDED\" /* ServerError.SECOND_FACTOR_LIMIT_EXCEEDED */]: \"maximum-second-factor-count-exceeded\" /* AuthErrorCode.SECOND_FACTOR_LIMIT_EXCEEDED */,\r\n // Blocking functions related errors.\r\n [\"BLOCKING_FUNCTION_ERROR_RESPONSE\" /* ServerError.BLOCKING_FUNCTION_ERROR_RESPONSE */]: \"internal-error\" /* AuthErrorCode.INTERNAL_ERROR */,\r\n // Recaptcha related errors.\r\n [\"RECAPTCHA_NOT_ENABLED\" /* ServerError.RECAPTCHA_NOT_ENABLED */]: \"recaptcha-not-enabled\" /* AuthErrorCode.RECAPTCHA_NOT_ENABLED */,\r\n [\"MISSING_RECAPTCHA_TOKEN\" /* ServerError.MISSING_RECAPTCHA_TOKEN */]: \"missing-recaptcha-token\" /* AuthErrorCode.MISSING_RECAPTCHA_TOKEN */,\r\n [\"INVALID_RECAPTCHA_TOKEN\" /* ServerError.INVALID_RECAPTCHA_TOKEN */]: \"invalid-recaptcha-token\" /* AuthErrorCode.INVALID_RECAPTCHA_TOKEN */,\r\n [\"INVALID_RECAPTCHA_ACTION\" /* ServerError.INVALID_RECAPTCHA_ACTION */]: \"invalid-recaptcha-action\" /* AuthErrorCode.INVALID_RECAPTCHA_ACTION */,\r\n [\"MISSING_CLIENT_TYPE\" /* ServerError.MISSING_CLIENT_TYPE */]: \"missing-client-type\" /* AuthErrorCode.MISSING_CLIENT_TYPE */,\r\n [\"MISSING_RECAPTCHA_VERSION\" /* ServerError.MISSING_RECAPTCHA_VERSION */]: \"missing-recaptcha-version\" /* AuthErrorCode.MISSING_RECAPTCHA_VERSION */,\r\n [\"INVALID_RECAPTCHA_VERSION\" /* ServerError.INVALID_RECAPTCHA_VERSION */]: \"invalid-recaptcha-version\" /* AuthErrorCode.INVALID_RECAPTCHA_VERSION */,\r\n [\"INVALID_REQ_TYPE\" /* ServerError.INVALID_REQ_TYPE */]: \"invalid-req-type\" /* AuthErrorCode.INVALID_REQ_TYPE */\r\n};\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nconst DEFAULT_API_TIMEOUT_MS = new Delay(30000, 60000);\r\nfunction _addTidIfNecessary(auth, request) {\r\n if (auth.tenantId && !request.tenantId) {\r\n return Object.assign(Object.assign({}, request), { tenantId: auth.tenantId });\r\n }\r\n return request;\r\n}\r\nasync function _performApiRequest(auth, method, path, request, customErrorMap = {}) {\r\n return _performFetchWithErrorHandling(auth, customErrorMap, async () => {\r\n let body = {};\r\n let params = {};\r\n if (request) {\r\n if (method === \"GET\" /* HttpMethod.GET */) {\r\n params = request;\r\n }\r\n else {\r\n body = {\r\n body: JSON.stringify(request)\r\n };\r\n }\r\n }\r\n const query = querystring(Object.assign({ key: auth.config.apiKey }, params)).slice(1);\r\n const headers = await auth._getAdditionalHeaders();\r\n headers[\"Content-Type\" /* HttpHeader.CONTENT_TYPE */] = 'application/json';\r\n if (auth.languageCode) {\r\n headers[\"X-Firebase-Locale\" /* HttpHeader.X_FIREBASE_LOCALE */] = auth.languageCode;\r\n }\r\n return FetchProvider.fetch()(_getFinalTarget(auth, auth.config.apiHost, path, query), Object.assign({ method,\r\n headers, referrerPolicy: 'no-referrer' }, body));\r\n });\r\n}\r\nasync function _performFetchWithErrorHandling(auth, customErrorMap, fetchFn) {\r\n auth._canInitEmulator = false;\r\n const errorMap = Object.assign(Object.assign({}, SERVER_ERROR_MAP), customErrorMap);\r\n try {\r\n const networkTimeout = new NetworkTimeout(auth);\r\n const response = await Promise.race([\r\n fetchFn(),\r\n networkTimeout.promise\r\n ]);\r\n // If we've reached this point, the fetch succeeded and the networkTimeout\r\n // didn't throw; clear the network timeout delay so that Node won't hang\r\n networkTimeout.clearNetworkTimeout();\r\n const json = await response.json();\r\n if ('needConfirmation' in json) {\r\n throw _makeTaggedError(auth, \"account-exists-with-different-credential\" /* AuthErrorCode.NEED_CONFIRMATION */, json);\r\n }\r\n if (response.ok && !('errorMessage' in json)) {\r\n return json;\r\n }\r\n else {\r\n const errorMessage = response.ok ? json.errorMessage : json.error.message;\r\n const [serverErrorCode, serverErrorMessage] = errorMessage.split(' : ');\r\n if (serverErrorCode === \"FEDERATED_USER_ID_ALREADY_LINKED\" /* ServerError.FEDERATED_USER_ID_ALREADY_LINKED */) {\r\n throw _makeTaggedError(auth, \"credential-already-in-use\" /* AuthErrorCode.CREDENTIAL_ALREADY_IN_USE */, json);\r\n }\r\n else if (serverErrorCode === \"EMAIL_EXISTS\" /* ServerError.EMAIL_EXISTS */) {\r\n throw _makeTaggedError(auth, \"email-already-in-use\" /* AuthErrorCode.EMAIL_EXISTS */, json);\r\n }\r\n else if (serverErrorCode === \"USER_DISABLED\" /* ServerError.USER_DISABLED */) {\r\n throw _makeTaggedError(auth, \"user-disabled\" /* AuthErrorCode.USER_DISABLED */, json);\r\n }\r\n const authError = errorMap[serverErrorCode] ||\r\n serverErrorCode\r\n .toLowerCase()\r\n .replace(/[_\\s]+/g, '-');\r\n if (serverErrorMessage) {\r\n throw _errorWithCustomMessage(auth, authError, serverErrorMessage);\r\n }\r\n else {\r\n _fail(auth, authError);\r\n }\r\n }\r\n }\r\n catch (e) {\r\n if (e instanceof FirebaseError) {\r\n throw e;\r\n }\r\n // Changing this to a different error code will log user out when there is a network error\r\n // because we treat any error other than NETWORK_REQUEST_FAILED as token is invalid.\r\n // https://github.com/firebase/firebase-js-sdk/blob/4fbc73610d70be4e0852e7de63a39cb7897e8546/packages/auth/src/core/auth/auth_impl.ts#L309-L316\r\n _fail(auth, \"network-request-failed\" /* AuthErrorCode.NETWORK_REQUEST_FAILED */, { 'message': String(e) });\r\n }\r\n}\r\nasync function _performSignInRequest(auth, method, path, request, customErrorMap = {}) {\r\n const serverResponse = (await _performApiRequest(auth, method, path, request, customErrorMap));\r\n if ('mfaPendingCredential' in serverResponse) {\r\n _fail(auth, \"multi-factor-auth-required\" /* AuthErrorCode.MFA_REQUIRED */, {\r\n _serverResponse: serverResponse\r\n });\r\n }\r\n return serverResponse;\r\n}\r\nfunction _getFinalTarget(auth, host, path, query) {\r\n const base = `${host}${path}?${query}`;\r\n if (!auth.config.emulator) {\r\n return `${auth.config.apiScheme}://${base}`;\r\n }\r\n return _emulatorUrl(auth.config, base);\r\n}\r\nclass NetworkTimeout {\r\n constructor(auth) {\r\n this.auth = auth;\r\n // Node timers and browser timers are fundamentally incompatible, but we\r\n // don't care about the value here\r\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\r\n this.timer = null;\r\n this.promise = new Promise((_, reject) => {\r\n this.timer = setTimeout(() => {\r\n return reject(_createError(this.auth, \"network-request-failed\" /* AuthErrorCode.NETWORK_REQUEST_FAILED */));\r\n }, DEFAULT_API_TIMEOUT_MS.get());\r\n });\r\n }\r\n clearNetworkTimeout() {\r\n clearTimeout(this.timer);\r\n }\r\n}\r\nfunction _makeTaggedError(auth, code, response) {\r\n const errorParams = {\r\n appName: auth.name\r\n };\r\n if (response.email) {\r\n errorParams.email = response.email;\r\n }\r\n if (response.phoneNumber) {\r\n errorParams.phoneNumber = response.phoneNumber;\r\n }\r\n const error = _createError(auth, code, errorParams);\r\n // We know customData is defined on error because errorParams is defined\r\n error.customData._tokenResponse = response;\r\n return error;\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nasync function deleteAccount(auth, request) {\r\n return _performApiRequest(auth, \"POST\" /* HttpMethod.POST */, \"/v1/accounts:delete\" /* Endpoint.DELETE_ACCOUNT */, request);\r\n}\r\nasync function deleteLinkedAccounts(auth, request) {\r\n return _performApiRequest(auth, \"POST\" /* HttpMethod.POST */, \"/v1/accounts:update\" /* Endpoint.SET_ACCOUNT_INFO */, request);\r\n}\r\nasync function getAccountInfo(auth, request) {\r\n return _performApiRequest(auth, \"POST\" /* HttpMethod.POST */, \"/v1/accounts:lookup\" /* Endpoint.GET_ACCOUNT_INFO */, request);\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nfunction utcTimestampToDateString(utcTimestamp) {\r\n if (!utcTimestamp) {\r\n return undefined;\r\n }\r\n try {\r\n // Convert to date object.\r\n const date = new Date(Number(utcTimestamp));\r\n // Test date is valid.\r\n if (!isNaN(date.getTime())) {\r\n // Convert to UTC date string.\r\n return date.toUTCString();\r\n }\r\n }\r\n catch (e) {\r\n // Do nothing. undefined will be returned.\r\n }\r\n return undefined;\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Returns a JSON Web Token (JWT) used to identify the user to a Firebase service.\r\n *\r\n * @remarks\r\n * Returns the current token if it has not expired or if it will not expire in the next five\r\n * minutes. Otherwise, this will refresh the token and return a new one.\r\n *\r\n * @param user - The user.\r\n * @param forceRefresh - Force refresh regardless of token expiration.\r\n *\r\n * @public\r\n */\r\nfunction getIdToken(user, forceRefresh = false) {\r\n return getModularInstance(user).getIdToken(forceRefresh);\r\n}\r\n/**\r\n * Returns a deserialized JSON Web Token (JWT) used to identify the user to a Firebase service.\r\n *\r\n * @remarks\r\n * Returns the current token if it has not expired or if it will not expire in the next five\r\n * minutes. Otherwise, this will refresh the token and return a new one.\r\n *\r\n * @param user - The user.\r\n * @param forceRefresh - Force refresh regardless of token expiration.\r\n *\r\n * @public\r\n */\r\nasync function getIdTokenResult(user, forceRefresh = false) {\r\n const userInternal = getModularInstance(user);\r\n const token = await userInternal.getIdToken(forceRefresh);\r\n const claims = _parseToken(token);\r\n _assert(claims && claims.exp && claims.auth_time && claims.iat, userInternal.auth, \"internal-error\" /* AuthErrorCode.INTERNAL_ERROR */);\r\n const firebase = typeof claims.firebase === 'object' ? claims.firebase : undefined;\r\n const signInProvider = firebase === null || firebase === void 0 ? void 0 : firebase['sign_in_provider'];\r\n return {\r\n claims,\r\n token,\r\n authTime: utcTimestampToDateString(secondsStringToMilliseconds(claims.auth_time)),\r\n issuedAtTime: utcTimestampToDateString(secondsStringToMilliseconds(claims.iat)),\r\n expirationTime: utcTimestampToDateString(secondsStringToMilliseconds(claims.exp)),\r\n signInProvider: signInProvider || null,\r\n signInSecondFactor: (firebase === null || firebase === void 0 ? void 0 : firebase['sign_in_second_factor']) || null\r\n };\r\n}\r\nfunction secondsStringToMilliseconds(seconds) {\r\n return Number(seconds) * 1000;\r\n}\r\nfunction _parseToken(token) {\r\n const [algorithm, payload, signature] = token.split('.');\r\n if (algorithm === undefined ||\r\n payload === undefined ||\r\n signature === undefined) {\r\n _logError('JWT malformed, contained fewer than 3 sections');\r\n return null;\r\n }\r\n try {\r\n const decoded = base64Decode(payload);\r\n if (!decoded) {\r\n _logError('Failed to decode base64 JWT payload');\r\n return null;\r\n }\r\n return JSON.parse(decoded);\r\n }\r\n catch (e) {\r\n _logError('Caught error parsing JWT payload as JSON', e === null || e === void 0 ? void 0 : e.toString());\r\n return null;\r\n }\r\n}\r\n/**\r\n * Extract expiresIn TTL from a token by subtracting the expiration from the issuance.\r\n */\r\nfunction _tokenExpiresIn(token) {\r\n const parsedToken = _parseToken(token);\r\n _assert(parsedToken, \"internal-error\" /* AuthErrorCode.INTERNAL_ERROR */);\r\n _assert(typeof parsedToken.exp !== 'undefined', \"internal-error\" /* AuthErrorCode.INTERNAL_ERROR */);\r\n _assert(typeof parsedToken.iat !== 'undefined', \"internal-error\" /* AuthErrorCode.INTERNAL_ERROR */);\r\n return Number(parsedToken.exp) - Number(parsedToken.iat);\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nasync function _logoutIfInvalidated(user, promise, bypassAuthState = false) {\r\n if (bypassAuthState) {\r\n return promise;\r\n }\r\n try {\r\n return await promise;\r\n }\r\n catch (e) {\r\n if (e instanceof FirebaseError && isUserInvalidated(e)) {\r\n if (user.auth.currentUser === user) {\r\n await user.auth.signOut();\r\n }\r\n }\r\n throw e;\r\n }\r\n}\r\nfunction isUserInvalidated({ code }) {\r\n return (code === `auth/${\"user-disabled\" /* AuthErrorCode.USER_DISABLED */}` ||\r\n code === `auth/${\"user-token-expired\" /* AuthErrorCode.TOKEN_EXPIRED */}`);\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nclass ProactiveRefresh {\r\n constructor(user) {\r\n this.user = user;\r\n this.isRunning = false;\r\n // Node timers and browser timers return fundamentally different types.\r\n // We don't actually care what the value is but TS won't accept unknown and\r\n // we can't cast properly in both environments.\r\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\r\n this.timerId = null;\r\n this.errorBackoff = 30000 /* Duration.RETRY_BACKOFF_MIN */;\r\n }\r\n _start() {\r\n if (this.isRunning) {\r\n return;\r\n }\r\n this.isRunning = true;\r\n this.schedule();\r\n }\r\n _stop() {\r\n if (!this.isRunning) {\r\n return;\r\n }\r\n this.isRunning = false;\r\n if (this.timerId !== null) {\r\n clearTimeout(this.timerId);\r\n }\r\n }\r\n getInterval(wasError) {\r\n var _a;\r\n if (wasError) {\r\n const interval = this.errorBackoff;\r\n this.errorBackoff = Math.min(this.errorBackoff * 2, 960000 /* Duration.RETRY_BACKOFF_MAX */);\r\n return interval;\r\n }\r\n else {\r\n // Reset the error backoff\r\n this.errorBackoff = 30000 /* Duration.RETRY_BACKOFF_MIN */;\r\n const expTime = (_a = this.user.stsTokenManager.expirationTime) !== null && _a !== void 0 ? _a : 0;\r\n const interval = expTime - Date.now() - 300000 /* Duration.OFFSET */;\r\n return Math.max(0, interval);\r\n }\r\n }\r\n schedule(wasError = false) {\r\n if (!this.isRunning) {\r\n // Just in case...\r\n return;\r\n }\r\n const interval = this.getInterval(wasError);\r\n this.timerId = setTimeout(async () => {\r\n await this.iteration();\r\n }, interval);\r\n }\r\n async iteration() {\r\n try {\r\n await this.user.getIdToken(true);\r\n }\r\n catch (e) {\r\n // Only retry on network errors\r\n if ((e === null || e === void 0 ? void 0 : e.code) ===\r\n `auth/${\"network-request-failed\" /* AuthErrorCode.NETWORK_REQUEST_FAILED */}`) {\r\n this.schedule(/* wasError */ true);\r\n }\r\n return;\r\n }\r\n this.schedule();\r\n }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nclass UserMetadata {\r\n constructor(createdAt, lastLoginAt) {\r\n this.createdAt = createdAt;\r\n this.lastLoginAt = lastLoginAt;\r\n this._initializeTime();\r\n }\r\n _initializeTime() {\r\n this.lastSignInTime = utcTimestampToDateString(this.lastLoginAt);\r\n this.creationTime = utcTimestampToDateString(this.createdAt);\r\n }\r\n _copy(metadata) {\r\n this.createdAt = metadata.createdAt;\r\n this.lastLoginAt = metadata.lastLoginAt;\r\n this._initializeTime();\r\n }\r\n toJSON() {\r\n return {\r\n createdAt: this.createdAt,\r\n lastLoginAt: this.lastLoginAt\r\n };\r\n }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2019 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nasync function _reloadWithoutSaving(user) {\r\n var _a;\r\n const auth = user.auth;\r\n const idToken = await user.getIdToken();\r\n const response = await _logoutIfInvalidated(user, getAccountInfo(auth, { idToken }));\r\n _assert(response === null || response === void 0 ? void 0 : response.users.length, auth, \"internal-error\" /* AuthErrorCode.INTERNAL_ERROR */);\r\n const coreAccount = response.users[0];\r\n user._notifyReloadListener(coreAccount);\r\n const newProviderData = ((_a = coreAccount.providerUserInfo) === null || _a === void 0 ? void 0 : _a.length)\r\n ? extractProviderData(coreAccount.providerUserInfo)\r\n : [];\r\n const providerData = mergeProviderData(user.providerData, newProviderData);\r\n // Preserves the non-nonymous status of the stored user, even if no more\r\n // credentials (federated or email/password) are linked to the user. If\r\n // the user was previously anonymous, then use provider data to update.\r\n // On the other hand, if it was not anonymous before, it should never be\r\n // considered anonymous now.\r\n const oldIsAnonymous = user.isAnonymous;\r\n const newIsAnonymous = !(user.email && coreAccount.passwordHash) && !(providerData === null || providerData === void 0 ? void 0 : providerData.length);\r\n const isAnonymous = !oldIsAnonymous ? false : newIsAnonymous;\r\n const updates = {\r\n uid: coreAccount.localId,\r\n displayName: coreAccount.displayName || null,\r\n photoURL: coreAccount.photoUrl || null,\r\n email: coreAccount.email || null,\r\n emailVerified: coreAccount.emailVerified || false,\r\n phoneNumber: coreAccount.phoneNumber || null,\r\n tenantId: coreAccount.tenantId || null,\r\n providerData,\r\n metadata: new UserMetadata(coreAccount.createdAt, coreAccount.lastLoginAt),\r\n isAnonymous\r\n };\r\n Object.assign(user, updates);\r\n}\r\n/**\r\n * Reloads user account data, if signed in.\r\n *\r\n * @param user - The user.\r\n *\r\n * @public\r\n */\r\nasync function reload(user) {\r\n const userInternal = getModularInstance(user);\r\n await _reloadWithoutSaving(userInternal);\r\n // Even though the current user hasn't changed, update\r\n // current user will trigger a persistence update w/ the\r\n // new info.\r\n await userInternal.auth._persistUserIfCurrent(userInternal);\r\n userInternal.auth._notifyListenersIfCurrent(userInternal);\r\n}\r\nfunction mergeProviderData(original, newData) {\r\n const deduped = original.filter(o => !newData.some(n => n.providerId === o.providerId));\r\n return [...deduped, ...newData];\r\n}\r\nfunction extractProviderData(providers) {\r\n return providers.map((_a) => {\r\n var { providerId } = _a, provider = __rest(_a, [\"providerId\"]);\r\n return {\r\n providerId,\r\n uid: provider.rawId || '',\r\n displayName: provider.displayName || null,\r\n email: provider.email || null,\r\n phoneNumber: provider.phoneNumber || null,\r\n photoURL: provider.photoUrl || null\r\n };\r\n });\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nasync function requestStsToken(auth, refreshToken) {\r\n const response = await _performFetchWithErrorHandling(auth, {}, async () => {\r\n const body = querystring({\r\n 'grant_type': 'refresh_token',\r\n 'refresh_token': refreshToken\r\n }).slice(1);\r\n const { tokenApiHost, apiKey } = auth.config;\r\n const url = _getFinalTarget(auth, tokenApiHost, \"/v1/token\" /* Endpoint.TOKEN */, `key=${apiKey}`);\r\n const headers = await auth._getAdditionalHeaders();\r\n headers[\"Content-Type\" /* HttpHeader.CONTENT_TYPE */] = 'application/x-www-form-urlencoded';\r\n return FetchProvider.fetch()(url, {\r\n method: \"POST\" /* HttpMethod.POST */,\r\n headers,\r\n body\r\n });\r\n });\r\n // The response comes back in snake_case. Convert to camel:\r\n return {\r\n accessToken: response.access_token,\r\n expiresIn: response.expires_in,\r\n refreshToken: response.refresh_token\r\n };\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * We need to mark this class as internal explicitly to exclude it in the public typings, because\r\n * it references AuthInternal which has a circular dependency with UserInternal.\r\n *\r\n * @internal\r\n */\r\nclass StsTokenManager {\r\n constructor() {\r\n this.refreshToken = null;\r\n this.accessToken = null;\r\n this.expirationTime = null;\r\n }\r\n get isExpired() {\r\n return (!this.expirationTime ||\r\n Date.now() > this.expirationTime - 30000 /* Buffer.TOKEN_REFRESH */);\r\n }\r\n updateFromServerResponse(response) {\r\n _assert(response.idToken, \"internal-error\" /* AuthErrorCode.INTERNAL_ERROR */);\r\n _assert(typeof response.idToken !== 'undefined', \"internal-error\" /* AuthErrorCode.INTERNAL_ERROR */);\r\n _assert(typeof response.refreshToken !== 'undefined', \"internal-error\" /* AuthErrorCode.INTERNAL_ERROR */);\r\n const expiresIn = 'expiresIn' in response && typeof response.expiresIn !== 'undefined'\r\n ? Number(response.expiresIn)\r\n : _tokenExpiresIn(response.idToken);\r\n this.updateTokensAndExpiration(response.idToken, response.refreshToken, expiresIn);\r\n }\r\n async getToken(auth, forceRefresh = false) {\r\n _assert(!this.accessToken || this.refreshToken, auth, \"user-token-expired\" /* AuthErrorCode.TOKEN_EXPIRED */);\r\n if (!forceRefresh && this.accessToken && !this.isExpired) {\r\n return this.accessToken;\r\n }\r\n if (this.refreshToken) {\r\n await this.refresh(auth, this.refreshToken);\r\n return this.accessToken;\r\n }\r\n return null;\r\n }\r\n clearRefreshToken() {\r\n this.refreshToken = null;\r\n }\r\n async refresh(auth, oldToken) {\r\n const { accessToken, refreshToken, expiresIn } = await requestStsToken(auth, oldToken);\r\n this.updateTokensAndExpiration(accessToken, refreshToken, Number(expiresIn));\r\n }\r\n updateTokensAndExpiration(accessToken, refreshToken, expiresInSec) {\r\n this.refreshToken = refreshToken || null;\r\n this.accessToken = accessToken || null;\r\n this.expirationTime = Date.now() + expiresInSec * 1000;\r\n }\r\n static fromJSON(appName, object) {\r\n const { refreshToken, accessToken, expirationTime } = object;\r\n const manager = new StsTokenManager();\r\n if (refreshToken) {\r\n _assert(typeof refreshToken === 'string', \"internal-error\" /* AuthErrorCode.INTERNAL_ERROR */, {\r\n appName\r\n });\r\n manager.refreshToken = refreshToken;\r\n }\r\n if (accessToken) {\r\n _assert(typeof accessToken === 'string', \"internal-error\" /* AuthErrorCode.INTERNAL_ERROR */, {\r\n appName\r\n });\r\n manager.accessToken = accessToken;\r\n }\r\n if (expirationTime) {\r\n _assert(typeof expirationTime === 'number', \"internal-error\" /* AuthErrorCode.INTERNAL_ERROR */, {\r\n appName\r\n });\r\n manager.expirationTime = expirationTime;\r\n }\r\n return manager;\r\n }\r\n toJSON() {\r\n return {\r\n refreshToken: this.refreshToken,\r\n accessToken: this.accessToken,\r\n expirationTime: this.expirationTime\r\n };\r\n }\r\n _assign(stsTokenManager) {\r\n this.accessToken = stsTokenManager.accessToken;\r\n this.refreshToken = stsTokenManager.refreshToken;\r\n this.expirationTime = stsTokenManager.expirationTime;\r\n }\r\n _clone() {\r\n return Object.assign(new StsTokenManager(), this.toJSON());\r\n }\r\n _performRefresh() {\r\n return debugFail('not implemented');\r\n }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nfunction assertStringOrUndefined(assertion, appName) {\r\n _assert(typeof assertion === 'string' || typeof assertion === 'undefined', \"internal-error\" /* AuthErrorCode.INTERNAL_ERROR */, { appName });\r\n}\r\nclass UserImpl {\r\n constructor(_a) {\r\n var { uid, auth, stsTokenManager } = _a, opt = __rest(_a, [\"uid\", \"auth\", \"stsTokenManager\"]);\r\n // For the user object, provider is always Firebase.\r\n this.providerId = \"firebase\" /* ProviderId.FIREBASE */;\r\n this.proactiveRefresh = new ProactiveRefresh(this);\r\n this.reloadUserInfo = null;\r\n this.reloadListener = null;\r\n this.uid = uid;\r\n this.auth = auth;\r\n this.stsTokenManager = stsTokenManager;\r\n this.accessToken = stsTokenManager.accessToken;\r\n this.displayName = opt.displayName || null;\r\n this.email = opt.email || null;\r\n this.emailVerified = opt.emailVerified || false;\r\n this.phoneNumber = opt.phoneNumber || null;\r\n this.photoURL = opt.photoURL || null;\r\n this.isAnonymous = opt.isAnonymous || false;\r\n this.tenantId = opt.tenantId || null;\r\n this.providerData = opt.providerData ? [...opt.providerData] : [];\r\n this.metadata = new UserMetadata(opt.createdAt || undefined, opt.lastLoginAt || undefined);\r\n }\r\n async getIdToken(forceRefresh) {\r\n const accessToken = await _logoutIfInvalidated(this, this.stsTokenManager.getToken(this.auth, forceRefresh));\r\n _assert(accessToken, this.auth, \"internal-error\" /* AuthErrorCode.INTERNAL_ERROR */);\r\n if (this.accessToken !== accessToken) {\r\n this.accessToken = accessToken;\r\n await this.auth._persistUserIfCurrent(this);\r\n this.auth._notifyListenersIfCurrent(this);\r\n }\r\n return accessToken;\r\n }\r\n getIdTokenResult(forceRefresh) {\r\n return getIdTokenResult(this, forceRefresh);\r\n }\r\n reload() {\r\n return reload(this);\r\n }\r\n _assign(user) {\r\n if (this === user) {\r\n return;\r\n }\r\n _assert(this.uid === user.uid, this.auth, \"internal-error\" /* AuthErrorCode.INTERNAL_ERROR */);\r\n this.displayName = user.displayName;\r\n this.photoURL = user.photoURL;\r\n this.email = user.email;\r\n this.emailVerified = user.emailVerified;\r\n this.phoneNumber = user.phoneNumber;\r\n this.isAnonymous = user.isAnonymous;\r\n this.tenantId = user.tenantId;\r\n this.providerData = user.providerData.map(userInfo => (Object.assign({}, userInfo)));\r\n this.metadata._copy(user.metadata);\r\n this.stsTokenManager._assign(user.stsTokenManager);\r\n }\r\n _clone(auth) {\r\n const newUser = new UserImpl(Object.assign(Object.assign({}, this), { auth, stsTokenManager: this.stsTokenManager._clone() }));\r\n newUser.metadata._copy(this.metadata);\r\n return newUser;\r\n }\r\n _onReload(callback) {\r\n // There should only ever be one listener, and that is a single instance of MultiFactorUser\r\n _assert(!this.reloadListener, this.auth, \"internal-error\" /* AuthErrorCode.INTERNAL_ERROR */);\r\n this.reloadListener = callback;\r\n if (this.reloadUserInfo) {\r\n this._notifyReloadListener(this.reloadUserInfo);\r\n this.reloadUserInfo = null;\r\n }\r\n }\r\n _notifyReloadListener(userInfo) {\r\n if (this.reloadListener) {\r\n this.reloadListener(userInfo);\r\n }\r\n else {\r\n // If no listener is subscribed yet, save the result so it's available when they do subscribe\r\n this.reloadUserInfo = userInfo;\r\n }\r\n }\r\n _startProactiveRefresh() {\r\n this.proactiveRefresh._start();\r\n }\r\n _stopProactiveRefresh() {\r\n this.proactiveRefresh._stop();\r\n }\r\n async _updateTokensIfNecessary(response, reload = false) {\r\n let tokensRefreshed = false;\r\n if (response.idToken &&\r\n response.idToken !== this.stsTokenManager.accessToken) {\r\n this.stsTokenManager.updateFromServerResponse(response);\r\n tokensRefreshed = true;\r\n }\r\n if (reload) {\r\n await _reloadWithoutSaving(this);\r\n }\r\n await this.auth._persistUserIfCurrent(this);\r\n if (tokensRefreshed) {\r\n this.auth._notifyListenersIfCurrent(this);\r\n }\r\n }\r\n async delete() {\r\n const idToken = await this.getIdToken();\r\n await _logoutIfInvalidated(this, deleteAccount(this.auth, { idToken }));\r\n this.stsTokenManager.clearRefreshToken();\r\n // TODO: Determine if cancellable-promises are necessary to use in this class so that delete()\r\n // cancels pending actions...\r\n return this.auth.signOut();\r\n }\r\n toJSON() {\r\n return Object.assign(Object.assign({ uid: this.uid, email: this.email || undefined, emailVerified: this.emailVerified, displayName: this.displayName || undefined, isAnonymous: this.isAnonymous, photoURL: this.photoURL || undefined, phoneNumber: this.phoneNumber || undefined, tenantId: this.tenantId || undefined, providerData: this.providerData.map(userInfo => (Object.assign({}, userInfo))), stsTokenManager: this.stsTokenManager.toJSON(), \r\n // Redirect event ID must be maintained in case there is a pending\r\n // redirect event.\r\n _redirectEventId: this._redirectEventId }, this.metadata.toJSON()), { \r\n // Required for compatibility with the legacy SDK (go/firebase-auth-sdk-persistence-parsing):\r\n apiKey: this.auth.config.apiKey, appName: this.auth.name });\r\n }\r\n get refreshToken() {\r\n return this.stsTokenManager.refreshToken || '';\r\n }\r\n static _fromJSON(auth, object) {\r\n var _a, _b, _c, _d, _e, _f, _g, _h;\r\n const displayName = (_a = object.displayName) !== null && _a !== void 0 ? _a : undefined;\r\n const email = (_b = object.email) !== null && _b !== void 0 ? _b : undefined;\r\n const phoneNumber = (_c = object.phoneNumber) !== null && _c !== void 0 ? _c : undefined;\r\n const photoURL = (_d = object.photoURL) !== null && _d !== void 0 ? _d : undefined;\r\n const tenantId = (_e = object.tenantId) !== null && _e !== void 0 ? _e : undefined;\r\n const _redirectEventId = (_f = object._redirectEventId) !== null && _f !== void 0 ? _f : undefined;\r\n const createdAt = (_g = object.createdAt) !== null && _g !== void 0 ? _g : undefined;\r\n const lastLoginAt = (_h = object.lastLoginAt) !== null && _h !== void 0 ? _h : undefined;\r\n const { uid, emailVerified, isAnonymous, providerData, stsTokenManager: plainObjectTokenManager } = object;\r\n _assert(uid && plainObjectTokenManager, auth, \"internal-error\" /* AuthErrorCode.INTERNAL_ERROR */);\r\n const stsTokenManager = StsTokenManager.fromJSON(this.name, plainObjectTokenManager);\r\n _assert(typeof uid === 'string', auth, \"internal-error\" /* AuthErrorCode.INTERNAL_ERROR */);\r\n assertStringOrUndefined(displayName, auth.name);\r\n assertStringOrUndefined(email, auth.name);\r\n _assert(typeof emailVerified === 'boolean', auth, \"internal-error\" /* AuthErrorCode.INTERNAL_ERROR */);\r\n _assert(typeof isAnonymous === 'boolean', auth, \"internal-error\" /* AuthErrorCode.INTERNAL_ERROR */);\r\n assertStringOrUndefined(phoneNumber, auth.name);\r\n assertStringOrUndefined(photoURL, auth.name);\r\n assertStringOrUndefined(tenantId, auth.name);\r\n assertStringOrUndefined(_redirectEventId, auth.name);\r\n assertStringOrUndefined(createdAt, auth.name);\r\n assertStringOrUndefined(lastLoginAt, auth.name);\r\n const user = new UserImpl({\r\n uid,\r\n auth,\r\n email,\r\n emailVerified,\r\n displayName,\r\n isAnonymous,\r\n photoURL,\r\n phoneNumber,\r\n tenantId,\r\n stsTokenManager,\r\n createdAt,\r\n lastLoginAt\r\n });\r\n if (providerData && Array.isArray(providerData)) {\r\n user.providerData = providerData.map(userInfo => (Object.assign({}, userInfo)));\r\n }\r\n if (_redirectEventId) {\r\n user._redirectEventId = _redirectEventId;\r\n }\r\n return user;\r\n }\r\n /**\r\n * Initialize a User from an idToken server response\r\n * @param auth\r\n * @param idTokenResponse\r\n */\r\n static async _fromIdTokenResponse(auth, idTokenResponse, isAnonymous = false) {\r\n const stsTokenManager = new StsTokenManager();\r\n stsTokenManager.updateFromServerResponse(idTokenResponse);\r\n // Initialize the Firebase Auth user.\r\n const user = new UserImpl({\r\n uid: idTokenResponse.localId,\r\n auth,\r\n stsTokenManager,\r\n isAnonymous\r\n });\r\n // Updates the user info and data and resolves with a user instance.\r\n await _reloadWithoutSaving(user);\r\n return user;\r\n }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nconst instanceCache = new Map();\r\nfunction _getInstance(cls) {\r\n debugAssert(cls instanceof Function, 'Expected a class definition');\r\n let instance = instanceCache.get(cls);\r\n if (instance) {\r\n debugAssert(instance instanceof cls, 'Instance stored in cache mismatched with class');\r\n return instance;\r\n }\r\n instance = new cls();\r\n instanceCache.set(cls, instance);\r\n return instance;\r\n}\n\n/**\r\n * @license\r\n * Copyright 2019 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nclass InMemoryPersistence {\r\n constructor() {\r\n this.type = \"NONE\" /* PersistenceType.NONE */;\r\n this.storage = {};\r\n }\r\n async _isAvailable() {\r\n return true;\r\n }\r\n async _set(key, value) {\r\n this.storage[key] = value;\r\n }\r\n async _get(key) {\r\n const value = this.storage[key];\r\n return value === undefined ? null : value;\r\n }\r\n async _remove(key) {\r\n delete this.storage[key];\r\n }\r\n _addListener(_key, _listener) {\r\n // Listeners are not supported for in-memory storage since it cannot be shared across windows/workers\r\n return;\r\n }\r\n _removeListener(_key, _listener) {\r\n // Listeners are not supported for in-memory storage since it cannot be shared across windows/workers\r\n return;\r\n }\r\n}\r\nInMemoryPersistence.type = 'NONE';\r\n/**\r\n * An implementation of {@link Persistence} of type 'NONE'.\r\n *\r\n * @public\r\n */\r\nconst inMemoryPersistence = InMemoryPersistence;\n\n/**\r\n * @license\r\n * Copyright 2019 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nfunction _persistenceKeyName(key, apiKey, appName) {\r\n return `${\"firebase\" /* Namespace.PERSISTENCE */}:${key}:${apiKey}:${appName}`;\r\n}\r\nclass PersistenceUserManager {\r\n constructor(persistence, auth, userKey) {\r\n this.persistence = persistence;\r\n this.auth = auth;\r\n this.userKey = userKey;\r\n const { config, name } = this.auth;\r\n this.fullUserKey = _persistenceKeyName(this.userKey, config.apiKey, name);\r\n this.fullPersistenceKey = _persistenceKeyName(\"persistence\" /* KeyName.PERSISTENCE_USER */, config.apiKey, name);\r\n this.boundEventHandler = auth._onStorageEvent.bind(auth);\r\n this.persistence._addListener(this.fullUserKey, this.boundEventHandler);\r\n }\r\n setCurrentUser(user) {\r\n return this.persistence._set(this.fullUserKey, user.toJSON());\r\n }\r\n async getCurrentUser() {\r\n const blob = await this.persistence._get(this.fullUserKey);\r\n return blob ? UserImpl._fromJSON(this.auth, blob) : null;\r\n }\r\n removeCurrentUser() {\r\n return this.persistence._remove(this.fullUserKey);\r\n }\r\n savePersistenceForRedirect() {\r\n return this.persistence._set(this.fullPersistenceKey, this.persistence.type);\r\n }\r\n async setPersistence(newPersistence) {\r\n if (this.persistence === newPersistence) {\r\n return;\r\n }\r\n const currentUser = await this.getCurrentUser();\r\n await this.removeCurrentUser();\r\n this.persistence = newPersistence;\r\n if (currentUser) {\r\n return this.setCurrentUser(currentUser);\r\n }\r\n }\r\n delete() {\r\n this.persistence._removeListener(this.fullUserKey, this.boundEventHandler);\r\n }\r\n static async create(auth, persistenceHierarchy, userKey = \"authUser\" /* KeyName.AUTH_USER */) {\r\n if (!persistenceHierarchy.length) {\r\n return new PersistenceUserManager(_getInstance(inMemoryPersistence), auth, userKey);\r\n }\r\n // Eliminate any persistences that are not available\r\n const availablePersistences = (await Promise.all(persistenceHierarchy.map(async (persistence) => {\r\n if (await persistence._isAvailable()) {\r\n return persistence;\r\n }\r\n return undefined;\r\n }))).filter(persistence => persistence);\r\n // Fall back to the first persistence listed, or in memory if none available\r\n let selectedPersistence = availablePersistences[0] ||\r\n _getInstance(inMemoryPersistence);\r\n const key = _persistenceKeyName(userKey, auth.config.apiKey, auth.name);\r\n // Pull out the existing user, setting the chosen persistence to that\r\n // persistence if the user exists.\r\n let userToMigrate = null;\r\n // Note, here we check for a user in _all_ persistences, not just the\r\n // ones deemed available. If we can migrate a user out of a broken\r\n // persistence, we will (but only if that persistence supports migration).\r\n for (const persistence of persistenceHierarchy) {\r\n try {\r\n const blob = await persistence._get(key);\r\n if (blob) {\r\n const user = UserImpl._fromJSON(auth, blob); // throws for unparsable blob (wrong format)\r\n if (persistence !== selectedPersistence) {\r\n userToMigrate = user;\r\n }\r\n selectedPersistence = persistence;\r\n break;\r\n }\r\n }\r\n catch (_a) { }\r\n }\r\n // If we find the user in a persistence that does support migration, use\r\n // that migration path (of only persistences that support migration)\r\n const migrationHierarchy = availablePersistences.filter(p => p._shouldAllowMigration);\r\n // If the persistence does _not_ allow migration, just finish off here\r\n if (!selectedPersistence._shouldAllowMigration ||\r\n !migrationHierarchy.length) {\r\n return new PersistenceUserManager(selectedPersistence, auth, userKey);\r\n }\r\n selectedPersistence = migrationHierarchy[0];\r\n if (userToMigrate) {\r\n // This normally shouldn't throw since chosenPersistence.isAvailable() is true, but if it does\r\n // we'll just let it bubble to surface the error.\r\n await selectedPersistence._set(key, userToMigrate.toJSON());\r\n }\r\n // Attempt to clear the key in other persistences but ignore errors. This helps prevent issues\r\n // such as users getting stuck with a previous account after signing out and refreshing the tab.\r\n await Promise.all(persistenceHierarchy.map(async (persistence) => {\r\n if (persistence !== selectedPersistence) {\r\n try {\r\n await persistence._remove(key);\r\n }\r\n catch (_a) { }\r\n }\r\n }));\r\n return new PersistenceUserManager(selectedPersistence, auth, userKey);\r\n }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Determine the browser for the purposes of reporting usage to the API\r\n */\r\nfunction _getBrowserName(userAgent) {\r\n const ua = userAgent.toLowerCase();\r\n if (ua.includes('opera/') || ua.includes('opr/') || ua.includes('opios/')) {\r\n return \"Opera\" /* BrowserName.OPERA */;\r\n }\r\n else if (_isIEMobile(ua)) {\r\n // Windows phone IEMobile browser.\r\n return \"IEMobile\" /* BrowserName.IEMOBILE */;\r\n }\r\n else if (ua.includes('msie') || ua.includes('trident/')) {\r\n return \"IE\" /* BrowserName.IE */;\r\n }\r\n else if (ua.includes('edge/')) {\r\n return \"Edge\" /* BrowserName.EDGE */;\r\n }\r\n else if (_isFirefox(ua)) {\r\n return \"Firefox\" /* BrowserName.FIREFOX */;\r\n }\r\n else if (ua.includes('silk/')) {\r\n return \"Silk\" /* BrowserName.SILK */;\r\n }\r\n else if (_isBlackBerry(ua)) {\r\n // Blackberry browser.\r\n return \"Blackberry\" /* BrowserName.BLACKBERRY */;\r\n }\r\n else if (_isWebOS(ua)) {\r\n // WebOS default browser.\r\n return \"Webos\" /* BrowserName.WEBOS */;\r\n }\r\n else if (_isSafari(ua)) {\r\n return \"Safari\" /* BrowserName.SAFARI */;\r\n }\r\n else if ((ua.includes('chrome/') || _isChromeIOS(ua)) &&\r\n !ua.includes('edge/')) {\r\n return \"Chrome\" /* BrowserName.CHROME */;\r\n }\r\n else if (_isAndroid(ua)) {\r\n // Android stock browser.\r\n return \"Android\" /* BrowserName.ANDROID */;\r\n }\r\n else {\r\n // Most modern browsers have name/version at end of user agent string.\r\n const re = /([a-zA-Z\\d\\.]+)\\/[a-zA-Z\\d\\.]*$/;\r\n const matches = userAgent.match(re);\r\n if ((matches === null || matches === void 0 ? void 0 : matches.length) === 2) {\r\n return matches[1];\r\n }\r\n }\r\n return \"Other\" /* BrowserName.OTHER */;\r\n}\r\nfunction _isFirefox(ua = getUA()) {\r\n return /firefox\\//i.test(ua);\r\n}\r\nfunction _isSafari(userAgent = getUA()) {\r\n const ua = userAgent.toLowerCase();\r\n return (ua.includes('safari/') &&\r\n !ua.includes('chrome/') &&\r\n !ua.includes('crios/') &&\r\n !ua.includes('android'));\r\n}\r\nfunction _isChromeIOS(ua = getUA()) {\r\n return /crios\\//i.test(ua);\r\n}\r\nfunction _isIEMobile(ua = getUA()) {\r\n return /iemobile/i.test(ua);\r\n}\r\nfunction _isAndroid(ua = getUA()) {\r\n return /android/i.test(ua);\r\n}\r\nfunction _isBlackBerry(ua = getUA()) {\r\n return /blackberry/i.test(ua);\r\n}\r\nfunction _isWebOS(ua = getUA()) {\r\n return /webos/i.test(ua);\r\n}\r\nfunction _isIOS(ua = getUA()) {\r\n return (/iphone|ipad|ipod/i.test(ua) ||\r\n (/macintosh/i.test(ua) && /mobile/i.test(ua)));\r\n}\r\nfunction _isIOS7Or8(ua = getUA()) {\r\n return (/(iPad|iPhone|iPod).*OS 7_\\d/i.test(ua) ||\r\n /(iPad|iPhone|iPod).*OS 8_\\d/i.test(ua));\r\n}\r\nfunction _isIOSStandalone(ua = getUA()) {\r\n var _a;\r\n return _isIOS(ua) && !!((_a = window.navigator) === null || _a === void 0 ? void 0 : _a.standalone);\r\n}\r\nfunction _isIE10() {\r\n return isIE() && document.documentMode === 10;\r\n}\r\nfunction _isMobileBrowser(ua = getUA()) {\r\n // TODO: implement getBrowserName equivalent for OS.\r\n return (_isIOS(ua) ||\r\n _isAndroid(ua) ||\r\n _isWebOS(ua) ||\r\n _isBlackBerry(ua) ||\r\n /windows phone/i.test(ua) ||\r\n _isIEMobile(ua));\r\n}\r\nfunction _isIframe() {\r\n try {\r\n // Check that the current window is not the top window.\r\n // If so, return true.\r\n return !!(window && window !== window.top);\r\n }\r\n catch (e) {\r\n return false;\r\n }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/*\r\n * Determine the SDK version string\r\n */\r\nfunction _getClientVersion(clientPlatform, frameworks = []) {\r\n let reportedPlatform;\r\n switch (clientPlatform) {\r\n case \"Browser\" /* ClientPlatform.BROWSER */:\r\n // In a browser environment, report the browser name.\r\n reportedPlatform = _getBrowserName(getUA());\r\n break;\r\n case \"Worker\" /* ClientPlatform.WORKER */:\r\n // Technically a worker runs from a browser but we need to differentiate a\r\n // worker from a browser.\r\n // For example: Chrome-Worker/JsCore/4.9.1/FirebaseCore-web.\r\n reportedPlatform = `${_getBrowserName(getUA())}-${clientPlatform}`;\r\n break;\r\n default:\r\n reportedPlatform = clientPlatform;\r\n }\r\n const reportedFrameworks = frameworks.length\r\n ? frameworks.join(',')\r\n : 'FirebaseCore-web'; /* default value if no other framework is used */\r\n return `${reportedPlatform}/${\"JsCore\" /* ClientImplementation.CORE */}/${SDK_VERSION}/${reportedFrameworks}`;\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nasync function getRecaptchaParams(auth) {\r\n return ((await _performApiRequest(auth, \"GET\" /* HttpMethod.GET */, \"/v1/recaptchaParams\" /* Endpoint.GET_RECAPTCHA_PARAM */)).recaptchaSiteKey || '');\r\n}\r\nasync function getRecaptchaConfig(auth, request) {\r\n return _performApiRequest(auth, \"GET\" /* HttpMethod.GET */, \"/v2/recaptchaConfig\" /* Endpoint.GET_RECAPTCHA_CONFIG */, _addTidIfNecessary(auth, request));\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nfunction isV2(grecaptcha) {\r\n return (grecaptcha !== undefined &&\r\n grecaptcha.getResponse !== undefined);\r\n}\r\nfunction isEnterprise(grecaptcha) {\r\n return (grecaptcha !== undefined &&\r\n grecaptcha.enterprise !== undefined);\r\n}\r\nclass RecaptchaConfig {\r\n constructor(response) {\r\n /**\r\n * The reCAPTCHA site key.\r\n */\r\n this.siteKey = '';\r\n /**\r\n * The reCAPTCHA enablement status of the {@link EmailAuthProvider} for the current tenant.\r\n */\r\n this.emailPasswordEnabled = false;\r\n if (response.recaptchaKey === undefined) {\r\n throw new Error('recaptchaKey undefined');\r\n }\r\n // Example response.recaptchaKey: \"projects/proj123/keys/sitekey123\"\r\n this.siteKey = response.recaptchaKey.split('/')[3];\r\n this.emailPasswordEnabled = response.recaptchaEnforcementState.some(enforcementState => enforcementState.provider === 'EMAIL_PASSWORD_PROVIDER' &&\r\n enforcementState.enforcementState !== 'OFF');\r\n }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nfunction getScriptParentElement() {\r\n var _a, _b;\r\n return (_b = (_a = document.getElementsByTagName('head')) === null || _a === void 0 ? void 0 : _a[0]) !== null && _b !== void 0 ? _b : document;\r\n}\r\nfunction _loadJS(url) {\r\n // TODO: consider adding timeout support & cancellation\r\n return new Promise((resolve, reject) => {\r\n const el = document.createElement('script');\r\n el.setAttribute('src', url);\r\n el.onload = resolve;\r\n el.onerror = e => {\r\n const error = _createError(\"internal-error\" /* AuthErrorCode.INTERNAL_ERROR */);\r\n error.customData = e;\r\n reject(error);\r\n };\r\n el.type = 'text/javascript';\r\n el.charset = 'UTF-8';\r\n getScriptParentElement().appendChild(el);\r\n });\r\n}\r\nfunction _generateCallbackName(prefix) {\r\n return `__${prefix}${Math.floor(Math.random() * 1000000)}`;\r\n}\n\n/* eslint-disable @typescript-eslint/no-require-imports */\r\nconst RECAPTCHA_ENTERPRISE_URL = 'https://www.google.com/recaptcha/enterprise.js?render=';\r\nconst RECAPTCHA_ENTERPRISE_VERIFIER_TYPE = 'recaptcha-enterprise';\r\nconst FAKE_TOKEN = 'NO_RECAPTCHA';\r\nclass RecaptchaEnterpriseVerifier {\r\n /**\r\n *\r\n * @param authExtern - The corresponding Firebase {@link Auth} instance.\r\n *\r\n */\r\n constructor(authExtern) {\r\n /**\r\n * Identifies the type of application verifier (e.g. \"recaptcha-enterprise\").\r\n */\r\n this.type = RECAPTCHA_ENTERPRISE_VERIFIER_TYPE;\r\n this.auth = _castAuth(authExtern);\r\n }\r\n /**\r\n * Executes the verification process.\r\n *\r\n * @returns A Promise for a token that can be used to assert the validity of a request.\r\n */\r\n async verify(action = 'verify', forceRefresh = false) {\r\n async function retrieveSiteKey(auth) {\r\n if (!forceRefresh) {\r\n if (auth.tenantId == null && auth._agentRecaptchaConfig != null) {\r\n return auth._agentRecaptchaConfig.siteKey;\r\n }\r\n if (auth.tenantId != null &&\r\n auth._tenantRecaptchaConfigs[auth.tenantId] !== undefined) {\r\n return auth._tenantRecaptchaConfigs[auth.tenantId].siteKey;\r\n }\r\n }\r\n return new Promise(async (resolve, reject) => {\r\n getRecaptchaConfig(auth, {\r\n clientType: \"CLIENT_TYPE_WEB\" /* RecaptchaClientType.WEB */,\r\n version: \"RECAPTCHA_ENTERPRISE\" /* RecaptchaVersion.ENTERPRISE */\r\n })\r\n .then(response => {\r\n if (response.recaptchaKey === undefined) {\r\n reject(new Error('recaptcha Enterprise site key undefined'));\r\n }\r\n else {\r\n const config = new RecaptchaConfig(response);\r\n if (auth.tenantId == null) {\r\n auth._agentRecaptchaConfig = config;\r\n }\r\n else {\r\n auth._tenantRecaptchaConfigs[auth.tenantId] = config;\r\n }\r\n return resolve(config.siteKey);\r\n }\r\n })\r\n .catch(error => {\r\n reject(error);\r\n });\r\n });\r\n }\r\n function retrieveRecaptchaToken(siteKey, resolve, reject) {\r\n const grecaptcha = window.grecaptcha;\r\n if (isEnterprise(grecaptcha)) {\r\n grecaptcha.enterprise.ready(() => {\r\n grecaptcha.enterprise\r\n .execute(siteKey, { action })\r\n .then(token => {\r\n resolve(token);\r\n })\r\n .catch(() => {\r\n resolve(FAKE_TOKEN);\r\n });\r\n });\r\n }\r\n else {\r\n reject(Error('No reCAPTCHA enterprise script loaded.'));\r\n }\r\n }\r\n return new Promise((resolve, reject) => {\r\n retrieveSiteKey(this.auth)\r\n .then(siteKey => {\r\n if (!forceRefresh && isEnterprise(window.grecaptcha)) {\r\n retrieveRecaptchaToken(siteKey, resolve, reject);\r\n }\r\n else {\r\n if (typeof window === 'undefined') {\r\n reject(new Error('RecaptchaVerifier is only supported in browser'));\r\n return;\r\n }\r\n _loadJS(RECAPTCHA_ENTERPRISE_URL + siteKey)\r\n .then(() => {\r\n retrieveRecaptchaToken(siteKey, resolve, reject);\r\n })\r\n .catch(error => {\r\n reject(error);\r\n });\r\n }\r\n })\r\n .catch(error => {\r\n reject(error);\r\n });\r\n });\r\n }\r\n}\r\nasync function injectRecaptchaFields(auth, request, action, captchaResp = false) {\r\n const verifier = new RecaptchaEnterpriseVerifier(auth);\r\n let captchaResponse;\r\n try {\r\n captchaResponse = await verifier.verify(action);\r\n }\r\n catch (error) {\r\n captchaResponse = await verifier.verify(action, true);\r\n }\r\n const newRequest = Object.assign({}, request);\r\n if (!captchaResp) {\r\n Object.assign(newRequest, { captchaResponse });\r\n }\r\n else {\r\n Object.assign(newRequest, { 'captchaResp': captchaResponse });\r\n }\r\n Object.assign(newRequest, { 'clientType': \"CLIENT_TYPE_WEB\" /* RecaptchaClientType.WEB */ });\r\n Object.assign(newRequest, {\r\n 'recaptchaVersion': \"RECAPTCHA_ENTERPRISE\" /* RecaptchaVersion.ENTERPRISE */\r\n });\r\n return newRequest;\r\n}\n\n/**\r\n * @license\r\n * Copyright 2022 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nclass AuthMiddlewareQueue {\r\n constructor(auth) {\r\n this.auth = auth;\r\n this.queue = [];\r\n }\r\n pushCallback(callback, onAbort) {\r\n // The callback could be sync or async. Wrap it into a\r\n // function that is always async.\r\n const wrappedCallback = (user) => new Promise((resolve, reject) => {\r\n try {\r\n const result = callback(user);\r\n // Either resolve with existing promise or wrap a non-promise\r\n // return value into a promise.\r\n resolve(result);\r\n }\r\n catch (e) {\r\n // Sync callback throws.\r\n reject(e);\r\n }\r\n });\r\n // Attach the onAbort if present\r\n wrappedCallback.onAbort = onAbort;\r\n this.queue.push(wrappedCallback);\r\n const index = this.queue.length - 1;\r\n return () => {\r\n // Unsubscribe. Replace with no-op. Do not remove from array, or it will disturb\r\n // indexing of other elements.\r\n this.queue[index] = () => Promise.resolve();\r\n };\r\n }\r\n async runMiddleware(nextUser) {\r\n if (this.auth.currentUser === nextUser) {\r\n return;\r\n }\r\n // While running the middleware, build a temporary stack of onAbort\r\n // callbacks to call if one middleware callback rejects.\r\n const onAbortStack = [];\r\n try {\r\n for (const beforeStateCallback of this.queue) {\r\n await beforeStateCallback(nextUser);\r\n // Only push the onAbort if the callback succeeds\r\n if (beforeStateCallback.onAbort) {\r\n onAbortStack.push(beforeStateCallback.onAbort);\r\n }\r\n }\r\n }\r\n catch (e) {\r\n // Run all onAbort, with separate try/catch to ignore any errors and\r\n // continue\r\n onAbortStack.reverse();\r\n for (const onAbort of onAbortStack) {\r\n try {\r\n onAbort();\r\n }\r\n catch (_) {\r\n /* swallow error */\r\n }\r\n }\r\n throw this.auth._errorFactory.create(\"login-blocked\" /* AuthErrorCode.LOGIN_BLOCKED */, {\r\n originalMessage: e === null || e === void 0 ? void 0 : e.message\r\n });\r\n }\r\n }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nclass AuthImpl {\r\n constructor(app, heartbeatServiceProvider, appCheckServiceProvider, config) {\r\n this.app = app;\r\n this.heartbeatServiceProvider = heartbeatServiceProvider;\r\n this.appCheckServiceProvider = appCheckServiceProvider;\r\n this.config = config;\r\n this.currentUser = null;\r\n this.emulatorConfig = null;\r\n this.operations = Promise.resolve();\r\n this.authStateSubscription = new Subscription(this);\r\n this.idTokenSubscription = new Subscription(this);\r\n this.beforeStateQueue = new AuthMiddlewareQueue(this);\r\n this.redirectUser = null;\r\n this.isProactiveRefreshEnabled = false;\r\n // Any network calls will set this to true and prevent subsequent emulator\r\n // initialization\r\n this._canInitEmulator = true;\r\n this._isInitialized = false;\r\n this._deleted = false;\r\n this._initializationPromise = null;\r\n this._popupRedirectResolver = null;\r\n this._errorFactory = _DEFAULT_AUTH_ERROR_FACTORY;\r\n this._agentRecaptchaConfig = null;\r\n this._tenantRecaptchaConfigs = {};\r\n // Tracks the last notified UID for state change listeners to prevent\r\n // repeated calls to the callbacks. Undefined means it's never been\r\n // called, whereas null means it's been called with a signed out user\r\n this.lastNotifiedUid = undefined;\r\n this.languageCode = null;\r\n this.tenantId = null;\r\n this.settings = { appVerificationDisabledForTesting: false };\r\n this.frameworks = [];\r\n this.name = app.name;\r\n this.clientVersion = config.sdkClientVersion;\r\n }\r\n _initializeWithPersistence(persistenceHierarchy, popupRedirectResolver) {\r\n if (popupRedirectResolver) {\r\n this._popupRedirectResolver = _getInstance(popupRedirectResolver);\r\n }\r\n // Have to check for app deletion throughout initialization (after each\r\n // promise resolution)\r\n this._initializationPromise = this.queue(async () => {\r\n var _a, _b;\r\n if (this._deleted) {\r\n return;\r\n }\r\n this.persistenceManager = await PersistenceUserManager.create(this, persistenceHierarchy);\r\n if (this._deleted) {\r\n return;\r\n }\r\n // Initialize the resolver early if necessary (only applicable to web:\r\n // this will cause the iframe to load immediately in certain cases)\r\n if ((_a = this._popupRedirectResolver) === null || _a === void 0 ? void 0 : _a._shouldInitProactively) {\r\n // If this fails, don't halt auth loading\r\n try {\r\n await this._popupRedirectResolver._initialize(this);\r\n }\r\n catch (e) {\r\n /* Ignore the error */\r\n }\r\n }\r\n await this.initializeCurrentUser(popupRedirectResolver);\r\n this.lastNotifiedUid = ((_b = this.currentUser) === null || _b === void 0 ? void 0 : _b.uid) || null;\r\n if (this._deleted) {\r\n return;\r\n }\r\n this._isInitialized = true;\r\n });\r\n return this._initializationPromise;\r\n }\r\n /**\r\n * If the persistence is changed in another window, the user manager will let us know\r\n */\r\n async _onStorageEvent() {\r\n if (this._deleted) {\r\n return;\r\n }\r\n const user = await this.assertedPersistence.getCurrentUser();\r\n if (!this.currentUser && !user) {\r\n // No change, do nothing (was signed out and remained signed out).\r\n return;\r\n }\r\n // If the same user is to be synchronized.\r\n if (this.currentUser && user && this.currentUser.uid === user.uid) {\r\n // Data update, simply copy data changes.\r\n this._currentUser._assign(user);\r\n // If tokens changed from previous user tokens, this will trigger\r\n // notifyAuthListeners_.\r\n await this.currentUser.getIdToken();\r\n return;\r\n }\r\n // Update current Auth state. Either a new login or logout.\r\n // Skip blocking callbacks, they should not apply to a change in another tab.\r\n await this._updateCurrentUser(user, /* skipBeforeStateCallbacks */ true);\r\n }\r\n async initializeCurrentUser(popupRedirectResolver) {\r\n var _a;\r\n // First check to see if we have a pending redirect event.\r\n const previouslyStoredUser = (await this.assertedPersistence.getCurrentUser());\r\n let futureCurrentUser = previouslyStoredUser;\r\n let needsTocheckMiddleware = false;\r\n if (popupRedirectResolver && this.config.authDomain) {\r\n await this.getOrInitRedirectPersistenceManager();\r\n const redirectUserEventId = (_a = this.redirectUser) === null || _a === void 0 ? void 0 : _a._redirectEventId;\r\n const storedUserEventId = futureCurrentUser === null || futureCurrentUser === void 0 ? void 0 : futureCurrentUser._redirectEventId;\r\n const result = await this.tryRedirectSignIn(popupRedirectResolver);\r\n // If the stored user (i.e. the old \"currentUser\") has a redirectId that\r\n // matches the redirect user, then we want to initially sign in with the\r\n // new user object from result.\r\n // TODO(samgho): More thoroughly test all of this\r\n if ((!redirectUserEventId || redirectUserEventId === storedUserEventId) &&\r\n (result === null || result === void 0 ? void 0 : result.user)) {\r\n futureCurrentUser = result.user;\r\n needsTocheckMiddleware = true;\r\n }\r\n }\r\n // If no user in persistence, there is no current user. Set to null.\r\n if (!futureCurrentUser) {\r\n return this.directlySetCurrentUser(null);\r\n }\r\n if (!futureCurrentUser._redirectEventId) {\r\n // This isn't a redirect link operation, we can reload and bail.\r\n // First though, ensure that we check the middleware is happy.\r\n if (needsTocheckMiddleware) {\r\n try {\r\n await this.beforeStateQueue.runMiddleware(futureCurrentUser);\r\n }\r\n catch (e) {\r\n futureCurrentUser = previouslyStoredUser;\r\n // We know this is available since the bit is only set when the\r\n // resolver is available\r\n this._popupRedirectResolver._overrideRedirectResult(this, () => Promise.reject(e));\r\n }\r\n }\r\n if (futureCurrentUser) {\r\n return this.reloadAndSetCurrentUserOrClear(futureCurrentUser);\r\n }\r\n else {\r\n return this.directlySetCurrentUser(null);\r\n }\r\n }\r\n _assert(this._popupRedirectResolver, this, \"argument-error\" /* AuthErrorCode.ARGUMENT_ERROR */);\r\n await this.getOrInitRedirectPersistenceManager();\r\n // If the redirect user's event ID matches the current user's event ID,\r\n // DO NOT reload the current user, otherwise they'll be cleared from storage.\r\n // This is important for the reauthenticateWithRedirect() flow.\r\n if (this.redirectUser &&\r\n this.redirectUser._redirectEventId === futureCurrentUser._redirectEventId) {\r\n return this.directlySetCurrentUser(futureCurrentUser);\r\n }\r\n return this.reloadAndSetCurrentUserOrClear(futureCurrentUser);\r\n }\r\n async tryRedirectSignIn(redirectResolver) {\r\n // The redirect user needs to be checked (and signed in if available)\r\n // during auth initialization. All of the normal sign in and link/reauth\r\n // flows call back into auth and push things onto the promise queue. We\r\n // need to await the result of the redirect sign in *inside the promise\r\n // queue*. This presents a problem: we run into deadlock. See:\r\n // ┌> [Initialization] ─────┐\r\n // ┌> [] │\r\n // └─ [getRedirectResult] <─┘\r\n // where [] are tasks on the queue and arrows denote awaits\r\n // Initialization will never complete because it's waiting on something\r\n // that's waiting for initialization to complete!\r\n //\r\n // Instead, this method calls getRedirectResult() (stored in\r\n // _completeRedirectFn) with an optional parameter that instructs all of\r\n // the underlying auth operations to skip anything that mutates auth state.\r\n let result = null;\r\n try {\r\n // We know this._popupRedirectResolver is set since redirectResolver\r\n // is passed in. The _completeRedirectFn expects the unwrapped extern.\r\n result = await this._popupRedirectResolver._completeRedirectFn(this, redirectResolver, true);\r\n }\r\n catch (e) {\r\n // Swallow any errors here; the code can retrieve them in\r\n // getRedirectResult().\r\n await this._setRedirectUser(null);\r\n }\r\n return result;\r\n }\r\n async reloadAndSetCurrentUserOrClear(user) {\r\n try {\r\n await _reloadWithoutSaving(user);\r\n }\r\n catch (e) {\r\n if ((e === null || e === void 0 ? void 0 : e.code) !==\r\n `auth/${\"network-request-failed\" /* AuthErrorCode.NETWORK_REQUEST_FAILED */}`) {\r\n // Something's wrong with the user's token. Log them out and remove\r\n // them from storage\r\n return this.directlySetCurrentUser(null);\r\n }\r\n }\r\n return this.directlySetCurrentUser(user);\r\n }\r\n useDeviceLanguage() {\r\n this.languageCode = _getUserLanguage();\r\n }\r\n async _delete() {\r\n this._deleted = true;\r\n }\r\n async updateCurrentUser(userExtern) {\r\n // The public updateCurrentUser method needs to make a copy of the user,\r\n // and also check that the project matches\r\n const user = userExtern\r\n ? getModularInstance(userExtern)\r\n : null;\r\n if (user) {\r\n _assert(user.auth.config.apiKey === this.config.apiKey, this, \"invalid-user-token\" /* AuthErrorCode.INVALID_AUTH */);\r\n }\r\n return this._updateCurrentUser(user && user._clone(this));\r\n }\r\n async _updateCurrentUser(user, skipBeforeStateCallbacks = false) {\r\n if (this._deleted) {\r\n return;\r\n }\r\n if (user) {\r\n _assert(this.tenantId === user.tenantId, this, \"tenant-id-mismatch\" /* AuthErrorCode.TENANT_ID_MISMATCH */);\r\n }\r\n if (!skipBeforeStateCallbacks) {\r\n await this.beforeStateQueue.runMiddleware(user);\r\n }\r\n return this.queue(async () => {\r\n await this.directlySetCurrentUser(user);\r\n this.notifyAuthListeners();\r\n });\r\n }\r\n async signOut() {\r\n // Run first, to block _setRedirectUser() if any callbacks fail.\r\n await this.beforeStateQueue.runMiddleware(null);\r\n // Clear the redirect user when signOut is called\r\n if (this.redirectPersistenceManager || this._popupRedirectResolver) {\r\n await this._setRedirectUser(null);\r\n }\r\n // Prevent callbacks from being called again in _updateCurrentUser, as\r\n // they were already called in the first line.\r\n return this._updateCurrentUser(null, /* skipBeforeStateCallbacks */ true);\r\n }\r\n setPersistence(persistence) {\r\n return this.queue(async () => {\r\n await this.assertedPersistence.setPersistence(_getInstance(persistence));\r\n });\r\n }\r\n async initializeRecaptchaConfig() {\r\n const response = await getRecaptchaConfig(this, {\r\n clientType: \"CLIENT_TYPE_WEB\" /* RecaptchaClientType.WEB */,\r\n version: \"RECAPTCHA_ENTERPRISE\" /* RecaptchaVersion.ENTERPRISE */\r\n });\r\n const config = new RecaptchaConfig(response);\r\n if (this.tenantId == null) {\r\n this._agentRecaptchaConfig = config;\r\n }\r\n else {\r\n this._tenantRecaptchaConfigs[this.tenantId] = config;\r\n }\r\n if (config.emailPasswordEnabled) {\r\n const verifier = new RecaptchaEnterpriseVerifier(this);\r\n void verifier.verify();\r\n }\r\n }\r\n _getRecaptchaConfig() {\r\n if (this.tenantId == null) {\r\n return this._agentRecaptchaConfig;\r\n }\r\n else {\r\n return this._tenantRecaptchaConfigs[this.tenantId];\r\n }\r\n }\r\n _getPersistence() {\r\n return this.assertedPersistence.persistence.type;\r\n }\r\n _updateErrorMap(errorMap) {\r\n this._errorFactory = new ErrorFactory('auth', 'Firebase', errorMap());\r\n }\r\n onAuthStateChanged(nextOrObserver, error, completed) {\r\n return this.registerStateListener(this.authStateSubscription, nextOrObserver, error, completed);\r\n }\r\n beforeAuthStateChanged(callback, onAbort) {\r\n return this.beforeStateQueue.pushCallback(callback, onAbort);\r\n }\r\n onIdTokenChanged(nextOrObserver, error, completed) {\r\n return this.registerStateListener(this.idTokenSubscription, nextOrObserver, error, completed);\r\n }\r\n toJSON() {\r\n var _a;\r\n return {\r\n apiKey: this.config.apiKey,\r\n authDomain: this.config.authDomain,\r\n appName: this.name,\r\n currentUser: (_a = this._currentUser) === null || _a === void 0 ? void 0 : _a.toJSON()\r\n };\r\n }\r\n async _setRedirectUser(user, popupRedirectResolver) {\r\n const redirectManager = await this.getOrInitRedirectPersistenceManager(popupRedirectResolver);\r\n return user === null\r\n ? redirectManager.removeCurrentUser()\r\n : redirectManager.setCurrentUser(user);\r\n }\r\n async getOrInitRedirectPersistenceManager(popupRedirectResolver) {\r\n if (!this.redirectPersistenceManager) {\r\n const resolver = (popupRedirectResolver && _getInstance(popupRedirectResolver)) ||\r\n this._popupRedirectResolver;\r\n _assert(resolver, this, \"argument-error\" /* AuthErrorCode.ARGUMENT_ERROR */);\r\n this.redirectPersistenceManager = await PersistenceUserManager.create(this, [_getInstance(resolver._redirectPersistence)], \"redirectUser\" /* KeyName.REDIRECT_USER */);\r\n this.redirectUser =\r\n await this.redirectPersistenceManager.getCurrentUser();\r\n }\r\n return this.redirectPersistenceManager;\r\n }\r\n async _redirectUserForId(id) {\r\n var _a, _b;\r\n // Make sure we've cleared any pending persistence actions if we're not in\r\n // the initializer\r\n if (this._isInitialized) {\r\n await this.queue(async () => { });\r\n }\r\n if (((_a = this._currentUser) === null || _a === void 0 ? void 0 : _a._redirectEventId) === id) {\r\n return this._currentUser;\r\n }\r\n if (((_b = this.redirectUser) === null || _b === void 0 ? void 0 : _b._redirectEventId) === id) {\r\n return this.redirectUser;\r\n }\r\n return null;\r\n }\r\n async _persistUserIfCurrent(user) {\r\n if (user === this.currentUser) {\r\n return this.queue(async () => this.directlySetCurrentUser(user));\r\n }\r\n }\r\n /** Notifies listeners only if the user is current */\r\n _notifyListenersIfCurrent(user) {\r\n if (user === this.currentUser) {\r\n this.notifyAuthListeners();\r\n }\r\n }\r\n _key() {\r\n return `${this.config.authDomain}:${this.config.apiKey}:${this.name}`;\r\n }\r\n _startProactiveRefresh() {\r\n this.isProactiveRefreshEnabled = true;\r\n if (this.currentUser) {\r\n this._currentUser._startProactiveRefresh();\r\n }\r\n }\r\n _stopProactiveRefresh() {\r\n this.isProactiveRefreshEnabled = false;\r\n if (this.currentUser) {\r\n this._currentUser._stopProactiveRefresh();\r\n }\r\n }\r\n /** Returns the current user cast as the internal type */\r\n get _currentUser() {\r\n return this.currentUser;\r\n }\r\n notifyAuthListeners() {\r\n var _a, _b;\r\n if (!this._isInitialized) {\r\n return;\r\n }\r\n this.idTokenSubscription.next(this.currentUser);\r\n const currentUid = (_b = (_a = this.currentUser) === null || _a === void 0 ? void 0 : _a.uid) !== null && _b !== void 0 ? _b : null;\r\n if (this.lastNotifiedUid !== currentUid) {\r\n this.lastNotifiedUid = currentUid;\r\n this.authStateSubscription.next(this.currentUser);\r\n }\r\n }\r\n registerStateListener(subscription, nextOrObserver, error, completed) {\r\n if (this._deleted) {\r\n return () => { };\r\n }\r\n const cb = typeof nextOrObserver === 'function'\r\n ? nextOrObserver\r\n : nextOrObserver.next.bind(nextOrObserver);\r\n const promise = this._isInitialized\r\n ? Promise.resolve()\r\n : this._initializationPromise;\r\n _assert(promise, this, \"internal-error\" /* AuthErrorCode.INTERNAL_ERROR */);\r\n // The callback needs to be called asynchronously per the spec.\r\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\r\n promise.then(() => cb(this.currentUser));\r\n if (typeof nextOrObserver === 'function') {\r\n return subscription.addObserver(nextOrObserver, error, completed);\r\n }\r\n else {\r\n return subscription.addObserver(nextOrObserver);\r\n }\r\n }\r\n /**\r\n * Unprotected (from race conditions) method to set the current user. This\r\n * should only be called from within a queued callback. This is necessary\r\n * because the queue shouldn't rely on another queued callback.\r\n */\r\n async directlySetCurrentUser(user) {\r\n if (this.currentUser && this.currentUser !== user) {\r\n this._currentUser._stopProactiveRefresh();\r\n }\r\n if (user && this.isProactiveRefreshEnabled) {\r\n user._startProactiveRefresh();\r\n }\r\n this.currentUser = user;\r\n if (user) {\r\n await this.assertedPersistence.setCurrentUser(user);\r\n }\r\n else {\r\n await this.assertedPersistence.removeCurrentUser();\r\n }\r\n }\r\n queue(action) {\r\n // In case something errors, the callback still should be called in order\r\n // to keep the promise chain alive\r\n this.operations = this.operations.then(action, action);\r\n return this.operations;\r\n }\r\n get assertedPersistence() {\r\n _assert(this.persistenceManager, this, \"internal-error\" /* AuthErrorCode.INTERNAL_ERROR */);\r\n return this.persistenceManager;\r\n }\r\n _logFramework(framework) {\r\n if (!framework || this.frameworks.includes(framework)) {\r\n return;\r\n }\r\n this.frameworks.push(framework);\r\n // Sort alphabetically so that \"FirebaseCore-web,FirebaseUI-web\" and\r\n // \"FirebaseUI-web,FirebaseCore-web\" aren't viewed as different.\r\n this.frameworks.sort();\r\n this.clientVersion = _getClientVersion(this.config.clientPlatform, this._getFrameworks());\r\n }\r\n _getFrameworks() {\r\n return this.frameworks;\r\n }\r\n async _getAdditionalHeaders() {\r\n var _a;\r\n // Additional headers on every request\r\n const headers = {\r\n [\"X-Client-Version\" /* HttpHeader.X_CLIENT_VERSION */]: this.clientVersion\r\n };\r\n if (this.app.options.appId) {\r\n headers[\"X-Firebase-gmpid\" /* HttpHeader.X_FIREBASE_GMPID */] = this.app.options.appId;\r\n }\r\n // If the heartbeat service exists, add the heartbeat string\r\n const heartbeatsHeader = await ((_a = this.heartbeatServiceProvider\r\n .getImmediate({\r\n optional: true\r\n })) === null || _a === void 0 ? void 0 : _a.getHeartbeatsHeader());\r\n if (heartbeatsHeader) {\r\n headers[\"X-Firebase-Client\" /* HttpHeader.X_FIREBASE_CLIENT */] = heartbeatsHeader;\r\n }\r\n // If the App Check service exists, add the App Check token in the headers\r\n const appCheckToken = await this._getAppCheckToken();\r\n if (appCheckToken) {\r\n headers[\"X-Firebase-AppCheck\" /* HttpHeader.X_FIREBASE_APP_CHECK */] = appCheckToken;\r\n }\r\n return headers;\r\n }\r\n async _getAppCheckToken() {\r\n var _a;\r\n const appCheckTokenResult = await ((_a = this.appCheckServiceProvider\r\n .getImmediate({ optional: true })) === null || _a === void 0 ? void 0 : _a.getToken());\r\n if (appCheckTokenResult === null || appCheckTokenResult === void 0 ? void 0 : appCheckTokenResult.error) {\r\n // Context: appCheck.getToken() will never throw even if an error happened.\r\n // In the error case, a dummy token will be returned along with an error field describing\r\n // the error. In general, we shouldn't care about the error condition and just use\r\n // the token (actual or dummy) to send requests.\r\n _logWarn(`Error while retrieving App Check token: ${appCheckTokenResult.error}`);\r\n }\r\n return appCheckTokenResult === null || appCheckTokenResult === void 0 ? void 0 : appCheckTokenResult.token;\r\n }\r\n}\r\n/**\r\n * Method to be used to cast down to our private implmentation of Auth.\r\n * It will also handle unwrapping from the compat type if necessary\r\n *\r\n * @param auth Auth object passed in from developer\r\n */\r\nfunction _castAuth(auth) {\r\n return getModularInstance(auth);\r\n}\r\n/** Helper class to wrap subscriber logic */\r\nclass Subscription {\r\n constructor(auth) {\r\n this.auth = auth;\r\n this.observer = null;\r\n this.addObserver = createSubscribe(observer => (this.observer = observer));\r\n }\r\n get next() {\r\n _assert(this.observer, this.auth, \"internal-error\" /* AuthErrorCode.INTERNAL_ERROR */);\r\n return this.observer.next.bind(this.observer);\r\n }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Initializes an {@link Auth} instance with fine-grained control over\r\n * {@link Dependencies}.\r\n *\r\n * @remarks\r\n *\r\n * This function allows more control over the {@link Auth} instance than\r\n * {@link getAuth}. `getAuth` uses platform-specific defaults to supply\r\n * the {@link Dependencies}. In general, `getAuth` is the easiest way to\r\n * initialize Auth and works for most use cases. Use `initializeAuth` if you\r\n * need control over which persistence layer is used, or to minimize bundle\r\n * size if you're not using either `signInWithPopup` or `signInWithRedirect`.\r\n *\r\n * For example, if your app only uses anonymous accounts and you only want\r\n * accounts saved for the current session, initialize `Auth` with:\r\n *\r\n * ```js\r\n * const auth = initializeAuth(app, {\r\n * persistence: browserSessionPersistence,\r\n * popupRedirectResolver: undefined,\r\n * });\r\n * ```\r\n *\r\n * @public\r\n */\r\nfunction initializeAuth(app, deps) {\r\n const provider = _getProvider(app, 'auth');\r\n if (provider.isInitialized()) {\r\n const auth = provider.getImmediate();\r\n const initialOptions = provider.getOptions();\r\n if (deepEqual(initialOptions, deps !== null && deps !== void 0 ? deps : {})) {\r\n return auth;\r\n }\r\n else {\r\n _fail(auth, \"already-initialized\" /* AuthErrorCode.ALREADY_INITIALIZED */);\r\n }\r\n }\r\n const auth = provider.initialize({ options: deps });\r\n return auth;\r\n}\r\nfunction _initializeAuthInstance(auth, deps) {\r\n const persistence = (deps === null || deps === void 0 ? void 0 : deps.persistence) || [];\r\n const hierarchy = (Array.isArray(persistence) ? persistence : [persistence]).map(_getInstance);\r\n if (deps === null || deps === void 0 ? void 0 : deps.errorMap) {\r\n auth._updateErrorMap(deps.errorMap);\r\n }\r\n // This promise is intended to float; auth initialization happens in the\r\n // background, meanwhile the auth object may be used by the app.\r\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\r\n auth._initializeWithPersistence(hierarchy, deps === null || deps === void 0 ? void 0 : deps.popupRedirectResolver);\r\n}\n\n/**\r\n * Changes the {@link Auth} instance to communicate with the Firebase Auth Emulator, instead of production\r\n * Firebase Auth services.\r\n *\r\n * @remarks\r\n * This must be called synchronously immediately following the first call to\r\n * {@link initializeAuth}. Do not use with production credentials as emulator\r\n * traffic is not encrypted.\r\n *\r\n *\r\n * @example\r\n * ```javascript\r\n * connectAuthEmulator(auth, 'http://127.0.0.1:9099', { disableWarnings: true });\r\n * ```\r\n *\r\n * @param auth - The {@link Auth} instance.\r\n * @param url - The URL at which the emulator is running (eg, 'http://localhost:9099').\r\n * @param options - Optional. `options.disableWarnings` defaults to `false`. Set it to\r\n * `true` to disable the warning banner attached to the DOM.\r\n *\r\n * @public\r\n */\r\nfunction connectAuthEmulator(auth, url, options) {\r\n const authInternal = _castAuth(auth);\r\n _assert(authInternal._canInitEmulator, authInternal, \"emulator-config-failed\" /* AuthErrorCode.EMULATOR_CONFIG_FAILED */);\r\n _assert(/^https?:\\/\\//.test(url), authInternal, \"invalid-emulator-scheme\" /* AuthErrorCode.INVALID_EMULATOR_SCHEME */);\r\n const disableWarnings = !!(options === null || options === void 0 ? void 0 : options.disableWarnings);\r\n const protocol = extractProtocol(url);\r\n const { host, port } = extractHostAndPort(url);\r\n const portStr = port === null ? '' : `:${port}`;\r\n // Always replace path with \"/\" (even if input url had no path at all, or had a different one).\r\n authInternal.config.emulator = { url: `${protocol}//${host}${portStr}/` };\r\n authInternal.settings.appVerificationDisabledForTesting = true;\r\n authInternal.emulatorConfig = Object.freeze({\r\n host,\r\n port,\r\n protocol: protocol.replace(':', ''),\r\n options: Object.freeze({ disableWarnings })\r\n });\r\n if (!disableWarnings) {\r\n emitEmulatorWarning();\r\n }\r\n}\r\nfunction extractProtocol(url) {\r\n const protocolEnd = url.indexOf(':');\r\n return protocolEnd < 0 ? '' : url.substr(0, protocolEnd + 1);\r\n}\r\nfunction extractHostAndPort(url) {\r\n const protocol = extractProtocol(url);\r\n const authority = /(\\/\\/)?([^?#/]+)/.exec(url.substr(protocol.length)); // Between // and /, ? or #.\r\n if (!authority) {\r\n return { host: '', port: null };\r\n }\r\n const hostAndPort = authority[2].split('@').pop() || ''; // Strip out \"username:password@\".\r\n const bracketedIPv6 = /^(\\[[^\\]]+\\])(:|$)/.exec(hostAndPort);\r\n if (bracketedIPv6) {\r\n const host = bracketedIPv6[1];\r\n return { host, port: parsePort(hostAndPort.substr(host.length + 1)) };\r\n }\r\n else {\r\n const [host, port] = hostAndPort.split(':');\r\n return { host, port: parsePort(port) };\r\n }\r\n}\r\nfunction parsePort(portStr) {\r\n if (!portStr) {\r\n return null;\r\n }\r\n const port = Number(portStr);\r\n if (isNaN(port)) {\r\n return null;\r\n }\r\n return port;\r\n}\r\nfunction emitEmulatorWarning() {\r\n function attachBanner() {\r\n const el = document.createElement('p');\r\n const sty = el.style;\r\n el.innerText =\r\n 'Running in emulator mode. Do not use with production credentials.';\r\n sty.position = 'fixed';\r\n sty.width = '100%';\r\n sty.backgroundColor = '#ffffff';\r\n sty.border = '.1em solid #000000';\r\n sty.color = '#b50000';\r\n sty.bottom = '0px';\r\n sty.left = '0px';\r\n sty.margin = '0px';\r\n sty.zIndex = '10000';\r\n sty.textAlign = 'center';\r\n el.classList.add('firebase-emulator-warning');\r\n document.body.appendChild(el);\r\n }\r\n if (typeof console !== 'undefined' && typeof console.info === 'function') {\r\n console.info('WARNING: You are using the Auth Emulator,' +\r\n ' which is intended for local testing only. Do not use with' +\r\n ' production credentials.');\r\n }\r\n if (typeof window !== 'undefined' && typeof document !== 'undefined') {\r\n if (document.readyState === 'loading') {\r\n window.addEventListener('DOMContentLoaded', attachBanner);\r\n }\r\n else {\r\n attachBanner();\r\n }\r\n }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Interface that represents the credentials returned by an {@link AuthProvider}.\r\n *\r\n * @remarks\r\n * Implementations specify the details about each auth provider's credential requirements.\r\n *\r\n * @public\r\n */\r\nclass AuthCredential {\r\n /** @internal */\r\n constructor(\r\n /**\r\n * The authentication provider ID for the credential.\r\n *\r\n * @remarks\r\n * For example, 'facebook.com', or 'google.com'.\r\n */\r\n providerId, \r\n /**\r\n * The authentication sign in method for the credential.\r\n *\r\n * @remarks\r\n * For example, {@link SignInMethod}.EMAIL_PASSWORD, or\r\n * {@link SignInMethod}.EMAIL_LINK. This corresponds to the sign-in method\r\n * identifier as returned in {@link fetchSignInMethodsForEmail}.\r\n */\r\n signInMethod) {\r\n this.providerId = providerId;\r\n this.signInMethod = signInMethod;\r\n }\r\n /**\r\n * Returns a JSON-serializable representation of this object.\r\n *\r\n * @returns a JSON-serializable representation of this object.\r\n */\r\n toJSON() {\r\n return debugFail('not implemented');\r\n }\r\n /** @internal */\r\n _getIdTokenResponse(_auth) {\r\n return debugFail('not implemented');\r\n }\r\n /** @internal */\r\n _linkToIdToken(_auth, _idToken) {\r\n return debugFail('not implemented');\r\n }\r\n /** @internal */\r\n _getReauthenticationResolver(_auth) {\r\n return debugFail('not implemented');\r\n }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nasync function resetPassword(auth, request) {\r\n return _performApiRequest(auth, \"POST\" /* HttpMethod.POST */, \"/v1/accounts:resetPassword\" /* Endpoint.RESET_PASSWORD */, _addTidIfNecessary(auth, request));\r\n}\r\nasync function updateEmailPassword(auth, request) {\r\n return _performApiRequest(auth, \"POST\" /* HttpMethod.POST */, \"/v1/accounts:update\" /* Endpoint.SET_ACCOUNT_INFO */, request);\r\n}\r\nasync function applyActionCode$1(auth, request) {\r\n return _performApiRequest(auth, \"POST\" /* HttpMethod.POST */, \"/v1/accounts:update\" /* Endpoint.SET_ACCOUNT_INFO */, _addTidIfNecessary(auth, request));\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nasync function signInWithPassword(auth, request) {\r\n return _performSignInRequest(auth, \"POST\" /* HttpMethod.POST */, \"/v1/accounts:signInWithPassword\" /* Endpoint.SIGN_IN_WITH_PASSWORD */, _addTidIfNecessary(auth, request));\r\n}\r\nasync function sendOobCode(auth, request) {\r\n return _performApiRequest(auth, \"POST\" /* HttpMethod.POST */, \"/v1/accounts:sendOobCode\" /* Endpoint.SEND_OOB_CODE */, _addTidIfNecessary(auth, request));\r\n}\r\nasync function sendEmailVerification$1(auth, request) {\r\n return sendOobCode(auth, request);\r\n}\r\nasync function sendPasswordResetEmail$1(auth, request) {\r\n return sendOobCode(auth, request);\r\n}\r\nasync function sendSignInLinkToEmail$1(auth, request) {\r\n return sendOobCode(auth, request);\r\n}\r\nasync function verifyAndChangeEmail(auth, request) {\r\n return sendOobCode(auth, request);\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nasync function signInWithEmailLink$1(auth, request) {\r\n return _performSignInRequest(auth, \"POST\" /* HttpMethod.POST */, \"/v1/accounts:signInWithEmailLink\" /* Endpoint.SIGN_IN_WITH_EMAIL_LINK */, _addTidIfNecessary(auth, request));\r\n}\r\nasync function signInWithEmailLinkForLinking(auth, request) {\r\n return _performSignInRequest(auth, \"POST\" /* HttpMethod.POST */, \"/v1/accounts:signInWithEmailLink\" /* Endpoint.SIGN_IN_WITH_EMAIL_LINK */, _addTidIfNecessary(auth, request));\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Interface that represents the credentials returned by {@link EmailAuthProvider} for\r\n * {@link ProviderId}.PASSWORD\r\n *\r\n * @remarks\r\n * Covers both {@link SignInMethod}.EMAIL_PASSWORD and\r\n * {@link SignInMethod}.EMAIL_LINK.\r\n *\r\n * @public\r\n */\r\nclass EmailAuthCredential extends AuthCredential {\r\n /** @internal */\r\n constructor(\r\n /** @internal */\r\n _email, \r\n /** @internal */\r\n _password, signInMethod, \r\n /** @internal */\r\n _tenantId = null) {\r\n super(\"password\" /* ProviderId.PASSWORD */, signInMethod);\r\n this._email = _email;\r\n this._password = _password;\r\n this._tenantId = _tenantId;\r\n }\r\n /** @internal */\r\n static _fromEmailAndPassword(email, password) {\r\n return new EmailAuthCredential(email, password, \"password\" /* SignInMethod.EMAIL_PASSWORD */);\r\n }\r\n /** @internal */\r\n static _fromEmailAndCode(email, oobCode, tenantId = null) {\r\n return new EmailAuthCredential(email, oobCode, \"emailLink\" /* SignInMethod.EMAIL_LINK */, tenantId);\r\n }\r\n /** {@inheritdoc AuthCredential.toJSON} */\r\n toJSON() {\r\n return {\r\n email: this._email,\r\n password: this._password,\r\n signInMethod: this.signInMethod,\r\n tenantId: this._tenantId\r\n };\r\n }\r\n /**\r\n * Static method to deserialize a JSON representation of an object into an {@link AuthCredential}.\r\n *\r\n * @param json - Either `object` or the stringified representation of the object. When string is\r\n * provided, `JSON.parse` would be called first.\r\n *\r\n * @returns If the JSON input does not represent an {@link AuthCredential}, null is returned.\r\n */\r\n static fromJSON(json) {\r\n const obj = typeof json === 'string' ? JSON.parse(json) : json;\r\n if ((obj === null || obj === void 0 ? void 0 : obj.email) && (obj === null || obj === void 0 ? void 0 : obj.password)) {\r\n if (obj.signInMethod === \"password\" /* SignInMethod.EMAIL_PASSWORD */) {\r\n return this._fromEmailAndPassword(obj.email, obj.password);\r\n }\r\n else if (obj.signInMethod === \"emailLink\" /* SignInMethod.EMAIL_LINK */) {\r\n return this._fromEmailAndCode(obj.email, obj.password, obj.tenantId);\r\n }\r\n }\r\n return null;\r\n }\r\n /** @internal */\r\n async _getIdTokenResponse(auth) {\r\n var _a;\r\n switch (this.signInMethod) {\r\n case \"password\" /* SignInMethod.EMAIL_PASSWORD */:\r\n const request = {\r\n returnSecureToken: true,\r\n email: this._email,\r\n password: this._password,\r\n clientType: \"CLIENT_TYPE_WEB\" /* RecaptchaClientType.WEB */\r\n };\r\n if ((_a = auth._getRecaptchaConfig()) === null || _a === void 0 ? void 0 : _a.emailPasswordEnabled) {\r\n const requestWithRecaptcha = await injectRecaptchaFields(auth, request, \"signInWithPassword\" /* RecaptchaActionName.SIGN_IN_WITH_PASSWORD */);\r\n return signInWithPassword(auth, requestWithRecaptcha);\r\n }\r\n else {\r\n return signInWithPassword(auth, request).catch(async (error) => {\r\n if (error.code === `auth/${\"missing-recaptcha-token\" /* AuthErrorCode.MISSING_RECAPTCHA_TOKEN */}`) {\r\n console.log('Sign-in with email address and password is protected by reCAPTCHA for this project. Automatically triggering the reCAPTCHA flow and restarting the sign-in flow.');\r\n const requestWithRecaptcha = await injectRecaptchaFields(auth, request, \"signInWithPassword\" /* RecaptchaActionName.SIGN_IN_WITH_PASSWORD */);\r\n return signInWithPassword(auth, requestWithRecaptcha);\r\n }\r\n else {\r\n return Promise.reject(error);\r\n }\r\n });\r\n }\r\n case \"emailLink\" /* SignInMethod.EMAIL_LINK */:\r\n return signInWithEmailLink$1(auth, {\r\n email: this._email,\r\n oobCode: this._password\r\n });\r\n default:\r\n _fail(auth, \"internal-error\" /* AuthErrorCode.INTERNAL_ERROR */);\r\n }\r\n }\r\n /** @internal */\r\n async _linkToIdToken(auth, idToken) {\r\n switch (this.signInMethod) {\r\n case \"password\" /* SignInMethod.EMAIL_PASSWORD */:\r\n return updateEmailPassword(auth, {\r\n idToken,\r\n returnSecureToken: true,\r\n email: this._email,\r\n password: this._password\r\n });\r\n case \"emailLink\" /* SignInMethod.EMAIL_LINK */:\r\n return signInWithEmailLinkForLinking(auth, {\r\n idToken,\r\n email: this._email,\r\n oobCode: this._password\r\n });\r\n default:\r\n _fail(auth, \"internal-error\" /* AuthErrorCode.INTERNAL_ERROR */);\r\n }\r\n }\r\n /** @internal */\r\n _getReauthenticationResolver(auth) {\r\n return this._getIdTokenResponse(auth);\r\n }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nasync function signInWithIdp(auth, request) {\r\n return _performSignInRequest(auth, \"POST\" /* HttpMethod.POST */, \"/v1/accounts:signInWithIdp\" /* Endpoint.SIGN_IN_WITH_IDP */, _addTidIfNecessary(auth, request));\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nconst IDP_REQUEST_URI$1 = 'http://localhost';\r\n/**\r\n * Represents the OAuth credentials returned by an {@link OAuthProvider}.\r\n *\r\n * @remarks\r\n * Implementations specify the details about each auth provider's credential requirements.\r\n *\r\n * @public\r\n */\r\nclass OAuthCredential extends AuthCredential {\r\n constructor() {\r\n super(...arguments);\r\n this.pendingToken = null;\r\n }\r\n /** @internal */\r\n static _fromParams(params) {\r\n const cred = new OAuthCredential(params.providerId, params.signInMethod);\r\n if (params.idToken || params.accessToken) {\r\n // OAuth 2 and either ID token or access token.\r\n if (params.idToken) {\r\n cred.idToken = params.idToken;\r\n }\r\n if (params.accessToken) {\r\n cred.accessToken = params.accessToken;\r\n }\r\n // Add nonce if available and no pendingToken is present.\r\n if (params.nonce && !params.pendingToken) {\r\n cred.nonce = params.nonce;\r\n }\r\n if (params.pendingToken) {\r\n cred.pendingToken = params.pendingToken;\r\n }\r\n }\r\n else if (params.oauthToken && params.oauthTokenSecret) {\r\n // OAuth 1 and OAuth token with token secret\r\n cred.accessToken = params.oauthToken;\r\n cred.secret = params.oauthTokenSecret;\r\n }\r\n else {\r\n _fail(\"argument-error\" /* AuthErrorCode.ARGUMENT_ERROR */);\r\n }\r\n return cred;\r\n }\r\n /** {@inheritdoc AuthCredential.toJSON} */\r\n toJSON() {\r\n return {\r\n idToken: this.idToken,\r\n accessToken: this.accessToken,\r\n secret: this.secret,\r\n nonce: this.nonce,\r\n pendingToken: this.pendingToken,\r\n providerId: this.providerId,\r\n signInMethod: this.signInMethod\r\n };\r\n }\r\n /**\r\n * Static method to deserialize a JSON representation of an object into an\r\n * {@link AuthCredential}.\r\n *\r\n * @param json - Input can be either Object or the stringified representation of the object.\r\n * When string is provided, JSON.parse would be called first.\r\n *\r\n * @returns If the JSON input does not represent an {@link AuthCredential}, null is returned.\r\n */\r\n static fromJSON(json) {\r\n const obj = typeof json === 'string' ? JSON.parse(json) : json;\r\n const { providerId, signInMethod } = obj, rest = __rest(obj, [\"providerId\", \"signInMethod\"]);\r\n if (!providerId || !signInMethod) {\r\n return null;\r\n }\r\n const cred = new OAuthCredential(providerId, signInMethod);\r\n cred.idToken = rest.idToken || undefined;\r\n cred.accessToken = rest.accessToken || undefined;\r\n cred.secret = rest.secret;\r\n cred.nonce = rest.nonce;\r\n cred.pendingToken = rest.pendingToken || null;\r\n return cred;\r\n }\r\n /** @internal */\r\n _getIdTokenResponse(auth) {\r\n const request = this.buildRequest();\r\n return signInWithIdp(auth, request);\r\n }\r\n /** @internal */\r\n _linkToIdToken(auth, idToken) {\r\n const request = this.buildRequest();\r\n request.idToken = idToken;\r\n return signInWithIdp(auth, request);\r\n }\r\n /** @internal */\r\n _getReauthenticationResolver(auth) {\r\n const request = this.buildRequest();\r\n request.autoCreate = false;\r\n return signInWithIdp(auth, request);\r\n }\r\n buildRequest() {\r\n const request = {\r\n requestUri: IDP_REQUEST_URI$1,\r\n returnSecureToken: true\r\n };\r\n if (this.pendingToken) {\r\n request.pendingToken = this.pendingToken;\r\n }\r\n else {\r\n const postBody = {};\r\n if (this.idToken) {\r\n postBody['id_token'] = this.idToken;\r\n }\r\n if (this.accessToken) {\r\n postBody['access_token'] = this.accessToken;\r\n }\r\n if (this.secret) {\r\n postBody['oauth_token_secret'] = this.secret;\r\n }\r\n postBody['providerId'] = this.providerId;\r\n if (this.nonce && !this.pendingToken) {\r\n postBody['nonce'] = this.nonce;\r\n }\r\n request.postBody = querystring(postBody);\r\n }\r\n return request;\r\n }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nasync function sendPhoneVerificationCode(auth, request) {\r\n return _performApiRequest(auth, \"POST\" /* HttpMethod.POST */, \"/v1/accounts:sendVerificationCode\" /* Endpoint.SEND_VERIFICATION_CODE */, _addTidIfNecessary(auth, request));\r\n}\r\nasync function signInWithPhoneNumber$1(auth, request) {\r\n return _performSignInRequest(auth, \"POST\" /* HttpMethod.POST */, \"/v1/accounts:signInWithPhoneNumber\" /* Endpoint.SIGN_IN_WITH_PHONE_NUMBER */, _addTidIfNecessary(auth, request));\r\n}\r\nasync function linkWithPhoneNumber$1(auth, request) {\r\n const response = await _performSignInRequest(auth, \"POST\" /* HttpMethod.POST */, \"/v1/accounts:signInWithPhoneNumber\" /* Endpoint.SIGN_IN_WITH_PHONE_NUMBER */, _addTidIfNecessary(auth, request));\r\n if (response.temporaryProof) {\r\n throw _makeTaggedError(auth, \"account-exists-with-different-credential\" /* AuthErrorCode.NEED_CONFIRMATION */, response);\r\n }\r\n return response;\r\n}\r\nconst VERIFY_PHONE_NUMBER_FOR_EXISTING_ERROR_MAP_ = {\r\n [\"USER_NOT_FOUND\" /* ServerError.USER_NOT_FOUND */]: \"user-not-found\" /* AuthErrorCode.USER_DELETED */\r\n};\r\nasync function verifyPhoneNumberForExisting(auth, request) {\r\n const apiRequest = Object.assign(Object.assign({}, request), { operation: 'REAUTH' });\r\n return _performSignInRequest(auth, \"POST\" /* HttpMethod.POST */, \"/v1/accounts:signInWithPhoneNumber\" /* Endpoint.SIGN_IN_WITH_PHONE_NUMBER */, _addTidIfNecessary(auth, apiRequest), VERIFY_PHONE_NUMBER_FOR_EXISTING_ERROR_MAP_);\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Represents the credentials returned by {@link PhoneAuthProvider}.\r\n *\r\n * @public\r\n */\r\nclass PhoneAuthCredential extends AuthCredential {\r\n constructor(params) {\r\n super(\"phone\" /* ProviderId.PHONE */, \"phone\" /* SignInMethod.PHONE */);\r\n this.params = params;\r\n }\r\n /** @internal */\r\n static _fromVerification(verificationId, verificationCode) {\r\n return new PhoneAuthCredential({ verificationId, verificationCode });\r\n }\r\n /** @internal */\r\n static _fromTokenResponse(phoneNumber, temporaryProof) {\r\n return new PhoneAuthCredential({ phoneNumber, temporaryProof });\r\n }\r\n /** @internal */\r\n _getIdTokenResponse(auth) {\r\n return signInWithPhoneNumber$1(auth, this._makeVerificationRequest());\r\n }\r\n /** @internal */\r\n _linkToIdToken(auth, idToken) {\r\n return linkWithPhoneNumber$1(auth, Object.assign({ idToken }, this._makeVerificationRequest()));\r\n }\r\n /** @internal */\r\n _getReauthenticationResolver(auth) {\r\n return verifyPhoneNumberForExisting(auth, this._makeVerificationRequest());\r\n }\r\n /** @internal */\r\n _makeVerificationRequest() {\r\n const { temporaryProof, phoneNumber, verificationId, verificationCode } = this.params;\r\n if (temporaryProof && phoneNumber) {\r\n return { temporaryProof, phoneNumber };\r\n }\r\n return {\r\n sessionInfo: verificationId,\r\n code: verificationCode\r\n };\r\n }\r\n /** {@inheritdoc AuthCredential.toJSON} */\r\n toJSON() {\r\n const obj = {\r\n providerId: this.providerId\r\n };\r\n if (this.params.phoneNumber) {\r\n obj.phoneNumber = this.params.phoneNumber;\r\n }\r\n if (this.params.temporaryProof) {\r\n obj.temporaryProof = this.params.temporaryProof;\r\n }\r\n if (this.params.verificationCode) {\r\n obj.verificationCode = this.params.verificationCode;\r\n }\r\n if (this.params.verificationId) {\r\n obj.verificationId = this.params.verificationId;\r\n }\r\n return obj;\r\n }\r\n /** Generates a phone credential based on a plain object or a JSON string. */\r\n static fromJSON(json) {\r\n if (typeof json === 'string') {\r\n json = JSON.parse(json);\r\n }\r\n const { verificationId, verificationCode, phoneNumber, temporaryProof } = json;\r\n if (!verificationCode &&\r\n !verificationId &&\r\n !phoneNumber &&\r\n !temporaryProof) {\r\n return null;\r\n }\r\n return new PhoneAuthCredential({\r\n verificationId,\r\n verificationCode,\r\n phoneNumber,\r\n temporaryProof\r\n });\r\n }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Maps the mode string in action code URL to Action Code Info operation.\r\n *\r\n * @param mode\r\n */\r\nfunction parseMode(mode) {\r\n switch (mode) {\r\n case 'recoverEmail':\r\n return \"RECOVER_EMAIL\" /* ActionCodeOperation.RECOVER_EMAIL */;\r\n case 'resetPassword':\r\n return \"PASSWORD_RESET\" /* ActionCodeOperation.PASSWORD_RESET */;\r\n case 'signIn':\r\n return \"EMAIL_SIGNIN\" /* ActionCodeOperation.EMAIL_SIGNIN */;\r\n case 'verifyEmail':\r\n return \"VERIFY_EMAIL\" /* ActionCodeOperation.VERIFY_EMAIL */;\r\n case 'verifyAndChangeEmail':\r\n return \"VERIFY_AND_CHANGE_EMAIL\" /* ActionCodeOperation.VERIFY_AND_CHANGE_EMAIL */;\r\n case 'revertSecondFactorAddition':\r\n return \"REVERT_SECOND_FACTOR_ADDITION\" /* ActionCodeOperation.REVERT_SECOND_FACTOR_ADDITION */;\r\n default:\r\n return null;\r\n }\r\n}\r\n/**\r\n * Helper to parse FDL links\r\n *\r\n * @param url\r\n */\r\nfunction parseDeepLink(url) {\r\n const link = querystringDecode(extractQuerystring(url))['link'];\r\n // Double link case (automatic redirect).\r\n const doubleDeepLink = link\r\n ? querystringDecode(extractQuerystring(link))['deep_link_id']\r\n : null;\r\n // iOS custom scheme links.\r\n const iOSDeepLink = querystringDecode(extractQuerystring(url))['deep_link_id'];\r\n const iOSDoubleDeepLink = iOSDeepLink\r\n ? querystringDecode(extractQuerystring(iOSDeepLink))['link']\r\n : null;\r\n return iOSDoubleDeepLink || iOSDeepLink || doubleDeepLink || link || url;\r\n}\r\n/**\r\n * A utility class to parse email action URLs such as password reset, email verification,\r\n * email link sign in, etc.\r\n *\r\n * @public\r\n */\r\nclass ActionCodeURL {\r\n /**\r\n * @param actionLink - The link from which to extract the URL.\r\n * @returns The {@link ActionCodeURL} object, or null if the link is invalid.\r\n *\r\n * @internal\r\n */\r\n constructor(actionLink) {\r\n var _a, _b, _c, _d, _e, _f;\r\n const searchParams = querystringDecode(extractQuerystring(actionLink));\r\n const apiKey = (_a = searchParams[\"apiKey\" /* QueryField.API_KEY */]) !== null && _a !== void 0 ? _a : null;\r\n const code = (_b = searchParams[\"oobCode\" /* QueryField.CODE */]) !== null && _b !== void 0 ? _b : null;\r\n const operation = parseMode((_c = searchParams[\"mode\" /* QueryField.MODE */]) !== null && _c !== void 0 ? _c : null);\r\n // Validate API key, code and mode.\r\n _assert(apiKey && code && operation, \"argument-error\" /* AuthErrorCode.ARGUMENT_ERROR */);\r\n this.apiKey = apiKey;\r\n this.operation = operation;\r\n this.code = code;\r\n this.continueUrl = (_d = searchParams[\"continueUrl\" /* QueryField.CONTINUE_URL */]) !== null && _d !== void 0 ? _d : null;\r\n this.languageCode = (_e = searchParams[\"languageCode\" /* QueryField.LANGUAGE_CODE */]) !== null && _e !== void 0 ? _e : null;\r\n this.tenantId = (_f = searchParams[\"tenantId\" /* QueryField.TENANT_ID */]) !== null && _f !== void 0 ? _f : null;\r\n }\r\n /**\r\n * Parses the email action link string and returns an {@link ActionCodeURL} if the link is valid,\r\n * otherwise returns null.\r\n *\r\n * @param link - The email action link string.\r\n * @returns The {@link ActionCodeURL} object, or null if the link is invalid.\r\n *\r\n * @public\r\n */\r\n static parseLink(link) {\r\n const actionLink = parseDeepLink(link);\r\n try {\r\n return new ActionCodeURL(actionLink);\r\n }\r\n catch (_a) {\r\n return null;\r\n }\r\n }\r\n}\r\n/**\r\n * Parses the email action link string and returns an {@link ActionCodeURL} if\r\n * the link is valid, otherwise returns null.\r\n *\r\n * @public\r\n */\r\nfunction parseActionCodeURL(link) {\r\n return ActionCodeURL.parseLink(link);\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Provider for generating {@link EmailAuthCredential}.\r\n *\r\n * @public\r\n */\r\nclass EmailAuthProvider {\r\n constructor() {\r\n /**\r\n * Always set to {@link ProviderId}.PASSWORD, even for email link.\r\n */\r\n this.providerId = EmailAuthProvider.PROVIDER_ID;\r\n }\r\n /**\r\n * Initialize an {@link AuthCredential} using an email and password.\r\n *\r\n * @example\r\n * ```javascript\r\n * const authCredential = EmailAuthProvider.credential(email, password);\r\n * const userCredential = await signInWithCredential(auth, authCredential);\r\n * ```\r\n *\r\n * @example\r\n * ```javascript\r\n * const userCredential = await signInWithEmailAndPassword(auth, email, password);\r\n * ```\r\n *\r\n * @param email - Email address.\r\n * @param password - User account password.\r\n * @returns The auth provider credential.\r\n */\r\n static credential(email, password) {\r\n return EmailAuthCredential._fromEmailAndPassword(email, password);\r\n }\r\n /**\r\n * Initialize an {@link AuthCredential} using an email and an email link after a sign in with\r\n * email link operation.\r\n *\r\n * @example\r\n * ```javascript\r\n * const authCredential = EmailAuthProvider.credentialWithLink(auth, email, emailLink);\r\n * const userCredential = await signInWithCredential(auth, authCredential);\r\n * ```\r\n *\r\n * @example\r\n * ```javascript\r\n * await sendSignInLinkToEmail(auth, email);\r\n * // Obtain emailLink from user.\r\n * const userCredential = await signInWithEmailLink(auth, email, emailLink);\r\n * ```\r\n *\r\n * @param auth - The {@link Auth} instance used to verify the link.\r\n * @param email - Email address.\r\n * @param emailLink - Sign-in email link.\r\n * @returns - The auth provider credential.\r\n */\r\n static credentialWithLink(email, emailLink) {\r\n const actionCodeUrl = ActionCodeURL.parseLink(emailLink);\r\n _assert(actionCodeUrl, \"argument-error\" /* AuthErrorCode.ARGUMENT_ERROR */);\r\n return EmailAuthCredential._fromEmailAndCode(email, actionCodeUrl.code, actionCodeUrl.tenantId);\r\n }\r\n}\r\n/**\r\n * Always set to {@link ProviderId}.PASSWORD, even for email link.\r\n */\r\nEmailAuthProvider.PROVIDER_ID = \"password\" /* ProviderId.PASSWORD */;\r\n/**\r\n * Always set to {@link SignInMethod}.EMAIL_PASSWORD.\r\n */\r\nEmailAuthProvider.EMAIL_PASSWORD_SIGN_IN_METHOD = \"password\" /* SignInMethod.EMAIL_PASSWORD */;\r\n/**\r\n * Always set to {@link SignInMethod}.EMAIL_LINK.\r\n */\r\nEmailAuthProvider.EMAIL_LINK_SIGN_IN_METHOD = \"emailLink\" /* SignInMethod.EMAIL_LINK */;\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * The base class for all Federated providers (OAuth (including OIDC), SAML).\r\n *\r\n * This class is not meant to be instantiated directly.\r\n *\r\n * @public\r\n */\r\nclass FederatedAuthProvider {\r\n /**\r\n * Constructor for generic OAuth providers.\r\n *\r\n * @param providerId - Provider for which credentials should be generated.\r\n */\r\n constructor(providerId) {\r\n this.providerId = providerId;\r\n /** @internal */\r\n this.defaultLanguageCode = null;\r\n /** @internal */\r\n this.customParameters = {};\r\n }\r\n /**\r\n * Set the language gode.\r\n *\r\n * @param languageCode - language code\r\n */\r\n setDefaultLanguage(languageCode) {\r\n this.defaultLanguageCode = languageCode;\r\n }\r\n /**\r\n * Sets the OAuth custom parameters to pass in an OAuth request for popup and redirect sign-in\r\n * operations.\r\n *\r\n * @remarks\r\n * For a detailed list, check the reserved required OAuth 2.0 parameters such as `client_id`,\r\n * `redirect_uri`, `scope`, `response_type`, and `state` are not allowed and will be ignored.\r\n *\r\n * @param customOAuthParameters - The custom OAuth parameters to pass in the OAuth request.\r\n */\r\n setCustomParameters(customOAuthParameters) {\r\n this.customParameters = customOAuthParameters;\r\n return this;\r\n }\r\n /**\r\n * Retrieve the current list of {@link CustomParameters}.\r\n */\r\n getCustomParameters() {\r\n return this.customParameters;\r\n }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2019 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Common code to all OAuth providers. This is separate from the\r\n * {@link OAuthProvider} so that child providers (like\r\n * {@link GoogleAuthProvider}) don't inherit the `credential` instance method.\r\n * Instead, they rely on a static `credential` method.\r\n */\r\nclass BaseOAuthProvider extends FederatedAuthProvider {\r\n constructor() {\r\n super(...arguments);\r\n /** @internal */\r\n this.scopes = [];\r\n }\r\n /**\r\n * Add an OAuth scope to the credential.\r\n *\r\n * @param scope - Provider OAuth scope to add.\r\n */\r\n addScope(scope) {\r\n // If not already added, add scope to list.\r\n if (!this.scopes.includes(scope)) {\r\n this.scopes.push(scope);\r\n }\r\n return this;\r\n }\r\n /**\r\n * Retrieve the current list of OAuth scopes.\r\n */\r\n getScopes() {\r\n return [...this.scopes];\r\n }\r\n}\r\n/**\r\n * Provider for generating generic {@link OAuthCredential}.\r\n *\r\n * @example\r\n * ```javascript\r\n * // Sign in using a redirect.\r\n * const provider = new OAuthProvider('google.com');\r\n * // Start a sign in process for an unauthenticated user.\r\n * provider.addScope('profile');\r\n * provider.addScope('email');\r\n * await signInWithRedirect(auth, provider);\r\n * // This will trigger a full page redirect away from your app\r\n *\r\n * // After returning from the redirect when your app initializes you can obtain the result\r\n * const result = await getRedirectResult(auth);\r\n * if (result) {\r\n * // This is the signed-in user\r\n * const user = result.user;\r\n * // This gives you a OAuth Access Token for the provider.\r\n * const credential = provider.credentialFromResult(auth, result);\r\n * const token = credential.accessToken;\r\n * }\r\n * ```\r\n *\r\n * @example\r\n * ```javascript\r\n * // Sign in using a popup.\r\n * const provider = new OAuthProvider('google.com');\r\n * provider.addScope('profile');\r\n * provider.addScope('email');\r\n * const result = await signInWithPopup(auth, provider);\r\n *\r\n * // The signed-in user info.\r\n * const user = result.user;\r\n * // This gives you a OAuth Access Token for the provider.\r\n * const credential = provider.credentialFromResult(auth, result);\r\n * const token = credential.accessToken;\r\n * ```\r\n * @public\r\n */\r\nclass OAuthProvider extends BaseOAuthProvider {\r\n /**\r\n * Creates an {@link OAuthCredential} from a JSON string or a plain object.\r\n * @param json - A plain object or a JSON string\r\n */\r\n static credentialFromJSON(json) {\r\n const obj = typeof json === 'string' ? JSON.parse(json) : json;\r\n _assert('providerId' in obj && 'signInMethod' in obj, \"argument-error\" /* AuthErrorCode.ARGUMENT_ERROR */);\r\n return OAuthCredential._fromParams(obj);\r\n }\r\n /**\r\n * Creates a {@link OAuthCredential} from a generic OAuth provider's access token or ID token.\r\n *\r\n * @remarks\r\n * The raw nonce is required when an ID token with a nonce field is provided. The SHA-256 hash of\r\n * the raw nonce must match the nonce field in the ID token.\r\n *\r\n * @example\r\n * ```javascript\r\n * // `googleUser` from the onsuccess Google Sign In callback.\r\n * // Initialize a generate OAuth provider with a `google.com` providerId.\r\n * const provider = new OAuthProvider('google.com');\r\n * const credential = provider.credential({\r\n * idToken: googleUser.getAuthResponse().id_token,\r\n * });\r\n * const result = await signInWithCredential(credential);\r\n * ```\r\n *\r\n * @param params - Either the options object containing the ID token, access token and raw nonce\r\n * or the ID token string.\r\n */\r\n credential(params) {\r\n return this._credential(Object.assign(Object.assign({}, params), { nonce: params.rawNonce }));\r\n }\r\n /** An internal credential method that accepts more permissive options */\r\n _credential(params) {\r\n _assert(params.idToken || params.accessToken, \"argument-error\" /* AuthErrorCode.ARGUMENT_ERROR */);\r\n // For OAuthCredential, sign in method is same as providerId.\r\n return OAuthCredential._fromParams(Object.assign(Object.assign({}, params), { providerId: this.providerId, signInMethod: this.providerId }));\r\n }\r\n /**\r\n * Used to extract the underlying {@link OAuthCredential} from a {@link UserCredential}.\r\n *\r\n * @param userCredential - The user credential.\r\n */\r\n static credentialFromResult(userCredential) {\r\n return OAuthProvider.oauthCredentialFromTaggedObject(userCredential);\r\n }\r\n /**\r\n * Used to extract the underlying {@link OAuthCredential} from a {@link AuthError} which was\r\n * thrown during a sign-in, link, or reauthenticate operation.\r\n *\r\n * @param userCredential - The user credential.\r\n */\r\n static credentialFromError(error) {\r\n return OAuthProvider.oauthCredentialFromTaggedObject((error.customData || {}));\r\n }\r\n static oauthCredentialFromTaggedObject({ _tokenResponse: tokenResponse }) {\r\n if (!tokenResponse) {\r\n return null;\r\n }\r\n const { oauthIdToken, oauthAccessToken, oauthTokenSecret, pendingToken, nonce, providerId } = tokenResponse;\r\n if (!oauthAccessToken &&\r\n !oauthTokenSecret &&\r\n !oauthIdToken &&\r\n !pendingToken) {\r\n return null;\r\n }\r\n if (!providerId) {\r\n return null;\r\n }\r\n try {\r\n return new OAuthProvider(providerId)._credential({\r\n idToken: oauthIdToken,\r\n accessToken: oauthAccessToken,\r\n nonce,\r\n pendingToken\r\n });\r\n }\r\n catch (e) {\r\n return null;\r\n }\r\n }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Provider for generating an {@link OAuthCredential} for {@link ProviderId}.FACEBOOK.\r\n *\r\n * @example\r\n * ```javascript\r\n * // Sign in using a redirect.\r\n * const provider = new FacebookAuthProvider();\r\n * // Start a sign in process for an unauthenticated user.\r\n * provider.addScope('user_birthday');\r\n * await signInWithRedirect(auth, provider);\r\n * // This will trigger a full page redirect away from your app\r\n *\r\n * // After returning from the redirect when your app initializes you can obtain the result\r\n * const result = await getRedirectResult(auth);\r\n * if (result) {\r\n * // This is the signed-in user\r\n * const user = result.user;\r\n * // This gives you a Facebook Access Token.\r\n * const credential = FacebookAuthProvider.credentialFromResult(result);\r\n * const token = credential.accessToken;\r\n * }\r\n * ```\r\n *\r\n * @example\r\n * ```javascript\r\n * // Sign in using a popup.\r\n * const provider = new FacebookAuthProvider();\r\n * provider.addScope('user_birthday');\r\n * const result = await signInWithPopup(auth, provider);\r\n *\r\n * // The signed-in user info.\r\n * const user = result.user;\r\n * // This gives you a Facebook Access Token.\r\n * const credential = FacebookAuthProvider.credentialFromResult(result);\r\n * const token = credential.accessToken;\r\n * ```\r\n *\r\n * @public\r\n */\r\nclass FacebookAuthProvider extends BaseOAuthProvider {\r\n constructor() {\r\n super(\"facebook.com\" /* ProviderId.FACEBOOK */);\r\n }\r\n /**\r\n * Creates a credential for Facebook.\r\n *\r\n * @example\r\n * ```javascript\r\n * // `event` from the Facebook auth.authResponseChange callback.\r\n * const credential = FacebookAuthProvider.credential(event.authResponse.accessToken);\r\n * const result = await signInWithCredential(credential);\r\n * ```\r\n *\r\n * @param accessToken - Facebook access token.\r\n */\r\n static credential(accessToken) {\r\n return OAuthCredential._fromParams({\r\n providerId: FacebookAuthProvider.PROVIDER_ID,\r\n signInMethod: FacebookAuthProvider.FACEBOOK_SIGN_IN_METHOD,\r\n accessToken\r\n });\r\n }\r\n /**\r\n * Used to extract the underlying {@link OAuthCredential} from a {@link UserCredential}.\r\n *\r\n * @param userCredential - The user credential.\r\n */\r\n static credentialFromResult(userCredential) {\r\n return FacebookAuthProvider.credentialFromTaggedObject(userCredential);\r\n }\r\n /**\r\n * Used to extract the underlying {@link OAuthCredential} from a {@link AuthError} which was\r\n * thrown during a sign-in, link, or reauthenticate operation.\r\n *\r\n * @param userCredential - The user credential.\r\n */\r\n static credentialFromError(error) {\r\n return FacebookAuthProvider.credentialFromTaggedObject((error.customData || {}));\r\n }\r\n static credentialFromTaggedObject({ _tokenResponse: tokenResponse }) {\r\n if (!tokenResponse || !('oauthAccessToken' in tokenResponse)) {\r\n return null;\r\n }\r\n if (!tokenResponse.oauthAccessToken) {\r\n return null;\r\n }\r\n try {\r\n return FacebookAuthProvider.credential(tokenResponse.oauthAccessToken);\r\n }\r\n catch (_a) {\r\n return null;\r\n }\r\n }\r\n}\r\n/** Always set to {@link SignInMethod}.FACEBOOK. */\r\nFacebookAuthProvider.FACEBOOK_SIGN_IN_METHOD = \"facebook.com\" /* SignInMethod.FACEBOOK */;\r\n/** Always set to {@link ProviderId}.FACEBOOK. */\r\nFacebookAuthProvider.PROVIDER_ID = \"facebook.com\" /* ProviderId.FACEBOOK */;\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Provider for generating an an {@link OAuthCredential} for {@link ProviderId}.GOOGLE.\r\n *\r\n * @example\r\n * ```javascript\r\n * // Sign in using a redirect.\r\n * const provider = new GoogleAuthProvider();\r\n * // Start a sign in process for an unauthenticated user.\r\n * provider.addScope('profile');\r\n * provider.addScope('email');\r\n * await signInWithRedirect(auth, provider);\r\n * // This will trigger a full page redirect away from your app\r\n *\r\n * // After returning from the redirect when your app initializes you can obtain the result\r\n * const result = await getRedirectResult(auth);\r\n * if (result) {\r\n * // This is the signed-in user\r\n * const user = result.user;\r\n * // This gives you a Google Access Token.\r\n * const credential = GoogleAuthProvider.credentialFromResult(result);\r\n * const token = credential.accessToken;\r\n * }\r\n * ```\r\n *\r\n * @example\r\n * ```javascript\r\n * // Sign in using a popup.\r\n * const provider = new GoogleAuthProvider();\r\n * provider.addScope('profile');\r\n * provider.addScope('email');\r\n * const result = await signInWithPopup(auth, provider);\r\n *\r\n * // The signed-in user info.\r\n * const user = result.user;\r\n * // This gives you a Google Access Token.\r\n * const credential = GoogleAuthProvider.credentialFromResult(result);\r\n * const token = credential.accessToken;\r\n * ```\r\n *\r\n * @public\r\n */\r\nclass GoogleAuthProvider extends BaseOAuthProvider {\r\n constructor() {\r\n super(\"google.com\" /* ProviderId.GOOGLE */);\r\n this.addScope('profile');\r\n }\r\n /**\r\n * Creates a credential for Google. At least one of ID token and access token is required.\r\n *\r\n * @example\r\n * ```javascript\r\n * // \\`googleUser\\` from the onsuccess Google Sign In callback.\r\n * const credential = GoogleAuthProvider.credential(googleUser.getAuthResponse().id_token);\r\n * const result = await signInWithCredential(credential);\r\n * ```\r\n *\r\n * @param idToken - Google ID token.\r\n * @param accessToken - Google access token.\r\n */\r\n static credential(idToken, accessToken) {\r\n return OAuthCredential._fromParams({\r\n providerId: GoogleAuthProvider.PROVIDER_ID,\r\n signInMethod: GoogleAuthProvider.GOOGLE_SIGN_IN_METHOD,\r\n idToken,\r\n accessToken\r\n });\r\n }\r\n /**\r\n * Used to extract the underlying {@link OAuthCredential} from a {@link UserCredential}.\r\n *\r\n * @param userCredential - The user credential.\r\n */\r\n static credentialFromResult(userCredential) {\r\n return GoogleAuthProvider.credentialFromTaggedObject(userCredential);\r\n }\r\n /**\r\n * Used to extract the underlying {@link OAuthCredential} from a {@link AuthError} which was\r\n * thrown during a sign-in, link, or reauthenticate operation.\r\n *\r\n * @param userCredential - The user credential.\r\n */\r\n static credentialFromError(error) {\r\n return GoogleAuthProvider.credentialFromTaggedObject((error.customData || {}));\r\n }\r\n static credentialFromTaggedObject({ _tokenResponse: tokenResponse }) {\r\n if (!tokenResponse) {\r\n return null;\r\n }\r\n const { oauthIdToken, oauthAccessToken } = tokenResponse;\r\n if (!oauthIdToken && !oauthAccessToken) {\r\n // This could be an oauth 1 credential or a phone credential\r\n return null;\r\n }\r\n try {\r\n return GoogleAuthProvider.credential(oauthIdToken, oauthAccessToken);\r\n }\r\n catch (_a) {\r\n return null;\r\n }\r\n }\r\n}\r\n/** Always set to {@link SignInMethod}.GOOGLE. */\r\nGoogleAuthProvider.GOOGLE_SIGN_IN_METHOD = \"google.com\" /* SignInMethod.GOOGLE */;\r\n/** Always set to {@link ProviderId}.GOOGLE. */\r\nGoogleAuthProvider.PROVIDER_ID = \"google.com\" /* ProviderId.GOOGLE */;\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Provider for generating an {@link OAuthCredential} for {@link ProviderId}.GITHUB.\r\n *\r\n * @remarks\r\n * GitHub requires an OAuth 2.0 redirect, so you can either handle the redirect directly, or use\r\n * the {@link signInWithPopup} handler:\r\n *\r\n * @example\r\n * ```javascript\r\n * // Sign in using a redirect.\r\n * const provider = new GithubAuthProvider();\r\n * // Start a sign in process for an unauthenticated user.\r\n * provider.addScope('repo');\r\n * await signInWithRedirect(auth, provider);\r\n * // This will trigger a full page redirect away from your app\r\n *\r\n * // After returning from the redirect when your app initializes you can obtain the result\r\n * const result = await getRedirectResult(auth);\r\n * if (result) {\r\n * // This is the signed-in user\r\n * const user = result.user;\r\n * // This gives you a Github Access Token.\r\n * const credential = GithubAuthProvider.credentialFromResult(result);\r\n * const token = credential.accessToken;\r\n * }\r\n * ```\r\n *\r\n * @example\r\n * ```javascript\r\n * // Sign in using a popup.\r\n * const provider = new GithubAuthProvider();\r\n * provider.addScope('repo');\r\n * const result = await signInWithPopup(auth, provider);\r\n *\r\n * // The signed-in user info.\r\n * const user = result.user;\r\n * // This gives you a Github Access Token.\r\n * const credential = GithubAuthProvider.credentialFromResult(result);\r\n * const token = credential.accessToken;\r\n * ```\r\n * @public\r\n */\r\nclass GithubAuthProvider extends BaseOAuthProvider {\r\n constructor() {\r\n super(\"github.com\" /* ProviderId.GITHUB */);\r\n }\r\n /**\r\n * Creates a credential for Github.\r\n *\r\n * @param accessToken - Github access token.\r\n */\r\n static credential(accessToken) {\r\n return OAuthCredential._fromParams({\r\n providerId: GithubAuthProvider.PROVIDER_ID,\r\n signInMethod: GithubAuthProvider.GITHUB_SIGN_IN_METHOD,\r\n accessToken\r\n });\r\n }\r\n /**\r\n * Used to extract the underlying {@link OAuthCredential} from a {@link UserCredential}.\r\n *\r\n * @param userCredential - The user credential.\r\n */\r\n static credentialFromResult(userCredential) {\r\n return GithubAuthProvider.credentialFromTaggedObject(userCredential);\r\n }\r\n /**\r\n * Used to extract the underlying {@link OAuthCredential} from a {@link AuthError} which was\r\n * thrown during a sign-in, link, or reauthenticate operation.\r\n *\r\n * @param userCredential - The user credential.\r\n */\r\n static credentialFromError(error) {\r\n return GithubAuthProvider.credentialFromTaggedObject((error.customData || {}));\r\n }\r\n static credentialFromTaggedObject({ _tokenResponse: tokenResponse }) {\r\n if (!tokenResponse || !('oauthAccessToken' in tokenResponse)) {\r\n return null;\r\n }\r\n if (!tokenResponse.oauthAccessToken) {\r\n return null;\r\n }\r\n try {\r\n return GithubAuthProvider.credential(tokenResponse.oauthAccessToken);\r\n }\r\n catch (_a) {\r\n return null;\r\n }\r\n }\r\n}\r\n/** Always set to {@link SignInMethod}.GITHUB. */\r\nGithubAuthProvider.GITHUB_SIGN_IN_METHOD = \"github.com\" /* SignInMethod.GITHUB */;\r\n/** Always set to {@link ProviderId}.GITHUB. */\r\nGithubAuthProvider.PROVIDER_ID = \"github.com\" /* ProviderId.GITHUB */;\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nconst IDP_REQUEST_URI = 'http://localhost';\r\n/**\r\n * @public\r\n */\r\nclass SAMLAuthCredential extends AuthCredential {\r\n /** @internal */\r\n constructor(providerId, pendingToken) {\r\n super(providerId, providerId);\r\n this.pendingToken = pendingToken;\r\n }\r\n /** @internal */\r\n _getIdTokenResponse(auth) {\r\n const request = this.buildRequest();\r\n return signInWithIdp(auth, request);\r\n }\r\n /** @internal */\r\n _linkToIdToken(auth, idToken) {\r\n const request = this.buildRequest();\r\n request.idToken = idToken;\r\n return signInWithIdp(auth, request);\r\n }\r\n /** @internal */\r\n _getReauthenticationResolver(auth) {\r\n const request = this.buildRequest();\r\n request.autoCreate = false;\r\n return signInWithIdp(auth, request);\r\n }\r\n /** {@inheritdoc AuthCredential.toJSON} */\r\n toJSON() {\r\n return {\r\n signInMethod: this.signInMethod,\r\n providerId: this.providerId,\r\n pendingToken: this.pendingToken\r\n };\r\n }\r\n /**\r\n * Static method to deserialize a JSON representation of an object into an\r\n * {@link AuthCredential}.\r\n *\r\n * @param json - Input can be either Object or the stringified representation of the object.\r\n * When string is provided, JSON.parse would be called first.\r\n *\r\n * @returns If the JSON input does not represent an {@link AuthCredential}, null is returned.\r\n */\r\n static fromJSON(json) {\r\n const obj = typeof json === 'string' ? JSON.parse(json) : json;\r\n const { providerId, signInMethod, pendingToken } = obj;\r\n if (!providerId ||\r\n !signInMethod ||\r\n !pendingToken ||\r\n providerId !== signInMethod) {\r\n return null;\r\n }\r\n return new SAMLAuthCredential(providerId, pendingToken);\r\n }\r\n /**\r\n * Helper static method to avoid exposing the constructor to end users.\r\n *\r\n * @internal\r\n */\r\n static _create(providerId, pendingToken) {\r\n return new SAMLAuthCredential(providerId, pendingToken);\r\n }\r\n buildRequest() {\r\n return {\r\n requestUri: IDP_REQUEST_URI,\r\n returnSecureToken: true,\r\n pendingToken: this.pendingToken\r\n };\r\n }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nconst SAML_PROVIDER_PREFIX = 'saml.';\r\n/**\r\n * An {@link AuthProvider} for SAML.\r\n *\r\n * @public\r\n */\r\nclass SAMLAuthProvider extends FederatedAuthProvider {\r\n /**\r\n * Constructor. The providerId must start with \"saml.\"\r\n * @param providerId - SAML provider ID.\r\n */\r\n constructor(providerId) {\r\n _assert(providerId.startsWith(SAML_PROVIDER_PREFIX), \"argument-error\" /* AuthErrorCode.ARGUMENT_ERROR */);\r\n super(providerId);\r\n }\r\n /**\r\n * Generates an {@link AuthCredential} from a {@link UserCredential} after a\r\n * successful SAML flow completes.\r\n *\r\n * @remarks\r\n *\r\n * For example, to get an {@link AuthCredential}, you could write the\r\n * following code:\r\n *\r\n * ```js\r\n * const userCredential = await signInWithPopup(auth, samlProvider);\r\n * const credential = SAMLAuthProvider.credentialFromResult(userCredential);\r\n * ```\r\n *\r\n * @param userCredential - The user credential.\r\n */\r\n static credentialFromResult(userCredential) {\r\n return SAMLAuthProvider.samlCredentialFromTaggedObject(userCredential);\r\n }\r\n /**\r\n * Used to extract the underlying {@link OAuthCredential} from a {@link AuthError} which was\r\n * thrown during a sign-in, link, or reauthenticate operation.\r\n *\r\n * @param userCredential - The user credential.\r\n */\r\n static credentialFromError(error) {\r\n return SAMLAuthProvider.samlCredentialFromTaggedObject((error.customData || {}));\r\n }\r\n /**\r\n * Creates an {@link AuthCredential} from a JSON string or a plain object.\r\n * @param json - A plain object or a JSON string\r\n */\r\n static credentialFromJSON(json) {\r\n const credential = SAMLAuthCredential.fromJSON(json);\r\n _assert(credential, \"argument-error\" /* AuthErrorCode.ARGUMENT_ERROR */);\r\n return credential;\r\n }\r\n static samlCredentialFromTaggedObject({ _tokenResponse: tokenResponse }) {\r\n if (!tokenResponse) {\r\n return null;\r\n }\r\n const { pendingToken, providerId } = tokenResponse;\r\n if (!pendingToken || !providerId) {\r\n return null;\r\n }\r\n try {\r\n return SAMLAuthCredential._create(providerId, pendingToken);\r\n }\r\n catch (e) {\r\n return null;\r\n }\r\n }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Provider for generating an {@link OAuthCredential} for {@link ProviderId}.TWITTER.\r\n *\r\n * @example\r\n * ```javascript\r\n * // Sign in using a redirect.\r\n * const provider = new TwitterAuthProvider();\r\n * // Start a sign in process for an unauthenticated user.\r\n * await signInWithRedirect(auth, provider);\r\n * // This will trigger a full page redirect away from your app\r\n *\r\n * // After returning from the redirect when your app initializes you can obtain the result\r\n * const result = await getRedirectResult(auth);\r\n * if (result) {\r\n * // This is the signed-in user\r\n * const user = result.user;\r\n * // This gives you a Twitter Access Token and Secret.\r\n * const credential = TwitterAuthProvider.credentialFromResult(result);\r\n * const token = credential.accessToken;\r\n * const secret = credential.secret;\r\n * }\r\n * ```\r\n *\r\n * @example\r\n * ```javascript\r\n * // Sign in using a popup.\r\n * const provider = new TwitterAuthProvider();\r\n * const result = await signInWithPopup(auth, provider);\r\n *\r\n * // The signed-in user info.\r\n * const user = result.user;\r\n * // This gives you a Twitter Access Token and Secret.\r\n * const credential = TwitterAuthProvider.credentialFromResult(result);\r\n * const token = credential.accessToken;\r\n * const secret = credential.secret;\r\n * ```\r\n *\r\n * @public\r\n */\r\nclass TwitterAuthProvider extends BaseOAuthProvider {\r\n constructor() {\r\n super(\"twitter.com\" /* ProviderId.TWITTER */);\r\n }\r\n /**\r\n * Creates a credential for Twitter.\r\n *\r\n * @param token - Twitter access token.\r\n * @param secret - Twitter secret.\r\n */\r\n static credential(token, secret) {\r\n return OAuthCredential._fromParams({\r\n providerId: TwitterAuthProvider.PROVIDER_ID,\r\n signInMethod: TwitterAuthProvider.TWITTER_SIGN_IN_METHOD,\r\n oauthToken: token,\r\n oauthTokenSecret: secret\r\n });\r\n }\r\n /**\r\n * Used to extract the underlying {@link OAuthCredential} from a {@link UserCredential}.\r\n *\r\n * @param userCredential - The user credential.\r\n */\r\n static credentialFromResult(userCredential) {\r\n return TwitterAuthProvider.credentialFromTaggedObject(userCredential);\r\n }\r\n /**\r\n * Used to extract the underlying {@link OAuthCredential} from a {@link AuthError} which was\r\n * thrown during a sign-in, link, or reauthenticate operation.\r\n *\r\n * @param userCredential - The user credential.\r\n */\r\n static credentialFromError(error) {\r\n return TwitterAuthProvider.credentialFromTaggedObject((error.customData || {}));\r\n }\r\n static credentialFromTaggedObject({ _tokenResponse: tokenResponse }) {\r\n if (!tokenResponse) {\r\n return null;\r\n }\r\n const { oauthAccessToken, oauthTokenSecret } = tokenResponse;\r\n if (!oauthAccessToken || !oauthTokenSecret) {\r\n return null;\r\n }\r\n try {\r\n return TwitterAuthProvider.credential(oauthAccessToken, oauthTokenSecret);\r\n }\r\n catch (_a) {\r\n return null;\r\n }\r\n }\r\n}\r\n/** Always set to {@link SignInMethod}.TWITTER. */\r\nTwitterAuthProvider.TWITTER_SIGN_IN_METHOD = \"twitter.com\" /* SignInMethod.TWITTER */;\r\n/** Always set to {@link ProviderId}.TWITTER. */\r\nTwitterAuthProvider.PROVIDER_ID = \"twitter.com\" /* ProviderId.TWITTER */;\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nasync function signUp(auth, request) {\r\n return _performSignInRequest(auth, \"POST\" /* HttpMethod.POST */, \"/v1/accounts:signUp\" /* Endpoint.SIGN_UP */, _addTidIfNecessary(auth, request));\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nclass UserCredentialImpl {\r\n constructor(params) {\r\n this.user = params.user;\r\n this.providerId = params.providerId;\r\n this._tokenResponse = params._tokenResponse;\r\n this.operationType = params.operationType;\r\n }\r\n static async _fromIdTokenResponse(auth, operationType, idTokenResponse, isAnonymous = false) {\r\n const user = await UserImpl._fromIdTokenResponse(auth, idTokenResponse, isAnonymous);\r\n const providerId = providerIdForResponse(idTokenResponse);\r\n const userCred = new UserCredentialImpl({\r\n user,\r\n providerId,\r\n _tokenResponse: idTokenResponse,\r\n operationType\r\n });\r\n return userCred;\r\n }\r\n static async _forOperation(user, operationType, response) {\r\n await user._updateTokensIfNecessary(response, /* reload */ true);\r\n const providerId = providerIdForResponse(response);\r\n return new UserCredentialImpl({\r\n user,\r\n providerId,\r\n _tokenResponse: response,\r\n operationType\r\n });\r\n }\r\n}\r\nfunction providerIdForResponse(response) {\r\n if (response.providerId) {\r\n return response.providerId;\r\n }\r\n if ('phoneNumber' in response) {\r\n return \"phone\" /* ProviderId.PHONE */;\r\n }\r\n return null;\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Asynchronously signs in as an anonymous user.\r\n *\r\n * @remarks\r\n * If there is already an anonymous user signed in, that user will be returned; otherwise, a\r\n * new anonymous user identity will be created and returned.\r\n *\r\n * @param auth - The {@link Auth} instance.\r\n *\r\n * @public\r\n */\r\nasync function signInAnonymously(auth) {\r\n var _a;\r\n const authInternal = _castAuth(auth);\r\n await authInternal._initializationPromise;\r\n if ((_a = authInternal.currentUser) === null || _a === void 0 ? void 0 : _a.isAnonymous) {\r\n // If an anonymous user is already signed in, no need to sign them in again.\r\n return new UserCredentialImpl({\r\n user: authInternal.currentUser,\r\n providerId: null,\r\n operationType: \"signIn\" /* OperationType.SIGN_IN */\r\n });\r\n }\r\n const response = await signUp(authInternal, {\r\n returnSecureToken: true\r\n });\r\n const userCredential = await UserCredentialImpl._fromIdTokenResponse(authInternal, \"signIn\" /* OperationType.SIGN_IN */, response, true);\r\n await authInternal._updateCurrentUser(userCredential.user);\r\n return userCredential;\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nclass MultiFactorError extends FirebaseError {\r\n constructor(auth, error, operationType, user) {\r\n var _a;\r\n super(error.code, error.message);\r\n this.operationType = operationType;\r\n this.user = user;\r\n // https://github.com/Microsoft/TypeScript-wiki/blob/master/Breaking-Changes.md#extending-built-ins-like-error-array-and-map-may-no-longer-work\r\n Object.setPrototypeOf(this, MultiFactorError.prototype);\r\n this.customData = {\r\n appName: auth.name,\r\n tenantId: (_a = auth.tenantId) !== null && _a !== void 0 ? _a : undefined,\r\n _serverResponse: error.customData._serverResponse,\r\n operationType\r\n };\r\n }\r\n static _fromErrorAndOperation(auth, error, operationType, user) {\r\n return new MultiFactorError(auth, error, operationType, user);\r\n }\r\n}\r\nfunction _processCredentialSavingMfaContextIfNecessary(auth, operationType, credential, user) {\r\n const idTokenProvider = operationType === \"reauthenticate\" /* OperationType.REAUTHENTICATE */\r\n ? credential._getReauthenticationResolver(auth)\r\n : credential._getIdTokenResponse(auth);\r\n return idTokenProvider.catch(error => {\r\n if (error.code === `auth/${\"multi-factor-auth-required\" /* AuthErrorCode.MFA_REQUIRED */}`) {\r\n throw MultiFactorError._fromErrorAndOperation(auth, error, operationType, user);\r\n }\r\n throw error;\r\n });\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Takes a set of UserInfo provider data and converts it to a set of names\r\n */\r\nfunction providerDataAsNames(providerData) {\r\n return new Set(providerData\r\n .map(({ providerId }) => providerId)\r\n .filter(pid => !!pid));\r\n}\n\n/**\r\n * @license\r\n * Copyright 2019 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Unlinks a provider from a user account.\r\n *\r\n * @param user - The user.\r\n * @param providerId - The provider to unlink.\r\n *\r\n * @public\r\n */\r\nasync function unlink(user, providerId) {\r\n const userInternal = getModularInstance(user);\r\n await _assertLinkedStatus(true, userInternal, providerId);\r\n const { providerUserInfo } = await deleteLinkedAccounts(userInternal.auth, {\r\n idToken: await userInternal.getIdToken(),\r\n deleteProvider: [providerId]\r\n });\r\n const providersLeft = providerDataAsNames(providerUserInfo || []);\r\n userInternal.providerData = userInternal.providerData.filter(pd => providersLeft.has(pd.providerId));\r\n if (!providersLeft.has(\"phone\" /* ProviderId.PHONE */)) {\r\n userInternal.phoneNumber = null;\r\n }\r\n await userInternal.auth._persistUserIfCurrent(userInternal);\r\n return userInternal;\r\n}\r\nasync function _link$1(user, credential, bypassAuthState = false) {\r\n const response = await _logoutIfInvalidated(user, credential._linkToIdToken(user.auth, await user.getIdToken()), bypassAuthState);\r\n return UserCredentialImpl._forOperation(user, \"link\" /* OperationType.LINK */, response);\r\n}\r\nasync function _assertLinkedStatus(expected, user, provider) {\r\n await _reloadWithoutSaving(user);\r\n const providerIds = providerDataAsNames(user.providerData);\r\n const code = expected === false\r\n ? \"provider-already-linked\" /* AuthErrorCode.PROVIDER_ALREADY_LINKED */\r\n : \"no-such-provider\" /* AuthErrorCode.NO_SUCH_PROVIDER */;\r\n _assert(providerIds.has(provider) === expected, user.auth, code);\r\n}\n\n/**\r\n * @license\r\n * Copyright 2019 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nasync function _reauthenticate(user, credential, bypassAuthState = false) {\r\n const { auth } = user;\r\n const operationType = \"reauthenticate\" /* OperationType.REAUTHENTICATE */;\r\n try {\r\n const response = await _logoutIfInvalidated(user, _processCredentialSavingMfaContextIfNecessary(auth, operationType, credential, user), bypassAuthState);\r\n _assert(response.idToken, auth, \"internal-error\" /* AuthErrorCode.INTERNAL_ERROR */);\r\n const parsed = _parseToken(response.idToken);\r\n _assert(parsed, auth, \"internal-error\" /* AuthErrorCode.INTERNAL_ERROR */);\r\n const { sub: localId } = parsed;\r\n _assert(user.uid === localId, auth, \"user-mismatch\" /* AuthErrorCode.USER_MISMATCH */);\r\n return UserCredentialImpl._forOperation(user, operationType, response);\r\n }\r\n catch (e) {\r\n // Convert user deleted error into user mismatch\r\n if ((e === null || e === void 0 ? void 0 : e.code) === `auth/${\"user-not-found\" /* AuthErrorCode.USER_DELETED */}`) {\r\n _fail(auth, \"user-mismatch\" /* AuthErrorCode.USER_MISMATCH */);\r\n }\r\n throw e;\r\n }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nasync function _signInWithCredential(auth, credential, bypassAuthState = false) {\r\n const operationType = \"signIn\" /* OperationType.SIGN_IN */;\r\n const response = await _processCredentialSavingMfaContextIfNecessary(auth, operationType, credential);\r\n const userCredential = await UserCredentialImpl._fromIdTokenResponse(auth, operationType, response);\r\n if (!bypassAuthState) {\r\n await auth._updateCurrentUser(userCredential.user);\r\n }\r\n return userCredential;\r\n}\r\n/**\r\n * Asynchronously signs in with the given credentials.\r\n *\r\n * @remarks\r\n * An {@link AuthProvider} can be used to generate the credential.\r\n *\r\n * @param auth - The {@link Auth} instance.\r\n * @param credential - The auth credential.\r\n *\r\n * @public\r\n */\r\nasync function signInWithCredential(auth, credential) {\r\n return _signInWithCredential(_castAuth(auth), credential);\r\n}\r\n/**\r\n * Links the user account with the given credentials.\r\n *\r\n * @remarks\r\n * An {@link AuthProvider} can be used to generate the credential.\r\n *\r\n * @param user - The user.\r\n * @param credential - The auth credential.\r\n *\r\n * @public\r\n */\r\nasync function linkWithCredential(user, credential) {\r\n const userInternal = getModularInstance(user);\r\n await _assertLinkedStatus(false, userInternal, credential.providerId);\r\n return _link$1(userInternal, credential);\r\n}\r\n/**\r\n * Re-authenticates a user using a fresh credential.\r\n *\r\n * @remarks\r\n * Use before operations such as {@link updatePassword} that require tokens from recent sign-in\r\n * attempts. This method can be used to recover from a `CREDENTIAL_TOO_OLD_LOGIN_AGAIN` error\r\n * or a `TOKEN_EXPIRED` error.\r\n *\r\n * @param user - The user.\r\n * @param credential - The auth credential.\r\n *\r\n * @public\r\n */\r\nasync function reauthenticateWithCredential(user, credential) {\r\n return _reauthenticate(getModularInstance(user), credential);\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nasync function signInWithCustomToken$1(auth, request) {\r\n return _performSignInRequest(auth, \"POST\" /* HttpMethod.POST */, \"/v1/accounts:signInWithCustomToken\" /* Endpoint.SIGN_IN_WITH_CUSTOM_TOKEN */, _addTidIfNecessary(auth, request));\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Asynchronously signs in using a custom token.\r\n *\r\n * @remarks\r\n * Custom tokens are used to integrate Firebase Auth with existing auth systems, and must\r\n * be generated by an auth backend using the\r\n * {@link https://firebase.google.com/docs/reference/admin/node/admin.auth.Auth#createcustomtoken | createCustomToken}\r\n * method in the {@link https://firebase.google.com/docs/auth/admin | Admin SDK} .\r\n *\r\n * Fails with an error if the token is invalid, expired, or not accepted by the Firebase Auth service.\r\n *\r\n * @param auth - The {@link Auth} instance.\r\n * @param customToken - The custom token to sign in with.\r\n *\r\n * @public\r\n */\r\nasync function signInWithCustomToken(auth, customToken) {\r\n const authInternal = _castAuth(auth);\r\n const response = await signInWithCustomToken$1(authInternal, {\r\n token: customToken,\r\n returnSecureToken: true\r\n });\r\n const cred = await UserCredentialImpl._fromIdTokenResponse(authInternal, \"signIn\" /* OperationType.SIGN_IN */, response);\r\n await authInternal._updateCurrentUser(cred.user);\r\n return cred;\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nclass MultiFactorInfoImpl {\r\n constructor(factorId, response) {\r\n this.factorId = factorId;\r\n this.uid = response.mfaEnrollmentId;\r\n this.enrollmentTime = new Date(response.enrolledAt).toUTCString();\r\n this.displayName = response.displayName;\r\n }\r\n static _fromServerResponse(auth, enrollment) {\r\n if ('phoneInfo' in enrollment) {\r\n return PhoneMultiFactorInfoImpl._fromServerResponse(auth, enrollment);\r\n }\r\n else if ('totpInfo' in enrollment) {\r\n return TotpMultiFactorInfoImpl._fromServerResponse(auth, enrollment);\r\n }\r\n return _fail(auth, \"internal-error\" /* AuthErrorCode.INTERNAL_ERROR */);\r\n }\r\n}\r\nclass PhoneMultiFactorInfoImpl extends MultiFactorInfoImpl {\r\n constructor(response) {\r\n super(\"phone\" /* FactorId.PHONE */, response);\r\n this.phoneNumber = response.phoneInfo;\r\n }\r\n static _fromServerResponse(_auth, enrollment) {\r\n return new PhoneMultiFactorInfoImpl(enrollment);\r\n }\r\n}\r\nclass TotpMultiFactorInfoImpl extends MultiFactorInfoImpl {\r\n constructor(response) {\r\n super(\"totp\" /* FactorId.TOTP */, response);\r\n }\r\n static _fromServerResponse(_auth, enrollment) {\r\n return new TotpMultiFactorInfoImpl(enrollment);\r\n }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nfunction _setActionCodeSettingsOnRequest(auth, request, actionCodeSettings) {\r\n var _a;\r\n _assert(((_a = actionCodeSettings.url) === null || _a === void 0 ? void 0 : _a.length) > 0, auth, \"invalid-continue-uri\" /* AuthErrorCode.INVALID_CONTINUE_URI */);\r\n _assert(typeof actionCodeSettings.dynamicLinkDomain === 'undefined' ||\r\n actionCodeSettings.dynamicLinkDomain.length > 0, auth, \"invalid-dynamic-link-domain\" /* AuthErrorCode.INVALID_DYNAMIC_LINK_DOMAIN */);\r\n request.continueUrl = actionCodeSettings.url;\r\n request.dynamicLinkDomain = actionCodeSettings.dynamicLinkDomain;\r\n request.canHandleCodeInApp = actionCodeSettings.handleCodeInApp;\r\n if (actionCodeSettings.iOS) {\r\n _assert(actionCodeSettings.iOS.bundleId.length > 0, auth, \"missing-ios-bundle-id\" /* AuthErrorCode.MISSING_IOS_BUNDLE_ID */);\r\n request.iOSBundleId = actionCodeSettings.iOS.bundleId;\r\n }\r\n if (actionCodeSettings.android) {\r\n _assert(actionCodeSettings.android.packageName.length > 0, auth, \"missing-android-pkg-name\" /* AuthErrorCode.MISSING_ANDROID_PACKAGE_NAME */);\r\n request.androidInstallApp = actionCodeSettings.android.installApp;\r\n request.androidMinimumVersionCode =\r\n actionCodeSettings.android.minimumVersion;\r\n request.androidPackageName = actionCodeSettings.android.packageName;\r\n }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Sends a password reset email to the given email address.\r\n *\r\n * @remarks\r\n * To complete the password reset, call {@link confirmPasswordReset} with the code supplied in\r\n * the email sent to the user, along with the new password specified by the user.\r\n *\r\n * @example\r\n * ```javascript\r\n * const actionCodeSettings = {\r\n * url: 'https://www.example.com/?email=user@example.com',\r\n * iOS: {\r\n * bundleId: 'com.example.ios'\r\n * },\r\n * android: {\r\n * packageName: 'com.example.android',\r\n * installApp: true,\r\n * minimumVersion: '12'\r\n * },\r\n * handleCodeInApp: true\r\n * };\r\n * await sendPasswordResetEmail(auth, 'user@example.com', actionCodeSettings);\r\n * // Obtain code from user.\r\n * await confirmPasswordReset('user@example.com', code);\r\n * ```\r\n *\r\n * @param auth - The {@link Auth} instance.\r\n * @param email - The user's email address.\r\n * @param actionCodeSettings - The {@link ActionCodeSettings}.\r\n *\r\n * @public\r\n */\r\nasync function sendPasswordResetEmail(auth, email, actionCodeSettings) {\r\n var _a;\r\n const authInternal = _castAuth(auth);\r\n const request = {\r\n requestType: \"PASSWORD_RESET\" /* ActionCodeOperation.PASSWORD_RESET */,\r\n email,\r\n clientType: \"CLIENT_TYPE_WEB\" /* RecaptchaClientType.WEB */\r\n };\r\n if ((_a = authInternal._getRecaptchaConfig()) === null || _a === void 0 ? void 0 : _a.emailPasswordEnabled) {\r\n const requestWithRecaptcha = await injectRecaptchaFields(authInternal, request, \"getOobCode\" /* RecaptchaActionName.GET_OOB_CODE */, true);\r\n if (actionCodeSettings) {\r\n _setActionCodeSettingsOnRequest(authInternal, requestWithRecaptcha, actionCodeSettings);\r\n }\r\n await sendPasswordResetEmail$1(authInternal, requestWithRecaptcha);\r\n }\r\n else {\r\n if (actionCodeSettings) {\r\n _setActionCodeSettingsOnRequest(authInternal, request, actionCodeSettings);\r\n }\r\n await sendPasswordResetEmail$1(authInternal, request)\r\n .catch(async (error) => {\r\n if (error.code === `auth/${\"missing-recaptcha-token\" /* AuthErrorCode.MISSING_RECAPTCHA_TOKEN */}`) {\r\n console.log('Password resets are protected by reCAPTCHA for this project. Automatically triggering the reCAPTCHA flow and restarting the password reset flow.');\r\n const requestWithRecaptcha = await injectRecaptchaFields(authInternal, request, \"getOobCode\" /* RecaptchaActionName.GET_OOB_CODE */, true);\r\n if (actionCodeSettings) {\r\n _setActionCodeSettingsOnRequest(authInternal, requestWithRecaptcha, actionCodeSettings);\r\n }\r\n await sendPasswordResetEmail$1(authInternal, requestWithRecaptcha);\r\n }\r\n else {\r\n return Promise.reject(error);\r\n }\r\n });\r\n }\r\n}\r\n/**\r\n * Completes the password reset process, given a confirmation code and new password.\r\n *\r\n * @param auth - The {@link Auth} instance.\r\n * @param oobCode - A confirmation code sent to the user.\r\n * @param newPassword - The new password.\r\n *\r\n * @public\r\n */\r\nasync function confirmPasswordReset(auth, oobCode, newPassword) {\r\n await resetPassword(getModularInstance(auth), {\r\n oobCode,\r\n newPassword\r\n });\r\n // Do not return the email.\r\n}\r\n/**\r\n * Applies a verification code sent to the user by email or other out-of-band mechanism.\r\n *\r\n * @param auth - The {@link Auth} instance.\r\n * @param oobCode - A verification code sent to the user.\r\n *\r\n * @public\r\n */\r\nasync function applyActionCode(auth, oobCode) {\r\n await applyActionCode$1(getModularInstance(auth), { oobCode });\r\n}\r\n/**\r\n * Checks a verification code sent to the user by email or other out-of-band mechanism.\r\n *\r\n * @returns metadata about the code.\r\n *\r\n * @param auth - The {@link Auth} instance.\r\n * @param oobCode - A verification code sent to the user.\r\n *\r\n * @public\r\n */\r\nasync function checkActionCode(auth, oobCode) {\r\n const authModular = getModularInstance(auth);\r\n const response = await resetPassword(authModular, { oobCode });\r\n // Email could be empty only if the request type is EMAIL_SIGNIN or\r\n // VERIFY_AND_CHANGE_EMAIL.\r\n // New email should not be empty if the request type is\r\n // VERIFY_AND_CHANGE_EMAIL.\r\n // Multi-factor info could not be empty if the request type is\r\n // REVERT_SECOND_FACTOR_ADDITION.\r\n const operation = response.requestType;\r\n _assert(operation, authModular, \"internal-error\" /* AuthErrorCode.INTERNAL_ERROR */);\r\n switch (operation) {\r\n case \"EMAIL_SIGNIN\" /* ActionCodeOperation.EMAIL_SIGNIN */:\r\n break;\r\n case \"VERIFY_AND_CHANGE_EMAIL\" /* ActionCodeOperation.VERIFY_AND_CHANGE_EMAIL */:\r\n _assert(response.newEmail, authModular, \"internal-error\" /* AuthErrorCode.INTERNAL_ERROR */);\r\n break;\r\n case \"REVERT_SECOND_FACTOR_ADDITION\" /* ActionCodeOperation.REVERT_SECOND_FACTOR_ADDITION */:\r\n _assert(response.mfaInfo, authModular, \"internal-error\" /* AuthErrorCode.INTERNAL_ERROR */);\r\n // fall through\r\n default:\r\n _assert(response.email, authModular, \"internal-error\" /* AuthErrorCode.INTERNAL_ERROR */);\r\n }\r\n // The multi-factor info for revert second factor addition\r\n let multiFactorInfo = null;\r\n if (response.mfaInfo) {\r\n multiFactorInfo = MultiFactorInfoImpl._fromServerResponse(_castAuth(authModular), response.mfaInfo);\r\n }\r\n return {\r\n data: {\r\n email: (response.requestType === \"VERIFY_AND_CHANGE_EMAIL\" /* ActionCodeOperation.VERIFY_AND_CHANGE_EMAIL */\r\n ? response.newEmail\r\n : response.email) || null,\r\n previousEmail: (response.requestType === \"VERIFY_AND_CHANGE_EMAIL\" /* ActionCodeOperation.VERIFY_AND_CHANGE_EMAIL */\r\n ? response.email\r\n : response.newEmail) || null,\r\n multiFactorInfo\r\n },\r\n operation\r\n };\r\n}\r\n/**\r\n * Checks a password reset code sent to the user by email or other out-of-band mechanism.\r\n *\r\n * @returns the user's email address if valid.\r\n *\r\n * @param auth - The {@link Auth} instance.\r\n * @param code - A verification code sent to the user.\r\n *\r\n * @public\r\n */\r\nasync function verifyPasswordResetCode(auth, code) {\r\n const { data } = await checkActionCode(getModularInstance(auth), code);\r\n // Email should always be present since a code was sent to it\r\n return data.email;\r\n}\r\n/**\r\n * Creates a new user account associated with the specified email address and password.\r\n *\r\n * @remarks\r\n * On successful creation of the user account, this user will also be signed in to your application.\r\n *\r\n * User account creation can fail if the account already exists or the password is invalid.\r\n *\r\n * Note: The email address acts as a unique identifier for the user and enables an email-based\r\n * password reset. This function will create a new user account and set the initial user password.\r\n *\r\n * @param auth - The {@link Auth} instance.\r\n * @param email - The user's email address.\r\n * @param password - The user's chosen password.\r\n *\r\n * @public\r\n */\r\nasync function createUserWithEmailAndPassword(auth, email, password) {\r\n var _a;\r\n const authInternal = _castAuth(auth);\r\n const request = {\r\n returnSecureToken: true,\r\n email,\r\n password,\r\n clientType: \"CLIENT_TYPE_WEB\" /* RecaptchaClientType.WEB */\r\n };\r\n let signUpResponse;\r\n if ((_a = authInternal._getRecaptchaConfig()) === null || _a === void 0 ? void 0 : _a.emailPasswordEnabled) {\r\n const requestWithRecaptcha = await injectRecaptchaFields(authInternal, request, \"signUpPassword\" /* RecaptchaActionName.SIGN_UP_PASSWORD */);\r\n signUpResponse = signUp(authInternal, requestWithRecaptcha);\r\n }\r\n else {\r\n signUpResponse = signUp(authInternal, request).catch(async (error) => {\r\n if (error.code === `auth/${\"missing-recaptcha-token\" /* AuthErrorCode.MISSING_RECAPTCHA_TOKEN */}`) {\r\n console.log('Sign-up is protected by reCAPTCHA for this project. Automatically triggering the reCAPTCHA flow and restarting the sign-up flow.');\r\n const requestWithRecaptcha = await injectRecaptchaFields(authInternal, request, \"signUpPassword\" /* RecaptchaActionName.SIGN_UP_PASSWORD */);\r\n return signUp(authInternal, requestWithRecaptcha);\r\n }\r\n else {\r\n return Promise.reject(error);\r\n }\r\n });\r\n }\r\n const response = await signUpResponse.catch(error => {\r\n return Promise.reject(error);\r\n });\r\n const userCredential = await UserCredentialImpl._fromIdTokenResponse(authInternal, \"signIn\" /* OperationType.SIGN_IN */, response);\r\n await authInternal._updateCurrentUser(userCredential.user);\r\n return userCredential;\r\n}\r\n/**\r\n * Asynchronously signs in using an email and password.\r\n *\r\n * @remarks\r\n * Fails with an error if the email address and password do not match.\r\n *\r\n * Note: The user's password is NOT the password used to access the user's email account. The\r\n * email address serves as a unique identifier for the user, and the password is used to access\r\n * the user's account in your Firebase project. See also: {@link createUserWithEmailAndPassword}.\r\n *\r\n * @param auth - The {@link Auth} instance.\r\n * @param email - The users email address.\r\n * @param password - The users password.\r\n *\r\n * @public\r\n */\r\nfunction signInWithEmailAndPassword(auth, email, password) {\r\n return signInWithCredential(getModularInstance(auth), EmailAuthProvider.credential(email, password));\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Sends a sign-in email link to the user with the specified email.\r\n *\r\n * @remarks\r\n * The sign-in operation has to always be completed in the app unlike other out of band email\r\n * actions (password reset and email verifications). This is because, at the end of the flow,\r\n * the user is expected to be signed in and their Auth state persisted within the app.\r\n *\r\n * To complete sign in with the email link, call {@link signInWithEmailLink} with the email\r\n * address and the email link supplied in the email sent to the user.\r\n *\r\n * @example\r\n * ```javascript\r\n * const actionCodeSettings = {\r\n * url: 'https://www.example.com/?email=user@example.com',\r\n * iOS: {\r\n * bundleId: 'com.example.ios'\r\n * },\r\n * android: {\r\n * packageName: 'com.example.android',\r\n * installApp: true,\r\n * minimumVersion: '12'\r\n * },\r\n * handleCodeInApp: true\r\n * };\r\n * await sendSignInLinkToEmail(auth, 'user@example.com', actionCodeSettings);\r\n * // Obtain emailLink from the user.\r\n * if(isSignInWithEmailLink(auth, emailLink)) {\r\n * await signInWithEmailLink(auth, 'user@example.com', emailLink);\r\n * }\r\n * ```\r\n *\r\n * @param authInternal - The {@link Auth} instance.\r\n * @param email - The user's email address.\r\n * @param actionCodeSettings - The {@link ActionCodeSettings}.\r\n *\r\n * @public\r\n */\r\nasync function sendSignInLinkToEmail(auth, email, actionCodeSettings) {\r\n var _a;\r\n const authInternal = _castAuth(auth);\r\n const request = {\r\n requestType: \"EMAIL_SIGNIN\" /* ActionCodeOperation.EMAIL_SIGNIN */,\r\n email,\r\n clientType: \"CLIENT_TYPE_WEB\" /* RecaptchaClientType.WEB */\r\n };\r\n function setActionCodeSettings(request, actionCodeSettings) {\r\n _assert(actionCodeSettings.handleCodeInApp, authInternal, \"argument-error\" /* AuthErrorCode.ARGUMENT_ERROR */);\r\n if (actionCodeSettings) {\r\n _setActionCodeSettingsOnRequest(authInternal, request, actionCodeSettings);\r\n }\r\n }\r\n if ((_a = authInternal._getRecaptchaConfig()) === null || _a === void 0 ? void 0 : _a.emailPasswordEnabled) {\r\n const requestWithRecaptcha = await injectRecaptchaFields(authInternal, request, \"getOobCode\" /* RecaptchaActionName.GET_OOB_CODE */, true);\r\n setActionCodeSettings(requestWithRecaptcha, actionCodeSettings);\r\n await sendSignInLinkToEmail$1(authInternal, requestWithRecaptcha);\r\n }\r\n else {\r\n setActionCodeSettings(request, actionCodeSettings);\r\n await sendSignInLinkToEmail$1(authInternal, request)\r\n .catch(async (error) => {\r\n if (error.code === `auth/${\"missing-recaptcha-token\" /* AuthErrorCode.MISSING_RECAPTCHA_TOKEN */}`) {\r\n console.log('Email link sign-in is protected by reCAPTCHA for this project. Automatically triggering the reCAPTCHA flow and restarting the sign-in flow.');\r\n const requestWithRecaptcha = await injectRecaptchaFields(authInternal, request, \"getOobCode\" /* RecaptchaActionName.GET_OOB_CODE */, true);\r\n setActionCodeSettings(requestWithRecaptcha, actionCodeSettings);\r\n await sendSignInLinkToEmail$1(authInternal, requestWithRecaptcha);\r\n }\r\n else {\r\n return Promise.reject(error);\r\n }\r\n });\r\n }\r\n}\r\n/**\r\n * Checks if an incoming link is a sign-in with email link suitable for {@link signInWithEmailLink}.\r\n *\r\n * @param auth - The {@link Auth} instance.\r\n * @param emailLink - The link sent to the user's email address.\r\n *\r\n * @public\r\n */\r\nfunction isSignInWithEmailLink(auth, emailLink) {\r\n const actionCodeUrl = ActionCodeURL.parseLink(emailLink);\r\n return (actionCodeUrl === null || actionCodeUrl === void 0 ? void 0 : actionCodeUrl.operation) === \"EMAIL_SIGNIN\" /* ActionCodeOperation.EMAIL_SIGNIN */;\r\n}\r\n/**\r\n * Asynchronously signs in using an email and sign-in email link.\r\n *\r\n * @remarks\r\n * If no link is passed, the link is inferred from the current URL.\r\n *\r\n * Fails with an error if the email address is invalid or OTP in email link expires.\r\n *\r\n * Note: Confirm the link is a sign-in email link before calling this method firebase.auth.Auth.isSignInWithEmailLink.\r\n *\r\n * @example\r\n * ```javascript\r\n * const actionCodeSettings = {\r\n * url: 'https://www.example.com/?email=user@example.com',\r\n * iOS: {\r\n * bundleId: 'com.example.ios'\r\n * },\r\n * android: {\r\n * packageName: 'com.example.android',\r\n * installApp: true,\r\n * minimumVersion: '12'\r\n * },\r\n * handleCodeInApp: true\r\n * };\r\n * await sendSignInLinkToEmail(auth, 'user@example.com', actionCodeSettings);\r\n * // Obtain emailLink from the user.\r\n * if(isSignInWithEmailLink(auth, emailLink)) {\r\n * await signInWithEmailLink(auth, 'user@example.com', emailLink);\r\n * }\r\n * ```\r\n *\r\n * @param auth - The {@link Auth} instance.\r\n * @param email - The user's email address.\r\n * @param emailLink - The link sent to the user's email address.\r\n *\r\n * @public\r\n */\r\nasync function signInWithEmailLink(auth, email, emailLink) {\r\n const authModular = getModularInstance(auth);\r\n const credential = EmailAuthProvider.credentialWithLink(email, emailLink || _getCurrentUrl());\r\n // Check if the tenant ID in the email link matches the tenant ID on Auth\r\n // instance.\r\n _assert(credential._tenantId === (authModular.tenantId || null), authModular, \"tenant-id-mismatch\" /* AuthErrorCode.TENANT_ID_MISMATCH */);\r\n return signInWithCredential(authModular, credential);\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nasync function createAuthUri(auth, request) {\r\n return _performApiRequest(auth, \"POST\" /* HttpMethod.POST */, \"/v1/accounts:createAuthUri\" /* Endpoint.CREATE_AUTH_URI */, _addTidIfNecessary(auth, request));\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Gets the list of possible sign in methods for the given email address.\r\n *\r\n * @remarks\r\n * This is useful to differentiate methods of sign-in for the same provider, eg.\r\n * {@link EmailAuthProvider} which has 2 methods of sign-in,\r\n * {@link SignInMethod}.EMAIL_PASSWORD and\r\n * {@link SignInMethod}.EMAIL_LINK.\r\n *\r\n * @param auth - The {@link Auth} instance.\r\n * @param email - The user's email address.\r\n *\r\n * @public\r\n */\r\nasync function fetchSignInMethodsForEmail(auth, email) {\r\n // createAuthUri returns an error if continue URI is not http or https.\r\n // For environments like Cordova, Chrome extensions, native frameworks, file\r\n // systems, etc, use http://localhost as continue URL.\r\n const continueUri = _isHttpOrHttps() ? _getCurrentUrl() : 'http://localhost';\r\n const request = {\r\n identifier: email,\r\n continueUri\r\n };\r\n const { signinMethods } = await createAuthUri(getModularInstance(auth), request);\r\n return signinMethods || [];\r\n}\r\n/**\r\n * Sends a verification email to a user.\r\n *\r\n * @remarks\r\n * The verification process is completed by calling {@link applyActionCode}.\r\n *\r\n * @example\r\n * ```javascript\r\n * const actionCodeSettings = {\r\n * url: 'https://www.example.com/?email=user@example.com',\r\n * iOS: {\r\n * bundleId: 'com.example.ios'\r\n * },\r\n * android: {\r\n * packageName: 'com.example.android',\r\n * installApp: true,\r\n * minimumVersion: '12'\r\n * },\r\n * handleCodeInApp: true\r\n * };\r\n * await sendEmailVerification(user, actionCodeSettings);\r\n * // Obtain code from the user.\r\n * await applyActionCode(auth, code);\r\n * ```\r\n *\r\n * @param user - The user.\r\n * @param actionCodeSettings - The {@link ActionCodeSettings}.\r\n *\r\n * @public\r\n */\r\nasync function sendEmailVerification(user, actionCodeSettings) {\r\n const userInternal = getModularInstance(user);\r\n const idToken = await user.getIdToken();\r\n const request = {\r\n requestType: \"VERIFY_EMAIL\" /* ActionCodeOperation.VERIFY_EMAIL */,\r\n idToken\r\n };\r\n if (actionCodeSettings) {\r\n _setActionCodeSettingsOnRequest(userInternal.auth, request, actionCodeSettings);\r\n }\r\n const { email } = await sendEmailVerification$1(userInternal.auth, request);\r\n if (email !== user.email) {\r\n await user.reload();\r\n }\r\n}\r\n/**\r\n * Sends a verification email to a new email address.\r\n *\r\n * @remarks\r\n * The user's email will be updated to the new one after being verified.\r\n *\r\n * If you have a custom email action handler, you can complete the verification process by calling\r\n * {@link applyActionCode}.\r\n *\r\n * @example\r\n * ```javascript\r\n * const actionCodeSettings = {\r\n * url: 'https://www.example.com/?email=user@example.com',\r\n * iOS: {\r\n * bundleId: 'com.example.ios'\r\n * },\r\n * android: {\r\n * packageName: 'com.example.android',\r\n * installApp: true,\r\n * minimumVersion: '12'\r\n * },\r\n * handleCodeInApp: true\r\n * };\r\n * await verifyBeforeUpdateEmail(user, 'newemail@example.com', actionCodeSettings);\r\n * // Obtain code from the user.\r\n * await applyActionCode(auth, code);\r\n * ```\r\n *\r\n * @param user - The user.\r\n * @param newEmail - The new email address to be verified before update.\r\n * @param actionCodeSettings - The {@link ActionCodeSettings}.\r\n *\r\n * @public\r\n */\r\nasync function verifyBeforeUpdateEmail(user, newEmail, actionCodeSettings) {\r\n const userInternal = getModularInstance(user);\r\n const idToken = await user.getIdToken();\r\n const request = {\r\n requestType: \"VERIFY_AND_CHANGE_EMAIL\" /* ActionCodeOperation.VERIFY_AND_CHANGE_EMAIL */,\r\n idToken,\r\n newEmail\r\n };\r\n if (actionCodeSettings) {\r\n _setActionCodeSettingsOnRequest(userInternal.auth, request, actionCodeSettings);\r\n }\r\n const { email } = await verifyAndChangeEmail(userInternal.auth, request);\r\n if (email !== user.email) {\r\n // If the local copy of the email on user is outdated, reload the\r\n // user.\r\n await user.reload();\r\n }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nasync function updateProfile$1(auth, request) {\r\n return _performApiRequest(auth, \"POST\" /* HttpMethod.POST */, \"/v1/accounts:update\" /* Endpoint.SET_ACCOUNT_INFO */, request);\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Updates a user's profile data.\r\n *\r\n * @param user - The user.\r\n * @param profile - The profile's `displayName` and `photoURL` to update.\r\n *\r\n * @public\r\n */\r\nasync function updateProfile(user, { displayName, photoURL: photoUrl }) {\r\n if (displayName === undefined && photoUrl === undefined) {\r\n return;\r\n }\r\n const userInternal = getModularInstance(user);\r\n const idToken = await userInternal.getIdToken();\r\n const profileRequest = {\r\n idToken,\r\n displayName,\r\n photoUrl,\r\n returnSecureToken: true\r\n };\r\n const response = await _logoutIfInvalidated(userInternal, updateProfile$1(userInternal.auth, profileRequest));\r\n userInternal.displayName = response.displayName || null;\r\n userInternal.photoURL = response.photoUrl || null;\r\n // Update the password provider as well\r\n const passwordProvider = userInternal.providerData.find(({ providerId }) => providerId === \"password\" /* ProviderId.PASSWORD */);\r\n if (passwordProvider) {\r\n passwordProvider.displayName = userInternal.displayName;\r\n passwordProvider.photoURL = userInternal.photoURL;\r\n }\r\n await userInternal._updateTokensIfNecessary(response);\r\n}\r\n/**\r\n * Updates the user's email address.\r\n *\r\n * @remarks\r\n * An email will be sent to the original email address (if it was set) that allows to revoke the\r\n * email address change, in order to protect them from account hijacking.\r\n *\r\n * Important: this is a security sensitive operation that requires the user to have recently signed\r\n * in. If this requirement isn't met, ask the user to authenticate again and then call\r\n * {@link reauthenticateWithCredential}.\r\n *\r\n * @param user - The user.\r\n * @param newEmail - The new email address.\r\n *\r\n * @public\r\n */\r\nfunction updateEmail(user, newEmail) {\r\n return updateEmailOrPassword(getModularInstance(user), newEmail, null);\r\n}\r\n/**\r\n * Updates the user's password.\r\n *\r\n * @remarks\r\n * Important: this is a security sensitive operation that requires the user to have recently signed\r\n * in. If this requirement isn't met, ask the user to authenticate again and then call\r\n * {@link reauthenticateWithCredential}.\r\n *\r\n * @param user - The user.\r\n * @param newPassword - The new password.\r\n *\r\n * @public\r\n */\r\nfunction updatePassword(user, newPassword) {\r\n return updateEmailOrPassword(getModularInstance(user), null, newPassword);\r\n}\r\nasync function updateEmailOrPassword(user, email, password) {\r\n const { auth } = user;\r\n const idToken = await user.getIdToken();\r\n const request = {\r\n idToken,\r\n returnSecureToken: true\r\n };\r\n if (email) {\r\n request.email = email;\r\n }\r\n if (password) {\r\n request.password = password;\r\n }\r\n const response = await _logoutIfInvalidated(user, updateEmailPassword(auth, request));\r\n await user._updateTokensIfNecessary(response, /* reload */ true);\r\n}\n\n/**\r\n * @license\r\n * Copyright 2019 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Parse the `AdditionalUserInfo` from the ID token response.\r\n *\r\n */\r\nfunction _fromIdTokenResponse(idTokenResponse) {\r\n var _a, _b;\r\n if (!idTokenResponse) {\r\n return null;\r\n }\r\n const { providerId } = idTokenResponse;\r\n const profile = idTokenResponse.rawUserInfo\r\n ? JSON.parse(idTokenResponse.rawUserInfo)\r\n : {};\r\n const isNewUser = idTokenResponse.isNewUser ||\r\n idTokenResponse.kind === \"identitytoolkit#SignupNewUserResponse\" /* IdTokenResponseKind.SignupNewUser */;\r\n if (!providerId && (idTokenResponse === null || idTokenResponse === void 0 ? void 0 : idTokenResponse.idToken)) {\r\n const signInProvider = (_b = (_a = _parseToken(idTokenResponse.idToken)) === null || _a === void 0 ? void 0 : _a.firebase) === null || _b === void 0 ? void 0 : _b['sign_in_provider'];\r\n if (signInProvider) {\r\n const filteredProviderId = signInProvider !== \"anonymous\" /* ProviderId.ANONYMOUS */ &&\r\n signInProvider !== \"custom\" /* ProviderId.CUSTOM */\r\n ? signInProvider\r\n : null;\r\n // Uses generic class in accordance with the legacy SDK.\r\n return new GenericAdditionalUserInfo(isNewUser, filteredProviderId);\r\n }\r\n }\r\n if (!providerId) {\r\n return null;\r\n }\r\n switch (providerId) {\r\n case \"facebook.com\" /* ProviderId.FACEBOOK */:\r\n return new FacebookAdditionalUserInfo(isNewUser, profile);\r\n case \"github.com\" /* ProviderId.GITHUB */:\r\n return new GithubAdditionalUserInfo(isNewUser, profile);\r\n case \"google.com\" /* ProviderId.GOOGLE */:\r\n return new GoogleAdditionalUserInfo(isNewUser, profile);\r\n case \"twitter.com\" /* ProviderId.TWITTER */:\r\n return new TwitterAdditionalUserInfo(isNewUser, profile, idTokenResponse.screenName || null);\r\n case \"custom\" /* ProviderId.CUSTOM */:\r\n case \"anonymous\" /* ProviderId.ANONYMOUS */:\r\n return new GenericAdditionalUserInfo(isNewUser, null);\r\n default:\r\n return new GenericAdditionalUserInfo(isNewUser, providerId, profile);\r\n }\r\n}\r\nclass GenericAdditionalUserInfo {\r\n constructor(isNewUser, providerId, profile = {}) {\r\n this.isNewUser = isNewUser;\r\n this.providerId = providerId;\r\n this.profile = profile;\r\n }\r\n}\r\nclass FederatedAdditionalUserInfoWithUsername extends GenericAdditionalUserInfo {\r\n constructor(isNewUser, providerId, profile, username) {\r\n super(isNewUser, providerId, profile);\r\n this.username = username;\r\n }\r\n}\r\nclass FacebookAdditionalUserInfo extends GenericAdditionalUserInfo {\r\n constructor(isNewUser, profile) {\r\n super(isNewUser, \"facebook.com\" /* ProviderId.FACEBOOK */, profile);\r\n }\r\n}\r\nclass GithubAdditionalUserInfo extends FederatedAdditionalUserInfoWithUsername {\r\n constructor(isNewUser, profile) {\r\n super(isNewUser, \"github.com\" /* ProviderId.GITHUB */, profile, typeof (profile === null || profile === void 0 ? void 0 : profile.login) === 'string' ? profile === null || profile === void 0 ? void 0 : profile.login : null);\r\n }\r\n}\r\nclass GoogleAdditionalUserInfo extends GenericAdditionalUserInfo {\r\n constructor(isNewUser, profile) {\r\n super(isNewUser, \"google.com\" /* ProviderId.GOOGLE */, profile);\r\n }\r\n}\r\nclass TwitterAdditionalUserInfo extends FederatedAdditionalUserInfoWithUsername {\r\n constructor(isNewUser, profile, screenName) {\r\n super(isNewUser, \"twitter.com\" /* ProviderId.TWITTER */, profile, screenName);\r\n }\r\n}\r\n/**\r\n * Extracts provider specific {@link AdditionalUserInfo} for the given credential.\r\n *\r\n * @param userCredential - The user credential.\r\n *\r\n * @public\r\n */\r\nfunction getAdditionalUserInfo(userCredential) {\r\n const { user, _tokenResponse } = userCredential;\r\n if (user.isAnonymous && !_tokenResponse) {\r\n // Handle the special case where signInAnonymously() gets called twice.\r\n // No network call is made so there's nothing to actually fill this in\r\n return {\r\n providerId: null,\r\n isNewUser: false,\r\n profile: null\r\n };\r\n }\r\n return _fromIdTokenResponse(_tokenResponse);\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n// Non-optional auth methods.\r\n/**\r\n * Changes the type of persistence on the {@link Auth} instance for the currently saved\r\n * `Auth` session and applies this type of persistence for future sign-in requests, including\r\n * sign-in with redirect requests.\r\n *\r\n * @remarks\r\n * This makes it easy for a user signing in to specify whether their session should be\r\n * remembered or not. It also makes it easier to never persist the `Auth` state for applications\r\n * that are shared by other users or have sensitive data.\r\n *\r\n * @example\r\n * ```javascript\r\n * setPersistence(auth, browserSessionPersistence);\r\n * ```\r\n *\r\n * @param auth - The {@link Auth} instance.\r\n * @param persistence - The {@link Persistence} to use.\r\n * @returns A `Promise` that resolves once the persistence change has completed\r\n *\r\n * @public\r\n */\r\nfunction setPersistence(auth, persistence) {\r\n return getModularInstance(auth).setPersistence(persistence);\r\n}\r\n/**\r\n * Loads the reCAPTCHA configuration into the `Auth` instance.\r\n *\r\n * @remarks\r\n * This will load the reCAPTCHA config, which indicates whether the reCAPTCHA\r\n * verification flow should be triggered for each auth provider, into the\r\n * current Auth session.\r\n *\r\n * If initializeRecaptchaConfig() is not invoked, the auth flow will always start\r\n * without reCAPTCHA verification. If the provider is configured to require reCAPTCHA\r\n * verification, the SDK will transparently load the reCAPTCHA config and restart the\r\n * auth flows.\r\n *\r\n * Thus, by calling this optional method, you will reduce the latency of future auth flows.\r\n * Loading the reCAPTCHA config early will also enhance the signal collected by reCAPTCHA.\r\n *\r\n * @example\r\n * ```javascript\r\n * initializeRecaptchaConfig(auth);\r\n * ```\r\n *\r\n * @param auth - The {@link Auth} instance.\r\n *\r\n * @public\r\n */\r\nfunction initializeRecaptchaConfig(auth) {\r\n const authInternal = _castAuth(auth);\r\n return authInternal.initializeRecaptchaConfig();\r\n}\r\n/**\r\n * Adds an observer for changes to the signed-in user's ID token.\r\n *\r\n * @remarks\r\n * This includes sign-in, sign-out, and token refresh events.\r\n * This will not be triggered automatically upon ID token expiration. Use {@link User.getIdToken} to refresh the ID token.\r\n *\r\n * @param auth - The {@link Auth} instance.\r\n * @param nextOrObserver - callback triggered on change.\r\n * @param error - Deprecated. This callback is never triggered. Errors\r\n * on signing in/out can be caught in promises returned from\r\n * sign-in/sign-out functions.\r\n * @param completed - Deprecated. This callback is never triggered.\r\n *\r\n * @public\r\n */\r\nfunction onIdTokenChanged(auth, nextOrObserver, error, completed) {\r\n return getModularInstance(auth).onIdTokenChanged(nextOrObserver, error, completed);\r\n}\r\n/**\r\n * Adds a blocking callback that runs before an auth state change\r\n * sets a new user.\r\n *\r\n * @param auth - The {@link Auth} instance.\r\n * @param callback - callback triggered before new user value is set.\r\n * If this throws, it blocks the user from being set.\r\n * @param onAbort - callback triggered if a later `beforeAuthStateChanged()`\r\n * callback throws, allowing you to undo any side effects.\r\n */\r\nfunction beforeAuthStateChanged(auth, callback, onAbort) {\r\n return getModularInstance(auth).beforeAuthStateChanged(callback, onAbort);\r\n}\r\n/**\r\n * Adds an observer for changes to the user's sign-in state.\r\n *\r\n * @remarks\r\n * To keep the old behavior, see {@link onIdTokenChanged}.\r\n *\r\n * @param auth - The {@link Auth} instance.\r\n * @param nextOrObserver - callback triggered on change.\r\n * @param error - Deprecated. This callback is never triggered. Errors\r\n * on signing in/out can be caught in promises returned from\r\n * sign-in/sign-out functions.\r\n * @param completed - Deprecated. This callback is never triggered.\r\n *\r\n * @public\r\n */\r\nfunction onAuthStateChanged(auth, nextOrObserver, error, completed) {\r\n return getModularInstance(auth).onAuthStateChanged(nextOrObserver, error, completed);\r\n}\r\n/**\r\n * Sets the current language to the default device/browser preference.\r\n *\r\n * @param auth - The {@link Auth} instance.\r\n *\r\n * @public\r\n */\r\nfunction useDeviceLanguage(auth) {\r\n getModularInstance(auth).useDeviceLanguage();\r\n}\r\n/**\r\n * Asynchronously sets the provided user as {@link Auth.currentUser} on the\r\n * {@link Auth} instance.\r\n *\r\n * @remarks\r\n * A new instance copy of the user provided will be made and set as currentUser.\r\n *\r\n * This will trigger {@link onAuthStateChanged} and {@link onIdTokenChanged} listeners\r\n * like other sign in methods.\r\n *\r\n * The operation fails with an error if the user to be updated belongs to a different Firebase\r\n * project.\r\n *\r\n * @param auth - The {@link Auth} instance.\r\n * @param user - The new {@link User}.\r\n *\r\n * @public\r\n */\r\nfunction updateCurrentUser(auth, user) {\r\n return getModularInstance(auth).updateCurrentUser(user);\r\n}\r\n/**\r\n * Signs out the current user.\r\n *\r\n * @param auth - The {@link Auth} instance.\r\n *\r\n * @public\r\n */\r\nfunction signOut(auth) {\r\n return getModularInstance(auth).signOut();\r\n}\r\n/**\r\n * Deletes and signs out the user.\r\n *\r\n * @remarks\r\n * Important: this is a security-sensitive operation that requires the user to have recently\r\n * signed in. If this requirement isn't met, ask the user to authenticate again and then call\r\n * {@link reauthenticateWithCredential}.\r\n *\r\n * @param user - The user.\r\n *\r\n * @public\r\n */\r\nasync function deleteUser(user) {\r\n return getModularInstance(user).delete();\r\n}\n\nclass MultiFactorSessionImpl {\r\n constructor(type, credential, auth) {\r\n this.type = type;\r\n this.credential = credential;\r\n this.auth = auth;\r\n }\r\n static _fromIdtoken(idToken, auth) {\r\n return new MultiFactorSessionImpl(\"enroll\" /* MultiFactorSessionType.ENROLL */, idToken, auth);\r\n }\r\n static _fromMfaPendingCredential(mfaPendingCredential) {\r\n return new MultiFactorSessionImpl(\"signin\" /* MultiFactorSessionType.SIGN_IN */, mfaPendingCredential);\r\n }\r\n toJSON() {\r\n const key = this.type === \"enroll\" /* MultiFactorSessionType.ENROLL */\r\n ? 'idToken'\r\n : 'pendingCredential';\r\n return {\r\n multiFactorSession: {\r\n [key]: this.credential\r\n }\r\n };\r\n }\r\n static fromJSON(obj) {\r\n var _a, _b;\r\n if (obj === null || obj === void 0 ? void 0 : obj.multiFactorSession) {\r\n if ((_a = obj.multiFactorSession) === null || _a === void 0 ? void 0 : _a.pendingCredential) {\r\n return MultiFactorSessionImpl._fromMfaPendingCredential(obj.multiFactorSession.pendingCredential);\r\n }\r\n else if ((_b = obj.multiFactorSession) === null || _b === void 0 ? void 0 : _b.idToken) {\r\n return MultiFactorSessionImpl._fromIdtoken(obj.multiFactorSession.idToken);\r\n }\r\n }\r\n return null;\r\n }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nclass MultiFactorResolverImpl {\r\n constructor(session, hints, signInResolver) {\r\n this.session = session;\r\n this.hints = hints;\r\n this.signInResolver = signInResolver;\r\n }\r\n /** @internal */\r\n static _fromError(authExtern, error) {\r\n const auth = _castAuth(authExtern);\r\n const serverResponse = error.customData._serverResponse;\r\n const hints = (serverResponse.mfaInfo || []).map(enrollment => MultiFactorInfoImpl._fromServerResponse(auth, enrollment));\r\n _assert(serverResponse.mfaPendingCredential, auth, \"internal-error\" /* AuthErrorCode.INTERNAL_ERROR */);\r\n const session = MultiFactorSessionImpl._fromMfaPendingCredential(serverResponse.mfaPendingCredential);\r\n return new MultiFactorResolverImpl(session, hints, async (assertion) => {\r\n const mfaResponse = await assertion._process(auth, session);\r\n // Clear out the unneeded fields from the old login response\r\n delete serverResponse.mfaInfo;\r\n delete serverResponse.mfaPendingCredential;\r\n // Use in the new token & refresh token in the old response\r\n const idTokenResponse = Object.assign(Object.assign({}, serverResponse), { idToken: mfaResponse.idToken, refreshToken: mfaResponse.refreshToken });\r\n // TODO: we should collapse this switch statement into UserCredentialImpl._forOperation and have it support the SIGN_IN case\r\n switch (error.operationType) {\r\n case \"signIn\" /* OperationType.SIGN_IN */:\r\n const userCredential = await UserCredentialImpl._fromIdTokenResponse(auth, error.operationType, idTokenResponse);\r\n await auth._updateCurrentUser(userCredential.user);\r\n return userCredential;\r\n case \"reauthenticate\" /* OperationType.REAUTHENTICATE */:\r\n _assert(error.user, auth, \"internal-error\" /* AuthErrorCode.INTERNAL_ERROR */);\r\n return UserCredentialImpl._forOperation(error.user, error.operationType, idTokenResponse);\r\n default:\r\n _fail(auth, \"internal-error\" /* AuthErrorCode.INTERNAL_ERROR */);\r\n }\r\n });\r\n }\r\n async resolveSignIn(assertionExtern) {\r\n const assertion = assertionExtern;\r\n return this.signInResolver(assertion);\r\n }\r\n}\r\n/**\r\n * Provides a {@link MultiFactorResolver} suitable for completion of a\r\n * multi-factor flow.\r\n *\r\n * @param auth - The {@link Auth} instance.\r\n * @param error - The {@link MultiFactorError} raised during a sign-in, or\r\n * reauthentication operation.\r\n *\r\n * @public\r\n */\r\nfunction getMultiFactorResolver(auth, error) {\r\n var _a;\r\n const authModular = getModularInstance(auth);\r\n const errorInternal = error;\r\n _assert(error.customData.operationType, authModular, \"argument-error\" /* AuthErrorCode.ARGUMENT_ERROR */);\r\n _assert((_a = errorInternal.customData._serverResponse) === null || _a === void 0 ? void 0 : _a.mfaPendingCredential, authModular, \"argument-error\" /* AuthErrorCode.ARGUMENT_ERROR */);\r\n return MultiFactorResolverImpl._fromError(authModular, errorInternal);\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nfunction startEnrollPhoneMfa(auth, request) {\r\n return _performApiRequest(auth, \"POST\" /* HttpMethod.POST */, \"/v2/accounts/mfaEnrollment:start\" /* Endpoint.START_MFA_ENROLLMENT */, _addTidIfNecessary(auth, request));\r\n}\r\nfunction finalizeEnrollPhoneMfa(auth, request) {\r\n return _performApiRequest(auth, \"POST\" /* HttpMethod.POST */, \"/v2/accounts/mfaEnrollment:finalize\" /* Endpoint.FINALIZE_MFA_ENROLLMENT */, _addTidIfNecessary(auth, request));\r\n}\r\nfunction startEnrollTotpMfa(auth, request) {\r\n return _performApiRequest(auth, \"POST\" /* HttpMethod.POST */, \"/v2/accounts/mfaEnrollment:start\" /* Endpoint.START_MFA_ENROLLMENT */, _addTidIfNecessary(auth, request));\r\n}\r\nfunction finalizeEnrollTotpMfa(auth, request) {\r\n return _performApiRequest(auth, \"POST\" /* HttpMethod.POST */, \"/v2/accounts/mfaEnrollment:finalize\" /* Endpoint.FINALIZE_MFA_ENROLLMENT */, _addTidIfNecessary(auth, request));\r\n}\r\nfunction withdrawMfa(auth, request) {\r\n return _performApiRequest(auth, \"POST\" /* HttpMethod.POST */, \"/v2/accounts/mfaEnrollment:withdraw\" /* Endpoint.WITHDRAW_MFA */, _addTidIfNecessary(auth, request));\r\n}\n\nclass MultiFactorUserImpl {\r\n constructor(user) {\r\n this.user = user;\r\n this.enrolledFactors = [];\r\n user._onReload(userInfo => {\r\n if (userInfo.mfaInfo) {\r\n this.enrolledFactors = userInfo.mfaInfo.map(enrollment => MultiFactorInfoImpl._fromServerResponse(user.auth, enrollment));\r\n }\r\n });\r\n }\r\n static _fromUser(user) {\r\n return new MultiFactorUserImpl(user);\r\n }\r\n async getSession() {\r\n return MultiFactorSessionImpl._fromIdtoken(await this.user.getIdToken(), this.user.auth);\r\n }\r\n async enroll(assertionExtern, displayName) {\r\n const assertion = assertionExtern;\r\n const session = (await this.getSession());\r\n const finalizeMfaResponse = await _logoutIfInvalidated(this.user, assertion._process(this.user.auth, session, displayName));\r\n // New tokens will be issued after enrollment of the new second factors.\r\n // They need to be updated on the user.\r\n await this.user._updateTokensIfNecessary(finalizeMfaResponse);\r\n // The user needs to be reloaded to get the new multi-factor information\r\n // from server. USER_RELOADED event will be triggered and `enrolledFactors`\r\n // will be updated.\r\n return this.user.reload();\r\n }\r\n async unenroll(infoOrUid) {\r\n const mfaEnrollmentId = typeof infoOrUid === 'string' ? infoOrUid : infoOrUid.uid;\r\n const idToken = await this.user.getIdToken();\r\n try {\r\n const idTokenResponse = await _logoutIfInvalidated(this.user, withdrawMfa(this.user.auth, {\r\n idToken,\r\n mfaEnrollmentId\r\n }));\r\n // Remove the second factor from the user's list.\r\n this.enrolledFactors = this.enrolledFactors.filter(({ uid }) => uid !== mfaEnrollmentId);\r\n // Depending on whether the backend decided to revoke the user's session,\r\n // the tokenResponse may be empty. If the tokens were not updated (and they\r\n // are now invalid), reloading the user will discover this and invalidate\r\n // the user's state accordingly.\r\n await this.user._updateTokensIfNecessary(idTokenResponse);\r\n await this.user.reload();\r\n }\r\n catch (e) {\r\n throw e;\r\n }\r\n }\r\n}\r\nconst multiFactorUserCache = new WeakMap();\r\n/**\r\n * The {@link MultiFactorUser} corresponding to the user.\r\n *\r\n * @remarks\r\n * This is used to access all multi-factor properties and operations related to the user.\r\n *\r\n * @param user - The user.\r\n *\r\n * @public\r\n */\r\nfunction multiFactor(user) {\r\n const userModular = getModularInstance(user);\r\n if (!multiFactorUserCache.has(userModular)) {\r\n multiFactorUserCache.set(userModular, MultiFactorUserImpl._fromUser(userModular));\r\n }\r\n return multiFactorUserCache.get(userModular);\r\n}\n\nconst STORAGE_AVAILABLE_KEY = '__sak';\n\n/**\r\n * @license\r\n * Copyright 2019 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n// There are two different browser persistence types: local and session.\r\n// Both have the same implementation but use a different underlying storage\r\n// object.\r\nclass BrowserPersistenceClass {\r\n constructor(storageRetriever, type) {\r\n this.storageRetriever = storageRetriever;\r\n this.type = type;\r\n }\r\n _isAvailable() {\r\n try {\r\n if (!this.storage) {\r\n return Promise.resolve(false);\r\n }\r\n this.storage.setItem(STORAGE_AVAILABLE_KEY, '1');\r\n this.storage.removeItem(STORAGE_AVAILABLE_KEY);\r\n return Promise.resolve(true);\r\n }\r\n catch (_a) {\r\n return Promise.resolve(false);\r\n }\r\n }\r\n _set(key, value) {\r\n this.storage.setItem(key, JSON.stringify(value));\r\n return Promise.resolve();\r\n }\r\n _get(key) {\r\n const json = this.storage.getItem(key);\r\n return Promise.resolve(json ? JSON.parse(json) : null);\r\n }\r\n _remove(key) {\r\n this.storage.removeItem(key);\r\n return Promise.resolve();\r\n }\r\n get storage() {\r\n return this.storageRetriever();\r\n }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nfunction _iframeCannotSyncWebStorage() {\r\n const ua = getUA();\r\n return _isSafari(ua) || _isIOS(ua);\r\n}\r\n// The polling period in case events are not supported\r\nconst _POLLING_INTERVAL_MS$1 = 1000;\r\n// The IE 10 localStorage cross tab synchronization delay in milliseconds\r\nconst IE10_LOCAL_STORAGE_SYNC_DELAY = 10;\r\nclass BrowserLocalPersistence extends BrowserPersistenceClass {\r\n constructor() {\r\n super(() => window.localStorage, \"LOCAL\" /* PersistenceType.LOCAL */);\r\n this.boundEventHandler = (event, poll) => this.onStorageEvent(event, poll);\r\n this.listeners = {};\r\n this.localCache = {};\r\n // setTimeout return value is platform specific\r\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\r\n this.pollTimer = null;\r\n // Safari or iOS browser and embedded in an iframe.\r\n this.safariLocalStorageNotSynced = _iframeCannotSyncWebStorage() && _isIframe();\r\n // Whether to use polling instead of depending on window events\r\n this.fallbackToPolling = _isMobileBrowser();\r\n this._shouldAllowMigration = true;\r\n }\r\n forAllChangedKeys(cb) {\r\n // Check all keys with listeners on them.\r\n for (const key of Object.keys(this.listeners)) {\r\n // Get value from localStorage.\r\n const newValue = this.storage.getItem(key);\r\n const oldValue = this.localCache[key];\r\n // If local map value does not match, trigger listener with storage event.\r\n // Differentiate this simulated event from the real storage event.\r\n if (newValue !== oldValue) {\r\n cb(key, oldValue, newValue);\r\n }\r\n }\r\n }\r\n onStorageEvent(event, poll = false) {\r\n // Key would be null in some situations, like when localStorage is cleared\r\n if (!event.key) {\r\n this.forAllChangedKeys((key, _oldValue, newValue) => {\r\n this.notifyListeners(key, newValue);\r\n });\r\n return;\r\n }\r\n const key = event.key;\r\n // Check the mechanism how this event was detected.\r\n // The first event will dictate the mechanism to be used.\r\n if (poll) {\r\n // Environment detects storage changes via polling.\r\n // Remove storage event listener to prevent possible event duplication.\r\n this.detachListener();\r\n }\r\n else {\r\n // Environment detects storage changes via storage event listener.\r\n // Remove polling listener to prevent possible event duplication.\r\n this.stopPolling();\r\n }\r\n // Safari embedded iframe. Storage event will trigger with the delta\r\n // changes but no changes will be applied to the iframe localStorage.\r\n if (this.safariLocalStorageNotSynced) {\r\n // Get current iframe page value.\r\n const storedValue = this.storage.getItem(key);\r\n // Value not synchronized, synchronize manually.\r\n if (event.newValue !== storedValue) {\r\n if (event.newValue !== null) {\r\n // Value changed from current value.\r\n this.storage.setItem(key, event.newValue);\r\n }\r\n else {\r\n // Current value deleted.\r\n this.storage.removeItem(key);\r\n }\r\n }\r\n else if (this.localCache[key] === event.newValue && !poll) {\r\n // Already detected and processed, do not trigger listeners again.\r\n return;\r\n }\r\n }\r\n const triggerListeners = () => {\r\n // Keep local map up to date in case storage event is triggered before\r\n // poll.\r\n const storedValue = this.storage.getItem(key);\r\n if (!poll && this.localCache[key] === storedValue) {\r\n // Real storage event which has already been detected, do nothing.\r\n // This seems to trigger in some IE browsers for some reason.\r\n return;\r\n }\r\n this.notifyListeners(key, storedValue);\r\n };\r\n const storedValue = this.storage.getItem(key);\r\n if (_isIE10() &&\r\n storedValue !== event.newValue &&\r\n event.newValue !== event.oldValue) {\r\n // IE 10 has this weird bug where a storage event would trigger with the\r\n // correct key, oldValue and newValue but localStorage.getItem(key) does\r\n // not yield the updated value until a few milliseconds. This ensures\r\n // this recovers from that situation.\r\n setTimeout(triggerListeners, IE10_LOCAL_STORAGE_SYNC_DELAY);\r\n }\r\n else {\r\n triggerListeners();\r\n }\r\n }\r\n notifyListeners(key, value) {\r\n this.localCache[key] = value;\r\n const listeners = this.listeners[key];\r\n if (listeners) {\r\n for (const listener of Array.from(listeners)) {\r\n listener(value ? JSON.parse(value) : value);\r\n }\r\n }\r\n }\r\n startPolling() {\r\n this.stopPolling();\r\n this.pollTimer = setInterval(() => {\r\n this.forAllChangedKeys((key, oldValue, newValue) => {\r\n this.onStorageEvent(new StorageEvent('storage', {\r\n key,\r\n oldValue,\r\n newValue\r\n }), \r\n /* poll */ true);\r\n });\r\n }, _POLLING_INTERVAL_MS$1);\r\n }\r\n stopPolling() {\r\n if (this.pollTimer) {\r\n clearInterval(this.pollTimer);\r\n this.pollTimer = null;\r\n }\r\n }\r\n attachListener() {\r\n window.addEventListener('storage', this.boundEventHandler);\r\n }\r\n detachListener() {\r\n window.removeEventListener('storage', this.boundEventHandler);\r\n }\r\n _addListener(key, listener) {\r\n if (Object.keys(this.listeners).length === 0) {\r\n // Whether browser can detect storage event when it had already been pushed to the background.\r\n // This may happen in some mobile browsers. A localStorage change in the foreground window\r\n // will not be detected in the background window via the storage event.\r\n // This was detected in iOS 7.x mobile browsers\r\n if (this.fallbackToPolling) {\r\n this.startPolling();\r\n }\r\n else {\r\n this.attachListener();\r\n }\r\n }\r\n if (!this.listeners[key]) {\r\n this.listeners[key] = new Set();\r\n // Populate the cache to avoid spuriously triggering on first poll.\r\n this.localCache[key] = this.storage.getItem(key);\r\n }\r\n this.listeners[key].add(listener);\r\n }\r\n _removeListener(key, listener) {\r\n if (this.listeners[key]) {\r\n this.listeners[key].delete(listener);\r\n if (this.listeners[key].size === 0) {\r\n delete this.listeners[key];\r\n }\r\n }\r\n if (Object.keys(this.listeners).length === 0) {\r\n this.detachListener();\r\n this.stopPolling();\r\n }\r\n }\r\n // Update local cache on base operations:\r\n async _set(key, value) {\r\n await super._set(key, value);\r\n this.localCache[key] = JSON.stringify(value);\r\n }\r\n async _get(key) {\r\n const value = await super._get(key);\r\n this.localCache[key] = JSON.stringify(value);\r\n return value;\r\n }\r\n async _remove(key) {\r\n await super._remove(key);\r\n delete this.localCache[key];\r\n }\r\n}\r\nBrowserLocalPersistence.type = 'LOCAL';\r\n/**\r\n * An implementation of {@link Persistence} of type `LOCAL` using `localStorage`\r\n * for the underlying storage.\r\n *\r\n * @public\r\n */\r\nconst browserLocalPersistence = BrowserLocalPersistence;\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nclass BrowserSessionPersistence extends BrowserPersistenceClass {\r\n constructor() {\r\n super(() => window.sessionStorage, \"SESSION\" /* PersistenceType.SESSION */);\r\n }\r\n _addListener(_key, _listener) {\r\n // Listeners are not supported for session storage since it cannot be shared across windows\r\n return;\r\n }\r\n _removeListener(_key, _listener) {\r\n // Listeners are not supported for session storage since it cannot be shared across windows\r\n return;\r\n }\r\n}\r\nBrowserSessionPersistence.type = 'SESSION';\r\n/**\r\n * An implementation of {@link Persistence} of `SESSION` using `sessionStorage`\r\n * for the underlying storage.\r\n *\r\n * @public\r\n */\r\nconst browserSessionPersistence = BrowserSessionPersistence;\n\n/**\r\n * @license\r\n * Copyright 2019 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Shim for Promise.allSettled, note the slightly different format of `fulfilled` vs `status`.\r\n *\r\n * @param promises - Array of promises to wait on.\r\n */\r\nfunction _allSettled(promises) {\r\n return Promise.all(promises.map(async (promise) => {\r\n try {\r\n const value = await promise;\r\n return {\r\n fulfilled: true,\r\n value\r\n };\r\n }\r\n catch (reason) {\r\n return {\r\n fulfilled: false,\r\n reason\r\n };\r\n }\r\n }));\r\n}\n\n/**\r\n * @license\r\n * Copyright 2019 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Interface class for receiving messages.\r\n *\r\n */\r\nclass Receiver {\r\n constructor(eventTarget) {\r\n this.eventTarget = eventTarget;\r\n this.handlersMap = {};\r\n this.boundEventHandler = this.handleEvent.bind(this);\r\n }\r\n /**\r\n * Obtain an instance of a Receiver for a given event target, if none exists it will be created.\r\n *\r\n * @param eventTarget - An event target (such as window or self) through which the underlying\r\n * messages will be received.\r\n */\r\n static _getInstance(eventTarget) {\r\n // The results are stored in an array since objects can't be keys for other\r\n // objects. In addition, setting a unique property on an event target as a\r\n // hash map key may not be allowed due to CORS restrictions.\r\n const existingInstance = this.receivers.find(receiver => receiver.isListeningto(eventTarget));\r\n if (existingInstance) {\r\n return existingInstance;\r\n }\r\n const newInstance = new Receiver(eventTarget);\r\n this.receivers.push(newInstance);\r\n return newInstance;\r\n }\r\n isListeningto(eventTarget) {\r\n return this.eventTarget === eventTarget;\r\n }\r\n /**\r\n * Fans out a MessageEvent to the appropriate listeners.\r\n *\r\n * @remarks\r\n * Sends an {@link Status.ACK} upon receipt and a {@link Status.DONE} once all handlers have\r\n * finished processing.\r\n *\r\n * @param event - The MessageEvent.\r\n *\r\n */\r\n async handleEvent(event) {\r\n const messageEvent = event;\r\n const { eventId, eventType, data } = messageEvent.data;\r\n const handlers = this.handlersMap[eventType];\r\n if (!(handlers === null || handlers === void 0 ? void 0 : handlers.size)) {\r\n return;\r\n }\r\n messageEvent.ports[0].postMessage({\r\n status: \"ack\" /* _Status.ACK */,\r\n eventId,\r\n eventType\r\n });\r\n const promises = Array.from(handlers).map(async (handler) => handler(messageEvent.origin, data));\r\n const response = await _allSettled(promises);\r\n messageEvent.ports[0].postMessage({\r\n status: \"done\" /* _Status.DONE */,\r\n eventId,\r\n eventType,\r\n response\r\n });\r\n }\r\n /**\r\n * Subscribe an event handler for a particular event.\r\n *\r\n * @param eventType - Event name to subscribe to.\r\n * @param eventHandler - The event handler which should receive the events.\r\n *\r\n */\r\n _subscribe(eventType, eventHandler) {\r\n if (Object.keys(this.handlersMap).length === 0) {\r\n this.eventTarget.addEventListener('message', this.boundEventHandler);\r\n }\r\n if (!this.handlersMap[eventType]) {\r\n this.handlersMap[eventType] = new Set();\r\n }\r\n this.handlersMap[eventType].add(eventHandler);\r\n }\r\n /**\r\n * Unsubscribe an event handler from a particular event.\r\n *\r\n * @param eventType - Event name to unsubscribe from.\r\n * @param eventHandler - Optinoal event handler, if none provided, unsubscribe all handlers on this event.\r\n *\r\n */\r\n _unsubscribe(eventType, eventHandler) {\r\n if (this.handlersMap[eventType] && eventHandler) {\r\n this.handlersMap[eventType].delete(eventHandler);\r\n }\r\n if (!eventHandler || this.handlersMap[eventType].size === 0) {\r\n delete this.handlersMap[eventType];\r\n }\r\n if (Object.keys(this.handlersMap).length === 0) {\r\n this.eventTarget.removeEventListener('message', this.boundEventHandler);\r\n }\r\n }\r\n}\r\nReceiver.receivers = [];\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nfunction _generateEventId(prefix = '', digits = 10) {\r\n let random = '';\r\n for (let i = 0; i < digits; i++) {\r\n random += Math.floor(Math.random() * 10);\r\n }\r\n return prefix + random;\r\n}\n\n/**\r\n * @license\r\n * Copyright 2019 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Interface for sending messages and waiting for a completion response.\r\n *\r\n */\r\nclass Sender {\r\n constructor(target) {\r\n this.target = target;\r\n this.handlers = new Set();\r\n }\r\n /**\r\n * Unsubscribe the handler and remove it from our tracking Set.\r\n *\r\n * @param handler - The handler to unsubscribe.\r\n */\r\n removeMessageHandler(handler) {\r\n if (handler.messageChannel) {\r\n handler.messageChannel.port1.removeEventListener('message', handler.onMessage);\r\n handler.messageChannel.port1.close();\r\n }\r\n this.handlers.delete(handler);\r\n }\r\n /**\r\n * Send a message to the Receiver located at {@link target}.\r\n *\r\n * @remarks\r\n * We'll first wait a bit for an ACK , if we get one we will wait significantly longer until the\r\n * receiver has had a chance to fully process the event.\r\n *\r\n * @param eventType - Type of event to send.\r\n * @param data - The payload of the event.\r\n * @param timeout - Timeout for waiting on an ACK from the receiver.\r\n *\r\n * @returns An array of settled promises from all the handlers that were listening on the receiver.\r\n */\r\n async _send(eventType, data, timeout = 50 /* _TimeoutDuration.ACK */) {\r\n const messageChannel = typeof MessageChannel !== 'undefined' ? new MessageChannel() : null;\r\n if (!messageChannel) {\r\n throw new Error(\"connection_unavailable\" /* _MessageError.CONNECTION_UNAVAILABLE */);\r\n }\r\n // Node timers and browser timers return fundamentally different types.\r\n // We don't actually care what the value is but TS won't accept unknown and\r\n // we can't cast properly in both environments.\r\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\r\n let completionTimer;\r\n let handler;\r\n return new Promise((resolve, reject) => {\r\n const eventId = _generateEventId('', 20);\r\n messageChannel.port1.start();\r\n const ackTimer = setTimeout(() => {\r\n reject(new Error(\"unsupported_event\" /* _MessageError.UNSUPPORTED_EVENT */));\r\n }, timeout);\r\n handler = {\r\n messageChannel,\r\n onMessage(event) {\r\n const messageEvent = event;\r\n if (messageEvent.data.eventId !== eventId) {\r\n return;\r\n }\r\n switch (messageEvent.data.status) {\r\n case \"ack\" /* _Status.ACK */:\r\n // The receiver should ACK first.\r\n clearTimeout(ackTimer);\r\n completionTimer = setTimeout(() => {\r\n reject(new Error(\"timeout\" /* _MessageError.TIMEOUT */));\r\n }, 3000 /* _TimeoutDuration.COMPLETION */);\r\n break;\r\n case \"done\" /* _Status.DONE */:\r\n // Once the receiver's handlers are finished we will get the results.\r\n clearTimeout(completionTimer);\r\n resolve(messageEvent.data.response);\r\n break;\r\n default:\r\n clearTimeout(ackTimer);\r\n clearTimeout(completionTimer);\r\n reject(new Error(\"invalid_response\" /* _MessageError.INVALID_RESPONSE */));\r\n break;\r\n }\r\n }\r\n };\r\n this.handlers.add(handler);\r\n messageChannel.port1.addEventListener('message', handler.onMessage);\r\n this.target.postMessage({\r\n eventType,\r\n eventId,\r\n data\r\n }, [messageChannel.port2]);\r\n }).finally(() => {\r\n if (handler) {\r\n this.removeMessageHandler(handler);\r\n }\r\n });\r\n }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Lazy accessor for window, since the compat layer won't tree shake this out,\r\n * we need to make sure not to mess with window unless we have to\r\n */\r\nfunction _window() {\r\n return window;\r\n}\r\nfunction _setWindowLocation(url) {\r\n _window().location.href = url;\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nfunction _isWorker() {\r\n return (typeof _window()['WorkerGlobalScope'] !== 'undefined' &&\r\n typeof _window()['importScripts'] === 'function');\r\n}\r\nasync function _getActiveServiceWorker() {\r\n if (!(navigator === null || navigator === void 0 ? void 0 : navigator.serviceWorker)) {\r\n return null;\r\n }\r\n try {\r\n const registration = await navigator.serviceWorker.ready;\r\n return registration.active;\r\n }\r\n catch (_a) {\r\n return null;\r\n }\r\n}\r\nfunction _getServiceWorkerController() {\r\n var _a;\r\n return ((_a = navigator === null || navigator === void 0 ? void 0 : navigator.serviceWorker) === null || _a === void 0 ? void 0 : _a.controller) || null;\r\n}\r\nfunction _getWorkerGlobalScope() {\r\n return _isWorker() ? self : null;\r\n}\n\n/**\r\n * @license\r\n * Copyright 2019 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nconst DB_NAME = 'firebaseLocalStorageDb';\r\nconst DB_VERSION = 1;\r\nconst DB_OBJECTSTORE_NAME = 'firebaseLocalStorage';\r\nconst DB_DATA_KEYPATH = 'fbase_key';\r\n/**\r\n * Promise wrapper for IDBRequest\r\n *\r\n * Unfortunately we can't cleanly extend Promise since promises are not callable in ES6\r\n *\r\n */\r\nclass DBPromise {\r\n constructor(request) {\r\n this.request = request;\r\n }\r\n toPromise() {\r\n return new Promise((resolve, reject) => {\r\n this.request.addEventListener('success', () => {\r\n resolve(this.request.result);\r\n });\r\n this.request.addEventListener('error', () => {\r\n reject(this.request.error);\r\n });\r\n });\r\n }\r\n}\r\nfunction getObjectStore(db, isReadWrite) {\r\n return db\r\n .transaction([DB_OBJECTSTORE_NAME], isReadWrite ? 'readwrite' : 'readonly')\r\n .objectStore(DB_OBJECTSTORE_NAME);\r\n}\r\nfunction _deleteDatabase() {\r\n const request = indexedDB.deleteDatabase(DB_NAME);\r\n return new DBPromise(request).toPromise();\r\n}\r\nfunction _openDatabase() {\r\n const request = indexedDB.open(DB_NAME, DB_VERSION);\r\n return new Promise((resolve, reject) => {\r\n request.addEventListener('error', () => {\r\n reject(request.error);\r\n });\r\n request.addEventListener('upgradeneeded', () => {\r\n const db = request.result;\r\n try {\r\n db.createObjectStore(DB_OBJECTSTORE_NAME, { keyPath: DB_DATA_KEYPATH });\r\n }\r\n catch (e) {\r\n reject(e);\r\n }\r\n });\r\n request.addEventListener('success', async () => {\r\n const db = request.result;\r\n // Strange bug that occurs in Firefox when multiple tabs are opened at the\r\n // same time. The only way to recover seems to be deleting the database\r\n // and re-initializing it.\r\n // https://github.com/firebase/firebase-js-sdk/issues/634\r\n if (!db.objectStoreNames.contains(DB_OBJECTSTORE_NAME)) {\r\n // Need to close the database or else you get a `blocked` event\r\n db.close();\r\n await _deleteDatabase();\r\n resolve(await _openDatabase());\r\n }\r\n else {\r\n resolve(db);\r\n }\r\n });\r\n });\r\n}\r\nasync function _putObject(db, key, value) {\r\n const request = getObjectStore(db, true).put({\r\n [DB_DATA_KEYPATH]: key,\r\n value\r\n });\r\n return new DBPromise(request).toPromise();\r\n}\r\nasync function getObject(db, key) {\r\n const request = getObjectStore(db, false).get(key);\r\n const data = await new DBPromise(request).toPromise();\r\n return data === undefined ? null : data.value;\r\n}\r\nfunction _deleteObject(db, key) {\r\n const request = getObjectStore(db, true).delete(key);\r\n return new DBPromise(request).toPromise();\r\n}\r\nconst _POLLING_INTERVAL_MS = 800;\r\nconst _TRANSACTION_RETRY_COUNT = 3;\r\nclass IndexedDBLocalPersistence {\r\n constructor() {\r\n this.type = \"LOCAL\" /* PersistenceType.LOCAL */;\r\n this._shouldAllowMigration = true;\r\n this.listeners = {};\r\n this.localCache = {};\r\n // setTimeout return value is platform specific\r\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\r\n this.pollTimer = null;\r\n this.pendingWrites = 0;\r\n this.receiver = null;\r\n this.sender = null;\r\n this.serviceWorkerReceiverAvailable = false;\r\n this.activeServiceWorker = null;\r\n // Fire & forget the service worker registration as it may never resolve\r\n this._workerInitializationPromise =\r\n this.initializeServiceWorkerMessaging().then(() => { }, () => { });\r\n }\r\n async _openDb() {\r\n if (this.db) {\r\n return this.db;\r\n }\r\n this.db = await _openDatabase();\r\n return this.db;\r\n }\r\n async _withRetries(op) {\r\n let numAttempts = 0;\r\n while (true) {\r\n try {\r\n const db = await this._openDb();\r\n return await op(db);\r\n }\r\n catch (e) {\r\n if (numAttempts++ > _TRANSACTION_RETRY_COUNT) {\r\n throw e;\r\n }\r\n if (this.db) {\r\n this.db.close();\r\n this.db = undefined;\r\n }\r\n // TODO: consider adding exponential backoff\r\n }\r\n }\r\n }\r\n /**\r\n * IndexedDB events do not propagate from the main window to the worker context. We rely on a\r\n * postMessage interface to send these events to the worker ourselves.\r\n */\r\n async initializeServiceWorkerMessaging() {\r\n return _isWorker() ? this.initializeReceiver() : this.initializeSender();\r\n }\r\n /**\r\n * As the worker we should listen to events from the main window.\r\n */\r\n async initializeReceiver() {\r\n this.receiver = Receiver._getInstance(_getWorkerGlobalScope());\r\n // Refresh from persistence if we receive a KeyChanged message.\r\n this.receiver._subscribe(\"keyChanged\" /* _EventType.KEY_CHANGED */, async (_origin, data) => {\r\n const keys = await this._poll();\r\n return {\r\n keyProcessed: keys.includes(data.key)\r\n };\r\n });\r\n // Let the sender know that we are listening so they give us more timeout.\r\n this.receiver._subscribe(\"ping\" /* _EventType.PING */, async (_origin, _data) => {\r\n return [\"keyChanged\" /* _EventType.KEY_CHANGED */];\r\n });\r\n }\r\n /**\r\n * As the main window, we should let the worker know when keys change (set and remove).\r\n *\r\n * @remarks\r\n * {@link https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorkerContainer/ready | ServiceWorkerContainer.ready}\r\n * may not resolve.\r\n */\r\n async initializeSender() {\r\n var _a, _b;\r\n // Check to see if there's an active service worker.\r\n this.activeServiceWorker = await _getActiveServiceWorker();\r\n if (!this.activeServiceWorker) {\r\n return;\r\n }\r\n this.sender = new Sender(this.activeServiceWorker);\r\n // Ping the service worker to check what events they can handle.\r\n const results = await this.sender._send(\"ping\" /* _EventType.PING */, {}, 800 /* _TimeoutDuration.LONG_ACK */);\r\n if (!results) {\r\n return;\r\n }\r\n if (((_a = results[0]) === null || _a === void 0 ? void 0 : _a.fulfilled) &&\r\n ((_b = results[0]) === null || _b === void 0 ? void 0 : _b.value.includes(\"keyChanged\" /* _EventType.KEY_CHANGED */))) {\r\n this.serviceWorkerReceiverAvailable = true;\r\n }\r\n }\r\n /**\r\n * Let the worker know about a changed key, the exact key doesn't technically matter since the\r\n * worker will just trigger a full sync anyway.\r\n *\r\n * @remarks\r\n * For now, we only support one service worker per page.\r\n *\r\n * @param key - Storage key which changed.\r\n */\r\n async notifyServiceWorker(key) {\r\n if (!this.sender ||\r\n !this.activeServiceWorker ||\r\n _getServiceWorkerController() !== this.activeServiceWorker) {\r\n return;\r\n }\r\n try {\r\n await this.sender._send(\"keyChanged\" /* _EventType.KEY_CHANGED */, { key }, \r\n // Use long timeout if receiver has previously responded to a ping from us.\r\n this.serviceWorkerReceiverAvailable\r\n ? 800 /* _TimeoutDuration.LONG_ACK */\r\n : 50 /* _TimeoutDuration.ACK */);\r\n }\r\n catch (_a) {\r\n // This is a best effort approach. Ignore errors.\r\n }\r\n }\r\n async _isAvailable() {\r\n try {\r\n if (!indexedDB) {\r\n return false;\r\n }\r\n const db = await _openDatabase();\r\n await _putObject(db, STORAGE_AVAILABLE_KEY, '1');\r\n await _deleteObject(db, STORAGE_AVAILABLE_KEY);\r\n return true;\r\n }\r\n catch (_a) { }\r\n return false;\r\n }\r\n async _withPendingWrite(write) {\r\n this.pendingWrites++;\r\n try {\r\n await write();\r\n }\r\n finally {\r\n this.pendingWrites--;\r\n }\r\n }\r\n async _set(key, value) {\r\n return this._withPendingWrite(async () => {\r\n await this._withRetries((db) => _putObject(db, key, value));\r\n this.localCache[key] = value;\r\n return this.notifyServiceWorker(key);\r\n });\r\n }\r\n async _get(key) {\r\n const obj = (await this._withRetries((db) => getObject(db, key)));\r\n this.localCache[key] = obj;\r\n return obj;\r\n }\r\n async _remove(key) {\r\n return this._withPendingWrite(async () => {\r\n await this._withRetries((db) => _deleteObject(db, key));\r\n delete this.localCache[key];\r\n return this.notifyServiceWorker(key);\r\n });\r\n }\r\n async _poll() {\r\n // TODO: check if we need to fallback if getAll is not supported\r\n const result = await this._withRetries((db) => {\r\n const getAllRequest = getObjectStore(db, false).getAll();\r\n return new DBPromise(getAllRequest).toPromise();\r\n });\r\n if (!result) {\r\n return [];\r\n }\r\n // If we have pending writes in progress abort, we'll get picked up on the next poll\r\n if (this.pendingWrites !== 0) {\r\n return [];\r\n }\r\n const keys = [];\r\n const keysInResult = new Set();\r\n for (const { fbase_key: key, value } of result) {\r\n keysInResult.add(key);\r\n if (JSON.stringify(this.localCache[key]) !== JSON.stringify(value)) {\r\n this.notifyListeners(key, value);\r\n keys.push(key);\r\n }\r\n }\r\n for (const localKey of Object.keys(this.localCache)) {\r\n if (this.localCache[localKey] && !keysInResult.has(localKey)) {\r\n // Deleted\r\n this.notifyListeners(localKey, null);\r\n keys.push(localKey);\r\n }\r\n }\r\n return keys;\r\n }\r\n notifyListeners(key, newValue) {\r\n this.localCache[key] = newValue;\r\n const listeners = this.listeners[key];\r\n if (listeners) {\r\n for (const listener of Array.from(listeners)) {\r\n listener(newValue);\r\n }\r\n }\r\n }\r\n startPolling() {\r\n this.stopPolling();\r\n this.pollTimer = setInterval(async () => this._poll(), _POLLING_INTERVAL_MS);\r\n }\r\n stopPolling() {\r\n if (this.pollTimer) {\r\n clearInterval(this.pollTimer);\r\n this.pollTimer = null;\r\n }\r\n }\r\n _addListener(key, listener) {\r\n if (Object.keys(this.listeners).length === 0) {\r\n this.startPolling();\r\n }\r\n if (!this.listeners[key]) {\r\n this.listeners[key] = new Set();\r\n // Populate the cache to avoid spuriously triggering on first poll.\r\n void this._get(key); // This can happen in the background async and we can return immediately.\r\n }\r\n this.listeners[key].add(listener);\r\n }\r\n _removeListener(key, listener) {\r\n if (this.listeners[key]) {\r\n this.listeners[key].delete(listener);\r\n if (this.listeners[key].size === 0) {\r\n delete this.listeners[key];\r\n }\r\n }\r\n if (Object.keys(this.listeners).length === 0) {\r\n this.stopPolling();\r\n }\r\n }\r\n}\r\nIndexedDBLocalPersistence.type = 'LOCAL';\r\n/**\r\n * An implementation of {@link Persistence} of type `LOCAL` using `indexedDB`\r\n * for the underlying storage.\r\n *\r\n * @public\r\n */\r\nconst indexedDBLocalPersistence = IndexedDBLocalPersistence;\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nfunction startSignInPhoneMfa(auth, request) {\r\n return _performApiRequest(auth, \"POST\" /* HttpMethod.POST */, \"/v2/accounts/mfaSignIn:start\" /* Endpoint.START_MFA_SIGN_IN */, _addTidIfNecessary(auth, request));\r\n}\r\nfunction finalizeSignInPhoneMfa(auth, request) {\r\n return _performApiRequest(auth, \"POST\" /* HttpMethod.POST */, \"/v2/accounts/mfaSignIn:finalize\" /* Endpoint.FINALIZE_MFA_SIGN_IN */, _addTidIfNecessary(auth, request));\r\n}\r\nfunction finalizeSignInTotpMfa(auth, request) {\r\n return _performApiRequest(auth, \"POST\" /* HttpMethod.POST */, \"/v2/accounts/mfaSignIn:finalize\" /* Endpoint.FINALIZE_MFA_SIGN_IN */, _addTidIfNecessary(auth, request));\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nconst _SOLVE_TIME_MS = 500;\r\nconst _EXPIRATION_TIME_MS = 60000;\r\nconst _WIDGET_ID_START = 1000000000000;\r\nclass MockReCaptcha {\r\n constructor(auth) {\r\n this.auth = auth;\r\n this.counter = _WIDGET_ID_START;\r\n this._widgets = new Map();\r\n }\r\n render(container, parameters) {\r\n const id = this.counter;\r\n this._widgets.set(id, new MockWidget(container, this.auth.name, parameters || {}));\r\n this.counter++;\r\n return id;\r\n }\r\n reset(optWidgetId) {\r\n var _a;\r\n const id = optWidgetId || _WIDGET_ID_START;\r\n void ((_a = this._widgets.get(id)) === null || _a === void 0 ? void 0 : _a.delete());\r\n this._widgets.delete(id);\r\n }\r\n getResponse(optWidgetId) {\r\n var _a;\r\n const id = optWidgetId || _WIDGET_ID_START;\r\n return ((_a = this._widgets.get(id)) === null || _a === void 0 ? void 0 : _a.getResponse()) || '';\r\n }\r\n async execute(optWidgetId) {\r\n var _a;\r\n const id = optWidgetId || _WIDGET_ID_START;\r\n void ((_a = this._widgets.get(id)) === null || _a === void 0 ? void 0 : _a.execute());\r\n return '';\r\n }\r\n}\r\nclass MockWidget {\r\n constructor(containerOrId, appName, params) {\r\n this.params = params;\r\n this.timerId = null;\r\n this.deleted = false;\r\n this.responseToken = null;\r\n this.clickHandler = () => {\r\n this.execute();\r\n };\r\n const container = typeof containerOrId === 'string'\r\n ? document.getElementById(containerOrId)\r\n : containerOrId;\r\n _assert(container, \"argument-error\" /* AuthErrorCode.ARGUMENT_ERROR */, { appName });\r\n this.container = container;\r\n this.isVisible = this.params.size !== 'invisible';\r\n if (this.isVisible) {\r\n this.execute();\r\n }\r\n else {\r\n this.container.addEventListener('click', this.clickHandler);\r\n }\r\n }\r\n getResponse() {\r\n this.checkIfDeleted();\r\n return this.responseToken;\r\n }\r\n delete() {\r\n this.checkIfDeleted();\r\n this.deleted = true;\r\n if (this.timerId) {\r\n clearTimeout(this.timerId);\r\n this.timerId = null;\r\n }\r\n this.container.removeEventListener('click', this.clickHandler);\r\n }\r\n execute() {\r\n this.checkIfDeleted();\r\n if (this.timerId) {\r\n return;\r\n }\r\n this.timerId = window.setTimeout(() => {\r\n this.responseToken = generateRandomAlphaNumericString(50);\r\n const { callback, 'expired-callback': expiredCallback } = this.params;\r\n if (callback) {\r\n try {\r\n callback(this.responseToken);\r\n }\r\n catch (e) { }\r\n }\r\n this.timerId = window.setTimeout(() => {\r\n this.timerId = null;\r\n this.responseToken = null;\r\n if (expiredCallback) {\r\n try {\r\n expiredCallback();\r\n }\r\n catch (e) { }\r\n }\r\n if (this.isVisible) {\r\n this.execute();\r\n }\r\n }, _EXPIRATION_TIME_MS);\r\n }, _SOLVE_TIME_MS);\r\n }\r\n checkIfDeleted() {\r\n if (this.deleted) {\r\n throw new Error('reCAPTCHA mock was already deleted!');\r\n }\r\n }\r\n}\r\nfunction generateRandomAlphaNumericString(len) {\r\n const chars = [];\r\n const allowedChars = '1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';\r\n for (let i = 0; i < len; i++) {\r\n chars.push(allowedChars.charAt(Math.floor(Math.random() * allowedChars.length)));\r\n }\r\n return chars.join('');\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n// ReCaptcha will load using the same callback, so the callback function needs\r\n// to be kept around\r\nconst _JSLOAD_CALLBACK = _generateCallbackName('rcb');\r\nconst NETWORK_TIMEOUT_DELAY = new Delay(30000, 60000);\r\nconst RECAPTCHA_BASE = 'https://www.google.com/recaptcha/api.js?';\r\n/**\r\n * Loader for the GReCaptcha library. There should only ever be one of this.\r\n */\r\nclass ReCaptchaLoaderImpl {\r\n constructor() {\r\n var _a;\r\n this.hostLanguage = '';\r\n this.counter = 0;\r\n /**\r\n * Check for `render()` method. `window.grecaptcha` will exist if the Enterprise\r\n * version of the ReCAPTCHA script was loaded by someone else (e.g. App Check) but\r\n * `window.grecaptcha.render()` will not. Another load will add it.\r\n */\r\n this.librarySeparatelyLoaded = !!((_a = _window().grecaptcha) === null || _a === void 0 ? void 0 : _a.render);\r\n }\r\n load(auth, hl = '') {\r\n _assert(isHostLanguageValid(hl), auth, \"argument-error\" /* AuthErrorCode.ARGUMENT_ERROR */);\r\n if (this.shouldResolveImmediately(hl) && isV2(_window().grecaptcha)) {\r\n return Promise.resolve(_window().grecaptcha);\r\n }\r\n return new Promise((resolve, reject) => {\r\n const networkTimeout = _window().setTimeout(() => {\r\n reject(_createError(auth, \"network-request-failed\" /* AuthErrorCode.NETWORK_REQUEST_FAILED */));\r\n }, NETWORK_TIMEOUT_DELAY.get());\r\n _window()[_JSLOAD_CALLBACK] = () => {\r\n _window().clearTimeout(networkTimeout);\r\n delete _window()[_JSLOAD_CALLBACK];\r\n const recaptcha = _window().grecaptcha;\r\n if (!recaptcha || !isV2(recaptcha)) {\r\n reject(_createError(auth, \"internal-error\" /* AuthErrorCode.INTERNAL_ERROR */));\r\n return;\r\n }\r\n // Wrap the greptcha render function so that we know if the developer has\r\n // called it separately\r\n const render = recaptcha.render;\r\n recaptcha.render = (container, params) => {\r\n const widgetId = render(container, params);\r\n this.counter++;\r\n return widgetId;\r\n };\r\n this.hostLanguage = hl;\r\n resolve(recaptcha);\r\n };\r\n const url = `${RECAPTCHA_BASE}?${querystring({\r\n onload: _JSLOAD_CALLBACK,\r\n render: 'explicit',\r\n hl\r\n })}`;\r\n _loadJS(url).catch(() => {\r\n clearTimeout(networkTimeout);\r\n reject(_createError(auth, \"internal-error\" /* AuthErrorCode.INTERNAL_ERROR */));\r\n });\r\n });\r\n }\r\n clearedOneInstance() {\r\n this.counter--;\r\n }\r\n shouldResolveImmediately(hl) {\r\n var _a;\r\n // We can resolve immediately if:\r\n // • grecaptcha is already defined AND (\r\n // 1. the requested language codes are the same OR\r\n // 2. there exists already a ReCaptcha on the page\r\n // 3. the library was already loaded by the app\r\n // In cases (2) and (3), we _can't_ reload as it would break the recaptchas\r\n // that are already in the page\r\n return (!!((_a = _window().grecaptcha) === null || _a === void 0 ? void 0 : _a.render) &&\r\n (hl === this.hostLanguage ||\r\n this.counter > 0 ||\r\n this.librarySeparatelyLoaded));\r\n }\r\n}\r\nfunction isHostLanguageValid(hl) {\r\n return hl.length <= 6 && /^\\s*[a-zA-Z0-9\\-]*\\s*$/.test(hl);\r\n}\r\nclass MockReCaptchaLoaderImpl {\r\n async load(auth) {\r\n return new MockReCaptcha(auth);\r\n }\r\n clearedOneInstance() { }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nconst RECAPTCHA_VERIFIER_TYPE = 'recaptcha';\r\nconst DEFAULT_PARAMS = {\r\n theme: 'light',\r\n type: 'image'\r\n};\r\n/**\r\n * An {@link https://www.google.com/recaptcha/ | reCAPTCHA}-based application verifier.\r\n *\r\n * @public\r\n */\r\nclass RecaptchaVerifier {\r\n /**\r\n *\r\n * @param containerOrId - The reCAPTCHA container parameter.\r\n *\r\n * @remarks\r\n * This has different meaning depending on whether the reCAPTCHA is hidden or visible. For a\r\n * visible reCAPTCHA the container must be empty. If a string is used, it has to correspond to\r\n * an element ID. The corresponding element must also must be in the DOM at the time of\r\n * initialization.\r\n *\r\n * @param parameters - The optional reCAPTCHA parameters.\r\n *\r\n * @remarks\r\n * Check the reCAPTCHA docs for a comprehensive list. All parameters are accepted except for\r\n * the sitekey. Firebase Auth backend provisions a reCAPTCHA for each project and will\r\n * configure this upon rendering. For an invisible reCAPTCHA, a size key must have the value\r\n * 'invisible'.\r\n *\r\n * @param authExtern - The corresponding Firebase {@link Auth} instance.\r\n */\r\n constructor(containerOrId, parameters = Object.assign({}, DEFAULT_PARAMS), authExtern) {\r\n this.parameters = parameters;\r\n /**\r\n * The application verifier type.\r\n *\r\n * @remarks\r\n * For a reCAPTCHA verifier, this is 'recaptcha'.\r\n */\r\n this.type = RECAPTCHA_VERIFIER_TYPE;\r\n this.destroyed = false;\r\n this.widgetId = null;\r\n this.tokenChangeListeners = new Set();\r\n this.renderPromise = null;\r\n this.recaptcha = null;\r\n this.auth = _castAuth(authExtern);\r\n this.isInvisible = this.parameters.size === 'invisible';\r\n _assert(typeof document !== 'undefined', this.auth, \"operation-not-supported-in-this-environment\" /* AuthErrorCode.OPERATION_NOT_SUPPORTED */);\r\n const container = typeof containerOrId === 'string'\r\n ? document.getElementById(containerOrId)\r\n : containerOrId;\r\n _assert(container, this.auth, \"argument-error\" /* AuthErrorCode.ARGUMENT_ERROR */);\r\n this.container = container;\r\n this.parameters.callback = this.makeTokenCallback(this.parameters.callback);\r\n this._recaptchaLoader = this.auth.settings.appVerificationDisabledForTesting\r\n ? new MockReCaptchaLoaderImpl()\r\n : new ReCaptchaLoaderImpl();\r\n this.validateStartingState();\r\n // TODO: Figure out if sdk version is needed\r\n }\r\n /**\r\n * Waits for the user to solve the reCAPTCHA and resolves with the reCAPTCHA token.\r\n *\r\n * @returns A Promise for the reCAPTCHA token.\r\n */\r\n async verify() {\r\n this.assertNotDestroyed();\r\n const id = await this.render();\r\n const recaptcha = this.getAssertedRecaptcha();\r\n const response = recaptcha.getResponse(id);\r\n if (response) {\r\n return response;\r\n }\r\n return new Promise(resolve => {\r\n const tokenChange = (token) => {\r\n if (!token) {\r\n return; // Ignore token expirations.\r\n }\r\n this.tokenChangeListeners.delete(tokenChange);\r\n resolve(token);\r\n };\r\n this.tokenChangeListeners.add(tokenChange);\r\n if (this.isInvisible) {\r\n recaptcha.execute(id);\r\n }\r\n });\r\n }\r\n /**\r\n * Renders the reCAPTCHA widget on the page.\r\n *\r\n * @returns A Promise that resolves with the reCAPTCHA widget ID.\r\n */\r\n render() {\r\n try {\r\n this.assertNotDestroyed();\r\n }\r\n catch (e) {\r\n // This method returns a promise. Since it's not async (we want to return the\r\n // _same_ promise if rendering is still occurring), the API surface should\r\n // reject with the error rather than just throw\r\n return Promise.reject(e);\r\n }\r\n if (this.renderPromise) {\r\n return this.renderPromise;\r\n }\r\n this.renderPromise = this.makeRenderPromise().catch(e => {\r\n this.renderPromise = null;\r\n throw e;\r\n });\r\n return this.renderPromise;\r\n }\r\n /** @internal */\r\n _reset() {\r\n this.assertNotDestroyed();\r\n if (this.widgetId !== null) {\r\n this.getAssertedRecaptcha().reset(this.widgetId);\r\n }\r\n }\r\n /**\r\n * Clears the reCAPTCHA widget from the page and destroys the instance.\r\n */\r\n clear() {\r\n this.assertNotDestroyed();\r\n this.destroyed = true;\r\n this._recaptchaLoader.clearedOneInstance();\r\n if (!this.isInvisible) {\r\n this.container.childNodes.forEach(node => {\r\n this.container.removeChild(node);\r\n });\r\n }\r\n }\r\n validateStartingState() {\r\n _assert(!this.parameters.sitekey, this.auth, \"argument-error\" /* AuthErrorCode.ARGUMENT_ERROR */);\r\n _assert(this.isInvisible || !this.container.hasChildNodes(), this.auth, \"argument-error\" /* AuthErrorCode.ARGUMENT_ERROR */);\r\n _assert(typeof document !== 'undefined', this.auth, \"operation-not-supported-in-this-environment\" /* AuthErrorCode.OPERATION_NOT_SUPPORTED */);\r\n }\r\n makeTokenCallback(existing) {\r\n return token => {\r\n this.tokenChangeListeners.forEach(listener => listener(token));\r\n if (typeof existing === 'function') {\r\n existing(token);\r\n }\r\n else if (typeof existing === 'string') {\r\n const globalFunc = _window()[existing];\r\n if (typeof globalFunc === 'function') {\r\n globalFunc(token);\r\n }\r\n }\r\n };\r\n }\r\n assertNotDestroyed() {\r\n _assert(!this.destroyed, this.auth, \"internal-error\" /* AuthErrorCode.INTERNAL_ERROR */);\r\n }\r\n async makeRenderPromise() {\r\n await this.init();\r\n if (!this.widgetId) {\r\n let container = this.container;\r\n if (!this.isInvisible) {\r\n const guaranteedEmpty = document.createElement('div');\r\n container.appendChild(guaranteedEmpty);\r\n container = guaranteedEmpty;\r\n }\r\n this.widgetId = this.getAssertedRecaptcha().render(container, this.parameters);\r\n }\r\n return this.widgetId;\r\n }\r\n async init() {\r\n _assert(_isHttpOrHttps() && !_isWorker(), this.auth, \"internal-error\" /* AuthErrorCode.INTERNAL_ERROR */);\r\n await domReady();\r\n this.recaptcha = await this._recaptchaLoader.load(this.auth, this.auth.languageCode || undefined);\r\n const siteKey = await getRecaptchaParams(this.auth);\r\n _assert(siteKey, this.auth, \"internal-error\" /* AuthErrorCode.INTERNAL_ERROR */);\r\n this.parameters.sitekey = siteKey;\r\n }\r\n getAssertedRecaptcha() {\r\n _assert(this.recaptcha, this.auth, \"internal-error\" /* AuthErrorCode.INTERNAL_ERROR */);\r\n return this.recaptcha;\r\n }\r\n}\r\nfunction domReady() {\r\n let resolver = null;\r\n return new Promise(resolve => {\r\n if (document.readyState === 'complete') {\r\n resolve();\r\n return;\r\n }\r\n // Document not ready, wait for load before resolving.\r\n // Save resolver, so we can remove listener in case it was externally\r\n // cancelled.\r\n resolver = () => resolve();\r\n window.addEventListener('load', resolver);\r\n }).catch(e => {\r\n if (resolver) {\r\n window.removeEventListener('load', resolver);\r\n }\r\n throw e;\r\n });\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nclass ConfirmationResultImpl {\r\n constructor(verificationId, onConfirmation) {\r\n this.verificationId = verificationId;\r\n this.onConfirmation = onConfirmation;\r\n }\r\n confirm(verificationCode) {\r\n const authCredential = PhoneAuthCredential._fromVerification(this.verificationId, verificationCode);\r\n return this.onConfirmation(authCredential);\r\n }\r\n}\r\n/**\r\n * Asynchronously signs in using a phone number.\r\n *\r\n * @remarks\r\n * This method sends a code via SMS to the given\r\n * phone number, and returns a {@link ConfirmationResult}. After the user\r\n * provides the code sent to their phone, call {@link ConfirmationResult.confirm}\r\n * with the code to sign the user in.\r\n *\r\n * For abuse prevention, this method also requires a {@link ApplicationVerifier}.\r\n * This SDK includes a reCAPTCHA-based implementation, {@link RecaptchaVerifier}.\r\n * This function can work on other platforms that do not support the\r\n * {@link RecaptchaVerifier} (like React Native), but you need to use a\r\n * third-party {@link ApplicationVerifier} implementation.\r\n *\r\n * @example\r\n * ```javascript\r\n * // 'recaptcha-container' is the ID of an element in the DOM.\r\n * const applicationVerifier = new firebase.auth.RecaptchaVerifier('recaptcha-container');\r\n * const confirmationResult = await signInWithPhoneNumber(auth, phoneNumber, applicationVerifier);\r\n * // Obtain a verificationCode from the user.\r\n * const credential = await confirmationResult.confirm(verificationCode);\r\n * ```\r\n *\r\n * @param auth - The {@link Auth} instance.\r\n * @param phoneNumber - The user's phone number in E.164 format (e.g. +16505550101).\r\n * @param appVerifier - The {@link ApplicationVerifier}.\r\n *\r\n * @public\r\n */\r\nasync function signInWithPhoneNumber(auth, phoneNumber, appVerifier) {\r\n const authInternal = _castAuth(auth);\r\n const verificationId = await _verifyPhoneNumber(authInternal, phoneNumber, getModularInstance(appVerifier));\r\n return new ConfirmationResultImpl(verificationId, cred => signInWithCredential(authInternal, cred));\r\n}\r\n/**\r\n * Links the user account with the given phone number.\r\n *\r\n * @param user - The user.\r\n * @param phoneNumber - The user's phone number in E.164 format (e.g. +16505550101).\r\n * @param appVerifier - The {@link ApplicationVerifier}.\r\n *\r\n * @public\r\n */\r\nasync function linkWithPhoneNumber(user, phoneNumber, appVerifier) {\r\n const userInternal = getModularInstance(user);\r\n await _assertLinkedStatus(false, userInternal, \"phone\" /* ProviderId.PHONE */);\r\n const verificationId = await _verifyPhoneNumber(userInternal.auth, phoneNumber, getModularInstance(appVerifier));\r\n return new ConfirmationResultImpl(verificationId, cred => linkWithCredential(userInternal, cred));\r\n}\r\n/**\r\n * Re-authenticates a user using a fresh phone credential.\r\n *\r\n * @remarks Use before operations such as {@link updatePassword} that require tokens from recent sign-in attempts.\r\n *\r\n * @param user - The user.\r\n * @param phoneNumber - The user's phone number in E.164 format (e.g. +16505550101).\r\n * @param appVerifier - The {@link ApplicationVerifier}.\r\n *\r\n * @public\r\n */\r\nasync function reauthenticateWithPhoneNumber(user, phoneNumber, appVerifier) {\r\n const userInternal = getModularInstance(user);\r\n const verificationId = await _verifyPhoneNumber(userInternal.auth, phoneNumber, getModularInstance(appVerifier));\r\n return new ConfirmationResultImpl(verificationId, cred => reauthenticateWithCredential(userInternal, cred));\r\n}\r\n/**\r\n * Returns a verification ID to be used in conjunction with the SMS code that is sent.\r\n *\r\n */\r\nasync function _verifyPhoneNumber(auth, options, verifier) {\r\n var _a;\r\n const recaptchaToken = await verifier.verify();\r\n try {\r\n _assert(typeof recaptchaToken === 'string', auth, \"argument-error\" /* AuthErrorCode.ARGUMENT_ERROR */);\r\n _assert(verifier.type === RECAPTCHA_VERIFIER_TYPE, auth, \"argument-error\" /* AuthErrorCode.ARGUMENT_ERROR */);\r\n let phoneInfoOptions;\r\n if (typeof options === 'string') {\r\n phoneInfoOptions = {\r\n phoneNumber: options\r\n };\r\n }\r\n else {\r\n phoneInfoOptions = options;\r\n }\r\n if ('session' in phoneInfoOptions) {\r\n const session = phoneInfoOptions.session;\r\n if ('phoneNumber' in phoneInfoOptions) {\r\n _assert(session.type === \"enroll\" /* MultiFactorSessionType.ENROLL */, auth, \"internal-error\" /* AuthErrorCode.INTERNAL_ERROR */);\r\n const response = await startEnrollPhoneMfa(auth, {\r\n idToken: session.credential,\r\n phoneEnrollmentInfo: {\r\n phoneNumber: phoneInfoOptions.phoneNumber,\r\n recaptchaToken\r\n }\r\n });\r\n return response.phoneSessionInfo.sessionInfo;\r\n }\r\n else {\r\n _assert(session.type === \"signin\" /* MultiFactorSessionType.SIGN_IN */, auth, \"internal-error\" /* AuthErrorCode.INTERNAL_ERROR */);\r\n const mfaEnrollmentId = ((_a = phoneInfoOptions.multiFactorHint) === null || _a === void 0 ? void 0 : _a.uid) ||\r\n phoneInfoOptions.multiFactorUid;\r\n _assert(mfaEnrollmentId, auth, \"missing-multi-factor-info\" /* AuthErrorCode.MISSING_MFA_INFO */);\r\n const response = await startSignInPhoneMfa(auth, {\r\n mfaPendingCredential: session.credential,\r\n mfaEnrollmentId,\r\n phoneSignInInfo: {\r\n recaptchaToken\r\n }\r\n });\r\n return response.phoneResponseInfo.sessionInfo;\r\n }\r\n }\r\n else {\r\n const { sessionInfo } = await sendPhoneVerificationCode(auth, {\r\n phoneNumber: phoneInfoOptions.phoneNumber,\r\n recaptchaToken\r\n });\r\n return sessionInfo;\r\n }\r\n }\r\n finally {\r\n verifier._reset();\r\n }\r\n}\r\n/**\r\n * Updates the user's phone number.\r\n *\r\n * @example\r\n * ```\r\n * // 'recaptcha-container' is the ID of an element in the DOM.\r\n * const applicationVerifier = new RecaptchaVerifier('recaptcha-container');\r\n * const provider = new PhoneAuthProvider(auth);\r\n * const verificationId = await provider.verifyPhoneNumber('+16505550101', applicationVerifier);\r\n * // Obtain the verificationCode from the user.\r\n * const phoneCredential = PhoneAuthProvider.credential(verificationId, verificationCode);\r\n * await updatePhoneNumber(user, phoneCredential);\r\n * ```\r\n *\r\n * @param user - The user.\r\n * @param credential - A credential authenticating the new phone number.\r\n *\r\n * @public\r\n */\r\nasync function updatePhoneNumber(user, credential) {\r\n await _link$1(getModularInstance(user), credential);\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Provider for generating an {@link PhoneAuthCredential}.\r\n *\r\n * @example\r\n * ```javascript\r\n * // 'recaptcha-container' is the ID of an element in the DOM.\r\n * const applicationVerifier = new RecaptchaVerifier('recaptcha-container');\r\n * const provider = new PhoneAuthProvider(auth);\r\n * const verificationId = await provider.verifyPhoneNumber('+16505550101', applicationVerifier);\r\n * // Obtain the verificationCode from the user.\r\n * const phoneCredential = PhoneAuthProvider.credential(verificationId, verificationCode);\r\n * const userCredential = await signInWithCredential(auth, phoneCredential);\r\n * ```\r\n *\r\n * @public\r\n */\r\nclass PhoneAuthProvider {\r\n /**\r\n * @param auth - The Firebase {@link Auth} instance in which sign-ins should occur.\r\n *\r\n */\r\n constructor(auth) {\r\n /** Always set to {@link ProviderId}.PHONE. */\r\n this.providerId = PhoneAuthProvider.PROVIDER_ID;\r\n this.auth = _castAuth(auth);\r\n }\r\n /**\r\n *\r\n * Starts a phone number authentication flow by sending a verification code to the given phone\r\n * number.\r\n *\r\n * @example\r\n * ```javascript\r\n * const provider = new PhoneAuthProvider(auth);\r\n * const verificationId = await provider.verifyPhoneNumber(phoneNumber, applicationVerifier);\r\n * // Obtain verificationCode from the user.\r\n * const authCredential = PhoneAuthProvider.credential(verificationId, verificationCode);\r\n * const userCredential = await signInWithCredential(auth, authCredential);\r\n * ```\r\n *\r\n * @example\r\n * An alternative flow is provided using the `signInWithPhoneNumber` method.\r\n * ```javascript\r\n * const confirmationResult = signInWithPhoneNumber(auth, phoneNumber, applicationVerifier);\r\n * // Obtain verificationCode from the user.\r\n * const userCredential = confirmationResult.confirm(verificationCode);\r\n * ```\r\n *\r\n * @param phoneInfoOptions - The user's {@link PhoneInfoOptions}. The phone number should be in\r\n * E.164 format (e.g. +16505550101).\r\n * @param applicationVerifier - For abuse prevention, this method also requires a\r\n * {@link ApplicationVerifier}. This SDK includes a reCAPTCHA-based implementation,\r\n * {@link RecaptchaVerifier}.\r\n *\r\n * @returns A Promise for a verification ID that can be passed to\r\n * {@link PhoneAuthProvider.credential} to identify this flow..\r\n */\r\n verifyPhoneNumber(phoneOptions, applicationVerifier) {\r\n return _verifyPhoneNumber(this.auth, phoneOptions, getModularInstance(applicationVerifier));\r\n }\r\n /**\r\n * Creates a phone auth credential, given the verification ID from\r\n * {@link PhoneAuthProvider.verifyPhoneNumber} and the code that was sent to the user's\r\n * mobile device.\r\n *\r\n * @example\r\n * ```javascript\r\n * const provider = new PhoneAuthProvider(auth);\r\n * const verificationId = provider.verifyPhoneNumber(phoneNumber, applicationVerifier);\r\n * // Obtain verificationCode from the user.\r\n * const authCredential = PhoneAuthProvider.credential(verificationId, verificationCode);\r\n * const userCredential = signInWithCredential(auth, authCredential);\r\n * ```\r\n *\r\n * @example\r\n * An alternative flow is provided using the `signInWithPhoneNumber` method.\r\n * ```javascript\r\n * const confirmationResult = await signInWithPhoneNumber(auth, phoneNumber, applicationVerifier);\r\n * // Obtain verificationCode from the user.\r\n * const userCredential = await confirmationResult.confirm(verificationCode);\r\n * ```\r\n *\r\n * @param verificationId - The verification ID returned from {@link PhoneAuthProvider.verifyPhoneNumber}.\r\n * @param verificationCode - The verification code sent to the user's mobile device.\r\n *\r\n * @returns The auth provider credential.\r\n */\r\n static credential(verificationId, verificationCode) {\r\n return PhoneAuthCredential._fromVerification(verificationId, verificationCode);\r\n }\r\n /**\r\n * Generates an {@link AuthCredential} from a {@link UserCredential}.\r\n * @param userCredential - The user credential.\r\n */\r\n static credentialFromResult(userCredential) {\r\n const credential = userCredential;\r\n return PhoneAuthProvider.credentialFromTaggedObject(credential);\r\n }\r\n /**\r\n * Returns an {@link AuthCredential} when passed an error.\r\n *\r\n * @remarks\r\n *\r\n * This method works for errors like\r\n * `auth/account-exists-with-different-credentials`. This is useful for\r\n * recovering when attempting to set a user's phone number but the number\r\n * in question is already tied to another account. For example, the following\r\n * code tries to update the current user's phone number, and if that\r\n * fails, links the user with the account associated with that number:\r\n *\r\n * ```js\r\n * const provider = new PhoneAuthProvider(auth);\r\n * const verificationId = await provider.verifyPhoneNumber(number, verifier);\r\n * try {\r\n * const code = ''; // Prompt the user for the verification code\r\n * await updatePhoneNumber(\r\n * auth.currentUser,\r\n * PhoneAuthProvider.credential(verificationId, code));\r\n * } catch (e) {\r\n * if ((e as FirebaseError)?.code === 'auth/account-exists-with-different-credential') {\r\n * const cred = PhoneAuthProvider.credentialFromError(e);\r\n * await linkWithCredential(auth.currentUser, cred);\r\n * }\r\n * }\r\n *\r\n * // At this point, auth.currentUser.phoneNumber === number.\r\n * ```\r\n *\r\n * @param error - The error to generate a credential from.\r\n */\r\n static credentialFromError(error) {\r\n return PhoneAuthProvider.credentialFromTaggedObject((error.customData || {}));\r\n }\r\n static credentialFromTaggedObject({ _tokenResponse: tokenResponse }) {\r\n if (!tokenResponse) {\r\n return null;\r\n }\r\n const { phoneNumber, temporaryProof } = tokenResponse;\r\n if (phoneNumber && temporaryProof) {\r\n return PhoneAuthCredential._fromTokenResponse(phoneNumber, temporaryProof);\r\n }\r\n return null;\r\n }\r\n}\r\n/** Always set to {@link ProviderId}.PHONE. */\r\nPhoneAuthProvider.PROVIDER_ID = \"phone\" /* ProviderId.PHONE */;\r\n/** Always set to {@link SignInMethod}.PHONE. */\r\nPhoneAuthProvider.PHONE_SIGN_IN_METHOD = \"phone\" /* SignInMethod.PHONE */;\n\n/**\r\n * @license\r\n * Copyright 2021 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Chooses a popup/redirect resolver to use. This prefers the override (which\r\n * is directly passed in), and falls back to the property set on the auth\r\n * object. If neither are available, this function errors w/ an argument error.\r\n */\r\nfunction _withDefaultResolver(auth, resolverOverride) {\r\n if (resolverOverride) {\r\n return _getInstance(resolverOverride);\r\n }\r\n _assert(auth._popupRedirectResolver, auth, \"argument-error\" /* AuthErrorCode.ARGUMENT_ERROR */);\r\n return auth._popupRedirectResolver;\r\n}\n\n/**\r\n * @license\r\n * Copyright 2019 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nclass IdpCredential extends AuthCredential {\r\n constructor(params) {\r\n super(\"custom\" /* ProviderId.CUSTOM */, \"custom\" /* ProviderId.CUSTOM */);\r\n this.params = params;\r\n }\r\n _getIdTokenResponse(auth) {\r\n return signInWithIdp(auth, this._buildIdpRequest());\r\n }\r\n _linkToIdToken(auth, idToken) {\r\n return signInWithIdp(auth, this._buildIdpRequest(idToken));\r\n }\r\n _getReauthenticationResolver(auth) {\r\n return signInWithIdp(auth, this._buildIdpRequest());\r\n }\r\n _buildIdpRequest(idToken) {\r\n const request = {\r\n requestUri: this.params.requestUri,\r\n sessionId: this.params.sessionId,\r\n postBody: this.params.postBody,\r\n tenantId: this.params.tenantId,\r\n pendingToken: this.params.pendingToken,\r\n returnSecureToken: true,\r\n returnIdpCredential: true\r\n };\r\n if (idToken) {\r\n request.idToken = idToken;\r\n }\r\n return request;\r\n }\r\n}\r\nfunction _signIn(params) {\r\n return _signInWithCredential(params.auth, new IdpCredential(params), params.bypassAuthState);\r\n}\r\nfunction _reauth(params) {\r\n const { auth, user } = params;\r\n _assert(user, auth, \"internal-error\" /* AuthErrorCode.INTERNAL_ERROR */);\r\n return _reauthenticate(user, new IdpCredential(params), params.bypassAuthState);\r\n}\r\nasync function _link(params) {\r\n const { auth, user } = params;\r\n _assert(user, auth, \"internal-error\" /* AuthErrorCode.INTERNAL_ERROR */);\r\n return _link$1(user, new IdpCredential(params), params.bypassAuthState);\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Popup event manager. Handles the popup's entire lifecycle; listens to auth\r\n * events\r\n */\r\nclass AbstractPopupRedirectOperation {\r\n constructor(auth, filter, resolver, user, bypassAuthState = false) {\r\n this.auth = auth;\r\n this.resolver = resolver;\r\n this.user = user;\r\n this.bypassAuthState = bypassAuthState;\r\n this.pendingPromise = null;\r\n this.eventManager = null;\r\n this.filter = Array.isArray(filter) ? filter : [filter];\r\n }\r\n execute() {\r\n return new Promise(async (resolve, reject) => {\r\n this.pendingPromise = { resolve, reject };\r\n try {\r\n this.eventManager = await this.resolver._initialize(this.auth);\r\n await this.onExecution();\r\n this.eventManager.registerConsumer(this);\r\n }\r\n catch (e) {\r\n this.reject(e);\r\n }\r\n });\r\n }\r\n async onAuthEvent(event) {\r\n const { urlResponse, sessionId, postBody, tenantId, error, type } = event;\r\n if (error) {\r\n this.reject(error);\r\n return;\r\n }\r\n const params = {\r\n auth: this.auth,\r\n requestUri: urlResponse,\r\n sessionId: sessionId,\r\n tenantId: tenantId || undefined,\r\n postBody: postBody || undefined,\r\n user: this.user,\r\n bypassAuthState: this.bypassAuthState\r\n };\r\n try {\r\n this.resolve(await this.getIdpTask(type)(params));\r\n }\r\n catch (e) {\r\n this.reject(e);\r\n }\r\n }\r\n onError(error) {\r\n this.reject(error);\r\n }\r\n getIdpTask(type) {\r\n switch (type) {\r\n case \"signInViaPopup\" /* AuthEventType.SIGN_IN_VIA_POPUP */:\r\n case \"signInViaRedirect\" /* AuthEventType.SIGN_IN_VIA_REDIRECT */:\r\n return _signIn;\r\n case \"linkViaPopup\" /* AuthEventType.LINK_VIA_POPUP */:\r\n case \"linkViaRedirect\" /* AuthEventType.LINK_VIA_REDIRECT */:\r\n return _link;\r\n case \"reauthViaPopup\" /* AuthEventType.REAUTH_VIA_POPUP */:\r\n case \"reauthViaRedirect\" /* AuthEventType.REAUTH_VIA_REDIRECT */:\r\n return _reauth;\r\n default:\r\n _fail(this.auth, \"internal-error\" /* AuthErrorCode.INTERNAL_ERROR */);\r\n }\r\n }\r\n resolve(cred) {\r\n debugAssert(this.pendingPromise, 'Pending promise was never set');\r\n this.pendingPromise.resolve(cred);\r\n this.unregisterAndCleanUp();\r\n }\r\n reject(error) {\r\n debugAssert(this.pendingPromise, 'Pending promise was never set');\r\n this.pendingPromise.reject(error);\r\n this.unregisterAndCleanUp();\r\n }\r\n unregisterAndCleanUp() {\r\n if (this.eventManager) {\r\n this.eventManager.unregisterConsumer(this);\r\n }\r\n this.pendingPromise = null;\r\n this.cleanUp();\r\n }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nconst _POLL_WINDOW_CLOSE_TIMEOUT = new Delay(2000, 10000);\r\n/**\r\n * Authenticates a Firebase client using a popup-based OAuth authentication flow.\r\n *\r\n * @remarks\r\n * If succeeds, returns the signed in user along with the provider's credential. If sign in was\r\n * unsuccessful, returns an error object containing additional information about the error.\r\n *\r\n * @example\r\n * ```javascript\r\n * // Sign in using a popup.\r\n * const provider = new FacebookAuthProvider();\r\n * const result = await signInWithPopup(auth, provider);\r\n *\r\n * // The signed-in user info.\r\n * const user = result.user;\r\n * // This gives you a Facebook Access Token.\r\n * const credential = provider.credentialFromResult(auth, result);\r\n * const token = credential.accessToken;\r\n * ```\r\n *\r\n * @param auth - The {@link Auth} instance.\r\n * @param provider - The provider to authenticate. The provider has to be an {@link OAuthProvider}.\r\n * Non-OAuth providers like {@link EmailAuthProvider} will throw an error.\r\n * @param resolver - An instance of {@link PopupRedirectResolver}, optional\r\n * if already supplied to {@link initializeAuth} or provided by {@link getAuth}.\r\n *\r\n *\r\n * @public\r\n */\r\nasync function signInWithPopup(auth, provider, resolver) {\r\n const authInternal = _castAuth(auth);\r\n _assertInstanceOf(auth, provider, FederatedAuthProvider);\r\n const resolverInternal = _withDefaultResolver(authInternal, resolver);\r\n const action = new PopupOperation(authInternal, \"signInViaPopup\" /* AuthEventType.SIGN_IN_VIA_POPUP */, provider, resolverInternal);\r\n return action.executeNotNull();\r\n}\r\n/**\r\n * Reauthenticates the current user with the specified {@link OAuthProvider} using a pop-up based\r\n * OAuth flow.\r\n *\r\n * @remarks\r\n * If the reauthentication is successful, the returned result will contain the user and the\r\n * provider's credential.\r\n *\r\n * @example\r\n * ```javascript\r\n * // Sign in using a popup.\r\n * const provider = new FacebookAuthProvider();\r\n * const result = await signInWithPopup(auth, provider);\r\n * // Reauthenticate using a popup.\r\n * await reauthenticateWithPopup(result.user, provider);\r\n * ```\r\n *\r\n * @param user - The user.\r\n * @param provider - The provider to authenticate. The provider has to be an {@link OAuthProvider}.\r\n * Non-OAuth providers like {@link EmailAuthProvider} will throw an error.\r\n * @param resolver - An instance of {@link PopupRedirectResolver}, optional\r\n * if already supplied to {@link initializeAuth} or provided by {@link getAuth}.\r\n *\r\n * @public\r\n */\r\nasync function reauthenticateWithPopup(user, provider, resolver) {\r\n const userInternal = getModularInstance(user);\r\n _assertInstanceOf(userInternal.auth, provider, FederatedAuthProvider);\r\n const resolverInternal = _withDefaultResolver(userInternal.auth, resolver);\r\n const action = new PopupOperation(userInternal.auth, \"reauthViaPopup\" /* AuthEventType.REAUTH_VIA_POPUP */, provider, resolverInternal, userInternal);\r\n return action.executeNotNull();\r\n}\r\n/**\r\n * Links the authenticated provider to the user account using a pop-up based OAuth flow.\r\n *\r\n * @remarks\r\n * If the linking is successful, the returned result will contain the user and the provider's credential.\r\n *\r\n *\r\n * @example\r\n * ```javascript\r\n * // Sign in using some other provider.\r\n * const result = await signInWithEmailAndPassword(auth, email, password);\r\n * // Link using a popup.\r\n * const provider = new FacebookAuthProvider();\r\n * await linkWithPopup(result.user, provider);\r\n * ```\r\n *\r\n * @param user - The user.\r\n * @param provider - The provider to authenticate. The provider has to be an {@link OAuthProvider}.\r\n * Non-OAuth providers like {@link EmailAuthProvider} will throw an error.\r\n * @param resolver - An instance of {@link PopupRedirectResolver}, optional\r\n * if already supplied to {@link initializeAuth} or provided by {@link getAuth}.\r\n *\r\n * @public\r\n */\r\nasync function linkWithPopup(user, provider, resolver) {\r\n const userInternal = getModularInstance(user);\r\n _assertInstanceOf(userInternal.auth, provider, FederatedAuthProvider);\r\n const resolverInternal = _withDefaultResolver(userInternal.auth, resolver);\r\n const action = new PopupOperation(userInternal.auth, \"linkViaPopup\" /* AuthEventType.LINK_VIA_POPUP */, provider, resolverInternal, userInternal);\r\n return action.executeNotNull();\r\n}\r\n/**\r\n * Popup event manager. Handles the popup's entire lifecycle; listens to auth\r\n * events\r\n *\r\n */\r\nclass PopupOperation extends AbstractPopupRedirectOperation {\r\n constructor(auth, filter, provider, resolver, user) {\r\n super(auth, filter, resolver, user);\r\n this.provider = provider;\r\n this.authWindow = null;\r\n this.pollId = null;\r\n if (PopupOperation.currentPopupAction) {\r\n PopupOperation.currentPopupAction.cancel();\r\n }\r\n PopupOperation.currentPopupAction = this;\r\n }\r\n async executeNotNull() {\r\n const result = await this.execute();\r\n _assert(result, this.auth, \"internal-error\" /* AuthErrorCode.INTERNAL_ERROR */);\r\n return result;\r\n }\r\n async onExecution() {\r\n debugAssert(this.filter.length === 1, 'Popup operations only handle one event');\r\n const eventId = _generateEventId();\r\n this.authWindow = await this.resolver._openPopup(this.auth, this.provider, this.filter[0], // There's always one, see constructor\r\n eventId);\r\n this.authWindow.associatedEvent = eventId;\r\n // Check for web storage support and origin validation _after_ the popup is\r\n // loaded. These operations are slow (~1 second or so) Rather than\r\n // waiting on them before opening the window, optimistically open the popup\r\n // and check for storage support at the same time. If storage support is\r\n // not available, this will cause the whole thing to reject properly. It\r\n // will also close the popup, but since the promise has already rejected,\r\n // the popup closed by user poll will reject into the void.\r\n this.resolver._originValidation(this.auth).catch(e => {\r\n this.reject(e);\r\n });\r\n this.resolver._isIframeWebStorageSupported(this.auth, isSupported => {\r\n if (!isSupported) {\r\n this.reject(_createError(this.auth, \"web-storage-unsupported\" /* AuthErrorCode.WEB_STORAGE_UNSUPPORTED */));\r\n }\r\n });\r\n // Handle user closure. Notice this does *not* use await\r\n this.pollUserCancellation();\r\n }\r\n get eventId() {\r\n var _a;\r\n return ((_a = this.authWindow) === null || _a === void 0 ? void 0 : _a.associatedEvent) || null;\r\n }\r\n cancel() {\r\n this.reject(_createError(this.auth, \"cancelled-popup-request\" /* AuthErrorCode.EXPIRED_POPUP_REQUEST */));\r\n }\r\n cleanUp() {\r\n if (this.authWindow) {\r\n this.authWindow.close();\r\n }\r\n if (this.pollId) {\r\n window.clearTimeout(this.pollId);\r\n }\r\n this.authWindow = null;\r\n this.pollId = null;\r\n PopupOperation.currentPopupAction = null;\r\n }\r\n pollUserCancellation() {\r\n const poll = () => {\r\n var _a, _b;\r\n if ((_b = (_a = this.authWindow) === null || _a === void 0 ? void 0 : _a.window) === null || _b === void 0 ? void 0 : _b.closed) {\r\n // Make sure that there is sufficient time for whatever action to\r\n // complete. The window could have closed but the sign in network\r\n // call could still be in flight. This is specifically true for\r\n // Firefox or if the opener is in an iframe, in which case the oauth\r\n // helper closes the popup.\r\n this.pollId = window.setTimeout(() => {\r\n this.pollId = null;\r\n this.reject(_createError(this.auth, \"popup-closed-by-user\" /* AuthErrorCode.POPUP_CLOSED_BY_USER */));\r\n }, 8000 /* _Timeout.AUTH_EVENT */);\r\n return;\r\n }\r\n this.pollId = window.setTimeout(poll, _POLL_WINDOW_CLOSE_TIMEOUT.get());\r\n };\r\n poll();\r\n }\r\n}\r\n// Only one popup is ever shown at once. The lifecycle of the current popup\r\n// can be managed / cancelled by the constructor.\r\nPopupOperation.currentPopupAction = null;\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nconst PENDING_REDIRECT_KEY = 'pendingRedirect';\r\n// We only get one redirect outcome for any one auth, so just store it\r\n// in here.\r\nconst redirectOutcomeMap = new Map();\r\nclass RedirectAction extends AbstractPopupRedirectOperation {\r\n constructor(auth, resolver, bypassAuthState = false) {\r\n super(auth, [\r\n \"signInViaRedirect\" /* AuthEventType.SIGN_IN_VIA_REDIRECT */,\r\n \"linkViaRedirect\" /* AuthEventType.LINK_VIA_REDIRECT */,\r\n \"reauthViaRedirect\" /* AuthEventType.REAUTH_VIA_REDIRECT */,\r\n \"unknown\" /* AuthEventType.UNKNOWN */\r\n ], resolver, undefined, bypassAuthState);\r\n this.eventId = null;\r\n }\r\n /**\r\n * Override the execute function; if we already have a redirect result, then\r\n * just return it.\r\n */\r\n async execute() {\r\n let readyOutcome = redirectOutcomeMap.get(this.auth._key());\r\n if (!readyOutcome) {\r\n try {\r\n const hasPendingRedirect = await _getAndClearPendingRedirectStatus(this.resolver, this.auth);\r\n const result = hasPendingRedirect ? await super.execute() : null;\r\n readyOutcome = () => Promise.resolve(result);\r\n }\r\n catch (e) {\r\n readyOutcome = () => Promise.reject(e);\r\n }\r\n redirectOutcomeMap.set(this.auth._key(), readyOutcome);\r\n }\r\n // If we're not bypassing auth state, the ready outcome should be set to\r\n // null.\r\n if (!this.bypassAuthState) {\r\n redirectOutcomeMap.set(this.auth._key(), () => Promise.resolve(null));\r\n }\r\n return readyOutcome();\r\n }\r\n async onAuthEvent(event) {\r\n if (event.type === \"signInViaRedirect\" /* AuthEventType.SIGN_IN_VIA_REDIRECT */) {\r\n return super.onAuthEvent(event);\r\n }\r\n else if (event.type === \"unknown\" /* AuthEventType.UNKNOWN */) {\r\n // This is a sentinel value indicating there's no pending redirect\r\n this.resolve(null);\r\n return;\r\n }\r\n if (event.eventId) {\r\n const user = await this.auth._redirectUserForId(event.eventId);\r\n if (user) {\r\n this.user = user;\r\n return super.onAuthEvent(event);\r\n }\r\n else {\r\n this.resolve(null);\r\n }\r\n }\r\n }\r\n async onExecution() { }\r\n cleanUp() { }\r\n}\r\nasync function _getAndClearPendingRedirectStatus(resolver, auth) {\r\n const key = pendingRedirectKey(auth);\r\n const persistence = resolverPersistence(resolver);\r\n if (!(await persistence._isAvailable())) {\r\n return false;\r\n }\r\n const hasPendingRedirect = (await persistence._get(key)) === 'true';\r\n await persistence._remove(key);\r\n return hasPendingRedirect;\r\n}\r\nasync function _setPendingRedirectStatus(resolver, auth) {\r\n return resolverPersistence(resolver)._set(pendingRedirectKey(auth), 'true');\r\n}\r\nfunction _clearRedirectOutcomes() {\r\n redirectOutcomeMap.clear();\r\n}\r\nfunction _overrideRedirectResult(auth, result) {\r\n redirectOutcomeMap.set(auth._key(), result);\r\n}\r\nfunction resolverPersistence(resolver) {\r\n return _getInstance(resolver._redirectPersistence);\r\n}\r\nfunction pendingRedirectKey(auth) {\r\n return _persistenceKeyName(PENDING_REDIRECT_KEY, auth.config.apiKey, auth.name);\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Authenticates a Firebase client using a full-page redirect flow.\r\n *\r\n * @remarks\r\n * To handle the results and errors for this operation, refer to {@link getRedirectResult}.\r\n * Follow the {@link https://firebase.google.com/docs/auth/web/redirect-best-practices\r\n * | best practices} when using {@link signInWithRedirect}.\r\n *\r\n * @example\r\n * ```javascript\r\n * // Sign in using a redirect.\r\n * const provider = new FacebookAuthProvider();\r\n * // You can add additional scopes to the provider:\r\n * provider.addScope('user_birthday');\r\n * // Start a sign in process for an unauthenticated user.\r\n * await signInWithRedirect(auth, provider);\r\n * // This will trigger a full page redirect away from your app\r\n *\r\n * // After returning from the redirect when your app initializes you can obtain the result\r\n * const result = await getRedirectResult(auth);\r\n * if (result) {\r\n * // This is the signed-in user\r\n * const user = result.user;\r\n * // This gives you a Facebook Access Token.\r\n * const credential = provider.credentialFromResult(auth, result);\r\n * const token = credential.accessToken;\r\n * }\r\n * // As this API can be used for sign-in, linking and reauthentication,\r\n * // check the operationType to determine what triggered this redirect\r\n * // operation.\r\n * const operationType = result.operationType;\r\n * ```\r\n *\r\n * @param auth - The {@link Auth} instance.\r\n * @param provider - The provider to authenticate. The provider has to be an {@link OAuthProvider}.\r\n * Non-OAuth providers like {@link EmailAuthProvider} will throw an error.\r\n * @param resolver - An instance of {@link PopupRedirectResolver}, optional\r\n * if already supplied to {@link initializeAuth} or provided by {@link getAuth}.\r\n *\r\n * @public\r\n */\r\nfunction signInWithRedirect(auth, provider, resolver) {\r\n return _signInWithRedirect(auth, provider, resolver);\r\n}\r\nasync function _signInWithRedirect(auth, provider, resolver) {\r\n const authInternal = _castAuth(auth);\r\n _assertInstanceOf(auth, provider, FederatedAuthProvider);\r\n // Wait for auth initialization to complete, this will process pending redirects and clear the\r\n // PENDING_REDIRECT_KEY in persistence. This should be completed before starting a new\r\n // redirect and creating a PENDING_REDIRECT_KEY entry.\r\n await authInternal._initializationPromise;\r\n const resolverInternal = _withDefaultResolver(authInternal, resolver);\r\n await _setPendingRedirectStatus(resolverInternal, authInternal);\r\n return resolverInternal._openRedirect(authInternal, provider, \"signInViaRedirect\" /* AuthEventType.SIGN_IN_VIA_REDIRECT */);\r\n}\r\n/**\r\n * Reauthenticates the current user with the specified {@link OAuthProvider} using a full-page redirect flow.\r\n * @remarks\r\n * To handle the results and errors for this operation, refer to {@link getRedirectResult}.\r\n * Follow the {@link https://firebase.google.com/docs/auth/web/redirect-best-practices\r\n * | best practices} when using {@link reauthenticateWithRedirect}.\r\n *\r\n * @example\r\n * ```javascript\r\n * // Sign in using a redirect.\r\n * const provider = new FacebookAuthProvider();\r\n * const result = await signInWithRedirect(auth, provider);\r\n * // This will trigger a full page redirect away from your app\r\n *\r\n * // After returning from the redirect when your app initializes you can obtain the result\r\n * const result = await getRedirectResult(auth);\r\n * // Reauthenticate using a redirect.\r\n * await reauthenticateWithRedirect(result.user, provider);\r\n * // This will again trigger a full page redirect away from your app\r\n *\r\n * // After returning from the redirect when your app initializes you can obtain the result\r\n * const result = await getRedirectResult(auth);\r\n * ```\r\n *\r\n * @param user - The user.\r\n * @param provider - The provider to authenticate. The provider has to be an {@link OAuthProvider}.\r\n * Non-OAuth providers like {@link EmailAuthProvider} will throw an error.\r\n * @param resolver - An instance of {@link PopupRedirectResolver}, optional\r\n * if already supplied to {@link initializeAuth} or provided by {@link getAuth}.\r\n *\r\n * @public\r\n */\r\nfunction reauthenticateWithRedirect(user, provider, resolver) {\r\n return _reauthenticateWithRedirect(user, provider, resolver);\r\n}\r\nasync function _reauthenticateWithRedirect(user, provider, resolver) {\r\n const userInternal = getModularInstance(user);\r\n _assertInstanceOf(userInternal.auth, provider, FederatedAuthProvider);\r\n // Wait for auth initialization to complete, this will process pending redirects and clear the\r\n // PENDING_REDIRECT_KEY in persistence. This should be completed before starting a new\r\n // redirect and creating a PENDING_REDIRECT_KEY entry.\r\n await userInternal.auth._initializationPromise;\r\n // Allow the resolver to error before persisting the redirect user\r\n const resolverInternal = _withDefaultResolver(userInternal.auth, resolver);\r\n await _setPendingRedirectStatus(resolverInternal, userInternal.auth);\r\n const eventId = await prepareUserForRedirect(userInternal);\r\n return resolverInternal._openRedirect(userInternal.auth, provider, \"reauthViaRedirect\" /* AuthEventType.REAUTH_VIA_REDIRECT */, eventId);\r\n}\r\n/**\r\n * Links the {@link OAuthProvider} to the user account using a full-page redirect flow.\r\n * @remarks\r\n * To handle the results and errors for this operation, refer to {@link getRedirectResult}.\r\n * Follow the {@link https://firebase.google.com/docs/auth/web/redirect-best-practices\r\n * | best practices} when using {@link linkWithRedirect}.\r\n *\r\n * @example\r\n * ```javascript\r\n * // Sign in using some other provider.\r\n * const result = await signInWithEmailAndPassword(auth, email, password);\r\n * // Link using a redirect.\r\n * const provider = new FacebookAuthProvider();\r\n * await linkWithRedirect(result.user, provider);\r\n * // This will trigger a full page redirect away from your app\r\n *\r\n * // After returning from the redirect when your app initializes you can obtain the result\r\n * const result = await getRedirectResult(auth);\r\n * ```\r\n *\r\n * @param user - The user.\r\n * @param provider - The provider to authenticate. The provider has to be an {@link OAuthProvider}.\r\n * Non-OAuth providers like {@link EmailAuthProvider} will throw an error.\r\n * @param resolver - An instance of {@link PopupRedirectResolver}, optional\r\n * if already supplied to {@link initializeAuth} or provided by {@link getAuth}.\r\n *\r\n *\r\n * @public\r\n */\r\nfunction linkWithRedirect(user, provider, resolver) {\r\n return _linkWithRedirect(user, provider, resolver);\r\n}\r\nasync function _linkWithRedirect(user, provider, resolver) {\r\n const userInternal = getModularInstance(user);\r\n _assertInstanceOf(userInternal.auth, provider, FederatedAuthProvider);\r\n // Wait for auth initialization to complete, this will process pending redirects and clear the\r\n // PENDING_REDIRECT_KEY in persistence. This should be completed before starting a new\r\n // redirect and creating a PENDING_REDIRECT_KEY entry.\r\n await userInternal.auth._initializationPromise;\r\n // Allow the resolver to error before persisting the redirect user\r\n const resolverInternal = _withDefaultResolver(userInternal.auth, resolver);\r\n await _assertLinkedStatus(false, userInternal, provider.providerId);\r\n await _setPendingRedirectStatus(resolverInternal, userInternal.auth);\r\n const eventId = await prepareUserForRedirect(userInternal);\r\n return resolverInternal._openRedirect(userInternal.auth, provider, \"linkViaRedirect\" /* AuthEventType.LINK_VIA_REDIRECT */, eventId);\r\n}\r\n/**\r\n * Returns a {@link UserCredential} from the redirect-based sign-in flow.\r\n *\r\n * @remarks\r\n * If sign-in succeeded, returns the signed in user. If sign-in was unsuccessful, fails with an\r\n * error. If no redirect operation was called, returns `null`.\r\n *\r\n * @example\r\n * ```javascript\r\n * // Sign in using a redirect.\r\n * const provider = new FacebookAuthProvider();\r\n * // You can add additional scopes to the provider:\r\n * provider.addScope('user_birthday');\r\n * // Start a sign in process for an unauthenticated user.\r\n * await signInWithRedirect(auth, provider);\r\n * // This will trigger a full page redirect away from your app\r\n *\r\n * // After returning from the redirect when your app initializes you can obtain the result\r\n * const result = await getRedirectResult(auth);\r\n * if (result) {\r\n * // This is the signed-in user\r\n * const user = result.user;\r\n * // This gives you a Facebook Access Token.\r\n * const credential = provider.credentialFromResult(auth, result);\r\n * const token = credential.accessToken;\r\n * }\r\n * // As this API can be used for sign-in, linking and reauthentication,\r\n * // check the operationType to determine what triggered this redirect\r\n * // operation.\r\n * const operationType = result.operationType;\r\n * ```\r\n *\r\n * @param auth - The {@link Auth} instance.\r\n * @param resolver - An instance of {@link PopupRedirectResolver}, optional\r\n * if already supplied to {@link initializeAuth} or provided by {@link getAuth}.\r\n *\r\n * @public\r\n */\r\nasync function getRedirectResult(auth, resolver) {\r\n await _castAuth(auth)._initializationPromise;\r\n return _getRedirectResult(auth, resolver, false);\r\n}\r\nasync function _getRedirectResult(auth, resolverExtern, bypassAuthState = false) {\r\n const authInternal = _castAuth(auth);\r\n const resolver = _withDefaultResolver(authInternal, resolverExtern);\r\n const action = new RedirectAction(authInternal, resolver, bypassAuthState);\r\n const result = await action.execute();\r\n if (result && !bypassAuthState) {\r\n delete result.user._redirectEventId;\r\n await authInternal._persistUserIfCurrent(result.user);\r\n await authInternal._setRedirectUser(null, resolverExtern);\r\n }\r\n return result;\r\n}\r\nasync function prepareUserForRedirect(user) {\r\n const eventId = _generateEventId(`${user.uid}:::`);\r\n user._redirectEventId = eventId;\r\n await user.auth._setRedirectUser(user);\r\n await user.auth._persistUserIfCurrent(user);\r\n return eventId;\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n// The amount of time to store the UIDs of seen events; this is\r\n// set to 10 min by default\r\nconst EVENT_DUPLICATION_CACHE_DURATION_MS = 10 * 60 * 1000;\r\nclass AuthEventManager {\r\n constructor(auth) {\r\n this.auth = auth;\r\n this.cachedEventUids = new Set();\r\n this.consumers = new Set();\r\n this.queuedRedirectEvent = null;\r\n this.hasHandledPotentialRedirect = false;\r\n this.lastProcessedEventTime = Date.now();\r\n }\r\n registerConsumer(authEventConsumer) {\r\n this.consumers.add(authEventConsumer);\r\n if (this.queuedRedirectEvent &&\r\n this.isEventForConsumer(this.queuedRedirectEvent, authEventConsumer)) {\r\n this.sendToConsumer(this.queuedRedirectEvent, authEventConsumer);\r\n this.saveEventToCache(this.queuedRedirectEvent);\r\n this.queuedRedirectEvent = null;\r\n }\r\n }\r\n unregisterConsumer(authEventConsumer) {\r\n this.consumers.delete(authEventConsumer);\r\n }\r\n onEvent(event) {\r\n // Check if the event has already been handled\r\n if (this.hasEventBeenHandled(event)) {\r\n return false;\r\n }\r\n let handled = false;\r\n this.consumers.forEach(consumer => {\r\n if (this.isEventForConsumer(event, consumer)) {\r\n handled = true;\r\n this.sendToConsumer(event, consumer);\r\n this.saveEventToCache(event);\r\n }\r\n });\r\n if (this.hasHandledPotentialRedirect || !isRedirectEvent(event)) {\r\n // If we've already seen a redirect before, or this is a popup event,\r\n // bail now\r\n return handled;\r\n }\r\n this.hasHandledPotentialRedirect = true;\r\n // If the redirect wasn't handled, hang on to it\r\n if (!handled) {\r\n this.queuedRedirectEvent = event;\r\n handled = true;\r\n }\r\n return handled;\r\n }\r\n sendToConsumer(event, consumer) {\r\n var _a;\r\n if (event.error && !isNullRedirectEvent(event)) {\r\n const code = ((_a = event.error.code) === null || _a === void 0 ? void 0 : _a.split('auth/')[1]) ||\r\n \"internal-error\" /* AuthErrorCode.INTERNAL_ERROR */;\r\n consumer.onError(_createError(this.auth, code));\r\n }\r\n else {\r\n consumer.onAuthEvent(event);\r\n }\r\n }\r\n isEventForConsumer(event, consumer) {\r\n const eventIdMatches = consumer.eventId === null ||\r\n (!!event.eventId && event.eventId === consumer.eventId);\r\n return consumer.filter.includes(event.type) && eventIdMatches;\r\n }\r\n hasEventBeenHandled(event) {\r\n if (Date.now() - this.lastProcessedEventTime >=\r\n EVENT_DUPLICATION_CACHE_DURATION_MS) {\r\n this.cachedEventUids.clear();\r\n }\r\n return this.cachedEventUids.has(eventUid(event));\r\n }\r\n saveEventToCache(event) {\r\n this.cachedEventUids.add(eventUid(event));\r\n this.lastProcessedEventTime = Date.now();\r\n }\r\n}\r\nfunction eventUid(e) {\r\n return [e.type, e.eventId, e.sessionId, e.tenantId].filter(v => v).join('-');\r\n}\r\nfunction isNullRedirectEvent({ type, error }) {\r\n return (type === \"unknown\" /* AuthEventType.UNKNOWN */ &&\r\n (error === null || error === void 0 ? void 0 : error.code) === `auth/${\"no-auth-event\" /* AuthErrorCode.NO_AUTH_EVENT */}`);\r\n}\r\nfunction isRedirectEvent(event) {\r\n switch (event.type) {\r\n case \"signInViaRedirect\" /* AuthEventType.SIGN_IN_VIA_REDIRECT */:\r\n case \"linkViaRedirect\" /* AuthEventType.LINK_VIA_REDIRECT */:\r\n case \"reauthViaRedirect\" /* AuthEventType.REAUTH_VIA_REDIRECT */:\r\n return true;\r\n case \"unknown\" /* AuthEventType.UNKNOWN */:\r\n return isNullRedirectEvent(event);\r\n default:\r\n return false;\r\n }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nasync function _getProjectConfig(auth, request = {}) {\r\n return _performApiRequest(auth, \"GET\" /* HttpMethod.GET */, \"/v1/projects\" /* Endpoint.GET_PROJECT_CONFIG */, request);\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nconst IP_ADDRESS_REGEX = /^\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}$/;\r\nconst HTTP_REGEX = /^https?/;\r\nasync function _validateOrigin(auth) {\r\n // Skip origin validation if we are in an emulated environment\r\n if (auth.config.emulator) {\r\n return;\r\n }\r\n const { authorizedDomains } = await _getProjectConfig(auth);\r\n for (const domain of authorizedDomains) {\r\n try {\r\n if (matchDomain(domain)) {\r\n return;\r\n }\r\n }\r\n catch (_a) {\r\n // Do nothing if there's a URL error; just continue searching\r\n }\r\n }\r\n // In the old SDK, this error also provides helpful messages.\r\n _fail(auth, \"unauthorized-domain\" /* AuthErrorCode.INVALID_ORIGIN */);\r\n}\r\nfunction matchDomain(expected) {\r\n const currentUrl = _getCurrentUrl();\r\n const { protocol, hostname } = new URL(currentUrl);\r\n if (expected.startsWith('chrome-extension://')) {\r\n const ceUrl = new URL(expected);\r\n if (ceUrl.hostname === '' && hostname === '') {\r\n // For some reason we're not parsing chrome URLs properly\r\n return (protocol === 'chrome-extension:' &&\r\n expected.replace('chrome-extension://', '') ===\r\n currentUrl.replace('chrome-extension://', ''));\r\n }\r\n return protocol === 'chrome-extension:' && ceUrl.hostname === hostname;\r\n }\r\n if (!HTTP_REGEX.test(protocol)) {\r\n return false;\r\n }\r\n if (IP_ADDRESS_REGEX.test(expected)) {\r\n // The domain has to be exactly equal to the pattern, as an IP domain will\r\n // only contain the IP, no extra character.\r\n return hostname === expected;\r\n }\r\n // Dots in pattern should be escaped.\r\n const escapedDomainPattern = expected.replace(/\\./g, '\\\\.');\r\n // Non ip address domains.\r\n // domain.com = *.domain.com OR domain.com\r\n const re = new RegExp('^(.+\\\\.' + escapedDomainPattern + '|' + escapedDomainPattern + ')$', 'i');\r\n return re.test(hostname);\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nconst NETWORK_TIMEOUT = new Delay(30000, 60000);\r\n/**\r\n * Reset unlaoded GApi modules. If gapi.load fails due to a network error,\r\n * it will stop working after a retrial. This is a hack to fix this issue.\r\n */\r\nfunction resetUnloadedGapiModules() {\r\n // Clear last failed gapi.load state to force next gapi.load to first\r\n // load the failed gapi.iframes module.\r\n // Get gapix.beacon context.\r\n const beacon = _window().___jsl;\r\n // Get current hint.\r\n if (beacon === null || beacon === void 0 ? void 0 : beacon.H) {\r\n // Get gapi hint.\r\n for (const hint of Object.keys(beacon.H)) {\r\n // Requested modules.\r\n beacon.H[hint].r = beacon.H[hint].r || [];\r\n // Loaded modules.\r\n beacon.H[hint].L = beacon.H[hint].L || [];\r\n // Set requested modules to a copy of the loaded modules.\r\n beacon.H[hint].r = [...beacon.H[hint].L];\r\n // Clear pending callbacks.\r\n if (beacon.CP) {\r\n for (let i = 0; i < beacon.CP.length; i++) {\r\n // Remove all failed pending callbacks.\r\n beacon.CP[i] = null;\r\n }\r\n }\r\n }\r\n }\r\n}\r\nfunction loadGapi(auth) {\r\n return new Promise((resolve, reject) => {\r\n var _a, _b, _c;\r\n // Function to run when gapi.load is ready.\r\n function loadGapiIframe() {\r\n // The developer may have tried to previously run gapi.load and failed.\r\n // Run this to fix that.\r\n resetUnloadedGapiModules();\r\n gapi.load('gapi.iframes', {\r\n callback: () => {\r\n resolve(gapi.iframes.getContext());\r\n },\r\n ontimeout: () => {\r\n // The above reset may be sufficient, but having this reset after\r\n // failure ensures that if the developer calls gapi.load after the\r\n // connection is re-established and before another attempt to embed\r\n // the iframe, it would work and would not be broken because of our\r\n // failed attempt.\r\n // Timeout when gapi.iframes.Iframe not loaded.\r\n resetUnloadedGapiModules();\r\n reject(_createError(auth, \"network-request-failed\" /* AuthErrorCode.NETWORK_REQUEST_FAILED */));\r\n },\r\n timeout: NETWORK_TIMEOUT.get()\r\n });\r\n }\r\n if ((_b = (_a = _window().gapi) === null || _a === void 0 ? void 0 : _a.iframes) === null || _b === void 0 ? void 0 : _b.Iframe) {\r\n // If gapi.iframes.Iframe available, resolve.\r\n resolve(gapi.iframes.getContext());\r\n }\r\n else if (!!((_c = _window().gapi) === null || _c === void 0 ? void 0 : _c.load)) {\r\n // Gapi loader ready, load gapi.iframes.\r\n loadGapiIframe();\r\n }\r\n else {\r\n // Create a new iframe callback when this is called so as not to overwrite\r\n // any previous defined callback. This happens if this method is called\r\n // multiple times in parallel and could result in the later callback\r\n // overwriting the previous one. This would end up with a iframe\r\n // timeout.\r\n const cbName = _generateCallbackName('iframefcb');\r\n // GApi loader not available, dynamically load platform.js.\r\n _window()[cbName] = () => {\r\n // GApi loader should be ready.\r\n if (!!gapi.load) {\r\n loadGapiIframe();\r\n }\r\n else {\r\n // Gapi loader failed, throw error.\r\n reject(_createError(auth, \"network-request-failed\" /* AuthErrorCode.NETWORK_REQUEST_FAILED */));\r\n }\r\n };\r\n // Load GApi loader.\r\n return _loadJS(`https://apis.google.com/js/api.js?onload=${cbName}`)\r\n .catch(e => reject(e));\r\n }\r\n }).catch(error => {\r\n // Reset cached promise to allow for retrial.\r\n cachedGApiLoader = null;\r\n throw error;\r\n });\r\n}\r\nlet cachedGApiLoader = null;\r\nfunction _loadGapi(auth) {\r\n cachedGApiLoader = cachedGApiLoader || loadGapi(auth);\r\n return cachedGApiLoader;\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nconst PING_TIMEOUT = new Delay(5000, 15000);\r\nconst IFRAME_PATH = '__/auth/iframe';\r\nconst EMULATED_IFRAME_PATH = 'emulator/auth/iframe';\r\nconst IFRAME_ATTRIBUTES = {\r\n style: {\r\n position: 'absolute',\r\n top: '-100px',\r\n width: '1px',\r\n height: '1px'\r\n },\r\n 'aria-hidden': 'true',\r\n tabindex: '-1'\r\n};\r\n// Map from apiHost to endpoint ID for passing into iframe. In current SDK, apiHost can be set to\r\n// anything (not from a list of endpoints with IDs as in legacy), so this is the closest we can get.\r\nconst EID_FROM_APIHOST = new Map([\r\n [\"identitytoolkit.googleapis.com\" /* DefaultConfig.API_HOST */, 'p'],\r\n ['staging-identitytoolkit.sandbox.googleapis.com', 's'],\r\n ['test-identitytoolkit.sandbox.googleapis.com', 't'] // test\r\n]);\r\nfunction getIframeUrl(auth) {\r\n const config = auth.config;\r\n _assert(config.authDomain, auth, \"auth-domain-config-required\" /* AuthErrorCode.MISSING_AUTH_DOMAIN */);\r\n const url = config.emulator\r\n ? _emulatorUrl(config, EMULATED_IFRAME_PATH)\r\n : `https://${auth.config.authDomain}/${IFRAME_PATH}`;\r\n const params = {\r\n apiKey: config.apiKey,\r\n appName: auth.name,\r\n v: SDK_VERSION\r\n };\r\n const eid = EID_FROM_APIHOST.get(auth.config.apiHost);\r\n if (eid) {\r\n params.eid = eid;\r\n }\r\n const frameworks = auth._getFrameworks();\r\n if (frameworks.length) {\r\n params.fw = frameworks.join(',');\r\n }\r\n return `${url}?${querystring(params).slice(1)}`;\r\n}\r\nasync function _openIframe(auth) {\r\n const context = await _loadGapi(auth);\r\n const gapi = _window().gapi;\r\n _assert(gapi, auth, \"internal-error\" /* AuthErrorCode.INTERNAL_ERROR */);\r\n return context.open({\r\n where: document.body,\r\n url: getIframeUrl(auth),\r\n messageHandlersFilter: gapi.iframes.CROSS_ORIGIN_IFRAMES_FILTER,\r\n attributes: IFRAME_ATTRIBUTES,\r\n dontclear: true\r\n }, (iframe) => new Promise(async (resolve, reject) => {\r\n await iframe.restyle({\r\n // Prevent iframe from closing on mouse out.\r\n setHideOnLeave: false\r\n });\r\n const networkError = _createError(auth, \"network-request-failed\" /* AuthErrorCode.NETWORK_REQUEST_FAILED */);\r\n // Confirm iframe is correctly loaded.\r\n // To fallback on failure, set a timeout.\r\n const networkErrorTimer = _window().setTimeout(() => {\r\n reject(networkError);\r\n }, PING_TIMEOUT.get());\r\n // Clear timer and resolve pending iframe ready promise.\r\n function clearTimerAndResolve() {\r\n _window().clearTimeout(networkErrorTimer);\r\n resolve(iframe);\r\n }\r\n // This returns an IThenable. However the reject part does not call\r\n // when the iframe is not loaded.\r\n iframe.ping(clearTimerAndResolve).then(clearTimerAndResolve, () => {\r\n reject(networkError);\r\n });\r\n }));\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nconst BASE_POPUP_OPTIONS = {\r\n location: 'yes',\r\n resizable: 'yes',\r\n statusbar: 'yes',\r\n toolbar: 'no'\r\n};\r\nconst DEFAULT_WIDTH = 500;\r\nconst DEFAULT_HEIGHT = 600;\r\nconst TARGET_BLANK = '_blank';\r\nconst FIREFOX_EMPTY_URL = 'http://localhost';\r\nclass AuthPopup {\r\n constructor(window) {\r\n this.window = window;\r\n this.associatedEvent = null;\r\n }\r\n close() {\r\n if (this.window) {\r\n try {\r\n this.window.close();\r\n }\r\n catch (e) { }\r\n }\r\n }\r\n}\r\nfunction _open(auth, url, name, width = DEFAULT_WIDTH, height = DEFAULT_HEIGHT) {\r\n const top = Math.max((window.screen.availHeight - height) / 2, 0).toString();\r\n const left = Math.max((window.screen.availWidth - width) / 2, 0).toString();\r\n let target = '';\r\n const options = Object.assign(Object.assign({}, BASE_POPUP_OPTIONS), { width: width.toString(), height: height.toString(), top,\r\n left });\r\n // Chrome iOS 7 and 8 is returning an undefined popup win when target is\r\n // specified, even though the popup is not necessarily blocked.\r\n const ua = getUA().toLowerCase();\r\n if (name) {\r\n target = _isChromeIOS(ua) ? TARGET_BLANK : name;\r\n }\r\n if (_isFirefox(ua)) {\r\n // Firefox complains when invalid URLs are popped out. Hacky way to bypass.\r\n url = url || FIREFOX_EMPTY_URL;\r\n // Firefox disables by default scrolling on popup windows, which can create\r\n // issues when the user has many Google accounts, for instance.\r\n options.scrollbars = 'yes';\r\n }\r\n const optionsString = Object.entries(options).reduce((accum, [key, value]) => `${accum}${key}=${value},`, '');\r\n if (_isIOSStandalone(ua) && target !== '_self') {\r\n openAsNewWindowIOS(url || '', target);\r\n return new AuthPopup(null);\r\n }\r\n // about:blank getting sanitized causing browsers like IE/Edge to display\r\n // brief error message before redirecting to handler.\r\n const newWin = window.open(url || '', target, optionsString);\r\n _assert(newWin, auth, \"popup-blocked\" /* AuthErrorCode.POPUP_BLOCKED */);\r\n // Flaky on IE edge, encapsulate with a try and catch.\r\n try {\r\n newWin.focus();\r\n }\r\n catch (e) { }\r\n return new AuthPopup(newWin);\r\n}\r\nfunction openAsNewWindowIOS(url, target) {\r\n const el = document.createElement('a');\r\n el.href = url;\r\n el.target = target;\r\n const click = document.createEvent('MouseEvent');\r\n click.initMouseEvent('click', true, true, window, 1, 0, 0, 0, 0, false, false, false, false, 1, null);\r\n el.dispatchEvent(click);\r\n}\n\n/**\r\n * @license\r\n * Copyright 2021 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * URL for Authentication widget which will initiate the OAuth handshake\r\n *\r\n * @internal\r\n */\r\nconst WIDGET_PATH = '__/auth/handler';\r\n/**\r\n * URL for emulated environment\r\n *\r\n * @internal\r\n */\r\nconst EMULATOR_WIDGET_PATH = 'emulator/auth/handler';\r\n/**\r\n * Fragment name for the App Check token that gets passed to the widget\r\n *\r\n * @internal\r\n */\r\nconst FIREBASE_APP_CHECK_FRAGMENT_ID = encodeURIComponent('fac');\r\nasync function _getRedirectUrl(auth, provider, authType, redirectUrl, eventId, additionalParams) {\r\n _assert(auth.config.authDomain, auth, \"auth-domain-config-required\" /* AuthErrorCode.MISSING_AUTH_DOMAIN */);\r\n _assert(auth.config.apiKey, auth, \"invalid-api-key\" /* AuthErrorCode.INVALID_API_KEY */);\r\n const params = {\r\n apiKey: auth.config.apiKey,\r\n appName: auth.name,\r\n authType,\r\n redirectUrl,\r\n v: SDK_VERSION,\r\n eventId\r\n };\r\n if (provider instanceof FederatedAuthProvider) {\r\n provider.setDefaultLanguage(auth.languageCode);\r\n params.providerId = provider.providerId || '';\r\n if (!isEmpty(provider.getCustomParameters())) {\r\n params.customParameters = JSON.stringify(provider.getCustomParameters());\r\n }\r\n // TODO set additionalParams from the provider as well?\r\n for (const [key, value] of Object.entries(additionalParams || {})) {\r\n params[key] = value;\r\n }\r\n }\r\n if (provider instanceof BaseOAuthProvider) {\r\n const scopes = provider.getScopes().filter(scope => scope !== '');\r\n if (scopes.length > 0) {\r\n params.scopes = scopes.join(',');\r\n }\r\n }\r\n if (auth.tenantId) {\r\n params.tid = auth.tenantId;\r\n }\r\n // TODO: maybe set eid as endipointId\r\n // TODO: maybe set fw as Frameworks.join(\",\")\r\n const paramsDict = params;\r\n for (const key of Object.keys(paramsDict)) {\r\n if (paramsDict[key] === undefined) {\r\n delete paramsDict[key];\r\n }\r\n }\r\n // Sets the App Check token to pass to the widget\r\n const appCheckToken = await auth._getAppCheckToken();\r\n const appCheckTokenFragment = appCheckToken\r\n ? `#${FIREBASE_APP_CHECK_FRAGMENT_ID}=${encodeURIComponent(appCheckToken)}`\r\n : '';\r\n // Start at index 1 to skip the leading '&' in the query string\r\n return `${getHandlerBase(auth)}?${querystring(paramsDict).slice(1)}${appCheckTokenFragment}`;\r\n}\r\nfunction getHandlerBase({ config }) {\r\n if (!config.emulator) {\r\n return `https://${config.authDomain}/${WIDGET_PATH}`;\r\n }\r\n return _emulatorUrl(config, EMULATOR_WIDGET_PATH);\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * The special web storage event\r\n *\r\n */\r\nconst WEB_STORAGE_SUPPORT_KEY = 'webStorageSupport';\r\nclass BrowserPopupRedirectResolver {\r\n constructor() {\r\n this.eventManagers = {};\r\n this.iframes = {};\r\n this.originValidationPromises = {};\r\n this._redirectPersistence = browserSessionPersistence;\r\n this._completeRedirectFn = _getRedirectResult;\r\n this._overrideRedirectResult = _overrideRedirectResult;\r\n }\r\n // Wrapping in async even though we don't await anywhere in order\r\n // to make sure errors are raised as promise rejections\r\n async _openPopup(auth, provider, authType, eventId) {\r\n var _a;\r\n debugAssert((_a = this.eventManagers[auth._key()]) === null || _a === void 0 ? void 0 : _a.manager, '_initialize() not called before _openPopup()');\r\n const url = await _getRedirectUrl(auth, provider, authType, _getCurrentUrl(), eventId);\r\n return _open(auth, url, _generateEventId());\r\n }\r\n async _openRedirect(auth, provider, authType, eventId) {\r\n await this._originValidation(auth);\r\n const url = await _getRedirectUrl(auth, provider, authType, _getCurrentUrl(), eventId);\r\n _setWindowLocation(url);\r\n return new Promise(() => { });\r\n }\r\n _initialize(auth) {\r\n const key = auth._key();\r\n if (this.eventManagers[key]) {\r\n const { manager, promise } = this.eventManagers[key];\r\n if (manager) {\r\n return Promise.resolve(manager);\r\n }\r\n else {\r\n debugAssert(promise, 'If manager is not set, promise should be');\r\n return promise;\r\n }\r\n }\r\n const promise = this.initAndGetManager(auth);\r\n this.eventManagers[key] = { promise };\r\n // If the promise is rejected, the key should be removed so that the\r\n // operation can be retried later.\r\n promise.catch(() => {\r\n delete this.eventManagers[key];\r\n });\r\n return promise;\r\n }\r\n async initAndGetManager(auth) {\r\n const iframe = await _openIframe(auth);\r\n const manager = new AuthEventManager(auth);\r\n iframe.register('authEvent', (iframeEvent) => {\r\n _assert(iframeEvent === null || iframeEvent === void 0 ? void 0 : iframeEvent.authEvent, auth, \"invalid-auth-event\" /* AuthErrorCode.INVALID_AUTH_EVENT */);\r\n // TODO: Consider splitting redirect and popup events earlier on\r\n const handled = manager.onEvent(iframeEvent.authEvent);\r\n return { status: handled ? \"ACK\" /* GapiOutcome.ACK */ : \"ERROR\" /* GapiOutcome.ERROR */ };\r\n }, gapi.iframes.CROSS_ORIGIN_IFRAMES_FILTER);\r\n this.eventManagers[auth._key()] = { manager };\r\n this.iframes[auth._key()] = iframe;\r\n return manager;\r\n }\r\n _isIframeWebStorageSupported(auth, cb) {\r\n const iframe = this.iframes[auth._key()];\r\n iframe.send(WEB_STORAGE_SUPPORT_KEY, { type: WEB_STORAGE_SUPPORT_KEY }, result => {\r\n var _a;\r\n const isSupported = (_a = result === null || result === void 0 ? void 0 : result[0]) === null || _a === void 0 ? void 0 : _a[WEB_STORAGE_SUPPORT_KEY];\r\n if (isSupported !== undefined) {\r\n cb(!!isSupported);\r\n }\r\n _fail(auth, \"internal-error\" /* AuthErrorCode.INTERNAL_ERROR */);\r\n }, gapi.iframes.CROSS_ORIGIN_IFRAMES_FILTER);\r\n }\r\n _originValidation(auth) {\r\n const key = auth._key();\r\n if (!this.originValidationPromises[key]) {\r\n this.originValidationPromises[key] = _validateOrigin(auth);\r\n }\r\n return this.originValidationPromises[key];\r\n }\r\n get _shouldInitProactively() {\r\n // Mobile browsers and Safari need to optimistically initialize\r\n return _isMobileBrowser() || _isSafari() || _isIOS();\r\n }\r\n}\r\n/**\r\n * An implementation of {@link PopupRedirectResolver} suitable for browser\r\n * based applications.\r\n *\r\n * @public\r\n */\r\nconst browserPopupRedirectResolver = BrowserPopupRedirectResolver;\n\nclass MultiFactorAssertionImpl {\r\n constructor(factorId) {\r\n this.factorId = factorId;\r\n }\r\n _process(auth, session, displayName) {\r\n switch (session.type) {\r\n case \"enroll\" /* MultiFactorSessionType.ENROLL */:\r\n return this._finalizeEnroll(auth, session.credential, displayName);\r\n case \"signin\" /* MultiFactorSessionType.SIGN_IN */:\r\n return this._finalizeSignIn(auth, session.credential);\r\n default:\r\n return debugFail('unexpected MultiFactorSessionType');\r\n }\r\n }\r\n}\n\n/**\r\n * {@inheritdoc PhoneMultiFactorAssertion}\r\n *\r\n * @public\r\n */\r\nclass PhoneMultiFactorAssertionImpl extends MultiFactorAssertionImpl {\r\n constructor(credential) {\r\n super(\"phone\" /* FactorId.PHONE */);\r\n this.credential = credential;\r\n }\r\n /** @internal */\r\n static _fromCredential(credential) {\r\n return new PhoneMultiFactorAssertionImpl(credential);\r\n }\r\n /** @internal */\r\n _finalizeEnroll(auth, idToken, displayName) {\r\n return finalizeEnrollPhoneMfa(auth, {\r\n idToken,\r\n displayName,\r\n phoneVerificationInfo: this.credential._makeVerificationRequest()\r\n });\r\n }\r\n /** @internal */\r\n _finalizeSignIn(auth, mfaPendingCredential) {\r\n return finalizeSignInPhoneMfa(auth, {\r\n mfaPendingCredential,\r\n phoneVerificationInfo: this.credential._makeVerificationRequest()\r\n });\r\n }\r\n}\r\n/**\r\n * Provider for generating a {@link PhoneMultiFactorAssertion}.\r\n *\r\n * @public\r\n */\r\nclass PhoneMultiFactorGenerator {\r\n constructor() { }\r\n /**\r\n * Provides a {@link PhoneMultiFactorAssertion} to confirm ownership of the phone second factor.\r\n *\r\n * @param phoneAuthCredential - A credential provided by {@link PhoneAuthProvider.credential}.\r\n * @returns A {@link PhoneMultiFactorAssertion} which can be used with\r\n * {@link MultiFactorResolver.resolveSignIn}\r\n */\r\n static assertion(credential) {\r\n return PhoneMultiFactorAssertionImpl._fromCredential(credential);\r\n }\r\n}\r\n/**\r\n * The identifier of the phone second factor: `phone`.\r\n */\r\nPhoneMultiFactorGenerator.FACTOR_ID = 'phone';\n\n/**\r\n * Provider for generating a {@link TotpMultiFactorAssertion}.\r\n *\r\n * @public\r\n */\r\nclass TotpMultiFactorGenerator {\r\n /**\r\n * Provides a {@link TotpMultiFactorAssertion} to confirm ownership of\r\n * the TOTP (time-based one-time password) second factor.\r\n * This assertion is used to complete enrollment in TOTP second factor.\r\n *\r\n * @param secret A {@link TotpSecret} containing the shared secret key and other TOTP parameters.\r\n * @param oneTimePassword One-time password from TOTP App.\r\n * @returns A {@link TotpMultiFactorAssertion} which can be used with\r\n * {@link MultiFactorUser.enroll}.\r\n */\r\n static assertionForEnrollment(secret, oneTimePassword) {\r\n return TotpMultiFactorAssertionImpl._fromSecret(secret, oneTimePassword);\r\n }\r\n /**\r\n * Provides a {@link TotpMultiFactorAssertion} to confirm ownership of the TOTP second factor.\r\n * This assertion is used to complete signIn with TOTP as the second factor.\r\n *\r\n * @param enrollmentId identifies the enrolled TOTP second factor.\r\n * @param oneTimePassword One-time password from TOTP App.\r\n * @returns A {@link TotpMultiFactorAssertion} which can be used with\r\n * {@link MultiFactorResolver.resolveSignIn}.\r\n */\r\n static assertionForSignIn(enrollmentId, oneTimePassword) {\r\n return TotpMultiFactorAssertionImpl._fromEnrollmentId(enrollmentId, oneTimePassword);\r\n }\r\n /**\r\n * Returns a promise to {@link TotpSecret} which contains the TOTP shared secret key and other parameters.\r\n * Creates a TOTP secret as part of enrolling a TOTP second factor.\r\n * Used for generating a QR code URL or inputting into a TOTP app.\r\n * This method uses the auth instance corresponding to the user in the multiFactorSession.\r\n *\r\n * @param session The {@link MultiFactorSession} that the user is part of.\r\n * @returns A promise to {@link TotpSecret}.\r\n */\r\n static async generateSecret(session) {\r\n const mfaSession = session;\r\n _assert(typeof mfaSession.auth !== 'undefined', \"internal-error\" /* AuthErrorCode.INTERNAL_ERROR */);\r\n const response = await startEnrollTotpMfa(mfaSession.auth, {\r\n idToken: mfaSession.credential,\r\n totpEnrollmentInfo: {}\r\n });\r\n return TotpSecret._fromStartTotpMfaEnrollmentResponse(response, mfaSession.auth);\r\n }\r\n}\r\n/**\r\n * The identifier of the TOTP second factor: `totp`.\r\n */\r\nTotpMultiFactorGenerator.FACTOR_ID = \"totp\" /* FactorId.TOTP */;\r\nclass TotpMultiFactorAssertionImpl extends MultiFactorAssertionImpl {\r\n constructor(otp, enrollmentId, secret) {\r\n super(\"totp\" /* FactorId.TOTP */);\r\n this.otp = otp;\r\n this.enrollmentId = enrollmentId;\r\n this.secret = secret;\r\n }\r\n /** @internal */\r\n static _fromSecret(secret, otp) {\r\n return new TotpMultiFactorAssertionImpl(otp, undefined, secret);\r\n }\r\n /** @internal */\r\n static _fromEnrollmentId(enrollmentId, otp) {\r\n return new TotpMultiFactorAssertionImpl(otp, enrollmentId);\r\n }\r\n /** @internal */\r\n async _finalizeEnroll(auth, idToken, displayName) {\r\n _assert(typeof this.secret !== 'undefined', auth, \"argument-error\" /* AuthErrorCode.ARGUMENT_ERROR */);\r\n return finalizeEnrollTotpMfa(auth, {\r\n idToken,\r\n displayName,\r\n totpVerificationInfo: this.secret._makeTotpVerificationInfo(this.otp)\r\n });\r\n }\r\n /** @internal */\r\n async _finalizeSignIn(auth, mfaPendingCredential) {\r\n _assert(this.enrollmentId !== undefined && this.otp !== undefined, auth, \"argument-error\" /* AuthErrorCode.ARGUMENT_ERROR */);\r\n const totpVerificationInfo = { verificationCode: this.otp };\r\n return finalizeSignInTotpMfa(auth, {\r\n mfaPendingCredential,\r\n mfaEnrollmentId: this.enrollmentId,\r\n totpVerificationInfo\r\n });\r\n }\r\n}\r\n/**\r\n * Provider for generating a {@link TotpMultiFactorAssertion}.\r\n *\r\n * Stores the shared secret key and other parameters to generate time-based OTPs.\r\n * Implements methods to retrieve the shared secret key and generate a QR code URL.\r\n * @public\r\n */\r\nclass TotpSecret {\r\n // The public members are declared outside the constructor so the docs can be generated.\r\n constructor(secretKey, hashingAlgorithm, codeLength, codeIntervalSeconds, enrollmentCompletionDeadline, sessionInfo, auth) {\r\n this.sessionInfo = sessionInfo;\r\n this.auth = auth;\r\n this.secretKey = secretKey;\r\n this.hashingAlgorithm = hashingAlgorithm;\r\n this.codeLength = codeLength;\r\n this.codeIntervalSeconds = codeIntervalSeconds;\r\n this.enrollmentCompletionDeadline = enrollmentCompletionDeadline;\r\n }\r\n /** @internal */\r\n static _fromStartTotpMfaEnrollmentResponse(response, auth) {\r\n return new TotpSecret(response.totpSessionInfo.sharedSecretKey, response.totpSessionInfo.hashingAlgorithm, response.totpSessionInfo.verificationCodeLength, response.totpSessionInfo.periodSec, new Date(response.totpSessionInfo.finalizeEnrollmentTime).toUTCString(), response.totpSessionInfo.sessionInfo, auth);\r\n }\r\n /** @internal */\r\n _makeTotpVerificationInfo(otp) {\r\n return { sessionInfo: this.sessionInfo, verificationCode: otp };\r\n }\r\n /**\r\n * Returns a QR code URL as described in\r\n * https://github.com/google/google-authenticator/wiki/Key-Uri-Format\r\n * This can be displayed to the user as a QR code to be scanned into a TOTP app like Google Authenticator.\r\n * If the optional parameters are unspecified, an accountName of and issuer of are used.\r\n *\r\n * @param accountName the name of the account/app along with a user identifier.\r\n * @param issuer issuer of the TOTP (likely the app name).\r\n * @returns A QR code URL string.\r\n */\r\n generateQrCodeUrl(accountName, issuer) {\r\n var _a;\r\n let useDefaults = false;\r\n if (_isEmptyString(accountName) || _isEmptyString(issuer)) {\r\n useDefaults = true;\r\n }\r\n if (useDefaults) {\r\n if (_isEmptyString(accountName)) {\r\n accountName = ((_a = this.auth.currentUser) === null || _a === void 0 ? void 0 : _a.email) || 'unknownuser';\r\n }\r\n if (_isEmptyString(issuer)) {\r\n issuer = this.auth.name;\r\n }\r\n }\r\n return `otpauth://totp/${issuer}:${accountName}?secret=${this.secretKey}&issuer=${issuer}&algorithm=${this.hashingAlgorithm}&digits=${this.codeLength}`;\r\n }\r\n}\r\n/** @internal */\r\nfunction _isEmptyString(input) {\r\n return typeof input === 'undefined' || (input === null || input === void 0 ? void 0 : input.length) === 0;\r\n}\n\nvar name = \"@firebase/auth\";\nvar version = \"0.23.2\";\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nclass AuthInterop {\r\n constructor(auth) {\r\n this.auth = auth;\r\n this.internalListeners = new Map();\r\n }\r\n getUid() {\r\n var _a;\r\n this.assertAuthConfigured();\r\n return ((_a = this.auth.currentUser) === null || _a === void 0 ? void 0 : _a.uid) || null;\r\n }\r\n async getToken(forceRefresh) {\r\n this.assertAuthConfigured();\r\n await this.auth._initializationPromise;\r\n if (!this.auth.currentUser) {\r\n return null;\r\n }\r\n const accessToken = await this.auth.currentUser.getIdToken(forceRefresh);\r\n return { accessToken };\r\n }\r\n addAuthTokenListener(listener) {\r\n this.assertAuthConfigured();\r\n if (this.internalListeners.has(listener)) {\r\n return;\r\n }\r\n const unsubscribe = this.auth.onIdTokenChanged(user => {\r\n listener((user === null || user === void 0 ? void 0 : user.stsTokenManager.accessToken) || null);\r\n });\r\n this.internalListeners.set(listener, unsubscribe);\r\n this.updateProactiveRefresh();\r\n }\r\n removeAuthTokenListener(listener) {\r\n this.assertAuthConfigured();\r\n const unsubscribe = this.internalListeners.get(listener);\r\n if (!unsubscribe) {\r\n return;\r\n }\r\n this.internalListeners.delete(listener);\r\n unsubscribe();\r\n this.updateProactiveRefresh();\r\n }\r\n assertAuthConfigured() {\r\n _assert(this.auth._initializationPromise, \"dependent-sdk-initialized-before-auth\" /* AuthErrorCode.DEPENDENT_SDK_INIT_BEFORE_AUTH */);\r\n }\r\n updateProactiveRefresh() {\r\n if (this.internalListeners.size > 0) {\r\n this.auth._startProactiveRefresh();\r\n }\r\n else {\r\n this.auth._stopProactiveRefresh();\r\n }\r\n }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nfunction getVersionForPlatform(clientPlatform) {\r\n switch (clientPlatform) {\r\n case \"Node\" /* ClientPlatform.NODE */:\r\n return 'node';\r\n case \"ReactNative\" /* ClientPlatform.REACT_NATIVE */:\r\n return 'rn';\r\n case \"Worker\" /* ClientPlatform.WORKER */:\r\n return 'webworker';\r\n case \"Cordova\" /* ClientPlatform.CORDOVA */:\r\n return 'cordova';\r\n default:\r\n return undefined;\r\n }\r\n}\r\n/** @internal */\r\nfunction registerAuth(clientPlatform) {\r\n _registerComponent(new Component(\"auth\" /* _ComponentName.AUTH */, (container, { options: deps }) => {\r\n const app = container.getProvider('app').getImmediate();\r\n const heartbeatServiceProvider = container.getProvider('heartbeat');\r\n const appCheckServiceProvider = container.getProvider('app-check-internal');\r\n const { apiKey, authDomain } = app.options;\r\n _assert(apiKey && !apiKey.includes(':'), \"invalid-api-key\" /* AuthErrorCode.INVALID_API_KEY */, { appName: app.name });\r\n const config = {\r\n apiKey,\r\n authDomain,\r\n clientPlatform,\r\n apiHost: \"identitytoolkit.googleapis.com\" /* DefaultConfig.API_HOST */,\r\n tokenApiHost: \"securetoken.googleapis.com\" /* DefaultConfig.TOKEN_API_HOST */,\r\n apiScheme: \"https\" /* DefaultConfig.API_SCHEME */,\r\n sdkClientVersion: _getClientVersion(clientPlatform)\r\n };\r\n const authInstance = new AuthImpl(app, heartbeatServiceProvider, appCheckServiceProvider, config);\r\n _initializeAuthInstance(authInstance, deps);\r\n return authInstance;\r\n }, \"PUBLIC\" /* ComponentType.PUBLIC */)\r\n /**\r\n * Auth can only be initialized by explicitly calling getAuth() or initializeAuth()\r\n * For why we do this, See go/firebase-next-auth-init\r\n */\r\n .setInstantiationMode(\"EXPLICIT\" /* InstantiationMode.EXPLICIT */)\r\n /**\r\n * Because all firebase products that depend on auth depend on auth-internal directly,\r\n * we need to initialize auth-internal after auth is initialized to make it available to other firebase products.\r\n */\r\n .setInstanceCreatedCallback((container, _instanceIdentifier, _instance) => {\r\n const authInternalProvider = container.getProvider(\"auth-internal\" /* _ComponentName.AUTH_INTERNAL */);\r\n authInternalProvider.initialize();\r\n }));\r\n _registerComponent(new Component(\"auth-internal\" /* _ComponentName.AUTH_INTERNAL */, container => {\r\n const auth = _castAuth(container.getProvider(\"auth\" /* _ComponentName.AUTH */).getImmediate());\r\n return (auth => new AuthInterop(auth))(auth);\r\n }, \"PRIVATE\" /* ComponentType.PRIVATE */).setInstantiationMode(\"EXPLICIT\" /* InstantiationMode.EXPLICIT */));\r\n registerVersion(name, version, getVersionForPlatform(clientPlatform));\r\n // BUILD_TARGET will be replaced by values like esm5, esm2017, cjs5, etc during the compilation\r\n registerVersion(name, version, 'esm2017');\r\n}\n\n/**\r\n * @license\r\n * Copyright 2021 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nconst DEFAULT_ID_TOKEN_MAX_AGE = 5 * 60;\r\nconst authIdTokenMaxAge = getExperimentalSetting('authIdTokenMaxAge') || DEFAULT_ID_TOKEN_MAX_AGE;\r\nlet lastPostedIdToken = null;\r\nconst mintCookieFactory = (url) => async (user) => {\r\n const idTokenResult = user && (await user.getIdTokenResult());\r\n const idTokenAge = idTokenResult &&\r\n (new Date().getTime() - Date.parse(idTokenResult.issuedAtTime)) / 1000;\r\n if (idTokenAge && idTokenAge > authIdTokenMaxAge) {\r\n return;\r\n }\r\n // Specifically trip null => undefined when logged out, to delete any existing cookie\r\n const idToken = idTokenResult === null || idTokenResult === void 0 ? void 0 : idTokenResult.token;\r\n if (lastPostedIdToken === idToken) {\r\n return;\r\n }\r\n lastPostedIdToken = idToken;\r\n await fetch(url, {\r\n method: idToken ? 'POST' : 'DELETE',\r\n headers: idToken\r\n ? {\r\n 'Authorization': `Bearer ${idToken}`\r\n }\r\n : {}\r\n });\r\n};\r\n/**\r\n * Returns the Auth instance associated with the provided {@link @firebase/app#FirebaseApp}.\r\n * If no instance exists, initializes an Auth instance with platform-specific default dependencies.\r\n *\r\n * @param app - The Firebase App.\r\n *\r\n * @public\r\n */\r\nfunction getAuth(app = getApp()) {\r\n const provider = _getProvider(app, 'auth');\r\n if (provider.isInitialized()) {\r\n return provider.getImmediate();\r\n }\r\n const auth = initializeAuth(app, {\r\n popupRedirectResolver: browserPopupRedirectResolver,\r\n persistence: [\r\n indexedDBLocalPersistence,\r\n browserLocalPersistence,\r\n browserSessionPersistence\r\n ]\r\n });\r\n const authTokenSyncUrl = getExperimentalSetting('authTokenSyncURL');\r\n if (authTokenSyncUrl) {\r\n const mintCookie = mintCookieFactory(authTokenSyncUrl);\r\n beforeAuthStateChanged(auth, mintCookie, () => mintCookie(auth.currentUser));\r\n onIdTokenChanged(auth, user => mintCookie(user));\r\n }\r\n const authEmulatorHost = getDefaultEmulatorHost('auth');\r\n if (authEmulatorHost) {\r\n connectAuthEmulator(auth, `http://${authEmulatorHost}`);\r\n }\r\n return auth;\r\n}\r\nregisterAuth(\"Browser\" /* ClientPlatform.BROWSER */);\n\nexport { signInWithCredential as $, ActionCodeOperation as A, signOut as B, deleteUser as C, debugErrorMap as D, prodErrorMap as E, FactorId as F, AUTH_ERROR_CODES_MAP_DO_NOT_USE_INTERNALLY as G, initializeAuth as H, connectAuthEmulator as I, AuthCredential as J, EmailAuthCredential as K, OAuthCredential as L, PhoneAuthCredential as M, inMemoryPersistence as N, OperationType as O, PhoneAuthProvider as P, EmailAuthProvider as Q, RecaptchaVerifier as R, SignInMethod as S, TotpMultiFactorGenerator as T, FacebookAuthProvider as U, GoogleAuthProvider as V, GithubAuthProvider as W, OAuthProvider as X, SAMLAuthProvider as Y, TwitterAuthProvider as Z, signInAnonymously as _, browserSessionPersistence as a, linkWithCredential as a0, reauthenticateWithCredential as a1, signInWithCustomToken as a2, sendPasswordResetEmail as a3, confirmPasswordReset as a4, applyActionCode as a5, checkActionCode as a6, verifyPasswordResetCode as a7, createUserWithEmailAndPassword as a8, signInWithEmailAndPassword as a9, _assert as aA, AuthEventManager as aB, _getInstance as aC, _persistenceKeyName as aD, _getRedirectResult as aE, _overrideRedirectResult as aF, _clearRedirectOutcomes as aG, _castAuth as aH, UserImpl as aI, AuthImpl as aJ, _getClientVersion as aK, _generateEventId as aL, AuthPopup as aM, FetchProvider as aN, SAMLAuthCredential as aO, sendSignInLinkToEmail as aa, isSignInWithEmailLink as ab, signInWithEmailLink as ac, fetchSignInMethodsForEmail as ad, sendEmailVerification as ae, verifyBeforeUpdateEmail as af, ActionCodeURL as ag, parseActionCodeURL as ah, updateProfile as ai, updateEmail as aj, updatePassword as ak, getIdToken as al, getIdTokenResult as am, unlink as an, getAdditionalUserInfo as ao, reload as ap, getMultiFactorResolver as aq, multiFactor as ar, debugAssert as as, _isIOS as at, _isAndroid as au, _fail as av, _getRedirectUrl as aw, _getProjectConfig as ax, _isIOS7Or8 as ay, _createError as az, browserLocalPersistence as b, signInWithPopup as c, linkWithPopup as d, reauthenticateWithPopup as e, signInWithRedirect as f, linkWithRedirect as g, reauthenticateWithRedirect as h, indexedDBLocalPersistence as i, getRedirectResult as j, browserPopupRedirectResolver as k, linkWithPhoneNumber as l, PhoneMultiFactorGenerator as m, TotpSecret as n, getAuth as o, ProviderId as p, setPersistence as q, reauthenticateWithPhoneNumber as r, signInWithPhoneNumber as s, initializeRecaptchaConfig as t, updatePhoneNumber as u, onIdTokenChanged as v, beforeAuthStateChanged as w, onAuthStateChanged as x, useDeviceLanguage as y, updateCurrentUser as z };\n//# sourceMappingURL=index-e3d5d3f4.js.map\n","var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {};\n\nvar esm = {};\n\n/*\n\n Copyright The Closure Library Authors.\n SPDX-License-Identifier: Apache-2.0\n*/\n\nvar k,goog=goog||{},l=commonjsGlobal||self;function aa(a){var b=typeof a;b=\"object\"!=b?b:a?Array.isArray(a)?\"array\":b:\"null\";return \"array\"==b||\"object\"==b&&\"number\"==typeof a.length}function p(a){var b=typeof a;return \"object\"==b&&null!=a||\"function\"==b}function ba(a){return Object.prototype.hasOwnProperty.call(a,ca)&&a[ca]||(a[ca]=++da)}var ca=\"closure_uid_\"+(1E9*Math.random()>>>0),da=0;function ea(a,b,c){return a.call.apply(a.bind,arguments)}\nfunction fa(a,b,c){if(!a)throw Error();if(2{},b),l.removeEventListener(\"test\",()=>{},b);}catch(c){}return a}();function x(a){return /^[\\s\\xa0]*$/.test(a)}function pa(){var a=l.navigator;return a&&(a=a.userAgent)?a:\"\"}function y(a){return -1!=pa().indexOf(a)}function qa(a){qa[\" \"](a);return a}qa[\" \"]=function(){};function ra(a,b){var c=sa;return Object.prototype.hasOwnProperty.call(c,a)?c[a]:c[a]=b(a)}var ta=y(\"Opera\"),z=y(\"Trident\")||y(\"MSIE\"),ua=y(\"Edge\"),va=ua||z,wa=y(\"Gecko\")&&!(-1!=pa().toLowerCase().indexOf(\"webkit\")&&!y(\"Edge\"))&&!(y(\"Trident\")||y(\"MSIE\"))&&!y(\"Edge\"),xa=-1!=pa().toLowerCase().indexOf(\"webkit\")&&!y(\"Edge\");function ya(){var a=l.document;return a?a.documentMode:void 0}var za;\na:{var Aa=\"\",Ba=function(){var a=pa();if(wa)return /rv:([^\\);]+)(\\)|;)/.exec(a);if(ua)return /Edge\\/([\\d\\.]+)/.exec(a);if(z)return /\\b(?:MSIE|rv)[: ]([^\\);]+)(\\)|;)/.exec(a);if(xa)return /WebKit\\/(\\S+)/.exec(a);if(ta)return /(?:Version)[ \\/]?(\\S+)/.exec(a)}();Ba&&(Aa=Ba?Ba[1]:\"\");if(z){var Ca=ya();if(null!=Ca&&Ca>parseFloat(Aa)){za=String(Ca);break a}}za=Aa;}var Da;if(l.document&&z){var Ea=ya();Da=Ea?Ea:parseInt(za,10)||void 0;}else Da=void 0;var Fa=Da;function A(a,b){w.call(this,a?a.type:\"\");this.relatedTarget=this.g=this.target=null;this.button=this.screenY=this.screenX=this.clientY=this.clientX=0;this.key=\"\";this.metaKey=this.shiftKey=this.altKey=this.ctrlKey=!1;this.state=null;this.pointerId=0;this.pointerType=\"\";this.i=null;if(a){var c=this.type=a.type,d=a.changedTouches&&a.changedTouches.length?a.changedTouches[0]:null;this.target=a.target||a.srcElement;this.g=b;if(b=a.relatedTarget){if(wa){a:{try{qa(b.nodeName);var e=!0;break a}catch(f){}e=\n!1;}e||(b=null);}}else \"mouseover\"==c?b=a.fromElement:\"mouseout\"==c&&(b=a.toElement);this.relatedTarget=b;d?(this.clientX=void 0!==d.clientX?d.clientX:d.pageX,this.clientY=void 0!==d.clientY?d.clientY:d.pageY,this.screenX=d.screenX||0,this.screenY=d.screenY||0):(this.clientX=void 0!==a.clientX?a.clientX:a.pageX,this.clientY=void 0!==a.clientY?a.clientY:a.pageY,this.screenX=a.screenX||0,this.screenY=a.screenY||0);this.button=a.button;this.key=a.key||\"\";this.ctrlKey=a.ctrlKey;this.altKey=a.altKey;this.shiftKey=\na.shiftKey;this.metaKey=a.metaKey;this.pointerId=a.pointerId||0;this.pointerType=\"string\"===typeof a.pointerType?a.pointerType:Ga[a.pointerType]||\"\";this.state=a.state;this.i=a;a.defaultPrevented&&A.$.h.call(this);}}r(A,w);var Ga={2:\"touch\",3:\"pen\",4:\"mouse\"};A.prototype.h=function(){A.$.h.call(this);var a=this.i;a.preventDefault?a.preventDefault():a.returnValue=!1;};var Ha=\"closure_listenable_\"+(1E6*Math.random()|0);var Ia=0;function Ja(a,b,c,d,e){this.listener=a;this.proxy=null;this.src=b;this.type=c;this.capture=!!d;this.la=e;this.key=++Ia;this.fa=this.ia=!1;}function Ka(a){a.fa=!0;a.listener=null;a.proxy=null;a.src=null;a.la=null;}function Na(a,b,c){for(const d in a)b.call(c,a[d],d,a);}function Oa(a,b){for(const c in a)b.call(void 0,a[c],c,a);}function Pa(a){const b={};for(const c in a)b[c]=a[c];return b}const Qa=\"constructor hasOwnProperty isPrototypeOf propertyIsEnumerable toLocaleString toString valueOf\".split(\" \");function Ra(a,b){let c,d;for(let e=1;e>>0);function $a(a){if(\"function\"===typeof a)return a;a[hb]||(a[hb]=function(b){return a.handleEvent(b)});return a[hb]}function B(){v.call(this);this.i=new Sa(this);this.S=this;this.J=null;}r(B,v);B.prototype[Ha]=!0;B.prototype.removeEventListener=function(a,b,c,d){fb(this,a,b,c,d);};\nfunction C(a,b){var c,d=a.J;if(d)for(c=[];d;d=d.J)c.push(d);a=a.S;d=b.type||b;if(\"string\"===typeof b)b=new w(b,a);else if(b instanceof w)b.target=b.target||a;else {var e=b;b=new w(d,a);Ra(b,e);}e=!0;if(c)for(var f=c.length-1;0<=f;f--){var h=b.g=c[f];e=ib(h,d,!0,b)&&e;}h=b.g=a;e=ib(h,d,!0,b)&&e;e=ib(h,d,!1,b)&&e;if(c)for(f=0;fnew pb,a=>a.reset());class pb{constructor(){this.next=this.g=this.h=null;}set(a,b){this.h=a;this.g=b;this.next=null;}reset(){this.next=this.g=this.h=null;}}function qb(a){var b=1;a=a.split(\":\");const c=[];for(;0{throw a;},0);}let sb,tb=!1,mb=new nb,vb=()=>{const a=l.Promise.resolve(void 0);sb=()=>{a.then(ub);};};var ub=()=>{for(var a;a=lb();){try{a.h.call(a.g);}catch(c){rb(c);}var b=ob;b.j(a);100>b.h&&(b.h++,a.next=b.g,b.g=a);}tb=!1;};function wb(a,b){B.call(this);this.h=a||1;this.g=b||l;this.j=q(this.qb,this);this.l=Date.now();}r(wb,B);k=wb.prototype;k.ga=!1;k.T=null;k.qb=function(){if(this.ga){var a=Date.now()-this.l;0{a.g=null;a.i&&(a.i=!1,zb(a));},a.j);const b=a.h;a.h=null;a.m.apply(null,b);}class Ab extends v{constructor(a,b){super();this.m=a;this.j=b;this.h=null;this.i=!1;this.g=null;}l(a){this.h=arguments;this.g?this.i=!0:zb(this);}N(){super.N();this.g&&(l.clearTimeout(this.g),this.g=null,this.i=!1,this.h=null);}}function Bb(a){v.call(this);this.h=a;this.g={};}r(Bb,v);var Cb=[];function Db(a,b,c,d){Array.isArray(c)||(c&&(Cb[0]=c.toString()),c=Cb);for(var e=0;ed.length)){var e=d[1];if(Array.isArray(e)&&!(1>e.length)){var f=e[0];if(\"noop\"!=f&&\"stop\"!=f&&\"close\"!=f)for(var h=1;hu)&&(3!=u||va||this.g&&(this.h.h||this.g.ja()||mc(this.g)))){this.J||4!=u||7==b||(8==b||0>=L?Ob(3):Ob(2));nc(this);var c=this.g.da();this.ca=c;b:if(oc(this)){var d=mc(this.g);a=\"\";var e=d.length,f=4==H(this.g);if(!this.h.i){if(\"undefined\"===typeof TextDecoder){I(this);pc(this);var h=\"\";break b}this.h.i=new l.TextDecoder;}for(b=0;bb.length)return fc;b=b.slice(d,d+c);a.C=d+c;return b}k.cancel=function(){this.J=!0;I(this);};function jc(a){a.Y=Date.now()+a.P;wc(a,a.P);}\nfunction wc(a,b){if(null!=a.B)throw Error(\"WatchDog timer not null\");a.B=Rb(q(a.lb,a),b);}function nc(a){a.B&&(l.clearTimeout(a.B),a.B=null);}k.lb=function(){this.B=null;const a=Date.now();0<=a-this.Y?(Kb(this.j,this.A),2!=this.L&&(Ob(),F(17)),I(this),this.o=2,pc(this)):wc(this,this.Y-a);};function pc(a){0==a.l.H||a.J||sc(a.l,a);}function I(a){nc(a);var b=a.M;b&&\"function\"==typeof b.sa&&b.sa();a.M=null;xb(a.V);Fb(a.U);a.g&&(b=a.g,a.g=null,b.abort(),b.sa());}\nfunction qc(a,b){try{var c=a.l;if(0!=c.H&&(c.g==a||xc(c.i,a)))if(!a.K&&xc(c.i,a)&&3==c.H){try{var d=c.Ja.g.parse(b);}catch(m){d=null;}if(Array.isArray(d)&&3==d.length){var e=d;if(0==e[0])a:{if(!c.u){if(c.g)if(c.g.G+3E3e[2]&&c.G&&0==c.A&&!c.v&&(c.v=Rb(q(c.ib,c),6E3));if(1>=Bc(c.i)&&c.oa){try{c.oa();}catch(m){}c.oa=void 0;}}else J(c,11);}else if((a.K||c.g==a)&&yc(c),!x(b))for(e=c.Ja.g.parse(b),b=0;bb)throw Error(\"Bad port number \"+b);a.m=b;}else a.m=null;}function Qc(a,b,c){b instanceof Pc?(a.i=b,Xc(a.i,a.h)):(c||(b=Sc(b,Yc)),a.i=new Pc(b,a.h));}function K(a,b,c){a.i.set(b,c);}function hc(a){K(a,\"zx\",Math.floor(2147483648*Math.random()).toString(36)+Math.abs(Math.floor(2147483648*Math.random())^Date.now()).toString(36));return a}\nfunction Rc(a,b){return a?b?decodeURI(a.replace(/%25/g,\"%2525\")):decodeURIComponent(a):\"\"}function Sc(a,b,c){return \"string\"===typeof a?(a=encodeURI(a).replace(b,Zc),c&&(a=a.replace(/%25([0-9a-fA-F]{2})/g,\"%$1\")),a):null}function Zc(a){a=a.charCodeAt(0);return \"%\"+(a>>4&15).toString(16)+(a&15).toString(16)}var Tc=/[#\\/\\?@]/g,Vc=/[#\\?:]/g,Uc=/[#\\?]/g,Yc=/[#\\?@]/g,Wc=/#/g;function Pc(a,b){this.h=this.g=null;this.i=a||null;this.j=!!b;}\nfunction N(a){a.g||(a.g=new Map,a.h=0,a.i&&Mc(a.i,function(b,c){a.add(decodeURIComponent(b.replace(/\\+/g,\" \")),c);}));}k=Pc.prototype;k.add=function(a,b){N(this);this.i=null;a=O(this,a);var c=this.g.get(a);c||this.g.set(a,c=[]);c.push(b);this.h+=1;return this};function $c(a,b){N(a);b=O(a,b);a.g.has(b)&&(a.i=null,a.h-=a.g.get(b).length,a.g.delete(b));}function ad(a,b){N(a);b=O(a,b);return a.g.has(b)}\nk.forEach=function(a,b){N(this);this.g.forEach(function(c,d){c.forEach(function(e){a.call(b,e,d,this);},this);},this);};k.ta=function(){N(this);const a=Array.from(this.g.values()),b=Array.from(this.g.keys()),c=[];for(let d=0;d=a.j:!1}function Bc(a){return a.h?1:a.g?a.g.size:0}function xc(a,b){return a.h?a.h==b:a.g?a.g.has(b):!1}function Cc(a,b){a.g?a.g.add(b):a.h=b;}\nfunction Ec(a,b){a.h&&a.h==b?a.h=null:a.g&&a.g.has(b)&&a.g.delete(b);}cd.prototype.cancel=function(){this.i=fd(this);if(this.h)this.h.cancel(),this.h=null;else if(this.g&&0!==this.g.size){for(const a of this.g.values())a.cancel();this.g.clear();}};function fd(a){if(null!=a.h)return a.i.concat(a.h.F);if(null!=a.g&&0!==a.g.size){let b=a.i;for(const c of a.g.values())b=b.concat(c.F);return b}return ma(a.i)}var gd=class{stringify(a){return l.JSON.stringify(a,void 0)}parse(a){return l.JSON.parse(a,void 0)}};function hd(){this.g=new gd;}function id(a,b,c){const d=c||\"\";try{Kc(a,function(e,f){let h=e;p(e)&&(h=jb(e));b.push(d+f+\"=\"+encodeURIComponent(h));});}catch(e){throw b.push(d+\"type=\"+encodeURIComponent(\"_badmap\")),e;}}function jd(a,b){const c=new Gb;if(l.Image){const d=new Image;d.onload=ha(kd,c,d,\"TestLoadImage: loaded\",!0,b);d.onerror=ha(kd,c,d,\"TestLoadImage: error\",!1,b);d.onabort=ha(kd,c,d,\"TestLoadImage: abort\",!1,b);d.ontimeout=ha(kd,c,d,\"TestLoadImage: timeout\",!1,b);l.setTimeout(function(){if(d.ontimeout)d.ontimeout();},1E4);d.src=a;}else b(!1);}function kd(a,b,c,d,e){try{b.onload=null,b.onerror=null,b.onabort=null,b.ontimeout=null,e(d);}catch(f){}}function ld(a){this.l=a.fc||null;this.j=a.ob||!1;}r(ld,Ub);ld.prototype.g=function(){return new md(this.l,this.j)};ld.prototype.i=function(a){return function(){return a}}({});function md(a,b){B.call(this);this.F=a;this.u=b;this.m=void 0;this.readyState=nd;this.status=0;this.responseType=this.responseText=this.response=this.statusText=\"\";this.onreadystatechange=null;this.v=new Headers;this.h=null;this.C=\"GET\";this.B=\"\";this.g=!1;this.A=this.j=this.l=null;}r(md,B);var nd=0;k=md.prototype;\nk.open=function(a,b){if(this.readyState!=nd)throw this.abort(),Error(\"Error reopening a connection\");this.C=a;this.B=b;this.readyState=1;od(this);};k.send=function(a){if(1!=this.readyState)throw this.abort(),Error(\"need to call open() first. \");this.g=!0;const b={headers:this.v,method:this.C,credentials:this.m,cache:void 0};a&&(b.body=a);(this.F||l).fetch(new Request(this.B,b)).then(this.$a.bind(this),this.ka.bind(this));};\nk.abort=function(){this.response=this.responseText=\"\";this.v=new Headers;this.status=0;this.j&&this.j.cancel(\"Request was aborted.\").catch(()=>{});1<=this.readyState&&this.g&&4!=this.readyState&&(this.g=!1,pd(this));this.readyState=nd;};\nk.$a=function(a){if(this.g&&(this.l=a,this.h||(this.status=this.l.status,this.statusText=this.l.statusText,this.h=a.headers,this.readyState=2,od(this)),this.g&&(this.readyState=3,od(this),this.g)))if(\"arraybuffer\"===this.responseType)a.arrayBuffer().then(this.Ya.bind(this),this.ka.bind(this));else if(\"undefined\"!==typeof l.ReadableStream&&\"body\"in a){this.j=a.body.getReader();if(this.u){if(this.responseType)throw Error('responseType must be empty for \"streamBinaryChunks\" mode responses.');this.response=\n[];}else this.response=this.responseText=\"\",this.A=new TextDecoder;qd(this);}else a.text().then(this.Za.bind(this),this.ka.bind(this));};function qd(a){a.j.read().then(a.Xa.bind(a)).catch(a.ka.bind(a));}k.Xa=function(a){if(this.g){if(this.u&&a.value)this.response.push(a.value);else if(!this.u){var b=a.value?a.value:new Uint8Array(0);if(b=this.A.decode(b,{stream:!a.done}))this.response=this.responseText+=b;}a.done?pd(this):od(this);3==this.readyState&&qd(this);}};\nk.Za=function(a){this.g&&(this.response=this.responseText=a,pd(this));};k.Ya=function(a){this.g&&(this.response=a,pd(this));};k.ka=function(){this.g&&pd(this);};function pd(a){a.readyState=4;a.l=null;a.j=null;a.A=null;od(a);}k.setRequestHeader=function(a,b){this.v.append(a,b);};k.getResponseHeader=function(a){return this.h?this.h.get(a.toLowerCase())||\"\":\"\"};\nk.getAllResponseHeaders=function(){if(!this.h)return \"\";const a=[],b=this.h.entries();for(var c=b.next();!c.done;)c=c.value,a.push(c[0]+\": \"+c[1]),c=b.next();return a.join(\"\\r\\n\")};function od(a){a.onreadystatechange&&a.onreadystatechange.call(a);}Object.defineProperty(md.prototype,\"withCredentials\",{get:function(){return \"include\"===this.m},set:function(a){this.m=a?\"include\":\"same-origin\";}});var rd=l.JSON.parse;function P(a){B.call(this);this.headers=new Map;this.u=a||null;this.h=!1;this.C=this.g=null;this.I=\"\";this.m=0;this.j=\"\";this.l=this.G=this.v=this.F=!1;this.B=0;this.A=null;this.K=sd;this.L=this.M=!1;}r(P,B);var sd=\"\",td=/^https?$/i,ud=[\"POST\",\"PUT\"];k=P.prototype;k.Oa=function(a){this.M=a;};\nk.ha=function(a,b,c,d){if(this.g)throw Error(\"[goog.net.XhrIo] Object is active with another request=\"+this.I+\"; newUri=\"+a);b=b?b.toUpperCase():\"GET\";this.I=a;this.j=\"\";this.m=0;this.F=!1;this.h=!0;this.g=this.u?this.u.g():$b.g();this.C=this.u?Vb(this.u):Vb($b);this.g.onreadystatechange=q(this.La,this);try{this.G=!0,this.g.open(b,String(a),!0),this.G=!1;}catch(f){vd(this,f);return}a=c||\"\";c=new Map(this.headers);if(d)if(Object.getPrototypeOf(d)===Object.prototype)for(var e in d)c.set(e,d[e]);else if(\"function\"===\ntypeof d.keys&&\"function\"===typeof d.get)for(const f of d.keys())c.set(f,d.get(f));else throw Error(\"Unknown input type for opt_headers: \"+String(d));d=Array.from(c.keys()).find(f=>\"content-type\"==f.toLowerCase());e=l.FormData&&a instanceof l.FormData;!(0<=ka(ud,b))||d||e||c.set(\"Content-Type\",\"application/x-www-form-urlencoded;charset=utf-8\");for(const [f,h]of c)this.g.setRequestHeader(f,h);this.K&&(this.g.responseType=this.K);\"withCredentials\"in this.g&&this.g.withCredentials!==this.M&&(this.g.withCredentials=\nthis.M);try{wd(this),0{}:null;a.g=null;a.C=null;b||C(a,\"ready\");try{c.onreadystatechange=d;}catch(e){}}}function wd(a){a.g&&a.L&&(a.g.ontimeout=null);a.A&&(l.clearTimeout(a.A),a.A=null);}k.isActive=function(){return !!this.g};function H(a){return a.g?a.g.readyState:0}k.da=function(){try{return 2=a.i.j-(a.m?1:0))return !1;if(a.m)return a.j=b.F.concat(a.j),!0;if(1==a.H||2==a.H||a.C>=(a.cb?0:a.eb))return !1;a.m=Rb(q(a.Na,a,b),Jd(a,a.C));a.C++;return !0}\nk.Na=function(a){if(this.m)if(this.m=null,1==this.H){if(!a){this.W=Math.floor(1E5*Math.random());a=this.W++;const e=new bc(this,this.l,a);let f=this.s;this.U&&(f?(f=Pa(f),Ra(f,this.U)):f=this.U);null!==this.o||this.O||(e.I=f,f=null);if(this.P)a:{var b=0;for(var c=0;cm)f=Math.max(0,e[t].g-100),n=!1;else try{id(u,h,\"req\"+m+\"_\");}catch(L){d&&d(u);}}if(n){d=h.join(\"&\");break a}}}a=a.j.splice(0,c);b.F=a;return d}function Fc(a){if(!a.g&&!a.u){a.ba=1;var b=a.Ma;sb||vb();tb||(sb(),tb=!0);mb.add(b,a);a.A=0;}}\nfunction Ac(a){if(a.g||a.u||3<=a.A)return !1;a.ba++;a.u=Rb(q(a.Ma,a),Jd(a,a.A));a.A++;return !0}k.Ma=function(){this.u=null;Md(this);if(this.ca&&!(this.M||null==this.g||0>=this.S)){var a=2*this.S;this.l.info(\"BP detection timer enabled: \"+a);this.B=Rb(q(this.jb,this),a);}};k.jb=function(){this.B&&(this.B=null,this.l.info(\"BP detection timeout reached.\"),this.l.info(\"Buffering proxy detected and switch to long-polling!\"),this.G=!1,this.M=!0,F(10),zc(this),Md(this));};\nfunction vc(a){null!=a.B&&(l.clearTimeout(a.B),a.B=null);}function Md(a){a.g=new bc(a,a.l,\"rpc\",a.ba);null===a.o&&(a.g.I=a.s);a.g.O=0;var b=G(a.wa);K(b,\"RID\",\"rpc\");K(b,\"SID\",a.K);K(b,\"AID\",a.V);K(b,\"CI\",a.G?\"0\":\"1\");!a.G&&a.qa&&K(b,\"TO\",a.qa);K(b,\"TYPE\",\"xmlhttp\");Gd(a,b);a.o&&a.s&&Cd(b,a.o,a.s);a.L&&a.g.setTimeout(a.L);var c=a.g;a=a.pa;c.L=1;c.v=hc(G(b));c.s=null;c.S=!0;ic(c,a);}k.ib=function(){null!=this.v&&(this.v=null,zc(this),Ac(this),F(19));};\nfunction yc(a){null!=a.v&&(l.clearTimeout(a.v),a.v=null);}function sc(a,b){var c=null;if(a.g==b){yc(a);vc(a);a.g=null;var d=2;}else if(xc(a.i,b))c=b.F,Ec(a.i,b),d=1;else return;if(0!=a.H)if(b.i)if(1==d){c=b.s?b.s.length:0;b=Date.now()-b.G;var e=a.C;d=Mb();C(d,new Qb(d,c));Gc(a);}else Fc(a);else if(e=b.o,3==e||0==e&&0e;++e)d[e]=b.charCodeAt(c++)|b.charCodeAt(c++)<<8|b.charCodeAt(c++)<<16|b.charCodeAt(c++)<<24;else for(e=0;16>e;++e)d[e]=b[c++]|b[c++]<<8|b[c++]<<16|b[c++]<<24;b=a.g[0];c=a.g[1];e=a.g[2];var f=a.g[3];var h=b+(f^c&(e^f))+d[0]+3614090360&4294967295;b=c+(h<<7&4294967295|h>>>25);h=f+(e^b&(c^e))+d[1]+3905402710&4294967295;f=b+(h<<12&4294967295|h>>>20);h=e+(c^f&(b^c))+d[2]+606105819&4294967295;e=f+(h<<17&4294967295|h>>>15);\nh=c+(b^e&(f^b))+d[3]+3250441966&4294967295;c=e+(h<<22&4294967295|h>>>10);h=b+(f^c&(e^f))+d[4]+4118548399&4294967295;b=c+(h<<7&4294967295|h>>>25);h=f+(e^b&(c^e))+d[5]+1200080426&4294967295;f=b+(h<<12&4294967295|h>>>20);h=e+(c^f&(b^c))+d[6]+2821735955&4294967295;e=f+(h<<17&4294967295|h>>>15);h=c+(b^e&(f^b))+d[7]+4249261313&4294967295;c=e+(h<<22&4294967295|h>>>10);h=b+(f^c&(e^f))+d[8]+1770035416&4294967295;b=c+(h<<7&4294967295|h>>>25);h=f+(e^b&(c^e))+d[9]+2336552879&4294967295;f=b+(h<<12&4294967295|\nh>>>20);h=e+(c^f&(b^c))+d[10]+4294925233&4294967295;e=f+(h<<17&4294967295|h>>>15);h=c+(b^e&(f^b))+d[11]+2304563134&4294967295;c=e+(h<<22&4294967295|h>>>10);h=b+(f^c&(e^f))+d[12]+1804603682&4294967295;b=c+(h<<7&4294967295|h>>>25);h=f+(e^b&(c^e))+d[13]+4254626195&4294967295;f=b+(h<<12&4294967295|h>>>20);h=e+(c^f&(b^c))+d[14]+2792965006&4294967295;e=f+(h<<17&4294967295|h>>>15);h=c+(b^e&(f^b))+d[15]+1236535329&4294967295;c=e+(h<<22&4294967295|h>>>10);h=b+(e^f&(c^e))+d[1]+4129170786&4294967295;b=c+(h<<\n5&4294967295|h>>>27);h=f+(c^e&(b^c))+d[6]+3225465664&4294967295;f=b+(h<<9&4294967295|h>>>23);h=e+(b^c&(f^b))+d[11]+643717713&4294967295;e=f+(h<<14&4294967295|h>>>18);h=c+(f^b&(e^f))+d[0]+3921069994&4294967295;c=e+(h<<20&4294967295|h>>>12);h=b+(e^f&(c^e))+d[5]+3593408605&4294967295;b=c+(h<<5&4294967295|h>>>27);h=f+(c^e&(b^c))+d[10]+38016083&4294967295;f=b+(h<<9&4294967295|h>>>23);h=e+(b^c&(f^b))+d[15]+3634488961&4294967295;e=f+(h<<14&4294967295|h>>>18);h=c+(f^b&(e^f))+d[4]+3889429448&4294967295;c=\ne+(h<<20&4294967295|h>>>12);h=b+(e^f&(c^e))+d[9]+568446438&4294967295;b=c+(h<<5&4294967295|h>>>27);h=f+(c^e&(b^c))+d[14]+3275163606&4294967295;f=b+(h<<9&4294967295|h>>>23);h=e+(b^c&(f^b))+d[3]+4107603335&4294967295;e=f+(h<<14&4294967295|h>>>18);h=c+(f^b&(e^f))+d[8]+1163531501&4294967295;c=e+(h<<20&4294967295|h>>>12);h=b+(e^f&(c^e))+d[13]+2850285829&4294967295;b=c+(h<<5&4294967295|h>>>27);h=f+(c^e&(b^c))+d[2]+4243563512&4294967295;f=b+(h<<9&4294967295|h>>>23);h=e+(b^c&(f^b))+d[7]+1735328473&4294967295;\ne=f+(h<<14&4294967295|h>>>18);h=c+(f^b&(e^f))+d[12]+2368359562&4294967295;c=e+(h<<20&4294967295|h>>>12);h=b+(c^e^f)+d[5]+4294588738&4294967295;b=c+(h<<4&4294967295|h>>>28);h=f+(b^c^e)+d[8]+2272392833&4294967295;f=b+(h<<11&4294967295|h>>>21);h=e+(f^b^c)+d[11]+1839030562&4294967295;e=f+(h<<16&4294967295|h>>>16);h=c+(e^f^b)+d[14]+4259657740&4294967295;c=e+(h<<23&4294967295|h>>>9);h=b+(c^e^f)+d[1]+2763975236&4294967295;b=c+(h<<4&4294967295|h>>>28);h=f+(b^c^e)+d[4]+1272893353&4294967295;f=b+(h<<11&4294967295|\nh>>>21);h=e+(f^b^c)+d[7]+4139469664&4294967295;e=f+(h<<16&4294967295|h>>>16);h=c+(e^f^b)+d[10]+3200236656&4294967295;c=e+(h<<23&4294967295|h>>>9);h=b+(c^e^f)+d[13]+681279174&4294967295;b=c+(h<<4&4294967295|h>>>28);h=f+(b^c^e)+d[0]+3936430074&4294967295;f=b+(h<<11&4294967295|h>>>21);h=e+(f^b^c)+d[3]+3572445317&4294967295;e=f+(h<<16&4294967295|h>>>16);h=c+(e^f^b)+d[6]+76029189&4294967295;c=e+(h<<23&4294967295|h>>>9);h=b+(c^e^f)+d[9]+3654602809&4294967295;b=c+(h<<4&4294967295|h>>>28);h=f+(b^c^e)+d[12]+\n3873151461&4294967295;f=b+(h<<11&4294967295|h>>>21);h=e+(f^b^c)+d[15]+530742520&4294967295;e=f+(h<<16&4294967295|h>>>16);h=c+(e^f^b)+d[2]+3299628645&4294967295;c=e+(h<<23&4294967295|h>>>9);h=b+(e^(c|~f))+d[0]+4096336452&4294967295;b=c+(h<<6&4294967295|h>>>26);h=f+(c^(b|~e))+d[7]+1126891415&4294967295;f=b+(h<<10&4294967295|h>>>22);h=e+(b^(f|~c))+d[14]+2878612391&4294967295;e=f+(h<<15&4294967295|h>>>17);h=c+(f^(e|~b))+d[5]+4237533241&4294967295;c=e+(h<<21&4294967295|h>>>11);h=b+(e^(c|~f))+d[12]+1700485571&\n4294967295;b=c+(h<<6&4294967295|h>>>26);h=f+(c^(b|~e))+d[3]+2399980690&4294967295;f=b+(h<<10&4294967295|h>>>22);h=e+(b^(f|~c))+d[10]+4293915773&4294967295;e=f+(h<<15&4294967295|h>>>17);h=c+(f^(e|~b))+d[1]+2240044497&4294967295;c=e+(h<<21&4294967295|h>>>11);h=b+(e^(c|~f))+d[8]+1873313359&4294967295;b=c+(h<<6&4294967295|h>>>26);h=f+(c^(b|~e))+d[15]+4264355552&4294967295;f=b+(h<<10&4294967295|h>>>22);h=e+(b^(f|~c))+d[6]+2734768916&4294967295;e=f+(h<<15&4294967295|h>>>17);h=c+(f^(e|~b))+d[13]+1309151649&\n4294967295;c=e+(h<<21&4294967295|h>>>11);h=b+(e^(c|~f))+d[4]+4149444226&4294967295;b=c+(h<<6&4294967295|h>>>26);h=f+(c^(b|~e))+d[11]+3174756917&4294967295;f=b+(h<<10&4294967295|h>>>22);h=e+(b^(f|~c))+d[2]+718787259&4294967295;e=f+(h<<15&4294967295|h>>>17);h=c+(f^(e|~b))+d[9]+3951481745&4294967295;a.g[0]=a.g[0]+b&4294967295;a.g[1]=a.g[1]+(e+(h<<21&4294967295|h>>>11))&4294967295;a.g[2]=a.g[2]+e&4294967295;a.g[3]=a.g[3]+f&4294967295;}\nS.prototype.j=function(a,b){void 0===b&&(b=a.length);for(var c=b-this.blockSize,d=this.m,e=this.h,f=0;fthis.h?this.blockSize:2*this.blockSize)-this.h);a[0]=128;for(var b=1;bb;++b)for(var d=0;32>d;d+=8)a[c++]=this.g[b]>>>d&255;return a};function T(a,b){this.h=b;for(var c=[],d=!0,e=a.length-1;0<=e;e--){var f=a[e]|0;d&&f==b||(c[e]=f,d=!1);}this.g=c;}var sa={};function Td(a){return -128<=a&&128>a?ra(a,function(b){return new T([b|0],0>b?-1:0)}):new T([a|0],0>a?-1:0)}function U(a){if(isNaN(a)||!isFinite(a))return V;if(0>a)return W(U(-a));for(var b=[],c=1,d=0;a>=c;d++)b[d]=a/c|0,c*=Ud;return new T(b,0)}\nfunction Vd(a,b){if(0==a.length)throw Error(\"number format error: empty string\");b=b||10;if(2>b||36f?(f=U(Math.pow(b,f)),d=d.R(f).add(U(h))):(d=d.R(c),d=d.add(U(h)));}return d}\nvar Ud=4294967296,V=Td(0),Wd=Td(1),Xd=Td(16777216);k=T.prototype;k.ea=function(){if(X(this))return -W(this).ea();for(var a=0,b=1,c=0;ca||36>>0).toString(a);c=e;if(Y(c))return f+d;for(;6>f.length;)f=\"0\"+f;d=f+d;}};k.D=function(a){return 0>a?0:a>>16)+(this.D(e)>>>16)+(a.D(e)>>>16);d=h>>>16;f&=65535;h&=65535;c[e]=h<<16|f;}return new T(c,c[c.length-1]&-2147483648?-1:0)};\nfunction Zd(a,b){return a.add(W(b))}\nk.R=function(a){if(Y(this)||Y(a))return V;if(X(this))return X(a)?W(this).R(W(a)):W(W(this).R(a));if(X(a))return W(this.R(W(a)));if(0>this.X(Xd)&&0>a.X(Xd))return U(this.ea()*a.ea());for(var b=this.g.length+a.g.length,c=[],d=0;d<2*b;d++)c[d]=0;for(d=0;d>>16,h=this.D(d)&65535,n=a.D(e)>>>16,t=a.D(e)&65535;c[2*d+2*e]+=h*t;$d(c,2*d+2*e);c[2*d+2*e+1]+=f*t;$d(c,2*d+2*e+1);c[2*d+2*e+1]+=h*n;$d(c,2*d+2*e+1);c[2*d+2*e+2]+=f*n;$d(c,2*d+2*e+2);}for(d=\n0;d>>16,a[b]&=65535,b++;}function ae(a,b){this.g=a;this.h=b;}\nfunction Yd(a,b){if(Y(b))throw Error(\"division by zero\");if(Y(a))return new ae(V,V);if(X(a))return b=Yd(W(a),b),new ae(W(b.g),W(b.h));if(X(b))return b=Yd(a,W(b)),new ae(W(b.g),b.h);if(30=d.X(a);)c=be(c),d=be(d);var e=Z(c,1),f=Z(d,1);d=Z(d,2);for(c=Z(c,2);!Y(d);){var h=f.add(d);0>=h.X(a)&&(e=e.add(c),f=h);d=Z(d,1);c=Z(c,1);}b=Zd(a,e.R(b));return new ae(e,b)}for(e=V;0<=a.X(b);){c=Math.max(1,Math.floor(a.ea()/\nb.ea()));d=Math.ceil(Math.log(c)/Math.LN2);d=48>=d?1:Math.pow(2,d-48);f=U(c);for(h=f.R(b);X(h)||0>>31;return new T(c,a.h)}function Z(a,b){var c=b>>5;b%=32;for(var d=a.g.length-c,e=[],f=0;f>>b|a.D(f+c+1)<<32-b:a.D(f+c);return new T(e,a.h)}Od.prototype.createWebChannel=Od.prototype.g;Q.prototype.send=Q.prototype.u;Q.prototype.open=Q.prototype.m;Q.prototype.close=Q.prototype.close;Sb.NO_ERROR=0;Sb.TIMEOUT=8;Sb.HTTP_ERROR=6;Tb.COMPLETE=\"complete\";Wb.EventType=Xb;Xb.OPEN=\"a\";Xb.CLOSE=\"b\";Xb.ERROR=\"c\";Xb.MESSAGE=\"d\";B.prototype.listen=B.prototype.O;P.prototype.listenOnce=P.prototype.P;P.prototype.getLastError=P.prototype.Sa;P.prototype.getLastErrorCode=P.prototype.Ia;P.prototype.getStatus=P.prototype.da;P.prototype.getResponseJson=P.prototype.Wa;\nP.prototype.getResponseText=P.prototype.ja;P.prototype.send=P.prototype.ha;P.prototype.setWithCredentials=P.prototype.Oa;S.prototype.digest=S.prototype.l;S.prototype.reset=S.prototype.reset;S.prototype.update=S.prototype.j;T.prototype.add=T.prototype.add;T.prototype.multiply=T.prototype.R;T.prototype.modulo=T.prototype.gb;T.prototype.compare=T.prototype.X;T.prototype.toNumber=T.prototype.ea;T.prototype.toString=T.prototype.toString;T.prototype.getBits=T.prototype.D;T.fromNumber=U;T.fromString=Vd;\nvar createWebChannelTransport = esm.createWebChannelTransport=function(){return new Od};var getStatEventTarget = esm.getStatEventTarget=function(){return Mb()};var ErrorCode = esm.ErrorCode=Sb;var EventType = esm.EventType=Tb;var Event = esm.Event=E;var Stat = esm.Stat={xb:0,Ab:1,Bb:2,Ub:3,Zb:4,Wb:5,Xb:6,Vb:7,Tb:8,Yb:9,PROXY:10,NOPROXY:11,Rb:12,Nb:13,Ob:14,Mb:15,Pb:16,Qb:17,tb:18,sb:19,ub:20};var FetchXmlHttpFactory = esm.FetchXmlHttpFactory=ld;var WebChannel = esm.WebChannel=Wb;var XhrIo = esm.XhrIo=P;var Md5 = esm.Md5=S;var Integer = esm.Integer=T;\n\nexport { ErrorCode, Event, EventType, FetchXmlHttpFactory, Integer, Md5, Stat, WebChannel, XhrIo, createWebChannelTransport, esm as default, getStatEventTarget };\n//# sourceMappingURL=index.esm2017.js.map\n","import { _registerComponent, registerVersion, _getProvider, getApp, _removeServiceInstance, SDK_VERSION } from '@firebase/app';\nimport { Component } from '@firebase/component';\nimport { Logger, LogLevel } from '@firebase/logger';\nimport { FirebaseError, createMockUserToken, getModularInstance, deepEqual, getDefaultEmulatorHostnameAndPort, getUA, isIndexedDBAvailable, isSafari } from '@firebase/util';\nimport { Integer, XhrIo, EventType, ErrorCode, createWebChannelTransport, getStatEventTarget, FetchXmlHttpFactory, WebChannel, Event, Stat, Md5 } from '@firebase/webchannel-wrapper';\n\nconst b = \"@firebase/firestore\";\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * Simple wrapper around a nullable UID. Mostly exists to make code more\n * readable.\n */\nclass V {\n constructor(t) {\n this.uid = t;\n }\n isAuthenticated() {\n return null != this.uid;\n }\n /**\n * Returns a key representing this user, suitable for inclusion in a\n * dictionary.\n */ toKey() {\n return this.isAuthenticated() ? \"uid:\" + this.uid : \"anonymous-user\";\n }\n isEqual(t) {\n return t.uid === this.uid;\n }\n}\n\n/** A user with a null UID. */ V.UNAUTHENTICATED = new V(null), \n// TODO(mikelehen): Look into getting a proper uid-equivalent for\n// non-FirebaseAuth providers.\nV.GOOGLE_CREDENTIALS = new V(\"google-credentials-uid\"), V.FIRST_PARTY = new V(\"first-party-uid\"), \nV.MOCK_USER = new V(\"mock-user\");\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nlet S = \"9.23.0\";\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nconst D = new Logger(\"@firebase/firestore\");\n\n// Helper methods are needed because variables can't be exported as read/write\nfunction C() {\n return D.logLevel;\n}\n\n/**\n * Sets the verbosity of Cloud Firestore logs (debug, error, or silent).\n *\n * @param logLevel - The verbosity you set for activity and error logging. Can\n * be any of the following values:\n *\n *

    \n *
  • `debug` for the most verbose logging level, primarily for\n * debugging.
  • \n *
  • `error` to log errors only.
  • \n *
  • `silent` to turn off logging.
  • \n *
\n */ function x(t) {\n D.setLogLevel(t);\n}\n\nfunction N(t, ...e) {\n if (D.logLevel <= LogLevel.DEBUG) {\n const n = e.map($);\n D.debug(`Firestore (${S}): ${t}`, ...n);\n }\n}\n\nfunction k(t, ...e) {\n if (D.logLevel <= LogLevel.ERROR) {\n const n = e.map($);\n D.error(`Firestore (${S}): ${t}`, ...n);\n }\n}\n\n/**\n * @internal\n */ function M(t, ...e) {\n if (D.logLevel <= LogLevel.WARN) {\n const n = e.map($);\n D.warn(`Firestore (${S}): ${t}`, ...n);\n }\n}\n\n/**\n * Converts an additional log parameter to a string representation.\n */ function $(t) {\n if (\"string\" == typeof t) return t;\n try {\n return e = t, JSON.stringify(e);\n } catch (e) {\n // Converting to JSON failed, just log the object directly\n return t;\n }\n /**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n /** Formats an object as a JSON string, suitable for logging. */\n var e;\n}\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * Unconditionally fails, throwing an Error with the given message.\n * Messages are stripped in production builds.\n *\n * Returns `never` and can be used in expressions:\n * @example\n * let futureVar = fail('not implemented yet');\n */ function O(t = \"Unexpected state\") {\n // Log the failure in addition to throw an exception, just in case the\n // exception is swallowed.\n const e = `FIRESTORE (${S}) INTERNAL ASSERTION FAILED: ` + t;\n // NOTE: We don't use FirestoreError here because these are internal failures\n // that cannot be handled by the user. (Also it would create a circular\n // dependency between the error and assert modules which doesn't work.)\n throw k(e), new Error(e);\n}\n\n/**\n * Fails if the given assertion condition is false, throwing an Error with the\n * given message if it did.\n *\n * Messages are stripped in production builds.\n */ function F(t, e) {\n t || O();\n}\n\n/**\n * Fails if the given assertion condition is false, throwing an Error with the\n * given message if it did.\n *\n * The code of callsites invoking this function are stripped out in production\n * builds. Any side-effects of code within the debugAssert() invocation will not\n * happen in this case.\n *\n * @internal\n */ function B(t, e) {\n t || O();\n}\n\n/**\n * Casts `obj` to `T`. In non-production builds, verifies that `obj` is an\n * instance of `T` before casting.\n */ function L(t, \n// eslint-disable-next-line @typescript-eslint/no-explicit-any\ne) {\n return t;\n}\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */ const q = {\n // Causes are copied from:\n // https://github.com/grpc/grpc/blob/bceec94ea4fc5f0085d81235d8e1c06798dc341a/include/grpc%2B%2B/impl/codegen/status_code_enum.h\n /** Not an error; returned on success. */\n OK: \"ok\",\n /** The operation was cancelled (typically by the caller). */\n CANCELLED: \"cancelled\",\n /** Unknown error or an error from a different error domain. */\n UNKNOWN: \"unknown\",\n /**\n * Client specified an invalid argument. Note that this differs from\n * FAILED_PRECONDITION. INVALID_ARGUMENT indicates arguments that are\n * problematic regardless of the state of the system (e.g., a malformed file\n * name).\n */\n INVALID_ARGUMENT: \"invalid-argument\",\n /**\n * Deadline expired before operation could complete. For operations that\n * change the state of the system, this error may be returned even if the\n * operation has completed successfully. For example, a successful response\n * from a server could have been delayed long enough for the deadline to\n * expire.\n */\n DEADLINE_EXCEEDED: \"deadline-exceeded\",\n /** Some requested entity (e.g., file or directory) was not found. */\n NOT_FOUND: \"not-found\",\n /**\n * Some entity that we attempted to create (e.g., file or directory) already\n * exists.\n */\n ALREADY_EXISTS: \"already-exists\",\n /**\n * The caller does not have permission to execute the specified operation.\n * PERMISSION_DENIED must not be used for rejections caused by exhausting\n * some resource (use RESOURCE_EXHAUSTED instead for those errors).\n * PERMISSION_DENIED must not be used if the caller can not be identified\n * (use UNAUTHENTICATED instead for those errors).\n */\n PERMISSION_DENIED: \"permission-denied\",\n /**\n * The request does not have valid authentication credentials for the\n * operation.\n */\n UNAUTHENTICATED: \"unauthenticated\",\n /**\n * Some resource has been exhausted, perhaps a per-user quota, or perhaps the\n * entire file system is out of space.\n */\n RESOURCE_EXHAUSTED: \"resource-exhausted\",\n /**\n * Operation was rejected because the system is not in a state required for\n * the operation's execution. For example, directory to be deleted may be\n * non-empty, an rmdir operation is applied to a non-directory, etc.\n *\n * A litmus test that may help a service implementor in deciding\n * between FAILED_PRECONDITION, ABORTED, and UNAVAILABLE:\n * (a) Use UNAVAILABLE if the client can retry just the failing call.\n * (b) Use ABORTED if the client should retry at a higher-level\n * (e.g., restarting a read-modify-write sequence).\n * (c) Use FAILED_PRECONDITION if the client should not retry until\n * the system state has been explicitly fixed. E.g., if an \"rmdir\"\n * fails because the directory is non-empty, FAILED_PRECONDITION\n * should be returned since the client should not retry unless\n * they have first fixed up the directory by deleting files from it.\n * (d) Use FAILED_PRECONDITION if the client performs conditional\n * REST Get/Update/Delete on a resource and the resource on the\n * server does not match the condition. E.g., conflicting\n * read-modify-write on the same resource.\n */\n FAILED_PRECONDITION: \"failed-precondition\",\n /**\n * The operation was aborted, typically due to a concurrency issue like\n * sequencer check failures, transaction aborts, etc.\n *\n * See litmus test above for deciding between FAILED_PRECONDITION, ABORTED,\n * and UNAVAILABLE.\n */\n ABORTED: \"aborted\",\n /**\n * Operation was attempted past the valid range. E.g., seeking or reading\n * past end of file.\n *\n * Unlike INVALID_ARGUMENT, this error indicates a problem that may be fixed\n * if the system state changes. For example, a 32-bit file system will\n * generate INVALID_ARGUMENT if asked to read at an offset that is not in the\n * range [0,2^32-1], but it will generate OUT_OF_RANGE if asked to read from\n * an offset past the current file size.\n *\n * There is a fair bit of overlap between FAILED_PRECONDITION and\n * OUT_OF_RANGE. We recommend using OUT_OF_RANGE (the more specific error)\n * when it applies so that callers who are iterating through a space can\n * easily look for an OUT_OF_RANGE error to detect when they are done.\n */\n OUT_OF_RANGE: \"out-of-range\",\n /** Operation is not implemented or not supported/enabled in this service. */\n UNIMPLEMENTED: \"unimplemented\",\n /**\n * Internal errors. Means some invariants expected by underlying System has\n * been broken. If you see one of these errors, Something is very broken.\n */\n INTERNAL: \"internal\",\n /**\n * The service is currently unavailable. This is a most likely a transient\n * condition and may be corrected by retrying with a backoff.\n *\n * See litmus test above for deciding between FAILED_PRECONDITION, ABORTED,\n * and UNAVAILABLE.\n */\n UNAVAILABLE: \"unavailable\",\n /** Unrecoverable data loss or corruption. */\n DATA_LOSS: \"data-loss\"\n};\n\n/** An error returned by a Firestore operation. */ class U extends FirebaseError {\n /** @hideconstructor */\n constructor(\n /**\n * The backend error code associated with this error.\n */\n t, \n /**\n * A custom error description.\n */\n e) {\n super(t, e), this.code = t, this.message = e, \n // HACK: We write a toString property directly because Error is not a real\n // class and so inheritance does not work correctly. We could alternatively\n // do the same \"back-door inheritance\" trick that FirebaseError does.\n this.toString = () => `${this.name}: [code=${this.code}]: ${this.message}`;\n }\n}\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */ class K {\n constructor() {\n this.promise = new Promise(((t, e) => {\n this.resolve = t, this.reject = e;\n }));\n }\n}\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */ class G {\n constructor(t, e) {\n this.user = e, this.type = \"OAuth\", this.headers = new Map, this.headers.set(\"Authorization\", `Bearer ${t}`);\n }\n}\n\n/**\n * A CredentialsProvider that always yields an empty token.\n * @internal\n */ class Q {\n getToken() {\n return Promise.resolve(null);\n }\n invalidateToken() {}\n start(t, e) {\n // Fire with initial user.\n t.enqueueRetryable((() => e(V.UNAUTHENTICATED)));\n }\n shutdown() {}\n}\n\n/**\n * A CredentialsProvider that always returns a constant token. Used for\n * emulator token mocking.\n */ class j {\n constructor(t) {\n this.token = t, \n /**\n * Stores the listener registered with setChangeListener()\n * This isn't actually necessary since the UID never changes, but we use this\n * to verify the listen contract is adhered to in tests.\n */\n this.changeListener = null;\n }\n getToken() {\n return Promise.resolve(this.token);\n }\n invalidateToken() {}\n start(t, e) {\n this.changeListener = e, \n // Fire with initial user.\n t.enqueueRetryable((() => e(this.token.user)));\n }\n shutdown() {\n this.changeListener = null;\n }\n}\n\nclass z {\n constructor(t) {\n this.t = t, \n /** Tracks the current User. */\n this.currentUser = V.UNAUTHENTICATED, \n /**\n * Counter used to detect if the token changed while a getToken request was\n * outstanding.\n */\n this.i = 0, this.forceRefresh = !1, this.auth = null;\n }\n start(t, e) {\n let n = this.i;\n // A change listener that prevents double-firing for the same token change.\n const s = t => this.i !== n ? (n = this.i, e(t)) : Promise.resolve();\n // A promise that can be waited on to block on the next token change.\n // This promise is re-created after each change.\n let i = new K;\n this.o = () => {\n this.i++, this.currentUser = this.u(), i.resolve(), i = new K, t.enqueueRetryable((() => s(this.currentUser)));\n };\n const r = () => {\n const e = i;\n t.enqueueRetryable((async () => {\n await e.promise, await s(this.currentUser);\n }));\n }, o = t => {\n N(\"FirebaseAuthCredentialsProvider\", \"Auth detected\"), this.auth = t, this.auth.addAuthTokenListener(this.o), \n r();\n };\n this.t.onInit((t => o(t))), \n // Our users can initialize Auth right after Firestore, so we give it\n // a chance to register itself with the component framework before we\n // determine whether to start up in unauthenticated mode.\n setTimeout((() => {\n if (!this.auth) {\n const t = this.t.getImmediate({\n optional: !0\n });\n t ? o(t) : (\n // If auth is still not available, proceed with `null` user\n N(\"FirebaseAuthCredentialsProvider\", \"Auth not yet detected\"), i.resolve(), i = new K);\n }\n }), 0), r();\n }\n getToken() {\n // Take note of the current value of the tokenCounter so that this method\n // can fail (with an ABORTED error) if there is a token change while the\n // request is outstanding.\n const t = this.i, e = this.forceRefresh;\n return this.forceRefresh = !1, this.auth ? this.auth.getToken(e).then((e => \n // Cancel the request since the token changed while the request was\n // outstanding so the response is potentially for a previous user (which\n // user, we can't be sure).\n this.i !== t ? (N(\"FirebaseAuthCredentialsProvider\", \"getToken aborted due to token change.\"), \n this.getToken()) : e ? (F(\"string\" == typeof e.accessToken), new G(e.accessToken, this.currentUser)) : null)) : Promise.resolve(null);\n }\n invalidateToken() {\n this.forceRefresh = !0;\n }\n shutdown() {\n this.auth && this.auth.removeAuthTokenListener(this.o);\n }\n // Auth.getUid() can return null even with a user logged in. It is because\n // getUid() is synchronous, but the auth code populating Uid is asynchronous.\n // This method should only be called in the AuthTokenListener callback\n // to guarantee to get the actual user.\n u() {\n const t = this.auth && this.auth.getUid();\n return F(null === t || \"string\" == typeof t), new V(t);\n }\n}\n\n/*\n * FirstPartyToken provides a fresh token each time its value\n * is requested, because if the token is too old, requests will be rejected.\n * Technically this may no longer be necessary since the SDK should gracefully\n * recover from unauthenticated errors (see b/33147818 for context), but it's\n * safer to keep the implementation as-is.\n */ class W {\n constructor(t, e, n) {\n this.h = t, this.l = e, this.m = n, this.type = \"FirstParty\", this.user = V.FIRST_PARTY, \n this.g = new Map;\n }\n /**\n * Gets an authorization token, using a provided factory function, or return\n * null.\n */ p() {\n return this.m ? this.m() : null;\n }\n get headers() {\n this.g.set(\"X-Goog-AuthUser\", this.h);\n // Use array notation to prevent minification\n const t = this.p();\n return t && this.g.set(\"Authorization\", t), this.l && this.g.set(\"X-Goog-Iam-Authorization-Token\", this.l), \n this.g;\n }\n}\n\n/*\n * Provides user credentials required for the Firestore JavaScript SDK\n * to authenticate the user, using technique that is only available\n * to applications hosted by Google.\n */ class H {\n constructor(t, e, n) {\n this.h = t, this.l = e, this.m = n;\n }\n getToken() {\n return Promise.resolve(new W(this.h, this.l, this.m));\n }\n start(t, e) {\n // Fire with initial uid.\n t.enqueueRetryable((() => e(V.FIRST_PARTY)));\n }\n shutdown() {}\n invalidateToken() {}\n}\n\nclass J {\n constructor(t) {\n this.value = t, this.type = \"AppCheck\", this.headers = new Map, t && t.length > 0 && this.headers.set(\"x-firebase-appcheck\", this.value);\n }\n}\n\nclass Y {\n constructor(t) {\n this.I = t, this.forceRefresh = !1, this.appCheck = null, this.T = null;\n }\n start(t, e) {\n const n = t => {\n null != t.error && N(\"FirebaseAppCheckTokenProvider\", `Error getting App Check token; using placeholder token instead. Error: ${t.error.message}`);\n const n = t.token !== this.T;\n return this.T = t.token, N(\"FirebaseAppCheckTokenProvider\", `Received ${n ? \"new\" : \"existing\"} token.`), \n n ? e(t.token) : Promise.resolve();\n };\n this.o = e => {\n t.enqueueRetryable((() => n(e)));\n };\n const s = t => {\n N(\"FirebaseAppCheckTokenProvider\", \"AppCheck detected\"), this.appCheck = t, this.appCheck.addTokenListener(this.o);\n };\n this.I.onInit((t => s(t))), \n // Our users can initialize AppCheck after Firestore, so we give it\n // a chance to register itself with the component framework.\n setTimeout((() => {\n if (!this.appCheck) {\n const t = this.I.getImmediate({\n optional: !0\n });\n t ? s(t) : \n // If AppCheck is still not available, proceed without it.\n N(\"FirebaseAppCheckTokenProvider\", \"AppCheck not yet detected\");\n }\n }), 0);\n }\n getToken() {\n const t = this.forceRefresh;\n return this.forceRefresh = !1, this.appCheck ? this.appCheck.getToken(t).then((t => t ? (F(\"string\" == typeof t.token), \n this.T = t.token, new J(t.token)) : null)) : Promise.resolve(null);\n }\n invalidateToken() {\n this.forceRefresh = !0;\n }\n shutdown() {\n this.appCheck && this.appCheck.removeTokenListener(this.o);\n }\n}\n\n/**\n * An AppCheck token provider that always yields an empty token.\n * @internal\n */ class X {\n getToken() {\n return Promise.resolve(new J(\"\"));\n }\n invalidateToken() {}\n start(t, e) {}\n shutdown() {}\n}\n\n/**\n * Builds a CredentialsProvider depending on the type of\n * the credentials passed in.\n */\n/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * Generates `nBytes` of random bytes.\n *\n * If `nBytes < 0` , an error will be thrown.\n */\nfunction Z(t) {\n // Polyfills for IE and WebWorker by using `self` and `msCrypto` when `crypto` is not available.\n const e = \n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n \"undefined\" != typeof self && (self.crypto || self.msCrypto), n = new Uint8Array(t);\n if (e && \"function\" == typeof e.getRandomValues) e.getRandomValues(n); else \n // Falls back to Math.random\n for (let e = 0; e < t; e++) n[e] = Math.floor(256 * Math.random());\n return n;\n}\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */ class tt {\n static A() {\n // Alphanumeric characters\n const t = \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789\", e = Math.floor(256 / t.length) * t.length;\n // The largest byte value that is a multiple of `char.length`.\n let n = \"\";\n for (;n.length < 20; ) {\n const s = Z(40);\n for (let i = 0; i < s.length; ++i) \n // Only accept values that are [0, maxMultiple), this ensures they can\n // be evenly mapped to indices of `chars` via a modulo operation.\n n.length < 20 && s[i] < e && (n += t.charAt(s[i] % t.length));\n }\n return n;\n }\n}\n\nfunction et(t, e) {\n return t < e ? -1 : t > e ? 1 : 0;\n}\n\n/** Helper to compare arrays using isEqual(). */ function nt(t, e, n) {\n return t.length === e.length && t.every(((t, s) => n(t, e[s])));\n}\n\n/**\n * Returns the immediate lexicographically-following string. This is useful to\n * construct an inclusive range for indexeddb iterators.\n */ function st(t) {\n // Return the input string, with an additional NUL byte appended.\n return t + \"\\0\";\n}\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n// The earliest date supported by Firestore timestamps (0001-01-01T00:00:00Z).\n/**\n * A `Timestamp` represents a point in time independent of any time zone or\n * calendar, represented as seconds and fractions of seconds at nanosecond\n * resolution in UTC Epoch time.\n *\n * It is encoded using the Proleptic Gregorian Calendar which extends the\n * Gregorian calendar backwards to year one. It is encoded assuming all minutes\n * are 60 seconds long, i.e. leap seconds are \"smeared\" so that no leap second\n * table is needed for interpretation. Range is from 0001-01-01T00:00:00Z to\n * 9999-12-31T23:59:59.999999999Z.\n *\n * For examples and further specifications, refer to the\n * {@link https://github.com/google/protobuf/blob/master/src/google/protobuf/timestamp.proto | Timestamp definition}.\n */\nclass it {\n /**\n * Creates a new timestamp.\n *\n * @param seconds - The number of seconds of UTC time since Unix epoch\n * 1970-01-01T00:00:00Z. Must be from 0001-01-01T00:00:00Z to\n * 9999-12-31T23:59:59Z inclusive.\n * @param nanoseconds - The non-negative fractions of a second at nanosecond\n * resolution. Negative second values with fractions must still have\n * non-negative nanoseconds values that count forward in time. Must be\n * from 0 to 999,999,999 inclusive.\n */\n constructor(\n /**\n * The number of seconds of UTC time since Unix epoch 1970-01-01T00:00:00Z.\n */\n t, \n /**\n * The fractions of a second at nanosecond resolution.*\n */\n e) {\n if (this.seconds = t, this.nanoseconds = e, e < 0) throw new U(q.INVALID_ARGUMENT, \"Timestamp nanoseconds out of range: \" + e);\n if (e >= 1e9) throw new U(q.INVALID_ARGUMENT, \"Timestamp nanoseconds out of range: \" + e);\n if (t < -62135596800) throw new U(q.INVALID_ARGUMENT, \"Timestamp seconds out of range: \" + t);\n // This will break in the year 10,000.\n if (t >= 253402300800) throw new U(q.INVALID_ARGUMENT, \"Timestamp seconds out of range: \" + t);\n }\n /**\n * Creates a new timestamp with the current date, with millisecond precision.\n *\n * @returns a new timestamp representing the current date.\n */ static now() {\n return it.fromMillis(Date.now());\n }\n /**\n * Creates a new timestamp from the given date.\n *\n * @param date - The date to initialize the `Timestamp` from.\n * @returns A new `Timestamp` representing the same point in time as the given\n * date.\n */ static fromDate(t) {\n return it.fromMillis(t.getTime());\n }\n /**\n * Creates a new timestamp from the given number of milliseconds.\n *\n * @param milliseconds - Number of milliseconds since Unix epoch\n * 1970-01-01T00:00:00Z.\n * @returns A new `Timestamp` representing the same point in time as the given\n * number of milliseconds.\n */ static fromMillis(t) {\n const e = Math.floor(t / 1e3), n = Math.floor(1e6 * (t - 1e3 * e));\n return new it(e, n);\n }\n /**\n * Converts a `Timestamp` to a JavaScript `Date` object. This conversion\n * causes a loss of precision since `Date` objects only support millisecond\n * precision.\n *\n * @returns JavaScript `Date` object representing the same point in time as\n * this `Timestamp`, with millisecond precision.\n */ toDate() {\n return new Date(this.toMillis());\n }\n /**\n * Converts a `Timestamp` to a numeric timestamp (in milliseconds since\n * epoch). This operation causes a loss of precision.\n *\n * @returns The point in time corresponding to this timestamp, represented as\n * the number of milliseconds since Unix epoch 1970-01-01T00:00:00Z.\n */ toMillis() {\n return 1e3 * this.seconds + this.nanoseconds / 1e6;\n }\n _compareTo(t) {\n return this.seconds === t.seconds ? et(this.nanoseconds, t.nanoseconds) : et(this.seconds, t.seconds);\n }\n /**\n * Returns true if this `Timestamp` is equal to the provided one.\n *\n * @param other - The `Timestamp` to compare against.\n * @returns true if this `Timestamp` is equal to the provided one.\n */ isEqual(t) {\n return t.seconds === this.seconds && t.nanoseconds === this.nanoseconds;\n }\n /** Returns a textual representation of this `Timestamp`. */ toString() {\n return \"Timestamp(seconds=\" + this.seconds + \", nanoseconds=\" + this.nanoseconds + \")\";\n }\n /** Returns a JSON-serializable representation of this `Timestamp`. */ toJSON() {\n return {\n seconds: this.seconds,\n nanoseconds: this.nanoseconds\n };\n }\n /**\n * Converts this object to a primitive string, which allows `Timestamp` objects\n * to be compared using the `>`, `<=`, `>=` and `>` operators.\n */ valueOf() {\n // This method returns a string of the form . where\n // is translated to have a non-negative value and both \n // and are left-padded with zeroes to be a consistent length.\n // Strings with this format then have a lexiographical ordering that matches\n // the expected ordering. The translation is done to avoid having\n // a leading negative sign (i.e. a leading '-' character) in its string\n // representation, which would affect its lexiographical ordering.\n const t = this.seconds - -62135596800;\n // Note: Up to 12 decimal digits are required to represent all valid\n // 'seconds' values.\n return String(t).padStart(12, \"0\") + \".\" + String(this.nanoseconds).padStart(9, \"0\");\n }\n}\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * A version of a document in Firestore. This corresponds to the version\n * timestamp, such as update_time or read_time.\n */ class rt {\n constructor(t) {\n this.timestamp = t;\n }\n static fromTimestamp(t) {\n return new rt(t);\n }\n static min() {\n return new rt(new it(0, 0));\n }\n static max() {\n return new rt(new it(253402300799, 999999999));\n }\n compareTo(t) {\n return this.timestamp._compareTo(t.timestamp);\n }\n isEqual(t) {\n return this.timestamp.isEqual(t.timestamp);\n }\n /** Returns a number representation of the version for use in spec tests. */ toMicroseconds() {\n // Convert to microseconds.\n return 1e6 * this.timestamp.seconds + this.timestamp.nanoseconds / 1e3;\n }\n toString() {\n return \"SnapshotVersion(\" + this.timestamp.toString() + \")\";\n }\n toTimestamp() {\n return this.timestamp;\n }\n}\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * Path represents an ordered sequence of string segments.\n */\nclass ot {\n constructor(t, e, n) {\n void 0 === e ? e = 0 : e > t.length && O(), void 0 === n ? n = t.length - e : n > t.length - e && O(), \n this.segments = t, this.offset = e, this.len = n;\n }\n get length() {\n return this.len;\n }\n isEqual(t) {\n return 0 === ot.comparator(this, t);\n }\n child(t) {\n const e = this.segments.slice(this.offset, this.limit());\n return t instanceof ot ? t.forEach((t => {\n e.push(t);\n })) : e.push(t), this.construct(e);\n }\n /** The index of one past the last segment of the path. */ limit() {\n return this.offset + this.length;\n }\n popFirst(t) {\n return t = void 0 === t ? 1 : t, this.construct(this.segments, this.offset + t, this.length - t);\n }\n popLast() {\n return this.construct(this.segments, this.offset, this.length - 1);\n }\n firstSegment() {\n return this.segments[this.offset];\n }\n lastSegment() {\n return this.get(this.length - 1);\n }\n get(t) {\n return this.segments[this.offset + t];\n }\n isEmpty() {\n return 0 === this.length;\n }\n isPrefixOf(t) {\n if (t.length < this.length) return !1;\n for (let e = 0; e < this.length; e++) if (this.get(e) !== t.get(e)) return !1;\n return !0;\n }\n isImmediateParentOf(t) {\n if (this.length + 1 !== t.length) return !1;\n for (let e = 0; e < this.length; e++) if (this.get(e) !== t.get(e)) return !1;\n return !0;\n }\n forEach(t) {\n for (let e = this.offset, n = this.limit(); e < n; e++) t(this.segments[e]);\n }\n toArray() {\n return this.segments.slice(this.offset, this.limit());\n }\n static comparator(t, e) {\n const n = Math.min(t.length, e.length);\n for (let s = 0; s < n; s++) {\n const n = t.get(s), i = e.get(s);\n if (n < i) return -1;\n if (n > i) return 1;\n }\n return t.length < e.length ? -1 : t.length > e.length ? 1 : 0;\n }\n}\n\n/**\n * A slash-separated path for navigating resources (documents and collections)\n * within Firestore.\n *\n * @internal\n */ class ut extends ot {\n construct(t, e, n) {\n return new ut(t, e, n);\n }\n canonicalString() {\n // NOTE: The client is ignorant of any path segments containing escape\n // sequences (e.g. __id123__) and just passes them through raw (they exist\n // for legacy reasons and should not be used frequently).\n return this.toArray().join(\"/\");\n }\n toString() {\n return this.canonicalString();\n }\n /**\n * Creates a resource path from the given slash-delimited string. If multiple\n * arguments are provided, all components are combined. Leading and trailing\n * slashes from all components are ignored.\n */ static fromString(...t) {\n // NOTE: The client is ignorant of any path segments containing escape\n // sequences (e.g. __id123__) and just passes them through raw (they exist\n // for legacy reasons and should not be used frequently).\n const e = [];\n for (const n of t) {\n if (n.indexOf(\"//\") >= 0) throw new U(q.INVALID_ARGUMENT, `Invalid segment (${n}). Paths must not contain // in them.`);\n // Strip leading and traling slashed.\n e.push(...n.split(\"/\").filter((t => t.length > 0)));\n }\n return new ut(e);\n }\n static emptyPath() {\n return new ut([]);\n }\n}\n\nconst ct = /^[_a-zA-Z][_a-zA-Z0-9]*$/;\n\n/**\n * A dot-separated path for navigating sub-objects within a document.\n * @internal\n */ class at extends ot {\n construct(t, e, n) {\n return new at(t, e, n);\n }\n /**\n * Returns true if the string could be used as a segment in a field path\n * without escaping.\n */ static isValidIdentifier(t) {\n return ct.test(t);\n }\n canonicalString() {\n return this.toArray().map((t => (t = t.replace(/\\\\/g, \"\\\\\\\\\").replace(/`/g, \"\\\\`\"), \n at.isValidIdentifier(t) || (t = \"`\" + t + \"`\"), t))).join(\".\");\n }\n toString() {\n return this.canonicalString();\n }\n /**\n * Returns true if this field references the key of a document.\n */ isKeyField() {\n return 1 === this.length && \"__name__\" === this.get(0);\n }\n /**\n * The field designating the key of a document.\n */ static keyField() {\n return new at([ \"__name__\" ]);\n }\n /**\n * Parses a field string from the given server-formatted string.\n *\n * - Splitting the empty string is not allowed (for now at least).\n * - Empty segments within the string (e.g. if there are two consecutive\n * separators) are not allowed.\n *\n * TODO(b/37244157): we should make this more strict. Right now, it allows\n * non-identifier path components, even if they aren't escaped.\n */ static fromServerFormat(t) {\n const e = [];\n let n = \"\", s = 0;\n const i = () => {\n if (0 === n.length) throw new U(q.INVALID_ARGUMENT, `Invalid field path (${t}). Paths must not be empty, begin with '.', end with '.', or contain '..'`);\n e.push(n), n = \"\";\n };\n let r = !1;\n for (;s < t.length; ) {\n const e = t[s];\n if (\"\\\\\" === e) {\n if (s + 1 === t.length) throw new U(q.INVALID_ARGUMENT, \"Path has trailing escape character: \" + t);\n const e = t[s + 1];\n if (\"\\\\\" !== e && \".\" !== e && \"`\" !== e) throw new U(q.INVALID_ARGUMENT, \"Path has invalid escape sequence: \" + t);\n n += e, s += 2;\n } else \"`\" === e ? (r = !r, s++) : \".\" !== e || r ? (n += e, s++) : (i(), s++);\n }\n if (i(), r) throw new U(q.INVALID_ARGUMENT, \"Unterminated ` in path: \" + t);\n return new at(e);\n }\n static emptyPath() {\n return new at([]);\n }\n}\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * @internal\n */ class ht {\n constructor(t) {\n this.path = t;\n }\n static fromPath(t) {\n return new ht(ut.fromString(t));\n }\n static fromName(t) {\n return new ht(ut.fromString(t).popFirst(5));\n }\n static empty() {\n return new ht(ut.emptyPath());\n }\n get collectionGroup() {\n return this.path.popLast().lastSegment();\n }\n /** Returns true if the document is in the specified collectionId. */ hasCollectionId(t) {\n return this.path.length >= 2 && this.path.get(this.path.length - 2) === t;\n }\n /** Returns the collection group (i.e. the name of the parent collection) for this key. */ getCollectionGroup() {\n return this.path.get(this.path.length - 2);\n }\n /** Returns the fully qualified path to the parent collection. */ getCollectionPath() {\n return this.path.popLast();\n }\n isEqual(t) {\n return null !== t && 0 === ut.comparator(this.path, t.path);\n }\n toString() {\n return this.path.toString();\n }\n static comparator(t, e) {\n return ut.comparator(t.path, e.path);\n }\n static isDocumentKey(t) {\n return t.length % 2 == 0;\n }\n /**\n * Creates and returns a new document key with the given segments.\n *\n * @param segments - The segments of the path to the document\n * @returns A new instance of DocumentKey\n */ static fromSegments(t) {\n return new ht(new ut(t.slice()));\n }\n}\n\n/**\n * @license\n * Copyright 2021 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * The initial mutation batch id for each index. Gets updated during index\n * backfill.\n */\n/**\n * An index definition for field indexes in Firestore.\n *\n * Every index is associated with a collection. The definition contains a list\n * of fields and their index kind (which can be `ASCENDING`, `DESCENDING` or\n * `CONTAINS` for ArrayContains/ArrayContainsAny queries).\n *\n * Unlike the backend, the SDK does not differentiate between collection or\n * collection group-scoped indices. Every index can be used for both single\n * collection and collection group queries.\n */\nclass lt {\n constructor(\n /**\n * The index ID. Returns -1 if the index ID is not available (e.g. the index\n * has not yet been persisted).\n */\n t, \n /** The collection ID this index applies to. */\n e, \n /** The field segments for this index. */\n n, \n /** Shows how up-to-date the index is for the current user. */\n s) {\n this.indexId = t, this.collectionGroup = e, this.fields = n, this.indexState = s;\n }\n}\n\n/** An ID for an index that has not yet been added to persistence. */\n/** Returns the ArrayContains/ArrayContainsAny segment for this index. */\nfunction ft(t) {\n return t.fields.find((t => 2 /* IndexKind.CONTAINS */ === t.kind));\n}\n\n/** Returns all directional (ascending/descending) segments for this index. */ function dt(t) {\n return t.fields.filter((t => 2 /* IndexKind.CONTAINS */ !== t.kind));\n}\n\n/**\n * Returns the order of the document key component for the given index.\n *\n * PORTING NOTE: This is only used in the Web IndexedDb implementation.\n */\n/**\n * Compares indexes by collection group and segments. Ignores update time and\n * index ID.\n */\nfunction wt(t, e) {\n let n = et(t.collectionGroup, e.collectionGroup);\n if (0 !== n) return n;\n for (let s = 0; s < Math.min(t.fields.length, e.fields.length); ++s) if (n = mt(t.fields[s], e.fields[s]), \n 0 !== n) return n;\n return et(t.fields.length, e.fields.length);\n}\n\n/** Returns a debug representation of the field index */ lt.UNKNOWN_ID = -1;\n\n/** An index component consisting of field path and index type. */\nclass _t {\n constructor(\n /** The field path of the component. */\n t, \n /** The fields sorting order. */\n e) {\n this.fieldPath = t, this.kind = e;\n }\n}\n\nfunction mt(t, e) {\n const n = at.comparator(t.fieldPath, e.fieldPath);\n return 0 !== n ? n : et(t.kind, e.kind);\n}\n\n/**\n * Stores the \"high water mark\" that indicates how updated the Index is for the\n * current user.\n */ class gt {\n constructor(\n /**\n * Indicates when the index was last updated (relative to other indexes).\n */\n t, \n /** The the latest indexed read time, document and batch id. */\n e) {\n this.sequenceNumber = t, this.offset = e;\n }\n /** The state of an index that has not yet been backfilled. */ static empty() {\n return new gt(0, It.min());\n }\n}\n\n/**\n * Creates an offset that matches all documents with a read time higher than\n * `readTime`.\n */ function yt(t, e) {\n // We want to create an offset that matches all documents with a read time\n // greater than the provided read time. To do so, we technically need to\n // create an offset for `(readTime, MAX_DOCUMENT_KEY)`. While we could use\n // Unicode codepoints to generate MAX_DOCUMENT_KEY, it is much easier to use\n // `(readTime + 1, DocumentKey.empty())` since `> DocumentKey.empty()` matches\n // all valid document IDs.\n const n = t.toTimestamp().seconds, s = t.toTimestamp().nanoseconds + 1, i = rt.fromTimestamp(1e9 === s ? new it(n + 1, 0) : new it(n, s));\n return new It(i, ht.empty(), e);\n}\n\n/** Creates a new offset based on the provided document. */ function pt(t) {\n return new It(t.readTime, t.key, -1);\n}\n\n/**\n * Stores the latest read time, document and batch ID that were processed for an\n * index.\n */ class It {\n constructor(\n /**\n * The latest read time version that has been indexed by Firestore for this\n * field index.\n */\n t, \n /**\n * The key of the last document that was indexed for this query. Use\n * `DocumentKey.empty()` if no document has been indexed.\n */\n e, \n /*\n * The largest mutation batch id that's been processed by Firestore.\n */\n n) {\n this.readTime = t, this.documentKey = e, this.largestBatchId = n;\n }\n /** Returns an offset that sorts before all regular offsets. */ static min() {\n return new It(rt.min(), ht.empty(), -1);\n }\n /** Returns an offset that sorts after all regular offsets. */ static max() {\n return new It(rt.max(), ht.empty(), -1);\n }\n}\n\nfunction Tt(t, e) {\n let n = t.readTime.compareTo(e.readTime);\n return 0 !== n ? n : (n = ht.comparator(t.documentKey, e.documentKey), 0 !== n ? n : et(t.largestBatchId, e.largestBatchId));\n}\n\n/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */ const Et = \"The current tab is not in the required state to perform this operation. It might be necessary to refresh the browser tab.\";\n\n/**\n * A base class representing a persistence transaction, encapsulating both the\n * transaction's sequence numbers as well as a list of onCommitted listeners.\n *\n * When you call Persistence.runTransaction(), it will create a transaction and\n * pass it to your callback. You then pass it to any method that operates\n * on persistence.\n */ class At {\n constructor() {\n this.onCommittedListeners = [];\n }\n addOnCommittedListener(t) {\n this.onCommittedListeners.push(t);\n }\n raiseOnCommittedEvent() {\n this.onCommittedListeners.forEach((t => t()));\n }\n}\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * Verifies the error thrown by a LocalStore operation. If a LocalStore\n * operation fails because the primary lease has been taken by another client,\n * we ignore the error (the persistence layer will immediately call\n * `applyPrimaryLease` to propagate the primary state change). All other errors\n * are re-thrown.\n *\n * @param err - An error returned by a LocalStore operation.\n * @returns A Promise that resolves after we recovered, or the original error.\n */ async function vt(t) {\n if (t.code !== q.FAILED_PRECONDITION || t.message !== Et) throw t;\n N(\"LocalStore\", \"Unexpectedly lost primary lease\");\n}\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * PersistencePromise is essentially a re-implementation of Promise except\n * it has a .next() method instead of .then() and .next() and .catch() callbacks\n * are executed synchronously when a PersistencePromise resolves rather than\n * asynchronously (Promise implementations use setImmediate() or similar).\n *\n * This is necessary to interoperate with IndexedDB which will automatically\n * commit transactions if control is returned to the event loop without\n * synchronously initiating another operation on the transaction.\n *\n * NOTE: .then() and .catch() only allow a single consumer, unlike normal\n * Promises.\n */ class Rt {\n constructor(t) {\n // NOTE: next/catchCallback will always point to our own wrapper functions,\n // not the user's raw next() or catch() callbacks.\n this.nextCallback = null, this.catchCallback = null, \n // When the operation resolves, we'll set result or error and mark isDone.\n this.result = void 0, this.error = void 0, this.isDone = !1, \n // Set to true when .then() or .catch() are called and prevents additional\n // chaining.\n this.callbackAttached = !1, t((t => {\n this.isDone = !0, this.result = t, this.nextCallback && \n // value should be defined unless T is Void, but we can't express\n // that in the type system.\n this.nextCallback(t);\n }), (t => {\n this.isDone = !0, this.error = t, this.catchCallback && this.catchCallback(t);\n }));\n }\n catch(t) {\n return this.next(void 0, t);\n }\n next(t, e) {\n return this.callbackAttached && O(), this.callbackAttached = !0, this.isDone ? this.error ? this.wrapFailure(e, this.error) : this.wrapSuccess(t, this.result) : new Rt(((n, s) => {\n this.nextCallback = e => {\n this.wrapSuccess(t, e).next(n, s);\n }, this.catchCallback = t => {\n this.wrapFailure(e, t).next(n, s);\n };\n }));\n }\n toPromise() {\n return new Promise(((t, e) => {\n this.next(t, e);\n }));\n }\n wrapUserFunction(t) {\n try {\n const e = t();\n return e instanceof Rt ? e : Rt.resolve(e);\n } catch (t) {\n return Rt.reject(t);\n }\n }\n wrapSuccess(t, e) {\n return t ? this.wrapUserFunction((() => t(e))) : Rt.resolve(e);\n }\n wrapFailure(t, e) {\n return t ? this.wrapUserFunction((() => t(e))) : Rt.reject(e);\n }\n static resolve(t) {\n return new Rt(((e, n) => {\n e(t);\n }));\n }\n static reject(t) {\n return new Rt(((e, n) => {\n n(t);\n }));\n }\n static waitFor(\n // Accept all Promise types in waitFor().\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n t) {\n return new Rt(((e, n) => {\n let s = 0, i = 0, r = !1;\n t.forEach((t => {\n ++s, t.next((() => {\n ++i, r && i === s && e();\n }), (t => n(t)));\n })), r = !0, i === s && e();\n }));\n }\n /**\n * Given an array of predicate functions that asynchronously evaluate to a\n * boolean, implements a short-circuiting `or` between the results. Predicates\n * will be evaluated until one of them returns `true`, then stop. The final\n * result will be whether any of them returned `true`.\n */ static or(t) {\n let e = Rt.resolve(!1);\n for (const n of t) e = e.next((t => t ? Rt.resolve(t) : n()));\n return e;\n }\n static forEach(t, e) {\n const n = [];\n return t.forEach(((t, s) => {\n n.push(e.call(this, t, s));\n })), this.waitFor(n);\n }\n /**\n * Concurrently map all array elements through asynchronous function.\n */ static mapArray(t, e) {\n return new Rt(((n, s) => {\n const i = t.length, r = new Array(i);\n let o = 0;\n for (let u = 0; u < i; u++) {\n const c = u;\n e(t[c]).next((t => {\n r[c] = t, ++o, o === i && n(r);\n }), (t => s(t)));\n }\n }));\n }\n /**\n * An alternative to recursive PersistencePromise calls, that avoids\n * potential memory problems from unbounded chains of promises.\n *\n * The `action` will be called repeatedly while `condition` is true.\n */ static doWhile(t, e) {\n return new Rt(((n, s) => {\n const i = () => {\n !0 === t() ? e().next((() => {\n i();\n }), s) : n();\n };\n i();\n }));\n }\n}\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n// References to `window` are guarded by SimpleDb.isAvailable()\n/* eslint-disable no-restricted-globals */\n/**\n * Wraps an IDBTransaction and exposes a store() method to get a handle to a\n * specific object store.\n */\nclass Pt {\n constructor(t, e) {\n this.action = t, this.transaction = e, this.aborted = !1, \n /**\n * A `Promise` that resolves with the result of the IndexedDb transaction.\n */\n this.v = new K, this.transaction.oncomplete = () => {\n this.v.resolve();\n }, this.transaction.onabort = () => {\n e.error ? this.v.reject(new St(t, e.error)) : this.v.resolve();\n }, this.transaction.onerror = e => {\n const n = kt(e.target.error);\n this.v.reject(new St(t, n));\n };\n }\n static open(t, e, n, s) {\n try {\n return new Pt(e, t.transaction(s, n));\n } catch (t) {\n throw new St(e, t);\n }\n }\n get R() {\n return this.v.promise;\n }\n abort(t) {\n t && this.v.reject(t), this.aborted || (N(\"SimpleDb\", \"Aborting transaction:\", t ? t.message : \"Client-initiated abort\"), \n this.aborted = !0, this.transaction.abort());\n }\n P() {\n // If the browser supports V3 IndexedDB, we invoke commit() explicitly to\n // speed up index DB processing if the event loop remains blocks.\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const t = this.transaction;\n this.aborted || \"function\" != typeof t.commit || t.commit();\n }\n /**\n * Returns a SimpleDbStore for the specified store. All\n * operations performed on the SimpleDbStore happen within the context of this\n * transaction and it cannot be used anymore once the transaction is\n * completed.\n *\n * Note that we can't actually enforce that the KeyType and ValueType are\n * correct, but they allow type safety through the rest of the consuming code.\n */ store(t) {\n const e = this.transaction.objectStore(t);\n return new Ct(e);\n }\n}\n\n/**\n * Provides a wrapper around IndexedDb with a simplified interface that uses\n * Promise-like return values to chain operations. Real promises cannot be used\n * since .then() continuations are executed asynchronously (e.g. via\n * .setImmediate), which would cause IndexedDB to end the transaction.\n * See PersistencePromise for more details.\n */ class bt {\n /*\n * Creates a new SimpleDb wrapper for IndexedDb database `name`.\n *\n * Note that `version` must not be a downgrade. IndexedDB does not support\n * downgrading the schema version. We currently do not support any way to do\n * versioning outside of IndexedDB's versioning mechanism, as only\n * version-upgrade transactions are allowed to do things like create\n * objectstores.\n */\n constructor(t, e, n) {\n this.name = t, this.version = e, this.V = n;\n // NOTE: According to https://bugs.webkit.org/show_bug.cgi?id=197050, the\n // bug we're checking for should exist in iOS >= 12.2 and < 13, but for\n // whatever reason it's much harder to hit after 12.2 so we only proactively\n // log on 12.2.\n 12.2 === bt.S(getUA()) && k(\"Firestore persistence suffers from a bug in iOS 12.2 Safari that may cause your app to stop working. See https://stackoverflow.com/q/56496296/110915 for details and a potential workaround.\");\n }\n /** Deletes the specified database. */ static delete(t) {\n return N(\"SimpleDb\", \"Removing database:\", t), xt(window.indexedDB.deleteDatabase(t)).toPromise();\n }\n /** Returns true if IndexedDB is available in the current environment. */ static D() {\n if (!isIndexedDBAvailable()) return !1;\n if (bt.C()) return !0;\n // We extensively use indexed array values and compound keys,\n // which IE and Edge do not support. However, they still have indexedDB\n // defined on the window, so we need to check for them here and make sure\n // to return that persistence is not enabled for those browsers.\n // For tracking support of this feature, see here:\n // https://developer.microsoft.com/en-us/microsoft-edge/platform/status/indexeddbarraysandmultientrysupport/\n // Check the UA string to find out the browser.\n const t = getUA(), e = bt.S(t), n = 0 < e && e < 10, s = bt.N(t), i = 0 < s && s < 4.5;\n // IE 10\n // ua = 'Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.2; Trident/6.0)';\n // IE 11\n // ua = 'Mozilla/5.0 (Windows NT 6.3; Trident/7.0; rv:11.0) like Gecko';\n // Edge\n // ua = 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML,\n // like Gecko) Chrome/39.0.2171.71 Safari/537.36 Edge/12.0';\n // iOS Safari: Disable for users running iOS version < 10.\n return !(t.indexOf(\"MSIE \") > 0 || t.indexOf(\"Trident/\") > 0 || t.indexOf(\"Edge/\") > 0 || n || i);\n }\n /**\n * Returns true if the backing IndexedDB store is the Node IndexedDBShim\n * (see https://github.com/axemclion/IndexedDBShim).\n */ static C() {\n var t;\n return \"undefined\" != typeof process && \"YES\" === (null === (t = process.env) || void 0 === t ? void 0 : t.k);\n }\n /** Helper to get a typed SimpleDbStore from a transaction. */ static M(t, e) {\n return t.store(e);\n }\n // visible for testing\n /** Parse User Agent to determine iOS version. Returns -1 if not found. */\n static S(t) {\n const e = t.match(/i(?:phone|pad|pod) os ([\\d_]+)/i), n = e ? e[1].split(\"_\").slice(0, 2).join(\".\") : \"-1\";\n return Number(n);\n }\n // visible for testing\n /** Parse User Agent to determine Android version. Returns -1 if not found. */\n static N(t) {\n const e = t.match(/Android ([\\d.]+)/i), n = e ? e[1].split(\".\").slice(0, 2).join(\".\") : \"-1\";\n return Number(n);\n }\n /**\n * Opens the specified database, creating or upgrading it if necessary.\n */ async $(t) {\n return this.db || (N(\"SimpleDb\", \"Opening database:\", this.name), this.db = await new Promise(((e, n) => {\n // TODO(mikelehen): Investigate browser compatibility.\n // https://developer.mozilla.org/en-US/docs/Web/API/IndexedDB_API/Using_IndexedDB\n // suggests IE9 and older WebKit browsers handle upgrade\n // differently. They expect setVersion, as described here:\n // https://developer.mozilla.org/en-US/docs/Web/API/IDBVersionChangeRequest/setVersion\n const s = indexedDB.open(this.name, this.version);\n s.onsuccess = t => {\n const n = t.target.result;\n e(n);\n }, s.onblocked = () => {\n n(new St(t, \"Cannot upgrade IndexedDB schema while another tab is open. Close all tabs that access Firestore and reload this page to proceed.\"));\n }, s.onerror = e => {\n const s = e.target.error;\n \"VersionError\" === s.name ? n(new U(q.FAILED_PRECONDITION, \"A newer version of the Firestore SDK was previously used and so the persisted data is not compatible with the version of the SDK you are now using. The SDK will operate with persistence disabled. If you need persistence, please re-upgrade to a newer version of the SDK or else clear the persisted IndexedDB data for your app to start fresh.\")) : \"InvalidStateError\" === s.name ? n(new U(q.FAILED_PRECONDITION, \"Unable to open an IndexedDB connection. This could be due to running in a private browsing session on a browser whose private browsing sessions do not support IndexedDB: \" + s)) : n(new St(t, s));\n }, s.onupgradeneeded = t => {\n N(\"SimpleDb\", 'Database \"' + this.name + '\" requires upgrade from version:', t.oldVersion);\n const e = t.target.result;\n this.V.O(e, s.transaction, t.oldVersion, this.version).next((() => {\n N(\"SimpleDb\", \"Database upgrade to version \" + this.version + \" complete\");\n }));\n };\n }))), this.F && (this.db.onversionchange = t => this.F(t)), this.db;\n }\n B(t) {\n this.F = t, this.db && (this.db.onversionchange = e => t(e));\n }\n async runTransaction(t, e, n, s) {\n const i = \"readonly\" === e;\n let r = 0;\n for (;;) {\n ++r;\n try {\n this.db = await this.$(t);\n const e = Pt.open(this.db, t, i ? \"readonly\" : \"readwrite\", n), r = s(e).next((t => (e.P(), \n t))).catch((t => (\n // Abort the transaction if there was an error.\n e.abort(t), Rt.reject(t)))).toPromise();\n // As noted above, errors are propagated by aborting the transaction. So\n // we swallow any error here to avoid the browser logging it as unhandled.\n return r.catch((() => {})), \n // Wait for the transaction to complete (i.e. IndexedDb's onsuccess event to\n // fire), but still return the original transactionFnResult back to the\n // caller.\n await e.R, r;\n } catch (t) {\n const e = t, n = \"FirebaseError\" !== e.name && r < 3;\n // TODO(schmidt-sebastian): We could probably be smarter about this and\n // not retry exceptions that are likely unrecoverable (such as quota\n // exceeded errors).\n // Note: We cannot use an instanceof check for FirestoreException, since the\n // exception is wrapped in a generic error by our async/await handling.\n if (N(\"SimpleDb\", \"Transaction failed with error:\", e.message, \"Retrying:\", n), \n this.close(), !n) return Promise.reject(e);\n }\n }\n }\n close() {\n this.db && this.db.close(), this.db = void 0;\n }\n}\n\n/**\n * A controller for iterating over a key range or index. It allows an iterate\n * callback to delete the currently-referenced object, or jump to a new key\n * within the key range or index.\n */ class Vt {\n constructor(t) {\n this.L = t, this.q = !1, this.U = null;\n }\n get isDone() {\n return this.q;\n }\n get K() {\n return this.U;\n }\n set cursor(t) {\n this.L = t;\n }\n /**\n * This function can be called to stop iteration at any point.\n */ done() {\n this.q = !0;\n }\n /**\n * This function can be called to skip to that next key, which could be\n * an index or a primary key.\n */ G(t) {\n this.U = t;\n }\n /**\n * Delete the current cursor value from the object store.\n *\n * NOTE: You CANNOT do this with a keysOnly query.\n */ delete() {\n return xt(this.L.delete());\n }\n}\n\n/** An error that wraps exceptions that thrown during IndexedDB execution. */ class St extends U {\n constructor(t, e) {\n super(q.UNAVAILABLE, `IndexedDB transaction '${t}' failed: ${e}`), this.name = \"IndexedDbTransactionError\";\n }\n}\n\n/** Verifies whether `e` is an IndexedDbTransactionError. */ function Dt(t) {\n // Use name equality, as instanceof checks on errors don't work with errors\n // that wrap other errors.\n return \"IndexedDbTransactionError\" === t.name;\n}\n\n/**\n * A wrapper around an IDBObjectStore providing an API that:\n *\n * 1) Has generic KeyType / ValueType parameters to provide strongly-typed\n * methods for acting against the object store.\n * 2) Deals with IndexedDB's onsuccess / onerror event callbacks, making every\n * method return a PersistencePromise instead.\n * 3) Provides a higher-level API to avoid needing to do excessive wrapping of\n * intermediate IndexedDB types (IDBCursorWithValue, etc.)\n */ class Ct {\n constructor(t) {\n this.store = t;\n }\n put(t, e) {\n let n;\n return void 0 !== e ? (N(\"SimpleDb\", \"PUT\", this.store.name, t, e), n = this.store.put(e, t)) : (N(\"SimpleDb\", \"PUT\", this.store.name, \"\", t), \n n = this.store.put(t)), xt(n);\n }\n /**\n * Adds a new value into an Object Store and returns the new key. Similar to\n * IndexedDb's `add()`, this method will fail on primary key collisions.\n *\n * @param value - The object to write.\n * @returns The key of the value to add.\n */ add(t) {\n N(\"SimpleDb\", \"ADD\", this.store.name, t, t);\n return xt(this.store.add(t));\n }\n /**\n * Gets the object with the specified key from the specified store, or null\n * if no object exists with the specified key.\n *\n * @key The key of the object to get.\n * @returns The object with the specified key or null if no object exists.\n */ get(t) {\n // We're doing an unsafe cast to ValueType.\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n return xt(this.store.get(t)).next((e => (\n // Normalize nonexistence to null.\n void 0 === e && (e = null), N(\"SimpleDb\", \"GET\", this.store.name, t, e), e)));\n }\n delete(t) {\n N(\"SimpleDb\", \"DELETE\", this.store.name, t);\n return xt(this.store.delete(t));\n }\n /**\n * If we ever need more of the count variants, we can add overloads. For now,\n * all we need is to count everything in a store.\n *\n * Returns the number of rows in the store.\n */ count() {\n N(\"SimpleDb\", \"COUNT\", this.store.name);\n return xt(this.store.count());\n }\n j(t, e) {\n const n = this.options(t, e);\n // Use `getAll()` if the browser supports IndexedDB v3, as it is roughly\n // 20% faster. Unfortunately, getAll() does not support custom indices.\n if (n.index || \"function\" != typeof this.store.getAll) {\n const t = this.cursor(n), e = [];\n return this.W(t, ((t, n) => {\n e.push(n);\n })).next((() => e));\n }\n {\n const t = this.store.getAll(n.range);\n return new Rt(((e, n) => {\n t.onerror = t => {\n n(t.target.error);\n }, t.onsuccess = t => {\n e(t.target.result);\n };\n }));\n }\n }\n /**\n * Loads the first `count` elements from the provided index range. Loads all\n * elements if no limit is provided.\n */ H(t, e) {\n const n = this.store.getAll(t, null === e ? void 0 : e);\n return new Rt(((t, e) => {\n n.onerror = t => {\n e(t.target.error);\n }, n.onsuccess = e => {\n t(e.target.result);\n };\n }));\n }\n J(t, e) {\n N(\"SimpleDb\", \"DELETE ALL\", this.store.name);\n const n = this.options(t, e);\n n.Y = !1;\n const s = this.cursor(n);\n return this.W(s, ((t, e, n) => n.delete()));\n }\n X(t, e) {\n let n;\n e ? n = t : (n = {}, e = t);\n const s = this.cursor(n);\n return this.W(s, e);\n }\n /**\n * Iterates over a store, but waits for the given callback to complete for\n * each entry before iterating the next entry. This allows the callback to do\n * asynchronous work to determine if this iteration should continue.\n *\n * The provided callback should return `true` to continue iteration, and\n * `false` otherwise.\n */ Z(t) {\n const e = this.cursor({});\n return new Rt(((n, s) => {\n e.onerror = t => {\n const e = kt(t.target.error);\n s(e);\n }, e.onsuccess = e => {\n const s = e.target.result;\n s ? t(s.primaryKey, s.value).next((t => {\n t ? s.continue() : n();\n })) : n();\n };\n }));\n }\n W(t, e) {\n const n = [];\n return new Rt(((s, i) => {\n t.onerror = t => {\n i(t.target.error);\n }, t.onsuccess = t => {\n const i = t.target.result;\n if (!i) return void s();\n const r = new Vt(i), o = e(i.primaryKey, i.value, r);\n if (o instanceof Rt) {\n const t = o.catch((t => (r.done(), Rt.reject(t))));\n n.push(t);\n }\n r.isDone ? s() : null === r.K ? i.continue() : i.continue(r.K);\n };\n })).next((() => Rt.waitFor(n)));\n }\n options(t, e) {\n let n;\n return void 0 !== t && (\"string\" == typeof t ? n = t : e = t), {\n index: n,\n range: e\n };\n }\n cursor(t) {\n let e = \"next\";\n if (t.reverse && (e = \"prev\"), t.index) {\n const n = this.store.index(t.index);\n return t.Y ? n.openKeyCursor(t.range, e) : n.openCursor(t.range, e);\n }\n return this.store.openCursor(t.range, e);\n }\n}\n\n/**\n * Wraps an IDBRequest in a PersistencePromise, using the onsuccess / onerror\n * handlers to resolve / reject the PersistencePromise as appropriate.\n */ function xt(t) {\n return new Rt(((e, n) => {\n t.onsuccess = t => {\n const n = t.target.result;\n e(n);\n }, t.onerror = t => {\n const e = kt(t.target.error);\n n(e);\n };\n }));\n}\n\n// Guard so we only report the error once.\nlet Nt = !1;\n\nfunction kt(t) {\n const e = bt.S(getUA());\n if (e >= 12.2 && e < 13) {\n const e = \"An internal error was encountered in the Indexed Database server\";\n if (t.message.indexOf(e) >= 0) {\n // Wrap error in a more descriptive one.\n const t = new U(\"internal\", `IOS_INDEXEDDB_BUG1: IndexedDb has thrown '${e}'. This is likely due to an unavoidable bug in iOS. See https://stackoverflow.com/q/56496296/110915 for details and a potential workaround.`);\n return Nt || (Nt = !0, \n // Throw a global exception outside of this promise chain, for the user to\n // potentially catch.\n setTimeout((() => {\n throw t;\n }), 0)), t;\n }\n }\n return t;\n}\n\n/** This class is responsible for the scheduling of Index Backfiller. */\nclass Mt {\n constructor(t, e) {\n this.asyncQueue = t, this.tt = e, this.task = null;\n }\n start() {\n this.et(15e3);\n }\n stop() {\n this.task && (this.task.cancel(), this.task = null);\n }\n get started() {\n return null !== this.task;\n }\n et(t) {\n N(\"IndexBackiller\", `Scheduled in ${t}ms`), this.task = this.asyncQueue.enqueueAfterDelay(\"index_backfill\" /* TimerId.IndexBackfill */ , t, (async () => {\n this.task = null;\n try {\n N(\"IndexBackiller\", `Documents written: ${await this.tt.nt()}`);\n } catch (t) {\n Dt(t) ? N(\"IndexBackiller\", \"Ignoring IndexedDB error during index backfill: \", t) : await vt(t);\n }\n await this.et(6e4);\n }));\n }\n}\n\n/** Implements the steps for backfilling indexes. */ class $t {\n constructor(\n /**\n * LocalStore provides access to IndexManager and LocalDocumentView.\n * These properties will update when the user changes. Consequently,\n * making a local copy of IndexManager and LocalDocumentView will require\n * updates over time. The simpler solution is to rely on LocalStore to have\n * an up-to-date references to IndexManager and LocalDocumentStore.\n */\n t, e) {\n this.localStore = t, this.persistence = e;\n }\n async nt(t = 50) {\n return this.persistence.runTransaction(\"Backfill Indexes\", \"readwrite-primary\", (e => this.st(e, t)));\n }\n /** Writes index entries until the cap is reached. Returns the number of documents processed. */ st(t, e) {\n const n = new Set;\n let s = e, i = !0;\n return Rt.doWhile((() => !0 === i && s > 0), (() => this.localStore.indexManager.getNextCollectionGroupToUpdate(t).next((e => {\n if (null !== e && !n.has(e)) return N(\"IndexBackiller\", `Processing collection: ${e}`), \n this.it(t, e, s).next((t => {\n s -= t, n.add(e);\n }));\n i = !1;\n })))).next((() => e - s));\n }\n /**\n * Writes entries for the provided collection group. Returns the number of documents processed.\n */ it(t, e, n) {\n // Use the earliest offset of all field indexes to query the local cache.\n return this.localStore.indexManager.getMinOffsetFromCollectionGroup(t, e).next((s => this.localStore.localDocuments.getNextDocuments(t, e, s, n).next((n => {\n const i = n.changes;\n return this.localStore.indexManager.updateIndexEntries(t, i).next((() => this.rt(s, n))).next((n => (N(\"IndexBackiller\", `Updating offset: ${n}`), \n this.localStore.indexManager.updateCollectionGroup(t, e, n)))).next((() => i.size));\n }))));\n }\n /** Returns the next offset based on the provided documents. */ rt(t, e) {\n let n = t;\n return e.changes.forEach(((t, e) => {\n const s = pt(e);\n Tt(s, n) > 0 && (n = s);\n })), new It(n.readTime, n.documentKey, Math.max(e.batchId, t.largestBatchId));\n }\n}\n\n/**\n * @license\n * Copyright 2018 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * `ListenSequence` is a monotonic sequence. It is initialized with a minimum value to\n * exceed. All subsequent calls to next will return increasing values. If provided with a\n * `SequenceNumberSyncer`, it will additionally bump its next value when told of a new value, as\n * well as write out sequence numbers that it produces via `next()`.\n */ class Ot {\n constructor(t, e) {\n this.previousValue = t, e && (e.sequenceNumberHandler = t => this.ot(t), this.ut = t => e.writeSequenceNumber(t));\n }\n ot(t) {\n return this.previousValue = Math.max(t, this.previousValue), this.previousValue;\n }\n next() {\n const t = ++this.previousValue;\n return this.ut && this.ut(t), t;\n }\n}\n\nOt.ct = -1;\n\n/**\n * Returns whether a variable is either undefined or null.\n */\nfunction Ft(t) {\n return null == t;\n}\n\n/** Returns whether the value represents -0. */ function Bt(t) {\n // Detect if the value is -0.0. Based on polyfill from\n // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is\n return 0 === t && 1 / t == -1 / 0;\n}\n\n/**\n * Returns whether a value is an integer and in the safe integer range\n * @param value - The value to test for being an integer and in the safe range\n */ function Lt(t) {\n return \"number\" == typeof t && Number.isInteger(t) && !Bt(t) && t <= Number.MAX_SAFE_INTEGER && t >= Number.MIN_SAFE_INTEGER;\n}\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * Encodes a resource path into a IndexedDb-compatible string form.\n */\nfunction qt(t) {\n let e = \"\";\n for (let n = 0; n < t.length; n++) e.length > 0 && (e = Kt(e)), e = Ut(t.get(n), e);\n return Kt(e);\n}\n\n/** Encodes a single segment of a resource path into the given result */ function Ut(t, e) {\n let n = e;\n const s = t.length;\n for (let e = 0; e < s; e++) {\n const s = t.charAt(e);\n switch (s) {\n case \"\\0\":\n n += \"\u0001\u0010\";\n break;\n\n case \"\u0001\":\n n += \"\u0001\u0011\";\n break;\n\n default:\n n += s;\n }\n }\n return n;\n}\n\n/** Encodes a path separator into the given result */ function Kt(t) {\n return t + \"\u0001\u0001\";\n}\n\n/**\n * Decodes the given IndexedDb-compatible string form of a resource path into\n * a ResourcePath instance. Note that this method is not suitable for use with\n * decoding resource names from the server; those are One Platform format\n * strings.\n */ function Gt(t) {\n // Event the empty path must encode as a path of at least length 2. A path\n // with exactly 2 must be the empty path.\n const e = t.length;\n if (F(e >= 2), 2 === e) return F(\"\u0001\" === t.charAt(0) && \"\u0001\" === t.charAt(1)), ut.emptyPath();\n // Escape characters cannot exist past the second-to-last position in the\n // source value.\n const __PRIVATE_lastReasonableEscapeIndex = e - 2, n = [];\n let s = \"\";\n for (let i = 0; i < e; ) {\n // The last two characters of a valid encoded path must be a separator, so\n // there must be an end to this segment.\n const e = t.indexOf(\"\u0001\", i);\n (e < 0 || e > __PRIVATE_lastReasonableEscapeIndex) && O();\n switch (t.charAt(e + 1)) {\n case \"\u0001\":\n const r = t.substring(i, e);\n let o;\n 0 === s.length ? \n // Avoid copying for the common case of a segment that excludes \\0\n // and \\001\n o = r : (s += r, o = s, s = \"\"), n.push(o);\n break;\n\n case \"\u0010\":\n s += t.substring(i, e), s += \"\\0\";\n break;\n\n case \"\u0011\":\n // The escape character can be used in the output to encode itself.\n s += t.substring(i, e + 1);\n break;\n\n default:\n O();\n }\n i = e + 2;\n }\n return new ut(n);\n}\n\n/**\n * @license\n * Copyright 2022 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */ const Qt = [ \"userId\", \"batchId\" ];\n\n/**\n * @license\n * Copyright 2022 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * Name of the IndexedDb object store.\n *\n * Note that the name 'owner' is chosen to ensure backwards compatibility with\n * older clients that only supported single locked access to the persistence\n * layer.\n */\n/**\n * Creates a [userId, encodedPath] key for use in the DbDocumentMutations\n * index to iterate over all at document mutations for a given path or lower.\n */\nfunction jt(t, e) {\n return [ t, qt(e) ];\n}\n\n/**\n * Creates a full index key of [userId, encodedPath, batchId] for inserting\n * and deleting into the DbDocumentMutations index.\n */ function zt(t, e, n) {\n return [ t, qt(e), n ];\n}\n\n/**\n * Because we store all the useful information for this store in the key,\n * there is no useful information to store as the value. The raw (unencoded)\n * path cannot be stored because IndexedDb doesn't store prototype\n * information.\n */ const Wt = {}, Ht = [ \"prefixPath\", \"collectionGroup\", \"readTime\", \"documentId\" ], Jt = [ \"prefixPath\", \"collectionGroup\", \"documentId\" ], Yt = [ \"collectionGroup\", \"readTime\", \"prefixPath\", \"documentId\" ], Xt = [ \"canonicalId\", \"targetId\" ], Zt = [ \"targetId\", \"path\" ], te = [ \"path\", \"targetId\" ], ee = [ \"collectionId\", \"parent\" ], ne = [ \"indexId\", \"uid\" ], se = [ \"uid\", \"sequenceNumber\" ], ie = [ \"indexId\", \"uid\", \"arrayValue\", \"directionalValue\", \"orderedDocumentKey\", \"documentKey\" ], re = [ \"indexId\", \"uid\", \"orderedDocumentKey\" ], oe = [ \"userId\", \"collectionPath\", \"documentId\" ], ue = [ \"userId\", \"collectionPath\", \"largestBatchId\" ], ce = [ \"userId\", \"collectionGroup\", \"largestBatchId\" ], ae = [ ...[ ...[ ...[ ...[ \"mutationQueues\", \"mutations\", \"documentMutations\", \"remoteDocuments\", \"targets\", \"owner\", \"targetGlobal\", \"targetDocuments\" ], \"clientMetadata\" ], \"remoteDocumentGlobal\" ], \"collectionParents\" ], \"bundles\", \"namedQueries\" ], he = [ ...ae, \"documentOverlays\" ], le = [ \"mutationQueues\", \"mutations\", \"documentMutations\", \"remoteDocumentsV14\", \"targets\", \"owner\", \"targetGlobal\", \"targetDocuments\", \"clientMetadata\", \"remoteDocumentGlobal\", \"collectionParents\", \"bundles\", \"namedQueries\", \"documentOverlays\" ], fe = le, de = [ ...fe, \"indexConfiguration\", \"indexState\", \"indexEntries\" ];\n\n/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nclass we extends At {\n constructor(t, e) {\n super(), this.ht = t, this.currentSequenceNumber = e;\n }\n}\n\nfunction _e(t, e) {\n const n = L(t);\n return bt.M(n.ht, e);\n}\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */ function me(t) {\n let e = 0;\n for (const n in t) Object.prototype.hasOwnProperty.call(t, n) && e++;\n return e;\n}\n\nfunction ge(t, e) {\n for (const n in t) Object.prototype.hasOwnProperty.call(t, n) && e(n, t[n]);\n}\n\nfunction ye(t) {\n for (const e in t) if (Object.prototype.hasOwnProperty.call(t, e)) return !1;\n return !0;\n}\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n// An immutable sorted map implementation, based on a Left-leaning Red-Black\n// tree.\nclass pe {\n constructor(t, e) {\n this.comparator = t, this.root = e || Te.EMPTY;\n }\n // Returns a copy of the map, with the specified key/value added or replaced.\n insert(t, e) {\n return new pe(this.comparator, this.root.insert(t, e, this.comparator).copy(null, null, Te.BLACK, null, null));\n }\n // Returns a copy of the map, with the specified key removed.\n remove(t) {\n return new pe(this.comparator, this.root.remove(t, this.comparator).copy(null, null, Te.BLACK, null, null));\n }\n // Returns the value of the node with the given key, or null.\n get(t) {\n let e = this.root;\n for (;!e.isEmpty(); ) {\n const n = this.comparator(t, e.key);\n if (0 === n) return e.value;\n n < 0 ? e = e.left : n > 0 && (e = e.right);\n }\n return null;\n }\n // Returns the index of the element in this sorted map, or -1 if it doesn't\n // exist.\n indexOf(t) {\n // Number of nodes that were pruned when descending right\n let e = 0, n = this.root;\n for (;!n.isEmpty(); ) {\n const s = this.comparator(t, n.key);\n if (0 === s) return e + n.left.size;\n s < 0 ? n = n.left : (\n // Count all nodes left of the node plus the node itself\n e += n.left.size + 1, n = n.right);\n }\n // Node not found\n return -1;\n }\n isEmpty() {\n return this.root.isEmpty();\n }\n // Returns the total number of nodes in the map.\n get size() {\n return this.root.size;\n }\n // Returns the minimum key in the map.\n minKey() {\n return this.root.minKey();\n }\n // Returns the maximum key in the map.\n maxKey() {\n return this.root.maxKey();\n }\n // Traverses the map in key order and calls the specified action function\n // for each key/value pair. If action returns true, traversal is aborted.\n // Returns the first truthy value returned by action, or the last falsey\n // value returned by action.\n inorderTraversal(t) {\n return this.root.inorderTraversal(t);\n }\n forEach(t) {\n this.inorderTraversal(((e, n) => (t(e, n), !1)));\n }\n toString() {\n const t = [];\n return this.inorderTraversal(((e, n) => (t.push(`${e}:${n}`), !1))), `{${t.join(\", \")}}`;\n }\n // Traverses the map in reverse key order and calls the specified action\n // function for each key/value pair. If action returns true, traversal is\n // aborted.\n // Returns the first truthy value returned by action, or the last falsey\n // value returned by action.\n reverseTraversal(t) {\n return this.root.reverseTraversal(t);\n }\n // Returns an iterator over the SortedMap.\n getIterator() {\n return new Ie(this.root, null, this.comparator, !1);\n }\n getIteratorFrom(t) {\n return new Ie(this.root, t, this.comparator, !1);\n }\n getReverseIterator() {\n return new Ie(this.root, null, this.comparator, !0);\n }\n getReverseIteratorFrom(t) {\n return new Ie(this.root, t, this.comparator, !0);\n }\n}\n\n // end SortedMap\n// An iterator over an LLRBNode.\nclass Ie {\n constructor(t, e, n, s) {\n this.isReverse = s, this.nodeStack = [];\n let i = 1;\n for (;!t.isEmpty(); ) if (i = e ? n(t.key, e) : 1, \n // flip the comparison if we're going in reverse\n e && s && (i *= -1), i < 0) \n // This node is less than our start key. ignore it\n t = this.isReverse ? t.left : t.right; else {\n if (0 === i) {\n // This node is exactly equal to our start key. Push it on the stack,\n // but stop iterating;\n this.nodeStack.push(t);\n break;\n }\n // This node is greater than our start key, add it to the stack and move\n // to the next one\n this.nodeStack.push(t), t = this.isReverse ? t.right : t.left;\n }\n }\n getNext() {\n let t = this.nodeStack.pop();\n const e = {\n key: t.key,\n value: t.value\n };\n if (this.isReverse) for (t = t.left; !t.isEmpty(); ) this.nodeStack.push(t), t = t.right; else for (t = t.right; !t.isEmpty(); ) this.nodeStack.push(t), \n t = t.left;\n return e;\n }\n hasNext() {\n return this.nodeStack.length > 0;\n }\n peek() {\n if (0 === this.nodeStack.length) return null;\n const t = this.nodeStack[this.nodeStack.length - 1];\n return {\n key: t.key,\n value: t.value\n };\n }\n}\n\n // end SortedMapIterator\n// Represents a node in a Left-leaning Red-Black tree.\nclass Te {\n constructor(t, e, n, s, i) {\n this.key = t, this.value = e, this.color = null != n ? n : Te.RED, this.left = null != s ? s : Te.EMPTY, \n this.right = null != i ? i : Te.EMPTY, this.size = this.left.size + 1 + this.right.size;\n }\n // Returns a copy of the current node, optionally replacing pieces of it.\n copy(t, e, n, s, i) {\n return new Te(null != t ? t : this.key, null != e ? e : this.value, null != n ? n : this.color, null != s ? s : this.left, null != i ? i : this.right);\n }\n isEmpty() {\n return !1;\n }\n // Traverses the tree in key order and calls the specified action function\n // for each node. If action returns true, traversal is aborted.\n // Returns the first truthy value returned by action, or the last falsey\n // value returned by action.\n inorderTraversal(t) {\n return this.left.inorderTraversal(t) || t(this.key, this.value) || this.right.inorderTraversal(t);\n }\n // Traverses the tree in reverse key order and calls the specified action\n // function for each node. If action returns true, traversal is aborted.\n // Returns the first truthy value returned by action, or the last falsey\n // value returned by action.\n reverseTraversal(t) {\n return this.right.reverseTraversal(t) || t(this.key, this.value) || this.left.reverseTraversal(t);\n }\n // Returns the minimum node in the tree.\n min() {\n return this.left.isEmpty() ? this : this.left.min();\n }\n // Returns the maximum key in the tree.\n minKey() {\n return this.min().key;\n }\n // Returns the maximum key in the tree.\n maxKey() {\n return this.right.isEmpty() ? this.key : this.right.maxKey();\n }\n // Returns new tree, with the key/value added.\n insert(t, e, n) {\n let s = this;\n const i = n(t, s.key);\n return s = i < 0 ? s.copy(null, null, null, s.left.insert(t, e, n), null) : 0 === i ? s.copy(null, e, null, null, null) : s.copy(null, null, null, null, s.right.insert(t, e, n)), \n s.fixUp();\n }\n removeMin() {\n if (this.left.isEmpty()) return Te.EMPTY;\n let t = this;\n return t.left.isRed() || t.left.left.isRed() || (t = t.moveRedLeft()), t = t.copy(null, null, null, t.left.removeMin(), null), \n t.fixUp();\n }\n // Returns new tree, with the specified item removed.\n remove(t, e) {\n let n, s = this;\n if (e(t, s.key) < 0) s.left.isEmpty() || s.left.isRed() || s.left.left.isRed() || (s = s.moveRedLeft()), \n s = s.copy(null, null, null, s.left.remove(t, e), null); else {\n if (s.left.isRed() && (s = s.rotateRight()), s.right.isEmpty() || s.right.isRed() || s.right.left.isRed() || (s = s.moveRedRight()), \n 0 === e(t, s.key)) {\n if (s.right.isEmpty()) return Te.EMPTY;\n n = s.right.min(), s = s.copy(n.key, n.value, null, null, s.right.removeMin());\n }\n s = s.copy(null, null, null, null, s.right.remove(t, e));\n }\n return s.fixUp();\n }\n isRed() {\n return this.color;\n }\n // Returns new tree after performing any needed rotations.\n fixUp() {\n let t = this;\n return t.right.isRed() && !t.left.isRed() && (t = t.rotateLeft()), t.left.isRed() && t.left.left.isRed() && (t = t.rotateRight()), \n t.left.isRed() && t.right.isRed() && (t = t.colorFlip()), t;\n }\n moveRedLeft() {\n let t = this.colorFlip();\n return t.right.left.isRed() && (t = t.copy(null, null, null, null, t.right.rotateRight()), \n t = t.rotateLeft(), t = t.colorFlip()), t;\n }\n moveRedRight() {\n let t = this.colorFlip();\n return t.left.left.isRed() && (t = t.rotateRight(), t = t.colorFlip()), t;\n }\n rotateLeft() {\n const t = this.copy(null, null, Te.RED, null, this.right.left);\n return this.right.copy(null, null, this.color, t, null);\n }\n rotateRight() {\n const t = this.copy(null, null, Te.RED, this.left.right, null);\n return this.left.copy(null, null, this.color, null, t);\n }\n colorFlip() {\n const t = this.left.copy(null, null, !this.left.color, null, null), e = this.right.copy(null, null, !this.right.color, null, null);\n return this.copy(null, null, !this.color, t, e);\n }\n // For testing.\n checkMaxDepth() {\n const t = this.check();\n return Math.pow(2, t) <= this.size + 1;\n }\n // In a balanced RB tree, the black-depth (number of black nodes) from root to\n // leaves is equal on both sides. This function verifies that or asserts.\n check() {\n if (this.isRed() && this.left.isRed()) throw O();\n if (this.right.isRed()) throw O();\n const t = this.left.check();\n if (t !== this.right.check()) throw O();\n return t + (this.isRed() ? 0 : 1);\n }\n}\n\n // end LLRBNode\n// Empty node is shared between all LLRB trees.\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nTe.EMPTY = null, Te.RED = !0, Te.BLACK = !1;\n\n// end LLRBEmptyNode\nTe.EMPTY = new \n// Represents an empty node (a leaf node in the Red-Black Tree).\nclass {\n constructor() {\n this.size = 0;\n }\n get key() {\n throw O();\n }\n get value() {\n throw O();\n }\n get color() {\n throw O();\n }\n get left() {\n throw O();\n }\n get right() {\n throw O();\n }\n // Returns a copy of the current node.\n copy(t, e, n, s, i) {\n return this;\n }\n // Returns a copy of the tree, with the specified key/value added.\n insert(t, e, n) {\n return new Te(t, e);\n }\n // Returns a copy of the tree, with the specified key removed.\n remove(t, e) {\n return this;\n }\n isEmpty() {\n return !0;\n }\n inorderTraversal(t) {\n return !1;\n }\n reverseTraversal(t) {\n return !1;\n }\n minKey() {\n return null;\n }\n maxKey() {\n return null;\n }\n isRed() {\n return !1;\n }\n // For testing.\n checkMaxDepth() {\n return !0;\n }\n check() {\n return 0;\n }\n};\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * SortedSet is an immutable (copy-on-write) collection that holds elements\n * in order specified by the provided comparator.\n *\n * NOTE: if provided comparator returns 0 for two elements, we consider them to\n * be equal!\n */\nclass Ee {\n constructor(t) {\n this.comparator = t, this.data = new pe(this.comparator);\n }\n has(t) {\n return null !== this.data.get(t);\n }\n first() {\n return this.data.minKey();\n }\n last() {\n return this.data.maxKey();\n }\n get size() {\n return this.data.size;\n }\n indexOf(t) {\n return this.data.indexOf(t);\n }\n /** Iterates elements in order defined by \"comparator\" */ forEach(t) {\n this.data.inorderTraversal(((e, n) => (t(e), !1)));\n }\n /** Iterates over `elem`s such that: range[0] <= elem < range[1]. */ forEachInRange(t, e) {\n const n = this.data.getIteratorFrom(t[0]);\n for (;n.hasNext(); ) {\n const s = n.getNext();\n if (this.comparator(s.key, t[1]) >= 0) return;\n e(s.key);\n }\n }\n /**\n * Iterates over `elem`s such that: start <= elem until false is returned.\n */ forEachWhile(t, e) {\n let n;\n for (n = void 0 !== e ? this.data.getIteratorFrom(e) : this.data.getIterator(); n.hasNext(); ) {\n if (!t(n.getNext().key)) return;\n }\n }\n /** Finds the least element greater than or equal to `elem`. */ firstAfterOrEqual(t) {\n const e = this.data.getIteratorFrom(t);\n return e.hasNext() ? e.getNext().key : null;\n }\n getIterator() {\n return new Ae(this.data.getIterator());\n }\n getIteratorFrom(t) {\n return new Ae(this.data.getIteratorFrom(t));\n }\n /** Inserts or updates an element */ add(t) {\n return this.copy(this.data.remove(t).insert(t, !0));\n }\n /** Deletes an element */ delete(t) {\n return this.has(t) ? this.copy(this.data.remove(t)) : this;\n }\n isEmpty() {\n return this.data.isEmpty();\n }\n unionWith(t) {\n let e = this;\n // Make sure `result` always refers to the larger one of the two sets.\n return e.size < t.size && (e = t, t = this), t.forEach((t => {\n e = e.add(t);\n })), e;\n }\n isEqual(t) {\n if (!(t instanceof Ee)) return !1;\n if (this.size !== t.size) return !1;\n const e = this.data.getIterator(), n = t.data.getIterator();\n for (;e.hasNext(); ) {\n const t = e.getNext().key, s = n.getNext().key;\n if (0 !== this.comparator(t, s)) return !1;\n }\n return !0;\n }\n toArray() {\n const t = [];\n return this.forEach((e => {\n t.push(e);\n })), t;\n }\n toString() {\n const t = [];\n return this.forEach((e => t.push(e))), \"SortedSet(\" + t.toString() + \")\";\n }\n copy(t) {\n const e = new Ee(this.comparator);\n return e.data = t, e;\n }\n}\n\nclass Ae {\n constructor(t) {\n this.iter = t;\n }\n getNext() {\n return this.iter.getNext().key;\n }\n hasNext() {\n return this.iter.hasNext();\n }\n}\n\n/**\n * Compares two sorted sets for equality using their natural ordering. The\n * method computes the intersection and invokes `onAdd` for every element that\n * is in `after` but not `before`. `onRemove` is invoked for every element in\n * `before` but missing from `after`.\n *\n * The method creates a copy of both `before` and `after` and runs in O(n log\n * n), where n is the size of the two lists.\n *\n * @param before - The elements that exist in the original set.\n * @param after - The elements to diff against the original set.\n * @param comparator - The comparator for the elements in before and after.\n * @param onAdd - A function to invoke for every element that is part of `\n * after` but not `before`.\n * @param onRemove - A function to invoke for every element that is part of\n * `before` but not `after`.\n */\n/**\n * Returns the next element from the iterator or `undefined` if none available.\n */\nfunction ve(t) {\n return t.hasNext() ? t.getNext() : void 0;\n}\n\n/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * Provides a set of fields that can be used to partially patch a document.\n * FieldMask is used in conjunction with ObjectValue.\n * Examples:\n * foo - Overwrites foo entirely with the provided value. If foo is not\n * present in the companion ObjectValue, the field is deleted.\n * foo.bar - Overwrites only the field bar of the object foo.\n * If foo is not an object, foo is replaced with an object\n * containing foo\n */ class Re {\n constructor(t) {\n this.fields = t, \n // TODO(dimond): validation of FieldMask\n // Sort the field mask to support `FieldMask.isEqual()` and assert below.\n t.sort(at.comparator);\n }\n static empty() {\n return new Re([]);\n }\n /**\n * Returns a new FieldMask object that is the result of adding all the given\n * fields paths to this field mask.\n */ unionWith(t) {\n let e = new Ee(at.comparator);\n for (const t of this.fields) e = e.add(t);\n for (const n of t) e = e.add(n);\n return new Re(e.toArray());\n }\n /**\n * Verifies that `fieldPath` is included by at least one field in this field\n * mask.\n *\n * This is an O(n) operation, where `n` is the size of the field mask.\n */ covers(t) {\n for (const e of this.fields) if (e.isPrefixOf(t)) return !0;\n return !1;\n }\n isEqual(t) {\n return nt(this.fields, t.fields, ((t, e) => t.isEqual(e)));\n }\n}\n\n/**\n * @license\n * Copyright 2023 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * An error encountered while decoding base64 string.\n */ class Pe extends Error {\n constructor() {\n super(...arguments), this.name = \"Base64DecodeError\";\n }\n}\n\n/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/** Converts a Base64 encoded string to a binary string. */\n/** True if and only if the Base64 conversion functions are available. */\nfunction be() {\n return \"undefined\" != typeof atob;\n}\n\n/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * Immutable class that represents a \"proto\" byte string.\n *\n * Proto byte strings can either be Base64-encoded strings or Uint8Arrays when\n * sent on the wire. This class abstracts away this differentiation by holding\n * the proto byte string in a common class that must be converted into a string\n * before being sent as a proto.\n * @internal\n */ class Ve {\n constructor(t) {\n this.binaryString = t;\n }\n static fromBase64String(t) {\n const e = function(t) {\n try {\n return atob(t);\n } catch (t) {\n // Check that `DOMException` is defined before using it to avoid\n // \"ReferenceError: Property 'DOMException' doesn't exist\" in react-native.\n // (https://github.com/firebase/firebase-js-sdk/issues/7115)\n throw \"undefined\" != typeof DOMException && t instanceof DOMException ? new Pe(\"Invalid base64 string: \" + t) : t;\n }\n }\n /** Converts a binary string to a Base64 encoded string. */ (t);\n return new Ve(e);\n }\n static fromUint8Array(t) {\n // TODO(indexing); Remove the copy of the byte string here as this method\n // is frequently called during indexing.\n const e = \n /**\n * Helper function to convert an Uint8array to a binary string.\n */\n function(t) {\n let e = \"\";\n for (let n = 0; n < t.length; ++n) e += String.fromCharCode(t[n]);\n return e;\n }\n /**\n * Helper function to convert a binary string to an Uint8Array.\n */ (t);\n return new Ve(e);\n }\n [Symbol.iterator]() {\n let t = 0;\n return {\n next: () => t < this.binaryString.length ? {\n value: this.binaryString.charCodeAt(t++),\n done: !1\n } : {\n value: void 0,\n done: !0\n }\n };\n }\n toBase64() {\n return t = this.binaryString, btoa(t);\n var t;\n }\n toUint8Array() {\n return function(t) {\n const e = new Uint8Array(t.length);\n for (let n = 0; n < t.length; n++) e[n] = t.charCodeAt(n);\n return e;\n }\n /**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n // A RegExp matching ISO 8601 UTC timestamps with optional fraction.\n (this.binaryString);\n }\n approximateByteSize() {\n return 2 * this.binaryString.length;\n }\n compareTo(t) {\n return et(this.binaryString, t.binaryString);\n }\n isEqual(t) {\n return this.binaryString === t.binaryString;\n }\n}\n\nVe.EMPTY_BYTE_STRING = new Ve(\"\");\n\nconst Se = new RegExp(/^\\d{4}-\\d\\d-\\d\\dT\\d\\d:\\d\\d:\\d\\d(?:\\.(\\d+))?Z$/);\n\n/**\n * Converts the possible Proto values for a timestamp value into a \"seconds and\n * nanos\" representation.\n */ function De(t) {\n // The json interface (for the browser) will return an iso timestamp string,\n // while the proto js library (for node) will return a\n // google.protobuf.Timestamp instance.\n if (F(!!t), \"string\" == typeof t) {\n // The date string can have higher precision (nanos) than the Date class\n // (millis), so we do some custom parsing here.\n // Parse the nanos right out of the string.\n let e = 0;\n const n = Se.exec(t);\n if (F(!!n), n[1]) {\n // Pad the fraction out to 9 digits (nanos).\n let t = n[1];\n t = (t + \"000000000\").substr(0, 9), e = Number(t);\n }\n // Parse the date to get the seconds.\n const s = new Date(t);\n return {\n seconds: Math.floor(s.getTime() / 1e3),\n nanos: e\n };\n }\n return {\n seconds: Ce(t.seconds),\n nanos: Ce(t.nanos)\n };\n}\n\n/**\n * Converts the possible Proto types for numbers into a JavaScript number.\n * Returns 0 if the value is not numeric.\n */ function Ce(t) {\n // TODO(bjornick): Handle int64 greater than 53 bits.\n return \"number\" == typeof t ? t : \"string\" == typeof t ? Number(t) : 0;\n}\n\n/** Converts the possible Proto types for Blobs into a ByteString. */ function xe(t) {\n return \"string\" == typeof t ? Ve.fromBase64String(t) : Ve.fromUint8Array(t);\n}\n\n/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * Represents a locally-applied ServerTimestamp.\n *\n * Server Timestamps are backed by MapValues that contain an internal field\n * `__type__` with a value of `server_timestamp`. The previous value and local\n * write time are stored in its `__previous_value__` and `__local_write_time__`\n * fields respectively.\n *\n * Notes:\n * - ServerTimestampValue instances are created as the result of applying a\n * transform. They can only exist in the local view of a document. Therefore\n * they do not need to be parsed or serialized.\n * - When evaluated locally (e.g. for snapshot.data()), they by default\n * evaluate to `null`. This behavior can be configured by passing custom\n * FieldValueOptions to value().\n * - With respect to other ServerTimestampValues, they sort by their\n * localWriteTime.\n */ function Ne(t) {\n var e, n;\n return \"server_timestamp\" === (null === (n = ((null === (e = null == t ? void 0 : t.mapValue) || void 0 === e ? void 0 : e.fields) || {}).__type__) || void 0 === n ? void 0 : n.stringValue);\n}\n\n/**\n * Creates a new ServerTimestamp proto value (using the internal format).\n */\n/**\n * Returns the value of the field before this ServerTimestamp was set.\n *\n * Preserving the previous values allows the user to display the last resoled\n * value until the backend responds with the timestamp.\n */\nfunction ke(t) {\n const e = t.mapValue.fields.__previous_value__;\n return Ne(e) ? ke(e) : e;\n}\n\n/**\n * Returns the local time at which this timestamp was first set.\n */ function Me(t) {\n const e = De(t.mapValue.fields.__local_write_time__.timestampValue);\n return new it(e.seconds, e.nanos);\n}\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */ class $e {\n /**\n * Constructs a DatabaseInfo using the provided host, databaseId and\n * persistenceKey.\n *\n * @param databaseId - The database to use.\n * @param appId - The Firebase App Id.\n * @param persistenceKey - A unique identifier for this Firestore's local\n * storage (used in conjunction with the databaseId).\n * @param host - The Firestore backend host to connect to.\n * @param ssl - Whether to use SSL when connecting.\n * @param forceLongPolling - Whether to use the forceLongPolling option\n * when using WebChannel as the network transport.\n * @param autoDetectLongPolling - Whether to use the detectBufferingProxy\n * option when using WebChannel as the network transport.\n * @param longPollingOptions Options that configure long-polling.\n * @param useFetchStreams Whether to use the Fetch API instead of\n * XMLHTTPRequest\n */\n constructor(t, e, n, s, i, r, o, u, c) {\n this.databaseId = t, this.appId = e, this.persistenceKey = n, this.host = s, this.ssl = i, \n this.forceLongPolling = r, this.autoDetectLongPolling = o, this.longPollingOptions = u, \n this.useFetchStreams = c;\n }\n}\n\n/** The default database name for a project. */\n/**\n * Represents the database ID a Firestore client is associated with.\n * @internal\n */\nclass Oe {\n constructor(t, e) {\n this.projectId = t, this.database = e || \"(default)\";\n }\n static empty() {\n return new Oe(\"\", \"\");\n }\n get isDefaultDatabase() {\n return \"(default)\" === this.database;\n }\n isEqual(t) {\n return t instanceof Oe && t.projectId === this.projectId && t.database === this.database;\n }\n}\n\n/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nconst Fe = {\n mapValue: {\n fields: {\n __type__: {\n stringValue: \"__max__\"\n }\n }\n }\n}, Be = {\n nullValue: \"NULL_VALUE\"\n};\n\n/** Extracts the backend's type order for the provided value. */\nfunction Le(t) {\n return \"nullValue\" in t ? 0 /* TypeOrder.NullValue */ : \"booleanValue\" in t ? 1 /* TypeOrder.BooleanValue */ : \"integerValue\" in t || \"doubleValue\" in t ? 2 /* TypeOrder.NumberValue */ : \"timestampValue\" in t ? 3 /* TypeOrder.TimestampValue */ : \"stringValue\" in t ? 5 /* TypeOrder.StringValue */ : \"bytesValue\" in t ? 6 /* TypeOrder.BlobValue */ : \"referenceValue\" in t ? 7 /* TypeOrder.RefValue */ : \"geoPointValue\" in t ? 8 /* TypeOrder.GeoPointValue */ : \"arrayValue\" in t ? 9 /* TypeOrder.ArrayValue */ : \"mapValue\" in t ? Ne(t) ? 4 /* TypeOrder.ServerTimestampValue */ : en(t) ? 9007199254740991 /* TypeOrder.MaxValue */ : 10 /* TypeOrder.ObjectValue */ : O();\n}\n\n/** Tests `left` and `right` for equality based on the backend semantics. */ function qe(t, e) {\n if (t === e) return !0;\n const n = Le(t);\n if (n !== Le(e)) return !1;\n switch (n) {\n case 0 /* TypeOrder.NullValue */ :\n case 9007199254740991 /* TypeOrder.MaxValue */ :\n return !0;\n\n case 1 /* TypeOrder.BooleanValue */ :\n return t.booleanValue === e.booleanValue;\n\n case 4 /* TypeOrder.ServerTimestampValue */ :\n return Me(t).isEqual(Me(e));\n\n case 3 /* TypeOrder.TimestampValue */ :\n return function(t, e) {\n if (\"string\" == typeof t.timestampValue && \"string\" == typeof e.timestampValue && t.timestampValue.length === e.timestampValue.length) \n // Use string equality for ISO 8601 timestamps\n return t.timestampValue === e.timestampValue;\n const n = De(t.timestampValue), s = De(e.timestampValue);\n return n.seconds === s.seconds && n.nanos === s.nanos;\n }(t, e);\n\n case 5 /* TypeOrder.StringValue */ :\n return t.stringValue === e.stringValue;\n\n case 6 /* TypeOrder.BlobValue */ :\n return function(t, e) {\n return xe(t.bytesValue).isEqual(xe(e.bytesValue));\n }(t, e);\n\n case 7 /* TypeOrder.RefValue */ :\n return t.referenceValue === e.referenceValue;\n\n case 8 /* TypeOrder.GeoPointValue */ :\n return function(t, e) {\n return Ce(t.geoPointValue.latitude) === Ce(e.geoPointValue.latitude) && Ce(t.geoPointValue.longitude) === Ce(e.geoPointValue.longitude);\n }(t, e);\n\n case 2 /* TypeOrder.NumberValue */ :\n return function(t, e) {\n if (\"integerValue\" in t && \"integerValue\" in e) return Ce(t.integerValue) === Ce(e.integerValue);\n if (\"doubleValue\" in t && \"doubleValue\" in e) {\n const n = Ce(t.doubleValue), s = Ce(e.doubleValue);\n return n === s ? Bt(n) === Bt(s) : isNaN(n) && isNaN(s);\n }\n return !1;\n }(t, e);\n\n case 9 /* TypeOrder.ArrayValue */ :\n return nt(t.arrayValue.values || [], e.arrayValue.values || [], qe);\n\n case 10 /* TypeOrder.ObjectValue */ :\n return function(t, e) {\n const n = t.mapValue.fields || {}, s = e.mapValue.fields || {};\n if (me(n) !== me(s)) return !1;\n for (const t in n) if (n.hasOwnProperty(t) && (void 0 === s[t] || !qe(n[t], s[t]))) return !1;\n return !0;\n }\n /** Returns true if the ArrayValue contains the specified element. */ (t, e);\n\n default:\n return O();\n }\n}\n\nfunction Ue(t, e) {\n return void 0 !== (t.values || []).find((t => qe(t, e)));\n}\n\nfunction Ke(t, e) {\n if (t === e) return 0;\n const n = Le(t), s = Le(e);\n if (n !== s) return et(n, s);\n switch (n) {\n case 0 /* TypeOrder.NullValue */ :\n case 9007199254740991 /* TypeOrder.MaxValue */ :\n return 0;\n\n case 1 /* TypeOrder.BooleanValue */ :\n return et(t.booleanValue, e.booleanValue);\n\n case 2 /* TypeOrder.NumberValue */ :\n return function(t, e) {\n const n = Ce(t.integerValue || t.doubleValue), s = Ce(e.integerValue || e.doubleValue);\n return n < s ? -1 : n > s ? 1 : n === s ? 0 : \n // one or both are NaN.\n isNaN(n) ? isNaN(s) ? 0 : -1 : 1;\n }(t, e);\n\n case 3 /* TypeOrder.TimestampValue */ :\n return Ge(t.timestampValue, e.timestampValue);\n\n case 4 /* TypeOrder.ServerTimestampValue */ :\n return Ge(Me(t), Me(e));\n\n case 5 /* TypeOrder.StringValue */ :\n return et(t.stringValue, e.stringValue);\n\n case 6 /* TypeOrder.BlobValue */ :\n return function(t, e) {\n const n = xe(t), s = xe(e);\n return n.compareTo(s);\n }(t.bytesValue, e.bytesValue);\n\n case 7 /* TypeOrder.RefValue */ :\n return function(t, e) {\n const n = t.split(\"/\"), s = e.split(\"/\");\n for (let t = 0; t < n.length && t < s.length; t++) {\n const e = et(n[t], s[t]);\n if (0 !== e) return e;\n }\n return et(n.length, s.length);\n }(t.referenceValue, e.referenceValue);\n\n case 8 /* TypeOrder.GeoPointValue */ :\n return function(t, e) {\n const n = et(Ce(t.latitude), Ce(e.latitude));\n if (0 !== n) return n;\n return et(Ce(t.longitude), Ce(e.longitude));\n }(t.geoPointValue, e.geoPointValue);\n\n case 9 /* TypeOrder.ArrayValue */ :\n return function(t, e) {\n const n = t.values || [], s = e.values || [];\n for (let t = 0; t < n.length && t < s.length; ++t) {\n const e = Ke(n[t], s[t]);\n if (e) return e;\n }\n return et(n.length, s.length);\n }(t.arrayValue, e.arrayValue);\n\n case 10 /* TypeOrder.ObjectValue */ :\n return function(t, e) {\n if (t === Fe.mapValue && e === Fe.mapValue) return 0;\n if (t === Fe.mapValue) return 1;\n if (e === Fe.mapValue) return -1;\n const n = t.fields || {}, s = Object.keys(n), i = e.fields || {}, r = Object.keys(i);\n // Even though MapValues are likely sorted correctly based on their insertion\n // order (e.g. when received from the backend), local modifications can bring\n // elements out of order. We need to re-sort the elements to ensure that\n // canonical IDs are independent of insertion order.\n s.sort(), r.sort();\n for (let t = 0; t < s.length && t < r.length; ++t) {\n const e = et(s[t], r[t]);\n if (0 !== e) return e;\n const o = Ke(n[s[t]], i[r[t]]);\n if (0 !== o) return o;\n }\n return et(s.length, r.length);\n }\n /**\n * Generates the canonical ID for the provided field value (as used in Target\n * serialization).\n */ (t.mapValue, e.mapValue);\n\n default:\n throw O();\n }\n}\n\nfunction Ge(t, e) {\n if (\"string\" == typeof t && \"string\" == typeof e && t.length === e.length) return et(t, e);\n const n = De(t), s = De(e), i = et(n.seconds, s.seconds);\n return 0 !== i ? i : et(n.nanos, s.nanos);\n}\n\nfunction Qe(t) {\n return je(t);\n}\n\nfunction je(t) {\n return \"nullValue\" in t ? \"null\" : \"booleanValue\" in t ? \"\" + t.booleanValue : \"integerValue\" in t ? \"\" + t.integerValue : \"doubleValue\" in t ? \"\" + t.doubleValue : \"timestampValue\" in t ? function(t) {\n const e = De(t);\n return `time(${e.seconds},${e.nanos})`;\n }(t.timestampValue) : \"stringValue\" in t ? t.stringValue : \"bytesValue\" in t ? xe(t.bytesValue).toBase64() : \"referenceValue\" in t ? (n = t.referenceValue, \n ht.fromName(n).toString()) : \"geoPointValue\" in t ? `geo(${(e = t.geoPointValue).latitude},${e.longitude})` : \"arrayValue\" in t ? function(t) {\n let e = \"[\", n = !0;\n for (const s of t.values || []) n ? n = !1 : e += \",\", e += je(s);\n return e + \"]\";\n }\n /**\n * Returns an approximate (and wildly inaccurate) in-memory size for the field\n * value.\n *\n * The memory size takes into account only the actual user data as it resides\n * in memory and ignores object overhead.\n */ (t.arrayValue) : \"mapValue\" in t ? function(t) {\n // Iteration order in JavaScript is not guaranteed. To ensure that we generate\n // matching canonical IDs for identical maps, we need to sort the keys.\n const e = Object.keys(t.fields || {}).sort();\n let n = \"{\", s = !0;\n for (const i of e) s ? s = !1 : n += \",\", n += `${i}:${je(t.fields[i])}`;\n return n + \"}\";\n }(t.mapValue) : O();\n var e, n;\n}\n\nfunction ze(t) {\n switch (Le(t)) {\n case 0 /* TypeOrder.NullValue */ :\n case 1 /* TypeOrder.BooleanValue */ :\n return 4;\n\n case 2 /* TypeOrder.NumberValue */ :\n return 8;\n\n case 3 /* TypeOrder.TimestampValue */ :\n case 8 /* TypeOrder.GeoPointValue */ :\n // GeoPoints are made up of two distinct numbers (latitude + longitude)\n return 16;\n\n case 4 /* TypeOrder.ServerTimestampValue */ :\n const e = ke(t);\n return e ? 16 + ze(e) : 16;\n\n case 5 /* TypeOrder.StringValue */ :\n // See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures:\n // \"JavaScript's String type is [...] a set of elements of 16-bit unsigned\n // integer values\"\n return 2 * t.stringValue.length;\n\n case 6 /* TypeOrder.BlobValue */ :\n return xe(t.bytesValue).approximateByteSize();\n\n case 7 /* TypeOrder.RefValue */ :\n return t.referenceValue.length;\n\n case 9 /* TypeOrder.ArrayValue */ :\n return (t.arrayValue.values || []).reduce(((t, e) => t + ze(e)), 0);\n\n case 10 /* TypeOrder.ObjectValue */ :\n return function(t) {\n let e = 0;\n return ge(t.fields, ((t, n) => {\n e += t.length + ze(n);\n })), e;\n }(t.mapValue);\n\n default:\n throw O();\n }\n}\n\n/** Returns a reference value for the provided database and key. */\nfunction We(t, e) {\n return {\n referenceValue: `projects/${t.projectId}/databases/${t.database}/documents/${e.path.canonicalString()}`\n };\n}\n\n/** Returns true if `value` is an IntegerValue . */ function He(t) {\n return !!t && \"integerValue\" in t;\n}\n\n/** Returns true if `value` is a DoubleValue. */\n/** Returns true if `value` is an ArrayValue. */\nfunction Je(t) {\n return !!t && \"arrayValue\" in t;\n}\n\n/** Returns true if `value` is a NullValue. */ function Ye(t) {\n return !!t && \"nullValue\" in t;\n}\n\n/** Returns true if `value` is NaN. */ function Xe(t) {\n return !!t && \"doubleValue\" in t && isNaN(Number(t.doubleValue));\n}\n\n/** Returns true if `value` is a MapValue. */ function Ze(t) {\n return !!t && \"mapValue\" in t;\n}\n\n/** Creates a deep copy of `source`. */ function tn(t) {\n if (t.geoPointValue) return {\n geoPointValue: Object.assign({}, t.geoPointValue)\n };\n if (t.timestampValue && \"object\" == typeof t.timestampValue) return {\n timestampValue: Object.assign({}, t.timestampValue)\n };\n if (t.mapValue) {\n const e = {\n mapValue: {\n fields: {}\n }\n };\n return ge(t.mapValue.fields, ((t, n) => e.mapValue.fields[t] = tn(n))), e;\n }\n if (t.arrayValue) {\n const e = {\n arrayValue: {\n values: []\n }\n };\n for (let n = 0; n < (t.arrayValue.values || []).length; ++n) e.arrayValue.values[n] = tn(t.arrayValue.values[n]);\n return e;\n }\n return Object.assign({}, t);\n}\n\n/** Returns true if the Value represents the canonical {@link #MAX_VALUE} . */ function en(t) {\n return \"__max__\" === (((t.mapValue || {}).fields || {}).__type__ || {}).stringValue;\n}\n\n/** Returns the lowest value for the given value type (inclusive). */ function nn(t) {\n return \"nullValue\" in t ? Be : \"booleanValue\" in t ? {\n booleanValue: !1\n } : \"integerValue\" in t || \"doubleValue\" in t ? {\n doubleValue: NaN\n } : \"timestampValue\" in t ? {\n timestampValue: {\n seconds: Number.MIN_SAFE_INTEGER\n }\n } : \"stringValue\" in t ? {\n stringValue: \"\"\n } : \"bytesValue\" in t ? {\n bytesValue: \"\"\n } : \"referenceValue\" in t ? We(Oe.empty(), ht.empty()) : \"geoPointValue\" in t ? {\n geoPointValue: {\n latitude: -90,\n longitude: -180\n }\n } : \"arrayValue\" in t ? {\n arrayValue: {}\n } : \"mapValue\" in t ? {\n mapValue: {}\n } : O();\n}\n\n/** Returns the largest value for the given value type (exclusive). */ function sn(t) {\n return \"nullValue\" in t ? {\n booleanValue: !1\n } : \"booleanValue\" in t ? {\n doubleValue: NaN\n } : \"integerValue\" in t || \"doubleValue\" in t ? {\n timestampValue: {\n seconds: Number.MIN_SAFE_INTEGER\n }\n } : \"timestampValue\" in t ? {\n stringValue: \"\"\n } : \"stringValue\" in t ? {\n bytesValue: \"\"\n } : \"bytesValue\" in t ? We(Oe.empty(), ht.empty()) : \"referenceValue\" in t ? {\n geoPointValue: {\n latitude: -90,\n longitude: -180\n }\n } : \"geoPointValue\" in t ? {\n arrayValue: {}\n } : \"arrayValue\" in t ? {\n mapValue: {}\n } : \"mapValue\" in t ? Fe : O();\n}\n\nfunction rn(t, e) {\n const n = Ke(t.value, e.value);\n return 0 !== n ? n : t.inclusive && !e.inclusive ? -1 : !t.inclusive && e.inclusive ? 1 : 0;\n}\n\nfunction on(t, e) {\n const n = Ke(t.value, e.value);\n return 0 !== n ? n : t.inclusive && !e.inclusive ? 1 : !t.inclusive && e.inclusive ? -1 : 0;\n}\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * An ObjectValue represents a MapValue in the Firestore Proto and offers the\n * ability to add and remove fields (via the ObjectValueBuilder).\n */ class un {\n constructor(t) {\n this.value = t;\n }\n static empty() {\n return new un({\n mapValue: {}\n });\n }\n /**\n * Returns the value at the given path or null.\n *\n * @param path - the path to search\n * @returns The value at the path or null if the path is not set.\n */ field(t) {\n if (t.isEmpty()) return this.value;\n {\n let e = this.value;\n for (let n = 0; n < t.length - 1; ++n) if (e = (e.mapValue.fields || {})[t.get(n)], \n !Ze(e)) return null;\n return e = (e.mapValue.fields || {})[t.lastSegment()], e || null;\n }\n }\n /**\n * Sets the field to the provided value.\n *\n * @param path - The field path to set.\n * @param value - The value to set.\n */ set(t, e) {\n this.getFieldsMap(t.popLast())[t.lastSegment()] = tn(e);\n }\n /**\n * Sets the provided fields to the provided values.\n *\n * @param data - A map of fields to values (or null for deletes).\n */ setAll(t) {\n let e = at.emptyPath(), n = {}, s = [];\n t.forEach(((t, i) => {\n if (!e.isImmediateParentOf(i)) {\n // Insert the accumulated changes at this parent location\n const t = this.getFieldsMap(e);\n this.applyChanges(t, n, s), n = {}, s = [], e = i.popLast();\n }\n t ? n[i.lastSegment()] = tn(t) : s.push(i.lastSegment());\n }));\n const i = this.getFieldsMap(e);\n this.applyChanges(i, n, s);\n }\n /**\n * Removes the field at the specified path. If there is no field at the\n * specified path, nothing is changed.\n *\n * @param path - The field path to remove.\n */ delete(t) {\n const e = this.field(t.popLast());\n Ze(e) && e.mapValue.fields && delete e.mapValue.fields[t.lastSegment()];\n }\n isEqual(t) {\n return qe(this.value, t.value);\n }\n /**\n * Returns the map that contains the leaf element of `path`. If the parent\n * entry does not yet exist, or if it is not a map, a new map will be created.\n */ getFieldsMap(t) {\n let e = this.value;\n e.mapValue.fields || (e.mapValue = {\n fields: {}\n });\n for (let n = 0; n < t.length; ++n) {\n let s = e.mapValue.fields[t.get(n)];\n Ze(s) && s.mapValue.fields || (s = {\n mapValue: {\n fields: {}\n }\n }, e.mapValue.fields[t.get(n)] = s), e = s;\n }\n return e.mapValue.fields;\n }\n /**\n * Modifies `fieldsMap` by adding, replacing or deleting the specified\n * entries.\n */ applyChanges(t, e, n) {\n ge(e, ((e, n) => t[e] = n));\n for (const e of n) delete t[e];\n }\n clone() {\n return new un(tn(this.value));\n }\n}\n\n/**\n * Returns a FieldMask built from all fields in a MapValue.\n */ function cn(t) {\n const e = [];\n return ge(t.fields, ((t, n) => {\n const s = new at([ t ]);\n if (Ze(n)) {\n const t = cn(n.mapValue).fields;\n if (0 === t.length) \n // Preserve the empty map by adding it to the FieldMask.\n e.push(s); else \n // For nested and non-empty ObjectValues, add the FieldPath of the\n // leaf nodes.\n for (const n of t) e.push(s.child(n));\n } else \n // For nested and non-empty ObjectValues, add the FieldPath of the leaf\n // nodes.\n e.push(s);\n })), new Re(e);\n}\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * Represents a document in Firestore with a key, version, data and whether it\n * has local mutations applied to it.\n *\n * Documents can transition between states via `convertToFoundDocument()`,\n * `convertToNoDocument()` and `convertToUnknownDocument()`. If a document does\n * not transition to one of these states even after all mutations have been\n * applied, `isValidDocument()` returns false and the document should be removed\n * from all views.\n */ class an {\n constructor(t, e, n, s, i, r, o) {\n this.key = t, this.documentType = e, this.version = n, this.readTime = s, this.createTime = i, \n this.data = r, this.documentState = o;\n }\n /**\n * Creates a document with no known version or data, but which can serve as\n * base document for mutations.\n */ static newInvalidDocument(t) {\n return new an(t, 0 /* DocumentType.INVALID */ , \n /* version */ rt.min(), \n /* readTime */ rt.min(), \n /* createTime */ rt.min(), un.empty(), 0 /* DocumentState.SYNCED */);\n }\n /**\n * Creates a new document that is known to exist with the given data at the\n * given version.\n */ static newFoundDocument(t, e, n, s) {\n return new an(t, 1 /* DocumentType.FOUND_DOCUMENT */ , \n /* version */ e, \n /* readTime */ rt.min(), \n /* createTime */ n, s, 0 /* DocumentState.SYNCED */);\n }\n /** Creates a new document that is known to not exist at the given version. */ static newNoDocument(t, e) {\n return new an(t, 2 /* DocumentType.NO_DOCUMENT */ , \n /* version */ e, \n /* readTime */ rt.min(), \n /* createTime */ rt.min(), un.empty(), 0 /* DocumentState.SYNCED */);\n }\n /**\n * Creates a new document that is known to exist at the given version but\n * whose data is not known (e.g. a document that was updated without a known\n * base document).\n */ static newUnknownDocument(t, e) {\n return new an(t, 3 /* DocumentType.UNKNOWN_DOCUMENT */ , \n /* version */ e, \n /* readTime */ rt.min(), \n /* createTime */ rt.min(), un.empty(), 2 /* DocumentState.HAS_COMMITTED_MUTATIONS */);\n }\n /**\n * Changes the document type to indicate that it exists and that its version\n * and data are known.\n */ convertToFoundDocument(t, e) {\n // If a document is switching state from being an invalid or deleted\n // document to a valid (FOUND_DOCUMENT) document, either due to receiving an\n // update from Watch or due to applying a local set mutation on top\n // of a deleted document, our best guess about its createTime would be the\n // version at which the document transitioned to a FOUND_DOCUMENT.\n return !this.createTime.isEqual(rt.min()) || 2 /* DocumentType.NO_DOCUMENT */ !== this.documentType && 0 /* DocumentType.INVALID */ !== this.documentType || (this.createTime = t), \n this.version = t, this.documentType = 1 /* DocumentType.FOUND_DOCUMENT */ , this.data = e, \n this.documentState = 0 /* DocumentState.SYNCED */ , this;\n }\n /**\n * Changes the document type to indicate that it doesn't exist at the given\n * version.\n */ convertToNoDocument(t) {\n return this.version = t, this.documentType = 2 /* DocumentType.NO_DOCUMENT */ , \n this.data = un.empty(), this.documentState = 0 /* DocumentState.SYNCED */ , this;\n }\n /**\n * Changes the document type to indicate that it exists at a given version but\n * that its data is not known (e.g. a document that was updated without a known\n * base document).\n */ convertToUnknownDocument(t) {\n return this.version = t, this.documentType = 3 /* DocumentType.UNKNOWN_DOCUMENT */ , \n this.data = un.empty(), this.documentState = 2 /* DocumentState.HAS_COMMITTED_MUTATIONS */ , \n this;\n }\n setHasCommittedMutations() {\n return this.documentState = 2 /* DocumentState.HAS_COMMITTED_MUTATIONS */ , this;\n }\n setHasLocalMutations() {\n return this.documentState = 1 /* DocumentState.HAS_LOCAL_MUTATIONS */ , this.version = rt.min(), \n this;\n }\n setReadTime(t) {\n return this.readTime = t, this;\n }\n get hasLocalMutations() {\n return 1 /* DocumentState.HAS_LOCAL_MUTATIONS */ === this.documentState;\n }\n get hasCommittedMutations() {\n return 2 /* DocumentState.HAS_COMMITTED_MUTATIONS */ === this.documentState;\n }\n get hasPendingWrites() {\n return this.hasLocalMutations || this.hasCommittedMutations;\n }\n isValidDocument() {\n return 0 /* DocumentType.INVALID */ !== this.documentType;\n }\n isFoundDocument() {\n return 1 /* DocumentType.FOUND_DOCUMENT */ === this.documentType;\n }\n isNoDocument() {\n return 2 /* DocumentType.NO_DOCUMENT */ === this.documentType;\n }\n isUnknownDocument() {\n return 3 /* DocumentType.UNKNOWN_DOCUMENT */ === this.documentType;\n }\n isEqual(t) {\n return t instanceof an && this.key.isEqual(t.key) && this.version.isEqual(t.version) && this.documentType === t.documentType && this.documentState === t.documentState && this.data.isEqual(t.data);\n }\n mutableCopy() {\n return new an(this.key, this.documentType, this.version, this.readTime, this.createTime, this.data.clone(), this.documentState);\n }\n toString() {\n return `Document(${this.key}, ${this.version}, ${JSON.stringify(this.data.value)}, {createTime: ${this.createTime}}), {documentType: ${this.documentType}}), {documentState: ${this.documentState}})`;\n }\n}\n\n/**\n * Compares the value for field `field` in the provided documents. Throws if\n * the field does not exist in both documents.\n */\n/**\n * @license\n * Copyright 2022 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * Represents a bound of a query.\n *\n * The bound is specified with the given components representing a position and\n * whether it's just before or just after the position (relative to whatever the\n * query order is).\n *\n * The position represents a logical index position for a query. It's a prefix\n * of values for the (potentially implicit) order by clauses of a query.\n *\n * Bound provides a function to determine whether a document comes before or\n * after a bound. This is influenced by whether the position is just before or\n * just after the provided values.\n */\nclass hn {\n constructor(t, e) {\n this.position = t, this.inclusive = e;\n }\n}\n\nfunction ln(t, e, n) {\n let s = 0;\n for (let i = 0; i < t.position.length; i++) {\n const r = e[i], o = t.position[i];\n if (r.field.isKeyField()) s = ht.comparator(ht.fromName(o.referenceValue), n.key); else {\n s = Ke(o, n.data.field(r.field));\n }\n if (\"desc\" /* Direction.DESCENDING */ === r.dir && (s *= -1), 0 !== s) break;\n }\n return s;\n}\n\n/**\n * Returns true if a document sorts after a bound using the provided sort\n * order.\n */ function fn(t, e) {\n if (null === t) return null === e;\n if (null === e) return !1;\n if (t.inclusive !== e.inclusive || t.position.length !== e.position.length) return !1;\n for (let n = 0; n < t.position.length; n++) {\n if (!qe(t.position[n], e.position[n])) return !1;\n }\n return !0;\n}\n\n/**\n * @license\n * Copyright 2022 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * An ordering on a field, in some Direction. Direction defaults to ASCENDING.\n */ class dn {\n constructor(t, e = \"asc\" /* Direction.ASCENDING */) {\n this.field = t, this.dir = e;\n }\n}\n\nfunction wn(t, e) {\n return t.dir === e.dir && t.field.isEqual(e.field);\n}\n\n/**\n * @license\n * Copyright 2022 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */ class _n {}\n\nclass mn extends _n {\n constructor(t, e, n) {\n super(), this.field = t, this.op = e, this.value = n;\n }\n /**\n * Creates a filter based on the provided arguments.\n */ static create(t, e, n) {\n return t.isKeyField() ? \"in\" /* Operator.IN */ === e || \"not-in\" /* Operator.NOT_IN */ === e ? this.createKeyFieldInFilter(t, e, n) : new Pn(t, e, n) : \"array-contains\" /* Operator.ARRAY_CONTAINS */ === e ? new Dn(t, n) : \"in\" /* Operator.IN */ === e ? new Cn(t, n) : \"not-in\" /* Operator.NOT_IN */ === e ? new xn(t, n) : \"array-contains-any\" /* Operator.ARRAY_CONTAINS_ANY */ === e ? new Nn(t, n) : new mn(t, e, n);\n }\n static createKeyFieldInFilter(t, e, n) {\n return \"in\" /* Operator.IN */ === e ? new bn(t, n) : new Vn(t, n);\n }\n matches(t) {\n const e = t.data.field(this.field);\n // Types do not have to match in NOT_EQUAL filters.\n return \"!=\" /* Operator.NOT_EQUAL */ === this.op ? null !== e && this.matchesComparison(Ke(e, this.value)) : null !== e && Le(this.value) === Le(e) && this.matchesComparison(Ke(e, this.value));\n // Only compare types with matching backend order (such as double and int).\n }\n matchesComparison(t) {\n switch (this.op) {\n case \"<\" /* Operator.LESS_THAN */ :\n return t < 0;\n\n case \"<=\" /* Operator.LESS_THAN_OR_EQUAL */ :\n return t <= 0;\n\n case \"==\" /* Operator.EQUAL */ :\n return 0 === t;\n\n case \"!=\" /* Operator.NOT_EQUAL */ :\n return 0 !== t;\n\n case \">\" /* Operator.GREATER_THAN */ :\n return t > 0;\n\n case \">=\" /* Operator.GREATER_THAN_OR_EQUAL */ :\n return t >= 0;\n\n default:\n return O();\n }\n }\n isInequality() {\n return [ \"<\" /* Operator.LESS_THAN */ , \"<=\" /* Operator.LESS_THAN_OR_EQUAL */ , \">\" /* Operator.GREATER_THAN */ , \">=\" /* Operator.GREATER_THAN_OR_EQUAL */ , \"!=\" /* Operator.NOT_EQUAL */ , \"not-in\" /* Operator.NOT_IN */ ].indexOf(this.op) >= 0;\n }\n getFlattenedFilters() {\n return [ this ];\n }\n getFilters() {\n return [ this ];\n }\n getFirstInequalityField() {\n return this.isInequality() ? this.field : null;\n }\n}\n\nclass gn extends _n {\n constructor(t, e) {\n super(), this.filters = t, this.op = e, this.lt = null;\n }\n /**\n * Creates a filter based on the provided arguments.\n */ static create(t, e) {\n return new gn(t, e);\n }\n matches(t) {\n return yn(this) ? void 0 === this.filters.find((e => !e.matches(t))) : void 0 !== this.filters.find((e => e.matches(t)));\n }\n getFlattenedFilters() {\n return null !== this.lt || (this.lt = this.filters.reduce(((t, e) => t.concat(e.getFlattenedFilters())), [])), \n this.lt;\n }\n // Returns a mutable copy of `this.filters`\n getFilters() {\n return Object.assign([], this.filters);\n }\n getFirstInequalityField() {\n const t = this.ft((t => t.isInequality()));\n return null !== t ? t.field : null;\n }\n // Performs a depth-first search to find and return the first FieldFilter in the composite filter\n // that satisfies the predicate. Returns `null` if none of the FieldFilters satisfy the\n // predicate.\n ft(t) {\n for (const e of this.getFlattenedFilters()) if (t(e)) return e;\n return null;\n }\n}\n\nfunction yn(t) {\n return \"and\" /* CompositeOperator.AND */ === t.op;\n}\n\nfunction pn(t) {\n return \"or\" /* CompositeOperator.OR */ === t.op;\n}\n\n/**\n * Returns true if this filter is a conjunction of field filters only. Returns false otherwise.\n */ function In(t) {\n return Tn(t) && yn(t);\n}\n\n/**\n * Returns true if this filter does not contain any composite filters. Returns false otherwise.\n */ function Tn(t) {\n for (const e of t.filters) if (e instanceof gn) return !1;\n return !0;\n}\n\nfunction En(t) {\n if (t instanceof mn) \n // TODO(b/29183165): Technically, this won't be unique if two values have\n // the same description, such as the int 3 and the string \"3\". So we should\n // add the types in here somehow, too.\n return t.field.canonicalString() + t.op.toString() + Qe(t.value);\n if (In(t)) \n // Older SDK versions use an implicit AND operation between their filters.\n // In the new SDK versions, the developer may use an explicit AND filter.\n // To stay consistent with the old usages, we add a special case to ensure\n // the canonical ID for these two are the same. For example:\n // `col.whereEquals(\"a\", 1).whereEquals(\"b\", 2)` should have the same\n // canonical ID as `col.where(and(equals(\"a\",1), equals(\"b\",2)))`.\n return t.filters.map((t => En(t))).join(\",\");\n {\n // filter instanceof CompositeFilter\n const e = t.filters.map((t => En(t))).join(\",\");\n return `${t.op}(${e})`;\n }\n}\n\nfunction An(t, e) {\n return t instanceof mn ? function(t, e) {\n return e instanceof mn && t.op === e.op && t.field.isEqual(e.field) && qe(t.value, e.value);\n }(t, e) : t instanceof gn ? function(t, e) {\n if (e instanceof gn && t.op === e.op && t.filters.length === e.filters.length) {\n return t.filters.reduce(((t, n, s) => t && An(n, e.filters[s])), !0);\n }\n return !1;\n }\n /**\n * Returns a new composite filter that contains all filter from\n * `compositeFilter` plus all the given filters in `otherFilters`.\n */ (t, e) : void O();\n}\n\nfunction vn(t, e) {\n const n = t.filters.concat(e);\n return gn.create(n, t.op);\n}\n\n/** Returns a debug description for `filter`. */ function Rn(t) {\n return t instanceof mn ? function(t) {\n return `${t.field.canonicalString()} ${t.op} ${Qe(t.value)}`;\n }\n /** Filter that matches on key fields (i.e. '__name__'). */ (t) : t instanceof gn ? function(t) {\n return t.op.toString() + \" {\" + t.getFilters().map(Rn).join(\" ,\") + \"}\";\n }(t) : \"Filter\";\n}\n\nclass Pn extends mn {\n constructor(t, e, n) {\n super(t, e, n), this.key = ht.fromName(n.referenceValue);\n }\n matches(t) {\n const e = ht.comparator(t.key, this.key);\n return this.matchesComparison(e);\n }\n}\n\n/** Filter that matches on key fields within an array. */ class bn extends mn {\n constructor(t, e) {\n super(t, \"in\" /* Operator.IN */ , e), this.keys = Sn(\"in\" /* Operator.IN */ , e);\n }\n matches(t) {\n return this.keys.some((e => e.isEqual(t.key)));\n }\n}\n\n/** Filter that matches on key fields not present within an array. */ class Vn extends mn {\n constructor(t, e) {\n super(t, \"not-in\" /* Operator.NOT_IN */ , e), this.keys = Sn(\"not-in\" /* Operator.NOT_IN */ , e);\n }\n matches(t) {\n return !this.keys.some((e => e.isEqual(t.key)));\n }\n}\n\nfunction Sn(t, e) {\n var n;\n return ((null === (n = e.arrayValue) || void 0 === n ? void 0 : n.values) || []).map((t => ht.fromName(t.referenceValue)));\n}\n\n/** A Filter that implements the array-contains operator. */ class Dn extends mn {\n constructor(t, e) {\n super(t, \"array-contains\" /* Operator.ARRAY_CONTAINS */ , e);\n }\n matches(t) {\n const e = t.data.field(this.field);\n return Je(e) && Ue(e.arrayValue, this.value);\n }\n}\n\n/** A Filter that implements the IN operator. */ class Cn extends mn {\n constructor(t, e) {\n super(t, \"in\" /* Operator.IN */ , e);\n }\n matches(t) {\n const e = t.data.field(this.field);\n return null !== e && Ue(this.value.arrayValue, e);\n }\n}\n\n/** A Filter that implements the not-in operator. */ class xn extends mn {\n constructor(t, e) {\n super(t, \"not-in\" /* Operator.NOT_IN */ , e);\n }\n matches(t) {\n if (Ue(this.value.arrayValue, {\n nullValue: \"NULL_VALUE\"\n })) return !1;\n const e = t.data.field(this.field);\n return null !== e && !Ue(this.value.arrayValue, e);\n }\n}\n\n/** A Filter that implements the array-contains-any operator. */ class Nn extends mn {\n constructor(t, e) {\n super(t, \"array-contains-any\" /* Operator.ARRAY_CONTAINS_ANY */ , e);\n }\n matches(t) {\n const e = t.data.field(this.field);\n return !(!Je(e) || !e.arrayValue.values) && e.arrayValue.values.some((t => Ue(this.value.arrayValue, t)));\n }\n}\n\n/**\n * @license\n * Copyright 2019 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n// Visible for testing\nclass kn {\n constructor(t, e = null, n = [], s = [], i = null, r = null, o = null) {\n this.path = t, this.collectionGroup = e, this.orderBy = n, this.filters = s, this.limit = i, \n this.startAt = r, this.endAt = o, this.dt = null;\n }\n}\n\n/**\n * Initializes a Target with a path and optional additional query constraints.\n * Path must currently be empty if this is a collection group query.\n *\n * NOTE: you should always construct `Target` from `Query.toTarget` instead of\n * using this factory method, because `Query` provides an implicit `orderBy`\n * property.\n */ function Mn(t, e = null, n = [], s = [], i = null, r = null, o = null) {\n return new kn(t, e, n, s, i, r, o);\n}\n\nfunction $n(t) {\n const e = L(t);\n if (null === e.dt) {\n let t = e.path.canonicalString();\n null !== e.collectionGroup && (t += \"|cg:\" + e.collectionGroup), t += \"|f:\", t += e.filters.map((t => En(t))).join(\",\"), \n t += \"|ob:\", t += e.orderBy.map((t => function(t) {\n // TODO(b/29183165): Make this collision robust.\n return t.field.canonicalString() + t.dir;\n }(t))).join(\",\"), Ft(e.limit) || (t += \"|l:\", t += e.limit), e.startAt && (t += \"|lb:\", \n t += e.startAt.inclusive ? \"b:\" : \"a:\", t += e.startAt.position.map((t => Qe(t))).join(\",\")), \n e.endAt && (t += \"|ub:\", t += e.endAt.inclusive ? \"a:\" : \"b:\", t += e.endAt.position.map((t => Qe(t))).join(\",\")), \n e.dt = t;\n }\n return e.dt;\n}\n\nfunction On(t, e) {\n if (t.limit !== e.limit) return !1;\n if (t.orderBy.length !== e.orderBy.length) return !1;\n for (let n = 0; n < t.orderBy.length; n++) if (!wn(t.orderBy[n], e.orderBy[n])) return !1;\n if (t.filters.length !== e.filters.length) return !1;\n for (let n = 0; n < t.filters.length; n++) if (!An(t.filters[n], e.filters[n])) return !1;\n return t.collectionGroup === e.collectionGroup && (!!t.path.isEqual(e.path) && (!!fn(t.startAt, e.startAt) && fn(t.endAt, e.endAt)));\n}\n\nfunction Fn(t) {\n return ht.isDocumentKey(t.path) && null === t.collectionGroup && 0 === t.filters.length;\n}\n\n/** Returns the field filters that target the given field path. */ function Bn(t, e) {\n return t.filters.filter((t => t instanceof mn && t.field.isEqual(e)));\n}\n\n/**\n * Returns the values that are used in ARRAY_CONTAINS or ARRAY_CONTAINS_ANY\n * filters. Returns `null` if there are no such filters.\n */\n/**\n * Returns the value to use as the lower bound for ascending index segment at\n * the provided `fieldPath` (or the upper bound for an descending segment).\n */\nfunction Ln(t, e, n) {\n let s = Be, i = !0;\n // Process all filters to find a value for the current field segment\n for (const n of Bn(t, e)) {\n let t = Be, e = !0;\n switch (n.op) {\n case \"<\" /* Operator.LESS_THAN */ :\n case \"<=\" /* Operator.LESS_THAN_OR_EQUAL */ :\n t = nn(n.value);\n break;\n\n case \"==\" /* Operator.EQUAL */ :\n case \"in\" /* Operator.IN */ :\n case \">=\" /* Operator.GREATER_THAN_OR_EQUAL */ :\n t = n.value;\n break;\n\n case \">\" /* Operator.GREATER_THAN */ :\n t = n.value, e = !1;\n break;\n\n case \"!=\" /* Operator.NOT_EQUAL */ :\n case \"not-in\" /* Operator.NOT_IN */ :\n t = Be;\n // Remaining filters cannot be used as lower bounds.\n }\n rn({\n value: s,\n inclusive: i\n }, {\n value: t,\n inclusive: e\n }) < 0 && (s = t, i = e);\n }\n // If there is an additional bound, compare the values against the existing\n // range to see if we can narrow the scope.\n if (null !== n) for (let r = 0; r < t.orderBy.length; ++r) {\n if (t.orderBy[r].field.isEqual(e)) {\n const t = n.position[r];\n rn({\n value: s,\n inclusive: i\n }, {\n value: t,\n inclusive: n.inclusive\n }) < 0 && (s = t, i = n.inclusive);\n break;\n }\n }\n return {\n value: s,\n inclusive: i\n };\n}\n\n/**\n * Returns the value to use as the upper bound for ascending index segment at\n * the provided `fieldPath` (or the lower bound for a descending segment).\n */ function qn(t, e, n) {\n let s = Fe, i = !0;\n // Process all filters to find a value for the current field segment\n for (const n of Bn(t, e)) {\n let t = Fe, e = !0;\n switch (n.op) {\n case \">=\" /* Operator.GREATER_THAN_OR_EQUAL */ :\n case \">\" /* Operator.GREATER_THAN */ :\n t = sn(n.value), e = !1;\n break;\n\n case \"==\" /* Operator.EQUAL */ :\n case \"in\" /* Operator.IN */ :\n case \"<=\" /* Operator.LESS_THAN_OR_EQUAL */ :\n t = n.value;\n break;\n\n case \"<\" /* Operator.LESS_THAN */ :\n t = n.value, e = !1;\n break;\n\n case \"!=\" /* Operator.NOT_EQUAL */ :\n case \"not-in\" /* Operator.NOT_IN */ :\n t = Fe;\n // Remaining filters cannot be used as upper bounds.\n }\n on({\n value: s,\n inclusive: i\n }, {\n value: t,\n inclusive: e\n }) > 0 && (s = t, i = e);\n }\n // If there is an additional bound, compare the values against the existing\n // range to see if we can narrow the scope.\n if (null !== n) for (let r = 0; r < t.orderBy.length; ++r) {\n if (t.orderBy[r].field.isEqual(e)) {\n const t = n.position[r];\n on({\n value: s,\n inclusive: i\n }, {\n value: t,\n inclusive: n.inclusive\n }) > 0 && (s = t, i = n.inclusive);\n break;\n }\n }\n return {\n value: s,\n inclusive: i\n };\n}\n\n/** Returns the number of segments of a perfect index for this target. */\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * Query encapsulates all the query attributes we support in the SDK. It can\n * be run against the LocalStore, as well as be converted to a `Target` to\n * query the RemoteStore results.\n *\n * Visible for testing.\n */\nclass Un {\n /**\n * Initializes a Query with a path and optional additional query constraints.\n * Path must currently be empty if this is a collection group query.\n */\n constructor(t, e = null, n = [], s = [], i = null, r = \"F\" /* LimitType.First */ , o = null, u = null) {\n this.path = t, this.collectionGroup = e, this.explicitOrderBy = n, this.filters = s, \n this.limit = i, this.limitType = r, this.startAt = o, this.endAt = u, this.wt = null, \n // The corresponding `Target` of this `Query` instance.\n this._t = null, this.startAt, this.endAt;\n }\n}\n\n/** Creates a new Query instance with the options provided. */ function Kn(t, e, n, s, i, r, o, u) {\n return new Un(t, e, n, s, i, r, o, u);\n}\n\n/** Creates a new Query for a query that matches all documents at `path` */ function Gn(t) {\n return new Un(t);\n}\n\n/**\n * Helper to convert a collection group query into a collection query at a\n * specific path. This is used when executing collection group queries, since\n * we have to split the query into a set of collection queries at multiple\n * paths.\n */\n/**\n * Returns true if this query does not specify any query constraints that\n * could remove results.\n */\nfunction Qn(t) {\n return 0 === t.filters.length && null === t.limit && null == t.startAt && null == t.endAt && (0 === t.explicitOrderBy.length || 1 === t.explicitOrderBy.length && t.explicitOrderBy[0].field.isKeyField());\n}\n\nfunction jn(t) {\n return t.explicitOrderBy.length > 0 ? t.explicitOrderBy[0].field : null;\n}\n\nfunction zn(t) {\n for (const e of t.filters) {\n const t = e.getFirstInequalityField();\n if (null !== t) return t;\n }\n return null;\n}\n\n/**\n * Creates a new Query for a collection group query that matches all documents\n * within the provided collection group.\n */\n/**\n * Returns whether the query matches a collection group rather than a specific\n * collection.\n */\nfunction Wn(t) {\n return null !== t.collectionGroup;\n}\n\n/**\n * Returns the implicit order by constraint that is used to execute the Query,\n * which can be different from the order by constraints the user provided (e.g.\n * the SDK and backend always orders by `__name__`).\n */ function Hn(t) {\n const e = L(t);\n if (null === e.wt) {\n e.wt = [];\n const t = zn(e), n = jn(e);\n if (null !== t && null === n) \n // In order to implicitly add key ordering, we must also add the\n // inequality filter field for it to be a valid query.\n // Note that the default inequality field and key ordering is ascending.\n t.isKeyField() || e.wt.push(new dn(t)), e.wt.push(new dn(at.keyField(), \"asc\" /* Direction.ASCENDING */)); else {\n let t = !1;\n for (const n of e.explicitOrderBy) e.wt.push(n), n.field.isKeyField() && (t = !0);\n if (!t) {\n // The order of the implicit key ordering always matches the last\n // explicit order by\n const t = e.explicitOrderBy.length > 0 ? e.explicitOrderBy[e.explicitOrderBy.length - 1].dir : \"asc\" /* Direction.ASCENDING */;\n e.wt.push(new dn(at.keyField(), t));\n }\n }\n }\n return e.wt;\n}\n\n/**\n * Converts this `Query` instance to it's corresponding `Target` representation.\n */ function Jn(t) {\n const e = L(t);\n if (!e._t) if (\"F\" /* LimitType.First */ === e.limitType) e._t = Mn(e.path, e.collectionGroup, Hn(e), e.filters, e.limit, e.startAt, e.endAt); else {\n // Flip the orderBy directions since we want the last results\n const t = [];\n for (const n of Hn(e)) {\n const e = \"desc\" /* Direction.DESCENDING */ === n.dir ? \"asc\" /* Direction.ASCENDING */ : \"desc\" /* Direction.DESCENDING */;\n t.push(new dn(n.field, e));\n }\n // We need to swap the cursors to match the now-flipped query ordering.\n const n = e.endAt ? new hn(e.endAt.position, e.endAt.inclusive) : null, s = e.startAt ? new hn(e.startAt.position, e.startAt.inclusive) : null;\n // Now return as a LimitType.First query.\n e._t = Mn(e.path, e.collectionGroup, t, e.filters, e.limit, n, s);\n }\n return e._t;\n}\n\nfunction Yn(t, e) {\n e.getFirstInequalityField(), zn(t);\n const n = t.filters.concat([ e ]);\n return new Un(t.path, t.collectionGroup, t.explicitOrderBy.slice(), n, t.limit, t.limitType, t.startAt, t.endAt);\n}\n\nfunction Xn(t, e, n) {\n return new Un(t.path, t.collectionGroup, t.explicitOrderBy.slice(), t.filters.slice(), e, n, t.startAt, t.endAt);\n}\n\nfunction Zn(t, e) {\n return On(Jn(t), Jn(e)) && t.limitType === e.limitType;\n}\n\n// TODO(b/29183165): This is used to get a unique string from a query to, for\n// example, use as a dictionary key, but the implementation is subject to\n// collisions. Make it collision-free.\nfunction ts(t) {\n return `${$n(Jn(t))}|lt:${t.limitType}`;\n}\n\nfunction es(t) {\n return `Query(target=${function(t) {\n let e = t.path.canonicalString();\n return null !== t.collectionGroup && (e += \" collectionGroup=\" + t.collectionGroup), \n t.filters.length > 0 && (e += `, filters: [${t.filters.map((t => Rn(t))).join(\", \")}]`), \n Ft(t.limit) || (e += \", limit: \" + t.limit), t.orderBy.length > 0 && (e += `, orderBy: [${t.orderBy.map((t => function(t) {\n return `${t.field.canonicalString()} (${t.dir})`;\n }(t))).join(\", \")}]`), t.startAt && (e += \", startAt: \", e += t.startAt.inclusive ? \"b:\" : \"a:\", \n e += t.startAt.position.map((t => Qe(t))).join(\",\")), t.endAt && (e += \", endAt: \", \n e += t.endAt.inclusive ? \"a:\" : \"b:\", e += t.endAt.position.map((t => Qe(t))).join(\",\")), \n `Target(${e})`;\n }(Jn(t))}; limitType=${t.limitType})`;\n}\n\n/** Returns whether `doc` matches the constraints of `query`. */ function ns(t, e) {\n return e.isFoundDocument() && function(t, e) {\n const n = e.key.path;\n return null !== t.collectionGroup ? e.key.hasCollectionId(t.collectionGroup) && t.path.isPrefixOf(n) : ht.isDocumentKey(t.path) ? t.path.isEqual(n) : t.path.isImmediateParentOf(n);\n }\n /**\n * A document must have a value for every ordering clause in order to show up\n * in the results.\n */ (t, e) && function(t, e) {\n // We must use `queryOrderBy()` to get the list of all orderBys (both implicit and explicit).\n // Note that for OR queries, orderBy applies to all disjunction terms and implicit orderBys must\n // be taken into account. For example, the query \"a > 1 || b==1\" has an implicit \"orderBy a\" due\n // to the inequality, and is evaluated as \"a > 1 orderBy a || b==1 orderBy a\".\n // A document with content of {b:1} matches the filters, but does not match the orderBy because\n // it's missing the field 'a'.\n for (const n of Hn(t)) \n // order by key always matches\n if (!n.field.isKeyField() && null === e.data.field(n.field)) return !1;\n return !0;\n }(t, e) && function(t, e) {\n for (const n of t.filters) if (!n.matches(e)) return !1;\n return !0;\n }\n /** Makes sure a document is within the bounds, if provided. */ (t, e) && function(t, e) {\n if (t.startAt && !\n /**\n * Returns true if a document sorts before a bound using the provided sort\n * order.\n */\n function(t, e, n) {\n const s = ln(t, e, n);\n return t.inclusive ? s <= 0 : s < 0;\n }(t.startAt, Hn(t), e)) return !1;\n if (t.endAt && !function(t, e, n) {\n const s = ln(t, e, n);\n return t.inclusive ? s >= 0 : s > 0;\n }(t.endAt, Hn(t), e)) return !1;\n return !0;\n }\n /**\n * Returns the collection group that this query targets.\n *\n * PORTING NOTE: This is only used in the Web SDK to facilitate multi-tab\n * synchronization for query results.\n */ (t, e);\n}\n\nfunction ss(t) {\n return t.collectionGroup || (t.path.length % 2 == 1 ? t.path.lastSegment() : t.path.get(t.path.length - 2));\n}\n\n/**\n * Returns a new comparator function that can be used to compare two documents\n * based on the Query's ordering constraint.\n */ function is(t) {\n return (e, n) => {\n let s = !1;\n for (const i of Hn(t)) {\n const t = rs(i, e, n);\n if (0 !== t) return t;\n s = s || i.field.isKeyField();\n }\n return 0;\n };\n}\n\nfunction rs(t, e, n) {\n const s = t.field.isKeyField() ? ht.comparator(e.key, n.key) : function(t, e, n) {\n const s = e.data.field(t), i = n.data.field(t);\n return null !== s && null !== i ? Ke(s, i) : O();\n }(t.field, e, n);\n switch (t.dir) {\n case \"asc\" /* Direction.ASCENDING */ :\n return s;\n\n case \"desc\" /* Direction.DESCENDING */ :\n return -1 * s;\n\n default:\n return O();\n }\n}\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * A map implementation that uses objects as keys. Objects must have an\n * associated equals function and must be immutable. Entries in the map are\n * stored together with the key being produced from the mapKeyFn. This map\n * automatically handles collisions of keys.\n */ class os {\n constructor(t, e) {\n this.mapKeyFn = t, this.equalsFn = e, \n /**\n * The inner map for a key/value pair. Due to the possibility of collisions we\n * keep a list of entries that we do a linear search through to find an actual\n * match. Note that collisions should be rare, so we still expect near\n * constant time lookups in practice.\n */\n this.inner = {}, \n /** The number of entries stored in the map */\n this.innerSize = 0;\n }\n /** Get a value for this key, or undefined if it does not exist. */ get(t) {\n const e = this.mapKeyFn(t), n = this.inner[e];\n if (void 0 !== n) for (const [e, s] of n) if (this.equalsFn(e, t)) return s;\n }\n has(t) {\n return void 0 !== this.get(t);\n }\n /** Put this key and value in the map. */ set(t, e) {\n const n = this.mapKeyFn(t), s = this.inner[n];\n if (void 0 === s) return this.inner[n] = [ [ t, e ] ], void this.innerSize++;\n for (let n = 0; n < s.length; n++) if (this.equalsFn(s[n][0], t)) \n // This is updating an existing entry and does not increase `innerSize`.\n return void (s[n] = [ t, e ]);\n s.push([ t, e ]), this.innerSize++;\n }\n /**\n * Remove this key from the map. Returns a boolean if anything was deleted.\n */ delete(t) {\n const e = this.mapKeyFn(t), n = this.inner[e];\n if (void 0 === n) return !1;\n for (let s = 0; s < n.length; s++) if (this.equalsFn(n[s][0], t)) return 1 === n.length ? delete this.inner[e] : n.splice(s, 1), \n this.innerSize--, !0;\n return !1;\n }\n forEach(t) {\n ge(this.inner, ((e, n) => {\n for (const [e, s] of n) t(e, s);\n }));\n }\n isEmpty() {\n return ye(this.inner);\n }\n size() {\n return this.innerSize;\n }\n}\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */ const us = new pe(ht.comparator);\n\nfunction cs() {\n return us;\n}\n\nconst as = new pe(ht.comparator);\n\nfunction hs(...t) {\n let e = as;\n for (const n of t) e = e.insert(n.key, n);\n return e;\n}\n\nfunction ls(t) {\n let e = as;\n return t.forEach(((t, n) => e = e.insert(t, n.overlayedDocument))), e;\n}\n\nfunction fs() {\n return ws();\n}\n\nfunction ds() {\n return ws();\n}\n\nfunction ws() {\n return new os((t => t.toString()), ((t, e) => t.isEqual(e)));\n}\n\nconst _s = new pe(ht.comparator);\n\nconst ms = new Ee(ht.comparator);\n\nfunction gs(...t) {\n let e = ms;\n for (const n of t) e = e.add(n);\n return e;\n}\n\nconst ys = new Ee(et);\n\nfunction ps() {\n return ys;\n}\n\n/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * Returns an DoubleValue for `value` that is encoded based the serializer's\n * `useProto3Json` setting.\n */ function Is(t, e) {\n if (t.useProto3Json) {\n if (isNaN(e)) return {\n doubleValue: \"NaN\"\n };\n if (e === 1 / 0) return {\n doubleValue: \"Infinity\"\n };\n if (e === -1 / 0) return {\n doubleValue: \"-Infinity\"\n };\n }\n return {\n doubleValue: Bt(e) ? \"-0\" : e\n };\n}\n\n/**\n * Returns an IntegerValue for `value`.\n */ function Ts(t) {\n return {\n integerValue: \"\" + t\n };\n}\n\n/**\n * Returns a value for a number that's appropriate to put into a proto.\n * The return value is an IntegerValue if it can safely represent the value,\n * otherwise a DoubleValue is returned.\n */ function Es(t, e) {\n return Lt(e) ? Ts(e) : Is(t, e);\n}\n\n/**\n * @license\n * Copyright 2018 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/** Used to represent a field transform on a mutation. */ class As {\n constructor() {\n // Make sure that the structural type of `TransformOperation` is unique.\n // See https://github.com/microsoft/TypeScript/issues/5451\n this._ = void 0;\n }\n}\n\n/**\n * Computes the local transform result against the provided `previousValue`,\n * optionally using the provided localWriteTime.\n */ function vs(t, e, n) {\n return t instanceof bs ? function(t, e) {\n const n = {\n fields: {\n __type__: {\n stringValue: \"server_timestamp\"\n },\n __local_write_time__: {\n timestampValue: {\n seconds: t.seconds,\n nanos: t.nanoseconds\n }\n }\n }\n };\n // We should avoid storing deeply nested server timestamp map values\n // because we never use the intermediate \"previous values\".\n // For example:\n // previous: 42L, add: t1, result: t1 -> 42L\n // previous: t1, add: t2, result: t2 -> 42L (NOT t2 -> t1 -> 42L)\n // previous: t2, add: t3, result: t3 -> 42L (NOT t3 -> t2 -> t1 -> 42L)\n // `getPreviousValue` recursively traverses server timestamps to find the\n // least recent Value.\n return e && Ne(e) && (e = ke(e)), e && (n.fields.__previous_value__ = e), \n {\n mapValue: n\n };\n }(n, e) : t instanceof Vs ? Ss(t, e) : t instanceof Ds ? Cs(t, e) : function(t, e) {\n // PORTING NOTE: Since JavaScript's integer arithmetic is limited to 53 bit\n // precision and resolves overflows by reducing precision, we do not\n // manually cap overflows at 2^63.\n const n = Ps(t, e), s = Ns(n) + Ns(t.gt);\n return He(n) && He(t.gt) ? Ts(s) : Is(t.serializer, s);\n }(t, e);\n}\n\n/**\n * Computes a final transform result after the transform has been acknowledged\n * by the server, potentially using the server-provided transformResult.\n */ function Rs(t, e, n) {\n // The server just sends null as the transform result for array operations,\n // so we have to calculate a result the same as we do for local\n // applications.\n return t instanceof Vs ? Ss(t, e) : t instanceof Ds ? Cs(t, e) : n;\n}\n\n/**\n * If this transform operation is not idempotent, returns the base value to\n * persist for this transform. If a base value is returned, the transform\n * operation is always applied to this base value, even if document has\n * already been updated.\n *\n * Base values provide consistent behavior for non-idempotent transforms and\n * allow us to return the same latency-compensated value even if the backend\n * has already applied the transform operation. The base value is null for\n * idempotent transforms, as they can be re-played even if the backend has\n * already applied them.\n *\n * @returns a base value to store along with the mutation, or null for\n * idempotent transforms.\n */ function Ps(t, e) {\n return t instanceof xs ? He(n = e) || function(t) {\n return !!t && \"doubleValue\" in t;\n }\n /** Returns true if `value` is either an IntegerValue or a DoubleValue. */ (n) ? e : {\n integerValue: 0\n } : null;\n var n;\n}\n\n/** Transforms a value into a server-generated timestamp. */\nclass bs extends As {}\n\n/** Transforms an array value via a union operation. */ class Vs extends As {\n constructor(t) {\n super(), this.elements = t;\n }\n}\n\nfunction Ss(t, e) {\n const n = ks(e);\n for (const e of t.elements) n.some((t => qe(t, e))) || n.push(e);\n return {\n arrayValue: {\n values: n\n }\n };\n}\n\n/** Transforms an array value via a remove operation. */ class Ds extends As {\n constructor(t) {\n super(), this.elements = t;\n }\n}\n\nfunction Cs(t, e) {\n let n = ks(e);\n for (const e of t.elements) n = n.filter((t => !qe(t, e)));\n return {\n arrayValue: {\n values: n\n }\n };\n}\n\n/**\n * Implements the backend semantics for locally computed NUMERIC_ADD (increment)\n * transforms. Converts all field values to integers or doubles, but unlike the\n * backend does not cap integer values at 2^63. Instead, JavaScript number\n * arithmetic is used and precision loss can occur for values greater than 2^53.\n */ class xs extends As {\n constructor(t, e) {\n super(), this.serializer = t, this.gt = e;\n }\n}\n\nfunction Ns(t) {\n return Ce(t.integerValue || t.doubleValue);\n}\n\nfunction ks(t) {\n return Je(t) && t.arrayValue.values ? t.arrayValue.values.slice() : [];\n}\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/** A field path and the TransformOperation to perform upon it. */ class Ms {\n constructor(t, e) {\n this.field = t, this.transform = e;\n }\n}\n\nfunction $s(t, e) {\n return t.field.isEqual(e.field) && function(t, e) {\n return t instanceof Vs && e instanceof Vs || t instanceof Ds && e instanceof Ds ? nt(t.elements, e.elements, qe) : t instanceof xs && e instanceof xs ? qe(t.gt, e.gt) : t instanceof bs && e instanceof bs;\n }(t.transform, e.transform);\n}\n\n/** The result of successfully applying a mutation to the backend. */\nclass Os {\n constructor(\n /**\n * The version at which the mutation was committed:\n *\n * - For most operations, this is the updateTime in the WriteResult.\n * - For deletes, the commitTime of the WriteResponse (because deletes are\n * not stored and have no updateTime).\n *\n * Note that these versions can be different: No-op writes will not change\n * the updateTime even though the commitTime advances.\n */\n t, \n /**\n * The resulting fields returned from the backend after a mutation\n * containing field transforms has been committed. Contains one FieldValue\n * for each FieldTransform that was in the mutation.\n *\n * Will be empty if the mutation did not contain any field transforms.\n */\n e) {\n this.version = t, this.transformResults = e;\n }\n}\n\n/**\n * Encodes a precondition for a mutation. This follows the model that the\n * backend accepts with the special case of an explicit \"empty\" precondition\n * (meaning no precondition).\n */ class Fs {\n constructor(t, e) {\n this.updateTime = t, this.exists = e;\n }\n /** Creates a new empty Precondition. */ static none() {\n return new Fs;\n }\n /** Creates a new Precondition with an exists flag. */ static exists(t) {\n return new Fs(void 0, t);\n }\n /** Creates a new Precondition based on a version a document exists at. */ static updateTime(t) {\n return new Fs(t);\n }\n /** Returns whether this Precondition is empty. */ get isNone() {\n return void 0 === this.updateTime && void 0 === this.exists;\n }\n isEqual(t) {\n return this.exists === t.exists && (this.updateTime ? !!t.updateTime && this.updateTime.isEqual(t.updateTime) : !t.updateTime);\n }\n}\n\n/** Returns true if the preconditions is valid for the given document. */ function Bs(t, e) {\n return void 0 !== t.updateTime ? e.isFoundDocument() && e.version.isEqual(t.updateTime) : void 0 === t.exists || t.exists === e.isFoundDocument();\n}\n\n/**\n * A mutation describes a self-contained change to a document. Mutations can\n * create, replace, delete, and update subsets of documents.\n *\n * Mutations not only act on the value of the document but also its version.\n *\n * For local mutations (mutations that haven't been committed yet), we preserve\n * the existing version for Set and Patch mutations. For Delete mutations, we\n * reset the version to 0.\n *\n * Here's the expected transition table.\n *\n * MUTATION APPLIED TO RESULTS IN\n *\n * SetMutation Document(v3) Document(v3)\n * SetMutation NoDocument(v3) Document(v0)\n * SetMutation InvalidDocument(v0) Document(v0)\n * PatchMutation Document(v3) Document(v3)\n * PatchMutation NoDocument(v3) NoDocument(v3)\n * PatchMutation InvalidDocument(v0) UnknownDocument(v3)\n * DeleteMutation Document(v3) NoDocument(v0)\n * DeleteMutation NoDocument(v3) NoDocument(v0)\n * DeleteMutation InvalidDocument(v0) NoDocument(v0)\n *\n * For acknowledged mutations, we use the updateTime of the WriteResponse as\n * the resulting version for Set and Patch mutations. As deletes have no\n * explicit update time, we use the commitTime of the WriteResponse for\n * Delete mutations.\n *\n * If a mutation is acknowledged by the backend but fails the precondition check\n * locally, we transition to an `UnknownDocument` and rely on Watch to send us\n * the updated version.\n *\n * Field transforms are used only with Patch and Set Mutations. We use the\n * `updateTransforms` message to store transforms, rather than the `transforms`s\n * messages.\n *\n * ## Subclassing Notes\n *\n * Every type of mutation needs to implement its own applyToRemoteDocument() and\n * applyToLocalView() to implement the actual behavior of applying the mutation\n * to some source document (see `setMutationApplyToRemoteDocument()` for an\n * example).\n */ class Ls {}\n\n/**\n * A utility method to calculate a `Mutation` representing the overlay from the\n * final state of the document, and a `FieldMask` representing the fields that\n * are mutated by the local mutations.\n */ function qs(t, e) {\n if (!t.hasLocalMutations || e && 0 === e.fields.length) return null;\n // mask is null when sets or deletes are applied to the current document.\n if (null === e) return t.isNoDocument() ? new Ys(t.key, Fs.none()) : new js(t.key, t.data, Fs.none());\n {\n const n = t.data, s = un.empty();\n let i = new Ee(at.comparator);\n for (let t of e.fields) if (!i.has(t)) {\n let e = n.field(t);\n // If we are deleting a nested field, we take the immediate parent as\n // the mask used to construct the resulting mutation.\n // Justification: Nested fields can create parent fields implicitly. If\n // only a leaf entry is deleted in later mutations, the parent field\n // should still remain, but we may have lost this information.\n // Consider mutation (foo.bar 1), then mutation (foo.bar delete()).\n // This leaves the final result (foo, {}). Despite the fact that `doc`\n // has the correct result, `foo` is not in `mask`, and the resulting\n // mutation would miss `foo`.\n null === e && t.length > 1 && (t = t.popLast(), e = n.field(t)), null === e ? s.delete(t) : s.set(t, e), \n i = i.add(t);\n }\n return new zs(t.key, s, new Re(i.toArray()), Fs.none());\n }\n}\n\n/**\n * Applies this mutation to the given document for the purposes of computing a\n * new remote document. If the input document doesn't match the expected state\n * (e.g. it is invalid or outdated), the document type may transition to\n * unknown.\n *\n * @param mutation - The mutation to apply.\n * @param document - The document to mutate. The input document can be an\n * invalid document if the client has no knowledge of the pre-mutation state\n * of the document.\n * @param mutationResult - The result of applying the mutation from the backend.\n */ function Us(t, e, n) {\n t instanceof js ? function(t, e, n) {\n // Unlike setMutationApplyToLocalView, if we're applying a mutation to a\n // remote document the server has accepted the mutation so the precondition\n // must have held.\n const s = t.value.clone(), i = Hs(t.fieldTransforms, e, n.transformResults);\n s.setAll(i), e.convertToFoundDocument(n.version, s).setHasCommittedMutations();\n }(t, e, n) : t instanceof zs ? function(t, e, n) {\n if (!Bs(t.precondition, e)) \n // Since the mutation was not rejected, we know that the precondition\n // matched on the backend. We therefore must not have the expected version\n // of the document in our cache and convert to an UnknownDocument with a\n // known updateTime.\n return void e.convertToUnknownDocument(n.version);\n const s = Hs(t.fieldTransforms, e, n.transformResults), i = e.data;\n i.setAll(Ws(t)), i.setAll(s), e.convertToFoundDocument(n.version, i).setHasCommittedMutations();\n }(t, e, n) : function(t, e, n) {\n // Unlike applyToLocalView, if we're applying a mutation to a remote\n // document the server has accepted the mutation so the precondition must\n // have held.\n e.convertToNoDocument(n.version).setHasCommittedMutations();\n }(0, e, n);\n}\n\n/**\n * Applies this mutation to the given document for the purposes of computing\n * the new local view of a document. If the input document doesn't match the\n * expected state, the document is not modified.\n *\n * @param mutation - The mutation to apply.\n * @param document - The document to mutate. The input document can be an\n * invalid document if the client has no knowledge of the pre-mutation state\n * of the document.\n * @param previousMask - The fields that have been updated before applying this mutation.\n * @param localWriteTime - A timestamp indicating the local write time of the\n * batch this mutation is a part of.\n * @returns A `FieldMask` representing the fields that are changed by applying this mutation.\n */ function Ks(t, e, n, s) {\n return t instanceof js ? function(t, e, n, s) {\n if (!Bs(t.precondition, e)) \n // The mutation failed to apply (e.g. a document ID created with add()\n // caused a name collision).\n return n;\n const i = t.value.clone(), r = Js(t.fieldTransforms, s, e);\n return i.setAll(r), e.convertToFoundDocument(e.version, i).setHasLocalMutations(), \n null;\n // SetMutation overwrites all fields.\n }\n /**\n * A mutation that modifies fields of the document at the given key with the\n * given values. The values are applied through a field mask:\n *\n * * When a field is in both the mask and the values, the corresponding field\n * is updated.\n * * When a field is in neither the mask nor the values, the corresponding\n * field is unmodified.\n * * When a field is in the mask but not in the values, the corresponding field\n * is deleted.\n * * When a field is not in the mask but is in the values, the values map is\n * ignored.\n */ (t, e, n, s) : t instanceof zs ? function(t, e, n, s) {\n if (!Bs(t.precondition, e)) return n;\n const i = Js(t.fieldTransforms, s, e), r = e.data;\n if (r.setAll(Ws(t)), r.setAll(i), e.convertToFoundDocument(e.version, r).setHasLocalMutations(), \n null === n) return null;\n return n.unionWith(t.fieldMask.fields).unionWith(t.fieldTransforms.map((t => t.field)));\n }\n /**\n * Returns a FieldPath/Value map with the content of the PatchMutation.\n */ (t, e, n, s) : function(t, e, n) {\n if (Bs(t.precondition, e)) return e.convertToNoDocument(e.version).setHasLocalMutations(), \n null;\n return n;\n }\n /**\n * A mutation that verifies the existence of the document at the given key with\n * the provided precondition.\n *\n * The `verify` operation is only used in Transactions, and this class serves\n * primarily to facilitate serialization into protos.\n */ (t, e, n);\n}\n\n/**\n * If this mutation is not idempotent, returns the base value to persist with\n * this mutation. If a base value is returned, the mutation is always applied\n * to this base value, even if document has already been updated.\n *\n * The base value is a sparse object that consists of only the document\n * fields for which this mutation contains a non-idempotent transformation\n * (e.g. a numeric increment). The provided value guarantees consistent\n * behavior for non-idempotent transforms and allow us to return the same\n * latency-compensated value even if the backend has already applied the\n * mutation. The base value is null for idempotent mutations, as they can be\n * re-played even if the backend has already applied them.\n *\n * @returns a base value to store along with the mutation, or null for\n * idempotent mutations.\n */ function Gs(t, e) {\n let n = null;\n for (const s of t.fieldTransforms) {\n const t = e.data.field(s.field), i = Ps(s.transform, t || null);\n null != i && (null === n && (n = un.empty()), n.set(s.field, i));\n }\n return n || null;\n}\n\nfunction Qs(t, e) {\n return t.type === e.type && (!!t.key.isEqual(e.key) && (!!t.precondition.isEqual(e.precondition) && (!!function(t, e) {\n return void 0 === t && void 0 === e || !(!t || !e) && nt(t, e, ((t, e) => $s(t, e)));\n }(t.fieldTransforms, e.fieldTransforms) && (0 /* MutationType.Set */ === t.type ? t.value.isEqual(e.value) : 1 /* MutationType.Patch */ !== t.type || t.data.isEqual(e.data) && t.fieldMask.isEqual(e.fieldMask)))));\n}\n\n/**\n * A mutation that creates or replaces the document at the given key with the\n * object value contents.\n */ class js extends Ls {\n constructor(t, e, n, s = []) {\n super(), this.key = t, this.value = e, this.precondition = n, this.fieldTransforms = s, \n this.type = 0 /* MutationType.Set */;\n }\n getFieldMask() {\n return null;\n }\n}\n\nclass zs extends Ls {\n constructor(t, e, n, s, i = []) {\n super(), this.key = t, this.data = e, this.fieldMask = n, this.precondition = s, \n this.fieldTransforms = i, this.type = 1 /* MutationType.Patch */;\n }\n getFieldMask() {\n return this.fieldMask;\n }\n}\n\nfunction Ws(t) {\n const e = new Map;\n return t.fieldMask.fields.forEach((n => {\n if (!n.isEmpty()) {\n const s = t.data.field(n);\n e.set(n, s);\n }\n })), e;\n}\n\n/**\n * Creates a list of \"transform results\" (a transform result is a field value\n * representing the result of applying a transform) for use after a mutation\n * containing transforms has been acknowledged by the server.\n *\n * @param fieldTransforms - The field transforms to apply the result to.\n * @param mutableDocument - The current state of the document after applying all\n * previous mutations.\n * @param serverTransformResults - The transform results received by the server.\n * @returns The transform results list.\n */ function Hs(t, e, n) {\n const s = new Map;\n F(t.length === n.length);\n for (let i = 0; i < n.length; i++) {\n const r = t[i], o = r.transform, u = e.data.field(r.field);\n s.set(r.field, Rs(o, u, n[i]));\n }\n return s;\n}\n\n/**\n * Creates a list of \"transform results\" (a transform result is a field value\n * representing the result of applying a transform) for use when applying a\n * transform locally.\n *\n * @param fieldTransforms - The field transforms to apply the result to.\n * @param localWriteTime - The local time of the mutation (used to\n * generate ServerTimestampValues).\n * @param mutableDocument - The document to apply transforms on.\n * @returns The transform results list.\n */ function Js(t, e, n) {\n const s = new Map;\n for (const i of t) {\n const t = i.transform, r = n.data.field(i.field);\n s.set(i.field, vs(t, r, e));\n }\n return s;\n}\n\n/** A mutation that deletes the document at the given key. */ class Ys extends Ls {\n constructor(t, e) {\n super(), this.key = t, this.precondition = e, this.type = 2 /* MutationType.Delete */ , \n this.fieldTransforms = [];\n }\n getFieldMask() {\n return null;\n }\n}\n\nclass Xs extends Ls {\n constructor(t, e) {\n super(), this.key = t, this.precondition = e, this.type = 3 /* MutationType.Verify */ , \n this.fieldTransforms = [];\n }\n getFieldMask() {\n return null;\n }\n}\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * A batch of mutations that will be sent as one unit to the backend.\n */ class Zs {\n /**\n * @param batchId - The unique ID of this mutation batch.\n * @param localWriteTime - The original write time of this mutation.\n * @param baseMutations - Mutations that are used to populate the base\n * values when this mutation is applied locally. This can be used to locally\n * overwrite values that are persisted in the remote document cache. Base\n * mutations are never sent to the backend.\n * @param mutations - The user-provided mutations in this mutation batch.\n * User-provided mutations are applied both locally and remotely on the\n * backend.\n */\n constructor(t, e, n, s) {\n this.batchId = t, this.localWriteTime = e, this.baseMutations = n, this.mutations = s;\n }\n /**\n * Applies all the mutations in this MutationBatch to the specified document\n * to compute the state of the remote document\n *\n * @param document - The document to apply mutations to.\n * @param batchResult - The result of applying the MutationBatch to the\n * backend.\n */ applyToRemoteDocument(t, e) {\n const n = e.mutationResults;\n for (let e = 0; e < this.mutations.length; e++) {\n const s = this.mutations[e];\n if (s.key.isEqual(t.key)) {\n Us(s, t, n[e]);\n }\n }\n }\n /**\n * Computes the local view of a document given all the mutations in this\n * batch.\n *\n * @param document - The document to apply mutations to.\n * @param mutatedFields - Fields that have been updated before applying this mutation batch.\n * @returns A `FieldMask` representing all the fields that are mutated.\n */ applyToLocalView(t, e) {\n // First, apply the base state. This allows us to apply non-idempotent\n // transform against a consistent set of values.\n for (const n of this.baseMutations) n.key.isEqual(t.key) && (e = Ks(n, t, e, this.localWriteTime));\n // Second, apply all user-provided mutations.\n for (const n of this.mutations) n.key.isEqual(t.key) && (e = Ks(n, t, e, this.localWriteTime));\n return e;\n }\n /**\n * Computes the local view for all provided documents given the mutations in\n * this batch. Returns a `DocumentKey` to `Mutation` map which can be used to\n * replace all the mutation applications.\n */ applyToLocalDocumentSet(t, e) {\n // TODO(mrschmidt): This implementation is O(n^2). If we apply the mutations\n // directly (as done in `applyToLocalView()`), we can reduce the complexity\n // to O(n).\n const n = ds();\n return this.mutations.forEach((s => {\n const i = t.get(s.key), r = i.overlayedDocument;\n // TODO(mutabledocuments): This method should take a MutableDocumentMap\n // and we should remove this cast.\n let o = this.applyToLocalView(r, i.mutatedFields);\n // Set mutatedFields to null if the document is only from local mutations.\n // This creates a Set or Delete mutation, instead of trying to create a\n // patch mutation as the overlay.\n o = e.has(s.key) ? null : o;\n const u = qs(r, o);\n null !== u && n.set(s.key, u), r.isValidDocument() || r.convertToNoDocument(rt.min());\n })), n;\n }\n keys() {\n return this.mutations.reduce(((t, e) => t.add(e.key)), gs());\n }\n isEqual(t) {\n return this.batchId === t.batchId && nt(this.mutations, t.mutations, ((t, e) => Qs(t, e))) && nt(this.baseMutations, t.baseMutations, ((t, e) => Qs(t, e)));\n }\n}\n\n/** The result of applying a mutation batch to the backend. */ class ti {\n constructor(t, e, n, \n /**\n * A pre-computed mapping from each mutated document to the resulting\n * version.\n */\n s) {\n this.batch = t, this.commitVersion = e, this.mutationResults = n, this.docVersions = s;\n }\n /**\n * Creates a new MutationBatchResult for the given batch and results. There\n * must be one result for each mutation in the batch. This static factory\n * caches a document=>version mapping (docVersions).\n */ static from(t, e, n) {\n F(t.mutations.length === n.length);\n let s = _s;\n const i = t.mutations;\n for (let t = 0; t < i.length; t++) s = s.insert(i[t].key, n[t].version);\n return new ti(t, e, n, s);\n }\n}\n\n/**\n * @license\n * Copyright 2022 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * Representation of an overlay computed by Firestore.\n *\n * Holds information about a mutation and the largest batch id in Firestore when\n * the mutation was created.\n */ class ei {\n constructor(t, e) {\n this.largestBatchId = t, this.mutation = e;\n }\n getKey() {\n return this.mutation.key;\n }\n isEqual(t) {\n return null !== t && this.mutation === t.mutation;\n }\n toString() {\n return `Overlay{\\n largestBatchId: ${this.largestBatchId},\\n mutation: ${this.mutation.toString()}\\n }`;\n }\n}\n\n/**\n * @license\n * Copyright 2023 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * Concrete implementation of the Aggregate type.\n */ class ni {\n constructor(t, e, n) {\n this.alias = t, this.yt = e, this.fieldPath = n;\n }\n}\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */ class si {\n constructor(t, e) {\n this.count = t, this.unchangedNames = e;\n }\n}\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * Error Codes describing the different ways GRPC can fail. These are copied\n * directly from GRPC's sources here:\n *\n * https://github.com/grpc/grpc/blob/bceec94ea4fc5f0085d81235d8e1c06798dc341a/include/grpc%2B%2B/impl/codegen/status_code_enum.h\n *\n * Important! The names of these identifiers matter because the string forms\n * are used for reverse lookups from the webchannel stream. Do NOT change the\n * names of these identifiers or change this into a const enum.\n */ var ii, ri;\n\n/**\n * Determines whether an error code represents a permanent error when received\n * in response to a non-write operation.\n *\n * See isPermanentWriteError for classifying write errors.\n */\nfunction oi(t) {\n switch (t) {\n default:\n return O();\n\n case q.CANCELLED:\n case q.UNKNOWN:\n case q.DEADLINE_EXCEEDED:\n case q.RESOURCE_EXHAUSTED:\n case q.INTERNAL:\n case q.UNAVAILABLE:\n // Unauthenticated means something went wrong with our token and we need\n // to retry with new credentials which will happen automatically.\n case q.UNAUTHENTICATED:\n return !1;\n\n case q.INVALID_ARGUMENT:\n case q.NOT_FOUND:\n case q.ALREADY_EXISTS:\n case q.PERMISSION_DENIED:\n case q.FAILED_PRECONDITION:\n // Aborted might be retried in some scenarios, but that is dependant on\n // the context and should handled individually by the calling code.\n // See https://cloud.google.com/apis/design/errors.\n case q.ABORTED:\n case q.OUT_OF_RANGE:\n case q.UNIMPLEMENTED:\n case q.DATA_LOSS:\n return !0;\n }\n}\n\n/**\n * Determines whether an error code represents a permanent error when received\n * in response to a write operation.\n *\n * Write operations must be handled specially because as of b/119437764, ABORTED\n * errors on the write stream should be retried too (even though ABORTED errors\n * are not generally retryable).\n *\n * Note that during the initial handshake on the write stream an ABORTED error\n * signals that we should discard our stream token (i.e. it is permanent). This\n * means a handshake error should be classified with isPermanentError, above.\n */\n/**\n * Maps an error Code from GRPC status code number, like 0, 1, or 14. These\n * are not the same as HTTP status codes.\n *\n * @returns The Code equivalent to the given GRPC status code. Fails if there\n * is no match.\n */\nfunction ui(t) {\n if (void 0 === t) \n // This shouldn't normally happen, but in certain error cases (like trying\n // to send invalid proto messages) we may get an error with no GRPC code.\n return k(\"GRPC error has no .code\"), q.UNKNOWN;\n switch (t) {\n case ii.OK:\n return q.OK;\n\n case ii.CANCELLED:\n return q.CANCELLED;\n\n case ii.UNKNOWN:\n return q.UNKNOWN;\n\n case ii.DEADLINE_EXCEEDED:\n return q.DEADLINE_EXCEEDED;\n\n case ii.RESOURCE_EXHAUSTED:\n return q.RESOURCE_EXHAUSTED;\n\n case ii.INTERNAL:\n return q.INTERNAL;\n\n case ii.UNAVAILABLE:\n return q.UNAVAILABLE;\n\n case ii.UNAUTHENTICATED:\n return q.UNAUTHENTICATED;\n\n case ii.INVALID_ARGUMENT:\n return q.INVALID_ARGUMENT;\n\n case ii.NOT_FOUND:\n return q.NOT_FOUND;\n\n case ii.ALREADY_EXISTS:\n return q.ALREADY_EXISTS;\n\n case ii.PERMISSION_DENIED:\n return q.PERMISSION_DENIED;\n\n case ii.FAILED_PRECONDITION:\n return q.FAILED_PRECONDITION;\n\n case ii.ABORTED:\n return q.ABORTED;\n\n case ii.OUT_OF_RANGE:\n return q.OUT_OF_RANGE;\n\n case ii.UNIMPLEMENTED:\n return q.UNIMPLEMENTED;\n\n case ii.DATA_LOSS:\n return q.DATA_LOSS;\n\n default:\n return O();\n }\n}\n\n/**\n * Converts an HTTP response's error status to the equivalent error code.\n *\n * @param status - An HTTP error response status (\"FAILED_PRECONDITION\",\n * \"UNKNOWN\", etc.)\n * @returns The equivalent Code. Non-matching responses are mapped to\n * Code.UNKNOWN.\n */ (ri = ii || (ii = {}))[ri.OK = 0] = \"OK\", ri[ri.CANCELLED = 1] = \"CANCELLED\", \nri[ri.UNKNOWN = 2] = \"UNKNOWN\", ri[ri.INVALID_ARGUMENT = 3] = \"INVALID_ARGUMENT\", \nri[ri.DEADLINE_EXCEEDED = 4] = \"DEADLINE_EXCEEDED\", ri[ri.NOT_FOUND = 5] = \"NOT_FOUND\", \nri[ri.ALREADY_EXISTS = 6] = \"ALREADY_EXISTS\", ri[ri.PERMISSION_DENIED = 7] = \"PERMISSION_DENIED\", \nri[ri.UNAUTHENTICATED = 16] = \"UNAUTHENTICATED\", ri[ri.RESOURCE_EXHAUSTED = 8] = \"RESOURCE_EXHAUSTED\", \nri[ri.FAILED_PRECONDITION = 9] = \"FAILED_PRECONDITION\", ri[ri.ABORTED = 10] = \"ABORTED\", \nri[ri.OUT_OF_RANGE = 11] = \"OUT_OF_RANGE\", ri[ri.UNIMPLEMENTED = 12] = \"UNIMPLEMENTED\", \nri[ri.INTERNAL = 13] = \"INTERNAL\", ri[ri.UNAVAILABLE = 14] = \"UNAVAILABLE\", ri[ri.DATA_LOSS = 15] = \"DATA_LOSS\";\n\n/**\n * @license\n * Copyright 2023 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * Manages \"testing hooks\", hooks into the internals of the SDK to verify\n * internal state and events during integration tests. Do not use this class\n * except for testing purposes.\n *\n * There are two ways to retrieve the global singleton instance of this class:\n * 1. The `instance` property, which returns null if the global singleton\n * instance has not been created. Use this property if the caller should\n * \"do nothing\" if there are no testing hooks registered, such as when\n * delivering an event to notify registered callbacks.\n * 2. The `getOrCreateInstance()` method, which creates the global singleton\n * instance if it has not been created. Use this method if the instance is\n * needed to, for example, register a callback.\n *\n * @internal\n */\nclass ci {\n constructor() {\n this.onExistenceFilterMismatchCallbacks = new Map;\n }\n /**\n * Returns the singleton instance of this class, or null if it has not been\n * initialized.\n */ static get instance() {\n return ai;\n }\n /**\n * Returns the singleton instance of this class, creating it if is has never\n * been created before.\n */ static getOrCreateInstance() {\n return null === ai && (ai = new ci), ai;\n }\n /**\n * Registers a callback to be notified when an existence filter mismatch\n * occurs in the Watch listen stream.\n *\n * The relative order in which callbacks are notified is unspecified; do not\n * rely on any particular ordering. If a given callback is registered multiple\n * times then it will be notified multiple times, once per registration.\n *\n * @param callback the callback to invoke upon existence filter mismatch.\n *\n * @return a function that, when called, unregisters the given callback; only\n * the first invocation of the returned function does anything; all subsequent\n * invocations do nothing.\n */ onExistenceFilterMismatch(t) {\n const e = Symbol();\n return this.onExistenceFilterMismatchCallbacks.set(e, t), () => this.onExistenceFilterMismatchCallbacks.delete(e);\n }\n /**\n * Invokes all currently-registered `onExistenceFilterMismatch` callbacks.\n * @param info Information about the existence filter mismatch.\n */ notifyOnExistenceFilterMismatch(t) {\n this.onExistenceFilterMismatchCallbacks.forEach((e => e(t)));\n }\n}\n\n/** The global singleton instance of `TestingHooks`. */ let ai = null;\n\n/**\n * @license\n * Copyright 2023 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * An instance of the Platform's 'TextEncoder' implementation.\n */ function hi() {\n return new TextEncoder;\n}\n\n/**\n * An instance of the Platform's 'TextDecoder' implementation.\n */\n/**\n * @license\n * Copyright 2022 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nconst li = new Integer([ 4294967295, 4294967295 ], 0);\n\n// Hash a string using md5 hashing algorithm.\nfunction fi(t) {\n const e = hi().encode(t), n = new Md5;\n return n.update(e), new Uint8Array(n.digest());\n}\n\n// Interpret the 16 bytes array as two 64-bit unsigned integers, encoded using\n// 2’s complement using little endian.\nfunction di(t) {\n const e = new DataView(t.buffer), n = e.getUint32(0, /* littleEndian= */ !0), s = e.getUint32(4, /* littleEndian= */ !0), i = e.getUint32(8, /* littleEndian= */ !0), r = e.getUint32(12, /* littleEndian= */ !0);\n return [ new Integer([ n, s ], 0), new Integer([ i, r ], 0) ];\n}\n\nclass wi {\n constructor(t, e, n) {\n if (this.bitmap = t, this.padding = e, this.hashCount = n, e < 0 || e >= 8) throw new _i(`Invalid padding: ${e}`);\n if (n < 0) throw new _i(`Invalid hash count: ${n}`);\n if (t.length > 0 && 0 === this.hashCount) \n // Only empty bloom filter can have 0 hash count.\n throw new _i(`Invalid hash count: ${n}`);\n if (0 === t.length && 0 !== e) \n // Empty bloom filter should have 0 padding.\n throw new _i(`Invalid padding when bitmap length is 0: ${e}`);\n this.It = 8 * t.length - e, \n // Set the bit count in Integer to avoid repetition in mightContain().\n this.Tt = Integer.fromNumber(this.It);\n }\n // Calculate the ith hash value based on the hashed 64bit integers,\n // and calculate its corresponding bit index in the bitmap to be checked.\n Et(t, e, n) {\n // Calculate hashed value h(i) = h1 + (i * h2).\n let s = t.add(e.multiply(Integer.fromNumber(n)));\n // Wrap if hash value overflow 64bit.\n return 1 === s.compare(li) && (s = new Integer([ s.getBits(0), s.getBits(1) ], 0)), \n s.modulo(this.Tt).toNumber();\n }\n // Return whether the bit on the given index in the bitmap is set to 1.\n At(t) {\n return 0 != (this.bitmap[Math.floor(t / 8)] & 1 << t % 8);\n }\n vt(t) {\n // Empty bitmap should always return false on membership check.\n if (0 === this.It) return !1;\n const e = fi(t), [n, s] = di(e);\n for (let t = 0; t < this.hashCount; t++) {\n const e = this.Et(n, s, t);\n if (!this.At(e)) return !1;\n }\n return !0;\n }\n /** Create bloom filter for testing purposes only. */ static create(t, e, n) {\n const s = t % 8 == 0 ? 0 : 8 - t % 8, i = new Uint8Array(Math.ceil(t / 8)), r = new wi(i, s, e);\n return n.forEach((t => r.insert(t))), r;\n }\n insert(t) {\n if (0 === this.It) return;\n const e = fi(t), [n, s] = di(e);\n for (let t = 0; t < this.hashCount; t++) {\n const e = this.Et(n, s, t);\n this.Rt(e);\n }\n }\n Rt(t) {\n const e = Math.floor(t / 8), n = t % 8;\n this.bitmap[e] |= 1 << n;\n }\n}\n\nclass _i extends Error {\n constructor() {\n super(...arguments), this.name = \"BloomFilterError\";\n }\n}\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * An event from the RemoteStore. It is split into targetChanges (changes to the\n * state or the set of documents in our watched targets) and documentUpdates\n * (changes to the actual documents).\n */ class mi {\n constructor(\n /**\n * The snapshot version this event brings us up to, or MIN if not set.\n */\n t, \n /**\n * A map from target to changes to the target. See TargetChange.\n */\n e, \n /**\n * A map of targets that is known to be inconsistent, and the purpose for\n * re-listening. Listens for these targets should be re-established without\n * resume tokens.\n */\n n, \n /**\n * A set of which documents have changed or been deleted, along with the\n * doc's new values (if not deleted).\n */\n s, \n /**\n * A set of which document updates are due only to limbo resolution targets.\n */\n i) {\n this.snapshotVersion = t, this.targetChanges = e, this.targetMismatches = n, this.documentUpdates = s, \n this.resolvedLimboDocuments = i;\n }\n /**\n * HACK: Views require RemoteEvents in order to determine whether the view is\n * CURRENT, but secondary tabs don't receive remote events. So this method is\n * used to create a synthesized RemoteEvent that can be used to apply a\n * CURRENT status change to a View, for queries executed in a different tab.\n */\n // PORTING NOTE: Multi-tab only\n static createSynthesizedRemoteEventForCurrentChange(t, e, n) {\n const s = new Map;\n return s.set(t, gi.createSynthesizedTargetChangeForCurrentChange(t, e, n)), new mi(rt.min(), s, new pe(et), cs(), gs());\n }\n}\n\n/**\n * A TargetChange specifies the set of changes for a specific target as part of\n * a RemoteEvent. These changes track which documents are added, modified or\n * removed, as well as the target's resume token and whether the target is\n * marked CURRENT.\n * The actual changes *to* documents are not part of the TargetChange since\n * documents may be part of multiple targets.\n */ class gi {\n constructor(\n /**\n * An opaque, server-assigned token that allows watching a query to be resumed\n * after disconnecting without retransmitting all the data that matches the\n * query. The resume token essentially identifies a point in time from which\n * the server should resume sending results.\n */\n t, \n /**\n * The \"current\" (synced) status of this target. Note that \"current\"\n * has special meaning in the RPC protocol that implies that a target is\n * both up-to-date and consistent with the rest of the watch stream.\n */\n e, \n /**\n * The set of documents that were newly assigned to this target as part of\n * this remote event.\n */\n n, \n /**\n * The set of documents that were already assigned to this target but received\n * an update during this remote event.\n */\n s, \n /**\n * The set of documents that were removed from this target as part of this\n * remote event.\n */\n i) {\n this.resumeToken = t, this.current = e, this.addedDocuments = n, this.modifiedDocuments = s, \n this.removedDocuments = i;\n }\n /**\n * This method is used to create a synthesized TargetChanges that can be used to\n * apply a CURRENT status change to a View (for queries executed in a different\n * tab) or for new queries (to raise snapshots with correct CURRENT status).\n */ static createSynthesizedTargetChangeForCurrentChange(t, e, n) {\n return new gi(n, e, gs(), gs(), gs());\n }\n}\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * Represents a changed document and a list of target ids to which this change\n * applies.\n *\n * If document has been deleted NoDocument will be provided.\n */ class yi {\n constructor(\n /** The new document applies to all of these targets. */\n t, \n /** The new document is removed from all of these targets. */\n e, \n /** The key of the document for this change. */\n n, \n /**\n * The new document or NoDocument if it was deleted. Is null if the\n * document went out of view without the server sending a new document.\n */\n s) {\n this.Pt = t, this.removedTargetIds = e, this.key = n, this.bt = s;\n }\n}\n\nclass pi {\n constructor(t, e) {\n this.targetId = t, this.Vt = e;\n }\n}\n\nclass Ii {\n constructor(\n /** What kind of change occurred to the watch target. */\n t, \n /** The target IDs that were added/removed/set. */\n e, \n /**\n * An opaque, server-assigned token that allows watching a target to be\n * resumed after disconnecting without retransmitting all the data that\n * matches the target. The resume token essentially identifies a point in\n * time from which the server should resume sending results.\n */\n n = Ve.EMPTY_BYTE_STRING\n /** An RPC error indicating why the watch failed. */ , s = null) {\n this.state = t, this.targetIds = e, this.resumeToken = n, this.cause = s;\n }\n}\n\n/** Tracks the internal state of a Watch target. */ class Ti {\n constructor() {\n /**\n * The number of pending responses (adds or removes) that we are waiting on.\n * We only consider targets active that have no pending responses.\n */\n this.St = 0, \n /**\n * Keeps track of the document changes since the last raised snapshot.\n *\n * These changes are continuously updated as we receive document updates and\n * always reflect the current set of changes against the last issued snapshot.\n */\n this.Dt = vi(), \n /** See public getters for explanations of these fields. */\n this.Ct = Ve.EMPTY_BYTE_STRING, this.xt = !1, \n /**\n * Whether this target state should be included in the next snapshot. We\n * initialize to true so that newly-added targets are included in the next\n * RemoteEvent.\n */\n this.Nt = !0;\n }\n /**\n * Whether this target has been marked 'current'.\n *\n * 'Current' has special meaning in the RPC protocol: It implies that the\n * Watch backend has sent us all changes up to the point at which the target\n * was added and that the target is consistent with the rest of the watch\n * stream.\n */ get current() {\n return this.xt;\n }\n /** The last resume token sent to us for this target. */ get resumeToken() {\n return this.Ct;\n }\n /** Whether this target has pending target adds or target removes. */ get kt() {\n return 0 !== this.St;\n }\n /** Whether we have modified any state that should trigger a snapshot. */ get Mt() {\n return this.Nt;\n }\n /**\n * Applies the resume token to the TargetChange, but only when it has a new\n * value. Empty resumeTokens are discarded.\n */ $t(t) {\n t.approximateByteSize() > 0 && (this.Nt = !0, this.Ct = t);\n }\n /**\n * Creates a target change from the current set of changes.\n *\n * To reset the document changes after raising this snapshot, call\n * `clearPendingChanges()`.\n */ Ot() {\n let t = gs(), e = gs(), n = gs();\n return this.Dt.forEach(((s, i) => {\n switch (i) {\n case 0 /* ChangeType.Added */ :\n t = t.add(s);\n break;\n\n case 2 /* ChangeType.Modified */ :\n e = e.add(s);\n break;\n\n case 1 /* ChangeType.Removed */ :\n n = n.add(s);\n break;\n\n default:\n O();\n }\n })), new gi(this.Ct, this.xt, t, e, n);\n }\n /**\n * Resets the document changes and sets `hasPendingChanges` to false.\n */ Ft() {\n this.Nt = !1, this.Dt = vi();\n }\n Bt(t, e) {\n this.Nt = !0, this.Dt = this.Dt.insert(t, e);\n }\n Lt(t) {\n this.Nt = !0, this.Dt = this.Dt.remove(t);\n }\n qt() {\n this.St += 1;\n }\n Ut() {\n this.St -= 1;\n }\n Kt() {\n this.Nt = !0, this.xt = !0;\n }\n}\n\n/**\n * A helper class to accumulate watch changes into a RemoteEvent.\n */\nclass Ei {\n constructor(t) {\n this.Gt = t, \n /** The internal state of all tracked targets. */\n this.Qt = new Map, \n /** Keeps track of the documents to update since the last raised snapshot. */\n this.jt = cs(), \n /** A mapping of document keys to their set of target IDs. */\n this.zt = Ai(), \n /**\n * A map of targets with existence filter mismatches. These targets are\n * known to be inconsistent and their listens needs to be re-established by\n * RemoteStore.\n */\n this.Wt = new pe(et);\n }\n /**\n * Processes and adds the DocumentWatchChange to the current set of changes.\n */ Ht(t) {\n for (const e of t.Pt) t.bt && t.bt.isFoundDocument() ? this.Jt(e, t.bt) : this.Yt(e, t.key, t.bt);\n for (const e of t.removedTargetIds) this.Yt(e, t.key, t.bt);\n }\n /** Processes and adds the WatchTargetChange to the current set of changes. */ Xt(t) {\n this.forEachTarget(t, (e => {\n const n = this.Zt(e);\n switch (t.state) {\n case 0 /* WatchTargetChangeState.NoChange */ :\n this.te(e) && n.$t(t.resumeToken);\n break;\n\n case 1 /* WatchTargetChangeState.Added */ :\n // We need to decrement the number of pending acks needed from watch\n // for this targetId.\n n.Ut(), n.kt || \n // We have a freshly added target, so we need to reset any state\n // that we had previously. This can happen e.g. when remove and add\n // back a target for existence filter mismatches.\n n.Ft(), n.$t(t.resumeToken);\n break;\n\n case 2 /* WatchTargetChangeState.Removed */ :\n // We need to keep track of removed targets to we can post-filter and\n // remove any target changes.\n // We need to decrement the number of pending acks needed from watch\n // for this targetId.\n n.Ut(), n.kt || this.removeTarget(e);\n break;\n\n case 3 /* WatchTargetChangeState.Current */ :\n this.te(e) && (n.Kt(), n.$t(t.resumeToken));\n break;\n\n case 4 /* WatchTargetChangeState.Reset */ :\n this.te(e) && (\n // Reset the target and synthesizes removes for all existing\n // documents. The backend will re-add any documents that still\n // match the target before it sends the next global snapshot.\n this.ee(e), n.$t(t.resumeToken));\n break;\n\n default:\n O();\n }\n }));\n }\n /**\n * Iterates over all targetIds that the watch change applies to: either the\n * targetIds explicitly listed in the change or the targetIds of all currently\n * active targets.\n */ forEachTarget(t, e) {\n t.targetIds.length > 0 ? t.targetIds.forEach(e) : this.Qt.forEach(((t, n) => {\n this.te(n) && e(n);\n }));\n }\n /**\n * Handles existence filters and synthesizes deletes for filter mismatches.\n * Targets that are invalidated by filter mismatches are added to\n * `pendingTargetResets`.\n */ ne(t) {\n var e;\n const n = t.targetId, s = t.Vt.count, i = this.se(n);\n if (i) {\n const r = i.target;\n if (Fn(r)) if (0 === s) {\n // The existence filter told us the document does not exist. We deduce\n // that this document does not exist and apply a deleted document to\n // our updates. Without applying this deleted document there might be\n // another query that will raise this document as part of a snapshot\n // until it is resolved, essentially exposing inconsistency between\n // queries.\n const t = new ht(r.path);\n this.Yt(n, t, an.newNoDocument(t, rt.min()));\n } else F(1 === s); else {\n const i = this.ie(n);\n // Existence filter mismatch. Mark the documents as being in limbo, and\n // raise a snapshot with `isFromCache:true`.\n if (i !== s) {\n // Apply bloom filter to identify and mark removed documents.\n const s = this.re(t, i);\n if (0 /* BloomFilterApplicationStatus.Success */ !== s) {\n // If bloom filter application fails, we reset the mapping and\n // trigger re-run of the query.\n this.ee(n);\n const t = 2 /* BloomFilterApplicationStatus.FalsePositive */ === s ? \"TargetPurposeExistenceFilterMismatchBloom\" /* TargetPurpose.ExistenceFilterMismatchBloom */ : \"TargetPurposeExistenceFilterMismatch\" /* TargetPurpose.ExistenceFilterMismatch */;\n this.Wt = this.Wt.insert(n, t);\n }\n null === (e = ci.instance) || void 0 === e || e.notifyOnExistenceFilterMismatch(function(t, e, n) {\n var s, i, r, o, u, c;\n const a = {\n localCacheCount: e,\n existenceFilterCount: n.count\n }, h = n.unchangedNames;\n h && (a.bloomFilter = {\n applied: 0 /* BloomFilterApplicationStatus.Success */ === t,\n hashCount: null !== (s = null == h ? void 0 : h.hashCount) && void 0 !== s ? s : 0,\n bitmapLength: null !== (o = null === (r = null === (i = null == h ? void 0 : h.bits) || void 0 === i ? void 0 : i.bitmap) || void 0 === r ? void 0 : r.length) && void 0 !== o ? o : 0,\n padding: null !== (c = null === (u = null == h ? void 0 : h.bits) || void 0 === u ? void 0 : u.padding) && void 0 !== c ? c : 0\n });\n return a;\n }\n /**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */ (s, i, t.Vt));\n }\n }\n }\n }\n /**\n * Apply bloom filter to remove the deleted documents, and return the\n * application status.\n */ re(t, e) {\n const {unchangedNames: n, count: s} = t.Vt;\n if (!n || !n.bits) return 1 /* BloomFilterApplicationStatus.Skipped */;\n const {bits: {bitmap: i = \"\", padding: r = 0}, hashCount: o = 0} = n;\n let u, c;\n try {\n u = xe(i).toUint8Array();\n } catch (t) {\n if (t instanceof Pe) return M(\"Decoding the base64 bloom filter in existence filter failed (\" + t.message + \"); ignoring the bloom filter and falling back to full re-query.\"), \n 1 /* BloomFilterApplicationStatus.Skipped */;\n throw t;\n }\n try {\n // BloomFilter throws error if the inputs are invalid.\n c = new wi(u, r, o);\n } catch (t) {\n return M(t instanceof _i ? \"BloomFilter error: \" : \"Applying bloom filter failed: \", t), \n 1 /* BloomFilterApplicationStatus.Skipped */;\n }\n if (0 === c.It) return 1 /* BloomFilterApplicationStatus.Skipped */;\n return s !== e - this.oe(t.targetId, c) ? 2 /* BloomFilterApplicationStatus.FalsePositive */ : 0 /* BloomFilterApplicationStatus.Success */;\n }\n /**\n * Filter out removed documents based on bloom filter membership result and\n * return number of documents removed.\n */ oe(t, e) {\n const n = this.Gt.getRemoteKeysForTarget(t);\n let s = 0;\n return n.forEach((n => {\n const i = this.Gt.ue(), r = `projects/${i.projectId}/databases/${i.database}/documents/${n.path.canonicalString()}`;\n e.vt(r) || (this.Yt(t, n, /*updatedDocument=*/ null), s++);\n })), s;\n }\n /**\n * Converts the currently accumulated state into a remote event at the\n * provided snapshot version. Resets the accumulated changes before returning.\n */ ce(t) {\n const e = new Map;\n this.Qt.forEach(((n, s) => {\n const i = this.se(s);\n if (i) {\n if (n.current && Fn(i.target)) {\n // Document queries for document that don't exist can produce an empty\n // result set. To update our local cache, we synthesize a document\n // delete if we have not previously received the document. This\n // resolves the limbo state of the document, removing it from\n // limboDocumentRefs.\n // TODO(dimond): Ideally we would have an explicit lookup target\n // instead resulting in an explicit delete message and we could\n // remove this special logic.\n const e = new ht(i.target.path);\n null !== this.jt.get(e) || this.ae(s, e) || this.Yt(s, e, an.newNoDocument(e, t));\n }\n n.Mt && (e.set(s, n.Ot()), n.Ft());\n }\n }));\n let n = gs();\n // We extract the set of limbo-only document updates as the GC logic\n // special-cases documents that do not appear in the target cache.\n \n // TODO(gsoltis): Expand on this comment once GC is available in the JS\n // client.\n this.zt.forEach(((t, e) => {\n let s = !0;\n e.forEachWhile((t => {\n const e = this.se(t);\n return !e || \"TargetPurposeLimboResolution\" /* TargetPurpose.LimboResolution */ === e.purpose || (s = !1, \n !1);\n })), s && (n = n.add(t));\n })), this.jt.forEach(((e, n) => n.setReadTime(t)));\n const s = new mi(t, e, this.Wt, this.jt, n);\n return this.jt = cs(), this.zt = Ai(), this.Wt = new pe(et), s;\n }\n /**\n * Adds the provided document to the internal list of document updates and\n * its document key to the given target's mapping.\n */\n // Visible for testing.\n Jt(t, e) {\n if (!this.te(t)) return;\n const n = this.ae(t, e.key) ? 2 /* ChangeType.Modified */ : 0 /* ChangeType.Added */;\n this.Zt(t).Bt(e.key, n), this.jt = this.jt.insert(e.key, e), this.zt = this.zt.insert(e.key, this.he(e.key).add(t));\n }\n /**\n * Removes the provided document from the target mapping. If the\n * document no longer matches the target, but the document's state is still\n * known (e.g. we know that the document was deleted or we received the change\n * that caused the filter mismatch), the new document can be provided\n * to update the remote document cache.\n */\n // Visible for testing.\n Yt(t, e, n) {\n if (!this.te(t)) return;\n const s = this.Zt(t);\n this.ae(t, e) ? s.Bt(e, 1 /* ChangeType.Removed */) : \n // The document may have entered and left the target before we raised a\n // snapshot, so we can just ignore the change.\n s.Lt(e), this.zt = this.zt.insert(e, this.he(e).delete(t)), n && (this.jt = this.jt.insert(e, n));\n }\n removeTarget(t) {\n this.Qt.delete(t);\n }\n /**\n * Returns the current count of documents in the target. This includes both\n * the number of documents that the LocalStore considers to be part of the\n * target as well as any accumulated changes.\n */ ie(t) {\n const e = this.Zt(t).Ot();\n return this.Gt.getRemoteKeysForTarget(t).size + e.addedDocuments.size - e.removedDocuments.size;\n }\n /**\n * Increment the number of acks needed from watch before we can consider the\n * server to be 'in-sync' with the client's active targets.\n */ qt(t) {\n this.Zt(t).qt();\n }\n Zt(t) {\n let e = this.Qt.get(t);\n return e || (e = new Ti, this.Qt.set(t, e)), e;\n }\n he(t) {\n let e = this.zt.get(t);\n return e || (e = new Ee(et), this.zt = this.zt.insert(t, e)), e;\n }\n /**\n * Verifies that the user is still interested in this target (by calling\n * `getTargetDataForTarget()`) and that we are not waiting for pending ADDs\n * from watch.\n */ te(t) {\n const e = null !== this.se(t);\n return e || N(\"WatchChangeAggregator\", \"Detected inactive target\", t), e;\n }\n /**\n * Returns the TargetData for an active target (i.e. a target that the user\n * is still interested in that has no outstanding target change requests).\n */ se(t) {\n const e = this.Qt.get(t);\n return e && e.kt ? null : this.Gt.le(t);\n }\n /**\n * Resets the state of a Watch target to its initial state (e.g. sets\n * 'current' to false, clears the resume token and removes its target mapping\n * from all documents).\n */ ee(t) {\n this.Qt.set(t, new Ti);\n this.Gt.getRemoteKeysForTarget(t).forEach((e => {\n this.Yt(t, e, /*updatedDocument=*/ null);\n }));\n }\n /**\n * Returns whether the LocalStore considers the document to be part of the\n * specified target.\n */ ae(t, e) {\n return this.Gt.getRemoteKeysForTarget(t).has(e);\n }\n}\n\nfunction Ai() {\n return new pe(ht.comparator);\n}\n\nfunction vi() {\n return new pe(ht.comparator);\n}\n\nconst Ri = (() => {\n const t = {\n asc: \"ASCENDING\",\n desc: \"DESCENDING\"\n };\n return t;\n})(), Pi = (() => {\n const t = {\n \"<\": \"LESS_THAN\",\n \"<=\": \"LESS_THAN_OR_EQUAL\",\n \">\": \"GREATER_THAN\",\n \">=\": \"GREATER_THAN_OR_EQUAL\",\n \"==\": \"EQUAL\",\n \"!=\": \"NOT_EQUAL\",\n \"array-contains\": \"ARRAY_CONTAINS\",\n in: \"IN\",\n \"not-in\": \"NOT_IN\",\n \"array-contains-any\": \"ARRAY_CONTAINS_ANY\"\n };\n return t;\n})(), bi = (() => {\n const t = {\n and: \"AND\",\n or: \"OR\"\n };\n return t;\n})();\n\n/**\n * This class generates JsonObject values for the Datastore API suitable for\n * sending to either GRPC stub methods or via the JSON/HTTP REST API.\n *\n * The serializer supports both Protobuf.js and Proto3 JSON formats. By\n * setting `useProto3Json` to true, the serializer will use the Proto3 JSON\n * format.\n *\n * For a description of the Proto3 JSON format check\n * https://developers.google.com/protocol-buffers/docs/proto3#json\n *\n * TODO(klimt): We can remove the databaseId argument if we keep the full\n * resource name in documents.\n */\nclass Vi {\n constructor(t, e) {\n this.databaseId = t, this.useProto3Json = e;\n }\n}\n\n/**\n * Returns a value for a number (or null) that's appropriate to put into\n * a google.protobuf.Int32Value proto.\n * DO NOT USE THIS FOR ANYTHING ELSE.\n * This method cheats. It's typed as returning \"number\" because that's what\n * our generated proto interfaces say Int32Value must be. But GRPC actually\n * expects a { value: } struct.\n */\nfunction Si(t, e) {\n return t.useProto3Json || Ft(e) ? e : {\n value: e\n };\n}\n\n/**\n * Returns a number (or null) from a google.protobuf.Int32Value proto.\n */\n/**\n * Returns a value for a Date that's appropriate to put into a proto.\n */\nfunction Di(t, e) {\n if (t.useProto3Json) {\n return `${new Date(1e3 * e.seconds).toISOString().replace(/\\.\\d*/, \"\").replace(\"Z\", \"\")}.${(\"000000000\" + e.nanoseconds).slice(-9)}Z`;\n }\n return {\n seconds: \"\" + e.seconds,\n nanos: e.nanoseconds\n };\n}\n\n/**\n * Returns a value for bytes that's appropriate to put in a proto.\n *\n * Visible for testing.\n */\nfunction Ci(t, e) {\n return t.useProto3Json ? e.toBase64() : e.toUint8Array();\n}\n\n/**\n * Returns a ByteString based on the proto string value.\n */ function xi(t, e) {\n return Di(t, e.toTimestamp());\n}\n\nfunction Ni(t) {\n return F(!!t), rt.fromTimestamp(function(t) {\n const e = De(t);\n return new it(e.seconds, e.nanos);\n }(t));\n}\n\nfunction ki(t, e) {\n return function(t) {\n return new ut([ \"projects\", t.projectId, \"databases\", t.database ]);\n }(t).child(\"documents\").child(e).canonicalString();\n}\n\nfunction Mi(t) {\n const e = ut.fromString(t);\n return F(ur(e)), e;\n}\n\nfunction $i(t, e) {\n return ki(t.databaseId, e.path);\n}\n\nfunction Oi(t, e) {\n const n = Mi(e);\n if (n.get(1) !== t.databaseId.projectId) throw new U(q.INVALID_ARGUMENT, \"Tried to deserialize key from different project: \" + n.get(1) + \" vs \" + t.databaseId.projectId);\n if (n.get(3) !== t.databaseId.database) throw new U(q.INVALID_ARGUMENT, \"Tried to deserialize key from different database: \" + n.get(3) + \" vs \" + t.databaseId.database);\n return new ht(qi(n));\n}\n\nfunction Fi(t, e) {\n return ki(t.databaseId, e);\n}\n\nfunction Bi(t) {\n const e = Mi(t);\n // In v1beta1 queries for collections at the root did not have a trailing\n // \"/documents\". In v1 all resource paths contain \"/documents\". Preserve the\n // ability to read the v1beta1 form for compatibility with queries persisted\n // in the local target cache.\n return 4 === e.length ? ut.emptyPath() : qi(e);\n}\n\nfunction Li(t) {\n return new ut([ \"projects\", t.databaseId.projectId, \"databases\", t.databaseId.database ]).canonicalString();\n}\n\nfunction qi(t) {\n return F(t.length > 4 && \"documents\" === t.get(4)), t.popFirst(5);\n}\n\n/** Creates a Document proto from key and fields (but no create/update time) */ function Ui(t, e, n) {\n return {\n name: $i(t, e),\n fields: n.value.mapValue.fields\n };\n}\n\nfunction Ki(t, e, n) {\n const s = Oi(t, e.name), i = Ni(e.updateTime), r = e.createTime ? Ni(e.createTime) : rt.min(), o = new un({\n mapValue: {\n fields: e.fields\n }\n }), u = an.newFoundDocument(s, i, r, o);\n return n && u.setHasCommittedMutations(), n ? u.setHasCommittedMutations() : u;\n}\n\nfunction Gi(t, e) {\n return \"found\" in e ? function(t, e) {\n F(!!e.found), e.found.name, e.found.updateTime;\n const n = Oi(t, e.found.name), s = Ni(e.found.updateTime), i = e.found.createTime ? Ni(e.found.createTime) : rt.min(), r = new un({\n mapValue: {\n fields: e.found.fields\n }\n });\n return an.newFoundDocument(n, s, i, r);\n }(t, e) : \"missing\" in e ? function(t, e) {\n F(!!e.missing), F(!!e.readTime);\n const n = Oi(t, e.missing), s = Ni(e.readTime);\n return an.newNoDocument(n, s);\n }(t, e) : O();\n}\n\nfunction Qi(t, e) {\n let n;\n if (\"targetChange\" in e) {\n e.targetChange;\n // proto3 default value is unset in JSON (undefined), so use 'NO_CHANGE'\n // if unset\n const s = function(t) {\n return \"NO_CHANGE\" === t ? 0 /* WatchTargetChangeState.NoChange */ : \"ADD\" === t ? 1 /* WatchTargetChangeState.Added */ : \"REMOVE\" === t ? 2 /* WatchTargetChangeState.Removed */ : \"CURRENT\" === t ? 3 /* WatchTargetChangeState.Current */ : \"RESET\" === t ? 4 /* WatchTargetChangeState.Reset */ : O();\n }(e.targetChange.targetChangeType || \"NO_CHANGE\"), i = e.targetChange.targetIds || [], r = function(t, e) {\n return t.useProto3Json ? (F(void 0 === e || \"string\" == typeof e), Ve.fromBase64String(e || \"\")) : (F(void 0 === e || e instanceof Uint8Array), \n Ve.fromUint8Array(e || new Uint8Array));\n }(t, e.targetChange.resumeToken), o = e.targetChange.cause, u = o && function(t) {\n const e = void 0 === t.code ? q.UNKNOWN : ui(t.code);\n return new U(e, t.message || \"\");\n }(o);\n n = new Ii(s, i, r, u || null);\n } else if (\"documentChange\" in e) {\n e.documentChange;\n const s = e.documentChange;\n s.document, s.document.name, s.document.updateTime;\n const i = Oi(t, s.document.name), r = Ni(s.document.updateTime), o = s.document.createTime ? Ni(s.document.createTime) : rt.min(), u = new un({\n mapValue: {\n fields: s.document.fields\n }\n }), c = an.newFoundDocument(i, r, o, u), a = s.targetIds || [], h = s.removedTargetIds || [];\n n = new yi(a, h, c.key, c);\n } else if (\"documentDelete\" in e) {\n e.documentDelete;\n const s = e.documentDelete;\n s.document;\n const i = Oi(t, s.document), r = s.readTime ? Ni(s.readTime) : rt.min(), o = an.newNoDocument(i, r), u = s.removedTargetIds || [];\n n = new yi([], u, o.key, o);\n } else if (\"documentRemove\" in e) {\n e.documentRemove;\n const s = e.documentRemove;\n s.document;\n const i = Oi(t, s.document), r = s.removedTargetIds || [];\n n = new yi([], r, i, null);\n } else {\n if (!(\"filter\" in e)) return O();\n {\n e.filter;\n const t = e.filter;\n t.targetId;\n const {count: s = 0, unchangedNames: i} = t, r = new si(s, i), o = t.targetId;\n n = new pi(o, r);\n }\n }\n return n;\n}\n\nfunction ji(t, e) {\n let n;\n if (e instanceof js) n = {\n update: Ui(t, e.key, e.value)\n }; else if (e instanceof Ys) n = {\n delete: $i(t, e.key)\n }; else if (e instanceof zs) n = {\n update: Ui(t, e.key, e.data),\n updateMask: or(e.fieldMask)\n }; else {\n if (!(e instanceof Xs)) return O();\n n = {\n verify: $i(t, e.key)\n };\n }\n return e.fieldTransforms.length > 0 && (n.updateTransforms = e.fieldTransforms.map((t => function(t, e) {\n const n = e.transform;\n if (n instanceof bs) return {\n fieldPath: e.field.canonicalString(),\n setToServerValue: \"REQUEST_TIME\"\n };\n if (n instanceof Vs) return {\n fieldPath: e.field.canonicalString(),\n appendMissingElements: {\n values: n.elements\n }\n };\n if (n instanceof Ds) return {\n fieldPath: e.field.canonicalString(),\n removeAllFromArray: {\n values: n.elements\n }\n };\n if (n instanceof xs) return {\n fieldPath: e.field.canonicalString(),\n increment: n.gt\n };\n throw O();\n }(0, t)))), e.precondition.isNone || (n.currentDocument = function(t, e) {\n return void 0 !== e.updateTime ? {\n updateTime: xi(t, e.updateTime)\n } : void 0 !== e.exists ? {\n exists: e.exists\n } : O();\n }(t, e.precondition)), n;\n}\n\nfunction zi(t, e) {\n const n = e.currentDocument ? function(t) {\n return void 0 !== t.updateTime ? Fs.updateTime(Ni(t.updateTime)) : void 0 !== t.exists ? Fs.exists(t.exists) : Fs.none();\n }(e.currentDocument) : Fs.none(), s = e.updateTransforms ? e.updateTransforms.map((e => function(t, e) {\n let n = null;\n if (\"setToServerValue\" in e) F(\"REQUEST_TIME\" === e.setToServerValue), n = new bs; else if (\"appendMissingElements\" in e) {\n const t = e.appendMissingElements.values || [];\n n = new Vs(t);\n } else if (\"removeAllFromArray\" in e) {\n const t = e.removeAllFromArray.values || [];\n n = new Ds(t);\n } else \"increment\" in e ? n = new xs(t, e.increment) : O();\n const s = at.fromServerFormat(e.fieldPath);\n return new Ms(s, n);\n }(t, e))) : [];\n if (e.update) {\n e.update.name;\n const i = Oi(t, e.update.name), r = new un({\n mapValue: {\n fields: e.update.fields\n }\n });\n if (e.updateMask) {\n const t = function(t) {\n const e = t.fieldPaths || [];\n return new Re(e.map((t => at.fromServerFormat(t))));\n }(e.updateMask);\n return new zs(i, r, t, n, s);\n }\n return new js(i, r, n, s);\n }\n if (e.delete) {\n const s = Oi(t, e.delete);\n return new Ys(s, n);\n }\n if (e.verify) {\n const s = Oi(t, e.verify);\n return new Xs(s, n);\n }\n return O();\n}\n\nfunction Wi(t, e) {\n return t && t.length > 0 ? (F(void 0 !== e), t.map((t => function(t, e) {\n // NOTE: Deletes don't have an updateTime.\n let n = t.updateTime ? Ni(t.updateTime) : Ni(e);\n return n.isEqual(rt.min()) && (\n // The Firestore Emulator currently returns an update time of 0 for\n // deletes of non-existing documents (rather than null). This breaks the\n // test \"get deleted doc while offline with source=cache\" as NoDocuments\n // with version 0 are filtered by IndexedDb's RemoteDocumentCache.\n // TODO(#2149): Remove this when Emulator is fixed\n n = Ni(e)), new Os(n, t.transformResults || []);\n }(t, e)))) : [];\n}\n\nfunction Hi(t, e) {\n return {\n documents: [ Fi(t, e.path) ]\n };\n}\n\nfunction Ji(t, e) {\n // Dissect the path into parent, collectionId, and optional key filter.\n const n = {\n structuredQuery: {}\n }, s = e.path;\n null !== e.collectionGroup ? (n.parent = Fi(t, s), n.structuredQuery.from = [ {\n collectionId: e.collectionGroup,\n allDescendants: !0\n } ]) : (n.parent = Fi(t, s.popLast()), n.structuredQuery.from = [ {\n collectionId: s.lastSegment()\n } ]);\n const i = function(t) {\n if (0 === t.length) return;\n return rr(gn.create(t, \"and\" /* CompositeOperator.AND */));\n }(e.filters);\n i && (n.structuredQuery.where = i);\n const r = function(t) {\n if (0 === t.length) return;\n return t.map((t => \n // visible for testing\n function(t) {\n return {\n field: sr(t.field),\n direction: tr(t.dir)\n };\n }(t)));\n }(e.orderBy);\n r && (n.structuredQuery.orderBy = r);\n const o = Si(t, e.limit);\n var u;\n return null !== o && (n.structuredQuery.limit = o), e.startAt && (n.structuredQuery.startAt = {\n before: (u = e.startAt).inclusive,\n values: u.position\n }), e.endAt && (n.structuredQuery.endAt = function(t) {\n return {\n before: !t.inclusive,\n values: t.position\n };\n }(e.endAt)), n;\n}\n\nfunction Yi(t) {\n let e = Bi(t.parent);\n const n = t.structuredQuery, s = n.from ? n.from.length : 0;\n let i = null;\n if (s > 0) {\n F(1 === s);\n const t = n.from[0];\n t.allDescendants ? i = t.collectionId : e = e.child(t.collectionId);\n }\n let r = [];\n n.where && (r = function(t) {\n const e = Zi(t);\n if (e instanceof gn && In(e)) return e.getFilters();\n return [ e ];\n }(n.where));\n let o = [];\n n.orderBy && (o = n.orderBy.map((t => function(t) {\n return new dn(ir(t.field), \n // visible for testing\n function(t) {\n switch (t) {\n case \"ASCENDING\":\n return \"asc\" /* Direction.ASCENDING */;\n\n case \"DESCENDING\":\n return \"desc\" /* Direction.DESCENDING */;\n\n default:\n return;\n }\n }\n // visible for testing\n (t.direction));\n }\n // visible for testing\n (t))));\n let u = null;\n n.limit && (u = function(t) {\n let e;\n return e = \"object\" == typeof t ? t.value : t, Ft(e) ? null : e;\n }(n.limit));\n let c = null;\n n.startAt && (c = function(t) {\n const e = !!t.before, n = t.values || [];\n return new hn(n, e);\n }(n.startAt));\n let a = null;\n return n.endAt && (a = function(t) {\n const e = !t.before, n = t.values || [];\n return new hn(n, e);\n }\n // visible for testing\n (n.endAt)), Kn(e, i, o, r, u, \"F\" /* LimitType.First */ , c, a);\n}\n\nfunction Xi(t, e) {\n const n = function(t) {\n switch (t) {\n case \"TargetPurposeListen\" /* TargetPurpose.Listen */ :\n return null;\n\n case \"TargetPurposeExistenceFilterMismatch\" /* TargetPurpose.ExistenceFilterMismatch */ :\n return \"existence-filter-mismatch\";\n\n case \"TargetPurposeExistenceFilterMismatchBloom\" /* TargetPurpose.ExistenceFilterMismatchBloom */ :\n return \"existence-filter-mismatch-bloom\";\n\n case \"TargetPurposeLimboResolution\" /* TargetPurpose.LimboResolution */ :\n return \"limbo-document\";\n\n default:\n return O();\n }\n }(e.purpose);\n return null == n ? null : {\n \"goog-listen-tags\": n\n };\n}\n\nfunction Zi(t) {\n return void 0 !== t.unaryFilter ? function(t) {\n switch (t.unaryFilter.op) {\n case \"IS_NAN\":\n const e = ir(t.unaryFilter.field);\n return mn.create(e, \"==\" /* Operator.EQUAL */ , {\n doubleValue: NaN\n });\n\n case \"IS_NULL\":\n const n = ir(t.unaryFilter.field);\n return mn.create(n, \"==\" /* Operator.EQUAL */ , {\n nullValue: \"NULL_VALUE\"\n });\n\n case \"IS_NOT_NAN\":\n const s = ir(t.unaryFilter.field);\n return mn.create(s, \"!=\" /* Operator.NOT_EQUAL */ , {\n doubleValue: NaN\n });\n\n case \"IS_NOT_NULL\":\n const i = ir(t.unaryFilter.field);\n return mn.create(i, \"!=\" /* Operator.NOT_EQUAL */ , {\n nullValue: \"NULL_VALUE\"\n });\n\n default:\n return O();\n }\n }(t) : void 0 !== t.fieldFilter ? function(t) {\n return mn.create(ir(t.fieldFilter.field), function(t) {\n switch (t) {\n case \"EQUAL\":\n return \"==\" /* Operator.EQUAL */;\n\n case \"NOT_EQUAL\":\n return \"!=\" /* Operator.NOT_EQUAL */;\n\n case \"GREATER_THAN\":\n return \">\" /* Operator.GREATER_THAN */;\n\n case \"GREATER_THAN_OR_EQUAL\":\n return \">=\" /* Operator.GREATER_THAN_OR_EQUAL */;\n\n case \"LESS_THAN\":\n return \"<\" /* Operator.LESS_THAN */;\n\n case \"LESS_THAN_OR_EQUAL\":\n return \"<=\" /* Operator.LESS_THAN_OR_EQUAL */;\n\n case \"ARRAY_CONTAINS\":\n return \"array-contains\" /* Operator.ARRAY_CONTAINS */;\n\n case \"IN\":\n return \"in\" /* Operator.IN */;\n\n case \"NOT_IN\":\n return \"not-in\" /* Operator.NOT_IN */;\n\n case \"ARRAY_CONTAINS_ANY\":\n return \"array-contains-any\" /* Operator.ARRAY_CONTAINS_ANY */;\n\n default:\n return O();\n }\n }(t.fieldFilter.op), t.fieldFilter.value);\n }(t) : void 0 !== t.compositeFilter ? function(t) {\n return gn.create(t.compositeFilter.filters.map((t => Zi(t))), function(t) {\n switch (t) {\n case \"AND\":\n return \"and\" /* CompositeOperator.AND */;\n\n case \"OR\":\n return \"or\" /* CompositeOperator.OR */;\n\n default:\n return O();\n }\n }(t.compositeFilter.op));\n }(t) : O();\n}\n\nfunction tr(t) {\n return Ri[t];\n}\n\nfunction er(t) {\n return Pi[t];\n}\n\nfunction nr(t) {\n return bi[t];\n}\n\nfunction sr(t) {\n return {\n fieldPath: t.canonicalString()\n };\n}\n\nfunction ir(t) {\n return at.fromServerFormat(t.fieldPath);\n}\n\nfunction rr(t) {\n return t instanceof mn ? function(t) {\n if (\"==\" /* Operator.EQUAL */ === t.op) {\n if (Xe(t.value)) return {\n unaryFilter: {\n field: sr(t.field),\n op: \"IS_NAN\"\n }\n };\n if (Ye(t.value)) return {\n unaryFilter: {\n field: sr(t.field),\n op: \"IS_NULL\"\n }\n };\n } else if (\"!=\" /* Operator.NOT_EQUAL */ === t.op) {\n if (Xe(t.value)) return {\n unaryFilter: {\n field: sr(t.field),\n op: \"IS_NOT_NAN\"\n }\n };\n if (Ye(t.value)) return {\n unaryFilter: {\n field: sr(t.field),\n op: \"IS_NOT_NULL\"\n }\n };\n }\n return {\n fieldFilter: {\n field: sr(t.field),\n op: er(t.op),\n value: t.value\n }\n };\n }(t) : t instanceof gn ? function(t) {\n const e = t.getFilters().map((t => rr(t)));\n if (1 === e.length) return e[0];\n return {\n compositeFilter: {\n op: nr(t.op),\n filters: e\n }\n };\n }(t) : O();\n}\n\nfunction or(t) {\n const e = [];\n return t.fields.forEach((t => e.push(t.canonicalString()))), {\n fieldPaths: e\n };\n}\n\nfunction ur(t) {\n // Resource names have at least 4 components (project ID, database ID)\n return t.length >= 4 && \"projects\" === t.get(0) && \"databases\" === t.get(2);\n}\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * An immutable set of metadata that the local store tracks for each target.\n */ class cr {\n constructor(\n /** The target being listened to. */\n t, \n /**\n * The target ID to which the target corresponds; Assigned by the\n * LocalStore for user listens and by the SyncEngine for limbo watches.\n */\n e, \n /** The purpose of the target. */\n n, \n /**\n * The sequence number of the last transaction during which this target data\n * was modified.\n */\n s, \n /** The latest snapshot version seen for this target. */\n i = rt.min()\n /**\n * The maximum snapshot version at which the associated view\n * contained no limbo documents.\n */ , r = rt.min()\n /**\n * An opaque, server-assigned token that allows watching a target to be\n * resumed after disconnecting without retransmitting all the data that\n * matches the target. The resume token essentially identifies a point in\n * time from which the server should resume sending results.\n */ , o = Ve.EMPTY_BYTE_STRING\n /**\n * The number of documents that last matched the query at the resume token or\n * read time. Documents are counted only when making a listen request with\n * resume token or read time, otherwise, keep it null.\n */ , u = null) {\n this.target = t, this.targetId = e, this.purpose = n, this.sequenceNumber = s, this.snapshotVersion = i, \n this.lastLimboFreeSnapshotVersion = r, this.resumeToken = o, this.expectedCount = u;\n }\n /** Creates a new target data instance with an updated sequence number. */ withSequenceNumber(t) {\n return new cr(this.target, this.targetId, this.purpose, t, this.snapshotVersion, this.lastLimboFreeSnapshotVersion, this.resumeToken, this.expectedCount);\n }\n /**\n * Creates a new target data instance with an updated resume token and\n * snapshot version.\n */ withResumeToken(t, e) {\n return new cr(this.target, this.targetId, this.purpose, this.sequenceNumber, e, this.lastLimboFreeSnapshotVersion, t, \n /* expectedCount= */ null);\n }\n /**\n * Creates a new target data instance with an updated expected count.\n */ withExpectedCount(t) {\n return new cr(this.target, this.targetId, this.purpose, this.sequenceNumber, this.snapshotVersion, this.lastLimboFreeSnapshotVersion, this.resumeToken, t);\n }\n /**\n * Creates a new target data instance with an updated last limbo free\n * snapshot version number.\n */ withLastLimboFreeSnapshotVersion(t) {\n return new cr(this.target, this.targetId, this.purpose, this.sequenceNumber, this.snapshotVersion, t, this.resumeToken, this.expectedCount);\n }\n}\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/** Serializer for values stored in the LocalStore. */ class ar {\n constructor(t) {\n this.fe = t;\n }\n}\n\n/** Decodes a remote document from storage locally to a Document. */ function hr(t, e) {\n let n;\n if (e.document) n = Ki(t.fe, e.document, !!e.hasCommittedMutations); else if (e.noDocument) {\n const t = ht.fromSegments(e.noDocument.path), s = wr(e.noDocument.readTime);\n n = an.newNoDocument(t, s), e.hasCommittedMutations && n.setHasCommittedMutations();\n } else {\n if (!e.unknownDocument) return O();\n {\n const t = ht.fromSegments(e.unknownDocument.path), s = wr(e.unknownDocument.version);\n n = an.newUnknownDocument(t, s);\n }\n }\n return e.readTime && n.setReadTime(function(t) {\n const e = new it(t[0], t[1]);\n return rt.fromTimestamp(e);\n }(e.readTime)), n;\n}\n\n/** Encodes a document for storage locally. */ function lr(t, e) {\n const n = e.key, s = {\n prefixPath: n.getCollectionPath().popLast().toArray(),\n collectionGroup: n.collectionGroup,\n documentId: n.path.lastSegment(),\n readTime: fr(e.readTime),\n hasCommittedMutations: e.hasCommittedMutations\n };\n if (e.isFoundDocument()) s.document = function(t, e) {\n return {\n name: $i(t, e.key),\n fields: e.data.value.mapValue.fields,\n updateTime: Di(t, e.version.toTimestamp()),\n createTime: Di(t, e.createTime.toTimestamp())\n };\n }(t.fe, e); else if (e.isNoDocument()) s.noDocument = {\n path: n.path.toArray(),\n readTime: dr(e.version)\n }; else {\n if (!e.isUnknownDocument()) return O();\n s.unknownDocument = {\n path: n.path.toArray(),\n version: dr(e.version)\n };\n }\n return s;\n}\n\nfunction fr(t) {\n const e = t.toTimestamp();\n return [ e.seconds, e.nanoseconds ];\n}\n\nfunction dr(t) {\n const e = t.toTimestamp();\n return {\n seconds: e.seconds,\n nanoseconds: e.nanoseconds\n };\n}\n\nfunction wr(t) {\n const e = new it(t.seconds, t.nanoseconds);\n return rt.fromTimestamp(e);\n}\n\n/** Encodes a batch of mutations into a DbMutationBatch for local storage. */\n/** Decodes a DbMutationBatch into a MutationBatch */\nfunction _r(t, e) {\n const n = (e.baseMutations || []).map((e => zi(t.fe, e)));\n // Squash old transform mutations into existing patch or set mutations.\n // The replacement of representing `transforms` with `update_transforms`\n // on the SDK means that old `transform` mutations stored in IndexedDB need\n // to be updated to `update_transforms`.\n // TODO(b/174608374): Remove this code once we perform a schema migration.\n for (let t = 0; t < e.mutations.length - 1; ++t) {\n const n = e.mutations[t];\n if (t + 1 < e.mutations.length && void 0 !== e.mutations[t + 1].transform) {\n const s = e.mutations[t + 1];\n n.updateTransforms = s.transform.fieldTransforms, e.mutations.splice(t + 1, 1), \n ++t;\n }\n }\n const s = e.mutations.map((e => zi(t.fe, e))), i = it.fromMillis(e.localWriteTimeMs);\n return new Zs(e.batchId, i, n, s);\n}\n\n/** Decodes a DbTarget into TargetData */ function mr(t) {\n const e = wr(t.readTime), n = void 0 !== t.lastLimboFreeSnapshotVersion ? wr(t.lastLimboFreeSnapshotVersion) : rt.min();\n let s;\n var i;\n return void 0 !== t.query.documents ? (F(1 === (i = t.query).documents.length), \n s = Jn(Gn(Bi(i.documents[0])))) : s = function(t) {\n return Jn(Yi(t));\n }(t.query), new cr(s, t.targetId, \"TargetPurposeListen\" /* TargetPurpose.Listen */ , t.lastListenSequenceNumber, e, n, Ve.fromBase64String(t.resumeToken));\n}\n\n/** Encodes TargetData into a DbTarget for storage locally. */ function gr(t, e) {\n const n = dr(e.snapshotVersion), s = dr(e.lastLimboFreeSnapshotVersion);\n let i;\n i = Fn(e.target) ? Hi(t.fe, e.target) : Ji(t.fe, e.target);\n // We can't store the resumeToken as a ByteString in IndexedDb, so we\n // convert it to a base64 string for storage.\n const r = e.resumeToken.toBase64();\n // lastListenSequenceNumber is always 0 until we do real GC.\n return {\n targetId: e.targetId,\n canonicalId: $n(e.target),\n readTime: n,\n resumeToken: r,\n lastListenSequenceNumber: e.sequenceNumber,\n lastLimboFreeSnapshotVersion: s,\n query: i\n };\n}\n\n/**\n * A helper function for figuring out what kind of query has been stored.\n */\n/**\n * Encodes a `BundledQuery` from bundle proto to a Query object.\n *\n * This reconstructs the original query used to build the bundle being loaded,\n * including features exists only in SDKs (for example: limit-to-last).\n */\nfunction yr(t) {\n const e = Yi({\n parent: t.parent,\n structuredQuery: t.structuredQuery\n });\n return \"LAST\" === t.limitType ? Xn(e, e.limit, \"L\" /* LimitType.Last */) : e;\n}\n\n/** Encodes a NamedQuery proto object to a NamedQuery model object. */\n/** Encodes a DbDocumentOverlay object to an Overlay model object. */\nfunction pr(t, e) {\n return new ei(e.largestBatchId, zi(t.fe, e.overlayMutation));\n}\n\n/** Decodes an Overlay model object into a DbDocumentOverlay object. */\n/**\n * Returns the DbDocumentOverlayKey corresponding to the given user and\n * document key.\n */\nfunction Ir(t, e) {\n const n = e.path.lastSegment();\n return [ t, qt(e.path.popLast()), n ];\n}\n\nfunction Tr(t, e, n, s) {\n return {\n indexId: t,\n uid: e.uid || \"\",\n sequenceNumber: n,\n readTime: dr(s.readTime),\n documentKey: qt(s.documentKey.path),\n largestBatchId: s.largestBatchId\n };\n}\n\n/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */ class Er {\n getBundleMetadata(t, e) {\n return Ar(t).get(e).next((t => {\n if (t) return {\n id: (e = t).bundleId,\n createTime: wr(e.createTime),\n version: e.version\n };\n /** Encodes a DbBundle to a BundleMetadata object. */\n var e;\n /** Encodes a BundleMetadata to a DbBundle. */ }));\n }\n saveBundleMetadata(t, e) {\n return Ar(t).put({\n bundleId: (n = e).id,\n createTime: dr(Ni(n.createTime)),\n version: n.version\n });\n var n;\n /** Encodes a DbNamedQuery to a NamedQuery. */ }\n getNamedQuery(t, e) {\n return vr(t).get(e).next((t => {\n if (t) return {\n name: (e = t).name,\n query: yr(e.bundledQuery),\n readTime: wr(e.readTime)\n };\n var e;\n /** Encodes a NamedQuery from a bundle proto to a DbNamedQuery. */ }));\n }\n saveNamedQuery(t, e) {\n return vr(t).put(function(t) {\n return {\n name: t.name,\n readTime: dr(Ni(t.readTime)),\n bundledQuery: t.bundledQuery\n };\n }(e));\n }\n}\n\n/**\n * Helper to get a typed SimpleDbStore for the bundles object store.\n */ function Ar(t) {\n return _e(t, \"bundles\");\n}\n\n/**\n * Helper to get a typed SimpleDbStore for the namedQueries object store.\n */ function vr(t) {\n return _e(t, \"namedQueries\");\n}\n\n/**\n * @license\n * Copyright 2022 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * Implementation of DocumentOverlayCache using IndexedDb.\n */ class Rr {\n /**\n * @param serializer - The document serializer.\n * @param userId - The userId for which we are accessing overlays.\n */\n constructor(t, e) {\n this.serializer = t, this.userId = e;\n }\n static de(t, e) {\n const n = e.uid || \"\";\n return new Rr(t, n);\n }\n getOverlay(t, e) {\n return Pr(t).get(Ir(this.userId, e)).next((t => t ? pr(this.serializer, t) : null));\n }\n getOverlays(t, e) {\n const n = fs();\n return Rt.forEach(e, (e => this.getOverlay(t, e).next((t => {\n null !== t && n.set(e, t);\n })))).next((() => n));\n }\n saveOverlays(t, e, n) {\n const s = [];\n return n.forEach(((n, i) => {\n const r = new ei(e, i);\n s.push(this.we(t, r));\n })), Rt.waitFor(s);\n }\n removeOverlaysForBatchId(t, e, n) {\n const s = new Set;\n // Get the set of unique collection paths.\n e.forEach((t => s.add(qt(t.getCollectionPath()))));\n const i = [];\n return s.forEach((e => {\n const s = IDBKeyRange.bound([ this.userId, e, n ], [ this.userId, e, n + 1 ], \n /*lowerOpen=*/ !1, \n /*upperOpen=*/ !0);\n i.push(Pr(t).J(\"collectionPathOverlayIndex\", s));\n })), Rt.waitFor(i);\n }\n getOverlaysForCollection(t, e, n) {\n const s = fs(), i = qt(e), r = IDBKeyRange.bound([ this.userId, i, n ], [ this.userId, i, Number.POSITIVE_INFINITY ], \n /*lowerOpen=*/ !0);\n return Pr(t).j(\"collectionPathOverlayIndex\", r).next((t => {\n for (const e of t) {\n const t = pr(this.serializer, e);\n s.set(t.getKey(), t);\n }\n return s;\n }));\n }\n getOverlaysForCollectionGroup(t, e, n, s) {\n const i = fs();\n let r;\n // We want batch IDs larger than `sinceBatchId`, and so the lower bound\n // is not inclusive.\n const o = IDBKeyRange.bound([ this.userId, e, n ], [ this.userId, e, Number.POSITIVE_INFINITY ], \n /*lowerOpen=*/ !0);\n return Pr(t).X({\n index: \"collectionGroupOverlayIndex\",\n range: o\n }, ((t, e, n) => {\n // We do not want to return partial batch overlays, even if the size\n // of the result set exceeds the given `count` argument. Therefore, we\n // continue to aggregate results even after the result size exceeds\n // `count` if there are more overlays from the `currentBatchId`.\n const o = pr(this.serializer, e);\n i.size() < s || o.largestBatchId === r ? (i.set(o.getKey(), o), r = o.largestBatchId) : n.done();\n })).next((() => i));\n }\n we(t, e) {\n return Pr(t).put(function(t, e, n) {\n const [s, i, r] = Ir(e, n.mutation.key);\n return {\n userId: e,\n collectionPath: i,\n documentId: r,\n collectionGroup: n.mutation.key.getCollectionGroup(),\n largestBatchId: n.largestBatchId,\n overlayMutation: ji(t.fe, n.mutation)\n };\n }(this.serializer, this.userId, e));\n }\n}\n\n/**\n * Helper to get a typed SimpleDbStore for the document overlay object store.\n */ function Pr(t) {\n return _e(t, \"documentOverlays\");\n}\n\n/**\n * @license\n * Copyright 2021 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n// Note: This code is copied from the backend. Code that is not used by\n// Firestore was removed.\n/** Firestore index value writer. */\nclass br {\n constructor() {}\n // The write methods below short-circuit writing terminators for values\n // containing a (terminating) truncated value.\n // As an example, consider the resulting encoding for:\n // [\"bar\", [2, \"foo\"]] -> (STRING, \"bar\", TERM, ARRAY, NUMBER, 2, STRING, \"foo\", TERM, TERM, TERM)\n // [\"bar\", [2, truncated(\"foo\")]] -> (STRING, \"bar\", TERM, ARRAY, NUMBER, 2, STRING, \"foo\", TRUNC)\n // [\"bar\", truncated([\"foo\"])] -> (STRING, \"bar\", TERM, ARRAY. STRING, \"foo\", TERM, TRUNC)\n /** Writes an index value. */\n _e(t, e) {\n this.me(t, e), \n // Write separator to split index values\n // (see go/firestore-storage-format#encodings).\n e.ge();\n }\n me(t, e) {\n if (\"nullValue\" in t) this.ye(e, 5); else if (\"booleanValue\" in t) this.ye(e, 10), \n e.pe(t.booleanValue ? 1 : 0); else if (\"integerValue\" in t) this.ye(e, 15), e.pe(Ce(t.integerValue)); else if (\"doubleValue\" in t) {\n const n = Ce(t.doubleValue);\n isNaN(n) ? this.ye(e, 13) : (this.ye(e, 15), Bt(n) ? \n // -0.0, 0 and 0.0 are all considered the same\n e.pe(0) : e.pe(n));\n } else if (\"timestampValue\" in t) {\n const n = t.timestampValue;\n this.ye(e, 20), \"string\" == typeof n ? e.Ie(n) : (e.Ie(`${n.seconds || \"\"}`), e.pe(n.nanos || 0));\n } else if (\"stringValue\" in t) this.Te(t.stringValue, e), this.Ee(e); else if (\"bytesValue\" in t) this.ye(e, 30), \n e.Ae(xe(t.bytesValue)), this.Ee(e); else if (\"referenceValue\" in t) this.ve(t.referenceValue, e); else if (\"geoPointValue\" in t) {\n const n = t.geoPointValue;\n this.ye(e, 45), e.pe(n.latitude || 0), e.pe(n.longitude || 0);\n } else \"mapValue\" in t ? en(t) ? this.ye(e, Number.MAX_SAFE_INTEGER) : (this.Re(t.mapValue, e), \n this.Ee(e)) : \"arrayValue\" in t ? (this.Pe(t.arrayValue, e), this.Ee(e)) : O();\n }\n Te(t, e) {\n this.ye(e, 25), this.be(t, e);\n }\n be(t, e) {\n e.Ie(t);\n }\n Re(t, e) {\n const n = t.fields || {};\n this.ye(e, 55);\n for (const t of Object.keys(n)) this.Te(t, e), this.me(n[t], e);\n }\n Pe(t, e) {\n const n = t.values || [];\n this.ye(e, 50);\n for (const t of n) this.me(t, e);\n }\n ve(t, e) {\n this.ye(e, 37);\n ht.fromName(t).path.forEach((t => {\n this.ye(e, 60), this.be(t, e);\n }));\n }\n ye(t, e) {\n t.pe(e);\n }\n Ee(t) {\n // While the SDK does not implement truncation, the truncation marker is\n // used to terminate all variable length values (which are strings, bytes,\n // references, arrays and maps).\n t.pe(2);\n }\n}\n\nbr.Ve = new br;\n\n/**\n * Counts the number of zeros in a byte.\n *\n * Visible for testing.\n */\nfunction Vr(t) {\n if (0 === t) return 8;\n let e = 0;\n return t >> 4 == 0 && (\n // Test if the first four bits are zero.\n e += 4, t <<= 4), t >> 6 == 0 && (\n // Test if the first two (or next two) bits are zero.\n e += 2, t <<= 2), t >> 7 == 0 && (\n // Test if the remaining bit is zero.\n e += 1), e;\n}\n\n/** Counts the number of leading zeros in the given byte array. */\n/**\n * Returns the number of bytes required to store \"value\". Leading zero bytes\n * are skipped.\n */\nfunction Sr(t) {\n // This is just the number of bytes for the unsigned representation of the number.\n const e = 64 - function(t) {\n let e = 0;\n for (let n = 0; n < 8; ++n) {\n const s = Vr(255 & t[n]);\n if (e += s, 8 !== s) break;\n }\n return e;\n }(t);\n return Math.ceil(e / 8);\n}\n\n/**\n * OrderedCodeWriter is a minimal-allocation implementation of the writing\n * behavior defined by the backend.\n *\n * The code is ported from its Java counterpart.\n */ class Dr {\n constructor() {\n this.buffer = new Uint8Array(1024), this.position = 0;\n }\n Se(t) {\n const e = t[Symbol.iterator]();\n let n = e.next();\n for (;!n.done; ) this.De(n.value), n = e.next();\n this.Ce();\n }\n xe(t) {\n const e = t[Symbol.iterator]();\n let n = e.next();\n for (;!n.done; ) this.Ne(n.value), n = e.next();\n this.ke();\n }\n /** Writes utf8 bytes into this byte sequence, ascending. */ Me(t) {\n for (const e of t) {\n const t = e.charCodeAt(0);\n if (t < 128) this.De(t); else if (t < 2048) this.De(960 | t >>> 6), this.De(128 | 63 & t); else if (e < \"\\ud800\" || \"\\udbff\" < e) this.De(480 | t >>> 12), \n this.De(128 | 63 & t >>> 6), this.De(128 | 63 & t); else {\n const t = e.codePointAt(0);\n this.De(240 | t >>> 18), this.De(128 | 63 & t >>> 12), this.De(128 | 63 & t >>> 6), \n this.De(128 | 63 & t);\n }\n }\n this.Ce();\n }\n /** Writes utf8 bytes into this byte sequence, descending */ $e(t) {\n for (const e of t) {\n const t = e.charCodeAt(0);\n if (t < 128) this.Ne(t); else if (t < 2048) this.Ne(960 | t >>> 6), this.Ne(128 | 63 & t); else if (e < \"\\ud800\" || \"\\udbff\" < e) this.Ne(480 | t >>> 12), \n this.Ne(128 | 63 & t >>> 6), this.Ne(128 | 63 & t); else {\n const t = e.codePointAt(0);\n this.Ne(240 | t >>> 18), this.Ne(128 | 63 & t >>> 12), this.Ne(128 | 63 & t >>> 6), \n this.Ne(128 | 63 & t);\n }\n }\n this.ke();\n }\n Oe(t) {\n // Values are encoded with a single byte length prefix, followed by the\n // actual value in big-endian format with leading 0 bytes dropped.\n const e = this.Fe(t), n = Sr(e);\n this.Be(1 + n), this.buffer[this.position++] = 255 & n;\n // Write the length\n for (let t = e.length - n; t < e.length; ++t) this.buffer[this.position++] = 255 & e[t];\n }\n Le(t) {\n // Values are encoded with a single byte length prefix, followed by the\n // inverted value in big-endian format with leading 0 bytes dropped.\n const e = this.Fe(t), n = Sr(e);\n this.Be(1 + n), this.buffer[this.position++] = ~(255 & n);\n // Write the length\n for (let t = e.length - n; t < e.length; ++t) this.buffer[this.position++] = ~(255 & e[t]);\n }\n /**\n * Writes the \"infinity\" byte sequence that sorts after all other byte\n * sequences written in ascending order.\n */ qe() {\n this.Ue(255), this.Ue(255);\n }\n /**\n * Writes the \"infinity\" byte sequence that sorts before all other byte\n * sequences written in descending order.\n */ Ke() {\n this.Ge(255), this.Ge(255);\n }\n /**\n * Resets the buffer such that it is the same as when it was newly\n * constructed.\n */ reset() {\n this.position = 0;\n }\n seed(t) {\n this.Be(t.length), this.buffer.set(t, this.position), this.position += t.length;\n }\n /** Makes a copy of the encoded bytes in this buffer. */ Qe() {\n return this.buffer.slice(0, this.position);\n }\n /**\n * Encodes `val` into an encoding so that the order matches the IEEE 754\n * floating-point comparison results with the following exceptions:\n * -0.0 < 0.0\n * all non-NaN < NaN\n * NaN = NaN\n */ Fe(t) {\n const e = \n /** Converts a JavaScript number to a byte array (using big endian encoding). */\n function(t) {\n const e = new DataView(new ArrayBuffer(8));\n return e.setFloat64(0, t, /* littleEndian= */ !1), new Uint8Array(e.buffer);\n }(t), n = 0 != (128 & e[0]);\n // Check if the first bit is set. We use a bit mask since value[0] is\n // encoded as a number from 0 to 255.\n // Revert the two complement to get natural ordering\n e[0] ^= n ? 255 : 128;\n for (let t = 1; t < e.length; ++t) e[t] ^= n ? 255 : 0;\n return e;\n }\n /** Writes a single byte ascending to the buffer. */ De(t) {\n const e = 255 & t;\n 0 === e ? (this.Ue(0), this.Ue(255)) : 255 === e ? (this.Ue(255), this.Ue(0)) : this.Ue(e);\n }\n /** Writes a single byte descending to the buffer. */ Ne(t) {\n const e = 255 & t;\n 0 === e ? (this.Ge(0), this.Ge(255)) : 255 === e ? (this.Ge(255), this.Ge(0)) : this.Ge(t);\n }\n Ce() {\n this.Ue(0), this.Ue(1);\n }\n ke() {\n this.Ge(0), this.Ge(1);\n }\n Ue(t) {\n this.Be(1), this.buffer[this.position++] = t;\n }\n Ge(t) {\n this.Be(1), this.buffer[this.position++] = ~t;\n }\n Be(t) {\n const e = t + this.position;\n if (e <= this.buffer.length) return;\n // Try doubling.\n let n = 2 * this.buffer.length;\n // Still not big enough? Just allocate the right size.\n n < e && (n = e);\n // Create the new buffer.\n const s = new Uint8Array(n);\n s.set(this.buffer), // copy old data\n this.buffer = s;\n }\n}\n\nclass Cr {\n constructor(t) {\n this.je = t;\n }\n Ae(t) {\n this.je.Se(t);\n }\n Ie(t) {\n this.je.Me(t);\n }\n pe(t) {\n this.je.Oe(t);\n }\n ge() {\n this.je.qe();\n }\n}\n\nclass xr {\n constructor(t) {\n this.je = t;\n }\n Ae(t) {\n this.je.xe(t);\n }\n Ie(t) {\n this.je.$e(t);\n }\n pe(t) {\n this.je.Le(t);\n }\n ge() {\n this.je.Ke();\n }\n}\n\n/**\n * Implements `DirectionalIndexByteEncoder` using `OrderedCodeWriter` for the\n * actual encoding.\n */ class Nr {\n constructor() {\n this.je = new Dr, this.ze = new Cr(this.je), this.We = new xr(this.je);\n }\n seed(t) {\n this.je.seed(t);\n }\n He(t) {\n return 0 /* IndexKind.ASCENDING */ === t ? this.ze : this.We;\n }\n Qe() {\n return this.je.Qe();\n }\n reset() {\n this.je.reset();\n }\n}\n\n/**\n * @license\n * Copyright 2022 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/** Represents an index entry saved by the SDK in persisted storage. */ class kr {\n constructor(t, e, n, s) {\n this.indexId = t, this.documentKey = e, this.arrayValue = n, this.directionalValue = s;\n }\n /**\n * Returns an IndexEntry entry that sorts immediately after the current\n * directional value.\n */ Je() {\n const t = this.directionalValue.length, e = 0 === t || 255 === this.directionalValue[t - 1] ? t + 1 : t, n = new Uint8Array(e);\n return n.set(this.directionalValue, 0), e !== t ? n.set([ 0 ], this.directionalValue.length) : ++n[n.length - 1], \n new kr(this.indexId, this.documentKey, this.arrayValue, n);\n }\n}\n\nfunction Mr(t, e) {\n let n = t.indexId - e.indexId;\n return 0 !== n ? n : (n = $r(t.arrayValue, e.arrayValue), 0 !== n ? n : (n = $r(t.directionalValue, e.directionalValue), \n 0 !== n ? n : ht.comparator(t.documentKey, e.documentKey)));\n}\n\nfunction $r(t, e) {\n for (let n = 0; n < t.length && n < e.length; ++n) {\n const s = t[n] - e[n];\n if (0 !== s) return s;\n }\n return t.length - e.length;\n}\n\n/**\n * @license\n * Copyright 2022 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * A light query planner for Firestore.\n *\n * This class matches a `FieldIndex` against a Firestore Query `Target`. It\n * determines whether a given index can be used to serve the specified target.\n *\n * The following table showcases some possible index configurations:\n *\n * Query | Index\n * -----------------------------------------------------------------------------\n * where('a', '==', 'a').where('b', '==', 'b') | a ASC, b DESC\n * where('a', '==', 'a').where('b', '==', 'b') | a ASC\n * where('a', '==', 'a').where('b', '==', 'b') | b DESC\n * where('a', '>=', 'a').orderBy('a') | a ASC\n * where('a', '>=', 'a').orderBy('a', 'desc') | a DESC\n * where('a', '>=', 'a').orderBy('a').orderBy('b') | a ASC, b ASC\n * where('a', '>=', 'a').orderBy('a').orderBy('b') | a ASC\n * where('a', 'array-contains', 'a').orderBy('b') | a CONTAINS, b ASCENDING\n * where('a', 'array-contains', 'a').orderBy('b') | a CONTAINS\n */ class Or {\n constructor(t) {\n this.collectionId = null != t.collectionGroup ? t.collectionGroup : t.path.lastSegment(), \n this.Ye = t.orderBy, this.Xe = [];\n for (const e of t.filters) {\n const t = e;\n t.isInequality() ? this.Ze = t : this.Xe.push(t);\n }\n }\n /**\n * Returns whether the index can be used to serve the TargetIndexMatcher's\n * target.\n *\n * An index is considered capable of serving the target when:\n * - The target uses all index segments for its filters and orderBy clauses.\n * The target can have additional filter and orderBy clauses, but not\n * fewer.\n * - If an ArrayContains/ArrayContainsAnyfilter is used, the index must also\n * have a corresponding `CONTAINS` segment.\n * - All directional index segments can be mapped to the target as a series of\n * equality filters, a single inequality filter and a series of orderBy\n * clauses.\n * - The segments that represent the equality filters may appear out of order.\n * - The optional segment for the inequality filter must appear after all\n * equality segments.\n * - The segments that represent that orderBy clause of the target must appear\n * in order after all equality and inequality segments. Single orderBy\n * clauses cannot be skipped, but a continuous orderBy suffix may be\n * omitted.\n */ tn(t) {\n F(t.collectionGroup === this.collectionId);\n // If there is an array element, find a matching filter.\n const e = ft(t);\n if (void 0 !== e && !this.en(e)) return !1;\n const n = dt(t);\n let s = new Set, i = 0, r = 0;\n // Process all equalities first. Equalities can appear out of order.\n for (;i < n.length && this.en(n[i]); ++i) s = s.add(n[i].fieldPath.canonicalString());\n // If we already have processed all segments, all segments are used to serve\n // the equality filters and we do not need to map any segments to the\n // target's inequality and orderBy clauses.\n if (i === n.length) return !0;\n if (void 0 !== this.Ze) {\n // If there is an inequality filter and the field was not in one of the\n // equality filters above, the next segment must match both the filter\n // and the first orderBy clause.\n if (!s.has(this.Ze.field.canonicalString())) {\n const t = n[i];\n if (!this.nn(this.Ze, t) || !this.sn(this.Ye[r++], t)) return !1;\n }\n ++i;\n }\n // All remaining segments need to represent the prefix of the target's\n // orderBy.\n for (;i < n.length; ++i) {\n const t = n[i];\n if (r >= this.Ye.length || !this.sn(this.Ye[r++], t)) return !1;\n }\n return !0;\n }\n en(t) {\n for (const e of this.Xe) if (this.nn(e, t)) return !0;\n return !1;\n }\n nn(t, e) {\n if (void 0 === t || !t.field.isEqual(e.fieldPath)) return !1;\n const n = \"array-contains\" /* Operator.ARRAY_CONTAINS */ === t.op || \"array-contains-any\" /* Operator.ARRAY_CONTAINS_ANY */ === t.op;\n return 2 /* IndexKind.CONTAINS */ === e.kind === n;\n }\n sn(t, e) {\n return !!t.field.isEqual(e.fieldPath) && (0 /* IndexKind.ASCENDING */ === e.kind && \"asc\" /* Direction.ASCENDING */ === t.dir || 1 /* IndexKind.DESCENDING */ === e.kind && \"desc\" /* Direction.DESCENDING */ === t.dir);\n }\n}\n\n/**\n * @license\n * Copyright 2022 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * Provides utility functions that help with boolean logic transformations needed for handling\n * complex filters used in queries.\n */\n/**\n * The `in` filter is only a syntactic sugar over a disjunction of equalities. For instance: `a in\n * [1,2,3]` is in fact `a==1 || a==2 || a==3`. This method expands any `in` filter in the given\n * input into a disjunction of equality filters and returns the expanded filter.\n */ function Fr(t) {\n var e, n;\n if (F(t instanceof mn || t instanceof gn), t instanceof mn) {\n if (t instanceof Cn) {\n const s = (null === (n = null === (e = t.value.arrayValue) || void 0 === e ? void 0 : e.values) || void 0 === n ? void 0 : n.map((e => mn.create(t.field, \"==\" /* Operator.EQUAL */ , e)))) || [];\n return gn.create(s, \"or\" /* CompositeOperator.OR */);\n }\n // We have reached other kinds of field filters.\n return t;\n }\n // We have a composite filter.\n const s = t.filters.map((t => Fr(t)));\n return gn.create(s, t.op);\n}\n\n/**\n * Given a composite filter, returns the list of terms in its disjunctive normal form.\n *\n *

Each element in the return value is one term of the resulting DNF. For instance: For the\n * input: (A || B) && C, the DNF form is: (A && C) || (B && C), and the return value is a list\n * with two elements: a composite filter that performs (A && C), and a composite filter that\n * performs (B && C).\n *\n * @param filter the composite filter to calculate DNF transform for.\n * @return the terms in the DNF transform.\n */ function Br(t) {\n if (0 === t.getFilters().length) return [];\n const e = Kr(Fr(t));\n return F(Ur(e)), Lr(e) || qr(e) ? [ e ] : e.getFilters();\n}\n\n/** Returns true if the given filter is a single field filter. e.g. (a == 10). */ function Lr(t) {\n return t instanceof mn;\n}\n\n/**\n * Returns true if the given filter is the conjunction of one or more field filters. e.g. (a == 10\n * && b == 20)\n */ function qr(t) {\n return t instanceof gn && In(t);\n}\n\n/**\n * Returns whether or not the given filter is in disjunctive normal form (DNF).\n *\n *

In boolean logic, a disjunctive normal form (DNF) is a canonical normal form of a logical\n * formula consisting of a disjunction of conjunctions; it can also be described as an OR of ANDs.\n *\n *

For more info, visit: https://en.wikipedia.org/wiki/Disjunctive_normal_form\n */ function Ur(t) {\n return Lr(t) || qr(t) || \n /**\n * Returns true if the given filter is the disjunction of one or more \"flat conjunctions\" and\n * field filters. e.g. (a == 10) || (b==20 && c==30)\n */\n function(t) {\n if (t instanceof gn && pn(t)) {\n for (const e of t.getFilters()) if (!Lr(e) && !qr(e)) return !1;\n return !0;\n }\n return !1;\n }(t);\n}\n\nfunction Kr(t) {\n if (F(t instanceof mn || t instanceof gn), t instanceof mn) return t;\n if (1 === t.filters.length) return Kr(t.filters[0]);\n // Compute DNF for each of the subfilters first\n const e = t.filters.map((t => Kr(t)));\n let n = gn.create(e, t.op);\n return n = jr(n), Ur(n) ? n : (F(n instanceof gn), F(yn(n)), F(n.filters.length > 1), \n n.filters.reduce(((t, e) => Gr(t, e))));\n}\n\nfunction Gr(t, e) {\n let n;\n return F(t instanceof mn || t instanceof gn), F(e instanceof mn || e instanceof gn), \n // FieldFilter FieldFilter\n n = t instanceof mn ? e instanceof mn ? function(t, e) {\n // Conjunction distribution for two field filters is the conjunction of them.\n return gn.create([ t, e ], \"and\" /* CompositeOperator.AND */);\n }(t, e) : Qr(t, e) : e instanceof mn ? Qr(e, t) : function(t, e) {\n // There are four cases:\n // (A & B) & (C & D) --> (A & B & C & D)\n // (A & B) & (C | D) --> (A & B & C) | (A & B & D)\n // (A | B) & (C & D) --> (C & D & A) | (C & D & B)\n // (A | B) & (C | D) --> (A & C) | (A & D) | (B & C) | (B & D)\n // Case 1 is a merge.\n if (F(t.filters.length > 0 && e.filters.length > 0), yn(t) && yn(e)) return vn(t, e.getFilters());\n // Case 2,3,4 all have at least one side (lhs or rhs) that is a disjunction. In all three cases\n // we should take each element of the disjunction and distribute it over the other side, and\n // return the disjunction of the distribution results.\n const n = pn(t) ? t : e, s = pn(t) ? e : t, i = n.filters.map((t => Gr(t, s)));\n return gn.create(i, \"or\" /* CompositeOperator.OR */);\n }(t, e), jr(n);\n}\n\nfunction Qr(t, e) {\n // There are two cases:\n // A & (B & C) --> (A & B & C)\n // A & (B | C) --> (A & B) | (A & C)\n if (yn(e)) \n // Case 1\n return vn(e, t.getFilters());\n {\n // Case 2\n const n = e.filters.map((e => Gr(t, e)));\n return gn.create(n, \"or\" /* CompositeOperator.OR */);\n }\n}\n\n/**\n * Applies the associativity property to the given filter and returns the resulting filter.\n *\n *

    \n *
  • A | (B | C) == (A | B) | C == (A | B | C)\n *
  • A & (B & C) == (A & B) & C == (A & B & C)\n *
\n *\n *

For more info, visit: https://en.wikipedia.org/wiki/Associative_property#Propositional_logic\n */ function jr(t) {\n if (F(t instanceof mn || t instanceof gn), t instanceof mn) return t;\n const e = t.getFilters();\n // If the composite filter only contains 1 filter, apply associativity to it.\n if (1 === e.length) return jr(e[0]);\n // Associativity applied to a flat composite filter results is itself.\n if (Tn(t)) return t;\n // First apply associativity to all subfilters. This will in turn recursively apply\n // associativity to all nested composite filters and field filters.\n const n = e.map((t => jr(t))), s = [];\n // For composite subfilters that perform the same kind of logical operation as `compositeFilter`\n // take out their filters and add them to `compositeFilter`. For example:\n // compositeFilter = (A | (B | C | D))\n // compositeSubfilter = (B | C | D)\n // Result: (A | B | C | D)\n // Note that the `compositeSubfilter` has been eliminated, and its filters (B, C, D) have been\n // added to the top-level \"compositeFilter\".\n return n.forEach((e => {\n e instanceof mn ? s.push(e) : e instanceof gn && (e.op === t.op ? \n // compositeFilter: (A | (B | C))\n // compositeSubfilter: (B | C)\n // Result: (A | B | C)\n s.push(...e.filters) : \n // compositeFilter: (A | (B & C))\n // compositeSubfilter: (B & C)\n // Result: (A | (B & C))\n s.push(e));\n })), 1 === s.length ? s[0] : gn.create(s, t.op);\n}\n\n/**\n * @license\n * Copyright 2019 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * An in-memory implementation of IndexManager.\n */ class zr {\n constructor() {\n this.rn = new Wr;\n }\n addToCollectionParentIndex(t, e) {\n return this.rn.add(e), Rt.resolve();\n }\n getCollectionParents(t, e) {\n return Rt.resolve(this.rn.getEntries(e));\n }\n addFieldIndex(t, e) {\n // Field indices are not supported with memory persistence.\n return Rt.resolve();\n }\n deleteFieldIndex(t, e) {\n // Field indices are not supported with memory persistence.\n return Rt.resolve();\n }\n getDocumentsMatchingTarget(t, e) {\n // Field indices are not supported with memory persistence.\n return Rt.resolve(null);\n }\n getIndexType(t, e) {\n // Field indices are not supported with memory persistence.\n return Rt.resolve(0 /* IndexType.NONE */);\n }\n getFieldIndexes(t, e) {\n // Field indices are not supported with memory persistence.\n return Rt.resolve([]);\n }\n getNextCollectionGroupToUpdate(t) {\n // Field indices are not supported with memory persistence.\n return Rt.resolve(null);\n }\n getMinOffset(t, e) {\n return Rt.resolve(It.min());\n }\n getMinOffsetFromCollectionGroup(t, e) {\n return Rt.resolve(It.min());\n }\n updateCollectionGroup(t, e, n) {\n // Field indices are not supported with memory persistence.\n return Rt.resolve();\n }\n updateIndexEntries(t, e) {\n // Field indices are not supported with memory persistence.\n return Rt.resolve();\n }\n}\n\n/**\n * Internal implementation of the collection-parent index exposed by MemoryIndexManager.\n * Also used for in-memory caching by IndexedDbIndexManager and initial index population\n * in indexeddb_schema.ts\n */ class Wr {\n constructor() {\n this.index = {};\n }\n // Returns false if the entry already existed.\n add(t) {\n const e = t.lastSegment(), n = t.popLast(), s = this.index[e] || new Ee(ut.comparator), i = !s.has(n);\n return this.index[e] = s.add(n), i;\n }\n has(t) {\n const e = t.lastSegment(), n = t.popLast(), s = this.index[e];\n return s && s.has(n);\n }\n getEntries(t) {\n return (this.index[t] || new Ee(ut.comparator)).toArray();\n }\n}\n\n/**\n * @license\n * Copyright 2019 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */ const Hr = new Uint8Array(0);\n\n/**\n * A persisted implementation of IndexManager.\n *\n * PORTING NOTE: Unlike iOS and Android, the Web SDK does not memoize index\n * data as it supports multi-tab access.\n */\nclass Jr {\n constructor(t, e) {\n this.user = t, this.databaseId = e, \n /**\n * An in-memory copy of the index entries we've already written since the SDK\n * launched. Used to avoid re-writing the same entry repeatedly.\n *\n * This is *NOT* a complete cache of what's in persistence and so can never be\n * used to satisfy reads.\n */\n this.on = new Wr, \n /**\n * Maps from a target to its equivalent list of sub-targets. Each sub-target\n * contains only one term from the target's disjunctive normal form (DNF).\n */\n this.un = new os((t => $n(t)), ((t, e) => On(t, e))), this.uid = t.uid || \"\";\n }\n /**\n * Adds a new entry to the collection parent index.\n *\n * Repeated calls for the same collectionPath should be avoided within a\n * transaction as IndexedDbIndexManager only caches writes once a transaction\n * has been committed.\n */ addToCollectionParentIndex(t, e) {\n if (!this.on.has(e)) {\n const n = e.lastSegment(), s = e.popLast();\n t.addOnCommittedListener((() => {\n // Add the collection to the in memory cache only if the transaction was\n // successfully committed.\n this.on.add(e);\n }));\n const i = {\n collectionId: n,\n parent: qt(s)\n };\n return Yr(t).put(i);\n }\n return Rt.resolve();\n }\n getCollectionParents(t, e) {\n const n = [], s = IDBKeyRange.bound([ e, \"\" ], [ st(e), \"\" ], \n /*lowerOpen=*/ !1, \n /*upperOpen=*/ !0);\n return Yr(t).j(s).next((t => {\n for (const s of t) {\n // This collectionId guard shouldn't be necessary (and isn't as long\n // as we're running in a real browser), but there's a bug in\n // indexeddbshim that breaks our range in our tests running in node:\n // https://github.com/axemclion/IndexedDBShim/issues/334\n if (s.collectionId !== e) break;\n n.push(Gt(s.parent));\n }\n return n;\n }));\n }\n addFieldIndex(t, e) {\n // TODO(indexing): Verify that the auto-incrementing index ID works in\n // Safari & Firefox.\n const n = Zr(t), s = function(t) {\n return {\n indexId: t.indexId,\n collectionGroup: t.collectionGroup,\n fields: t.fields.map((t => [ t.fieldPath.canonicalString(), t.kind ]))\n };\n }(e);\n delete s.indexId;\n // `indexId` is auto-populated by IndexedDb\n const i = n.add(s);\n if (e.indexState) {\n const n = to(t);\n return i.next((t => {\n n.put(Tr(t, this.user, e.indexState.sequenceNumber, e.indexState.offset));\n }));\n }\n return i.next();\n }\n deleteFieldIndex(t, e) {\n const n = Zr(t), s = to(t), i = Xr(t);\n return n.delete(e.indexId).next((() => s.delete(IDBKeyRange.bound([ e.indexId ], [ e.indexId + 1 ], \n /*lowerOpen=*/ !1, \n /*upperOpen=*/ !0)))).next((() => i.delete(IDBKeyRange.bound([ e.indexId ], [ e.indexId + 1 ], \n /*lowerOpen=*/ !1, \n /*upperOpen=*/ !0))));\n }\n getDocumentsMatchingTarget(t, e) {\n const n = Xr(t);\n let s = !0;\n const i = new Map;\n return Rt.forEach(this.cn(e), (e => this.an(t, e).next((t => {\n s && (s = !!t), i.set(e, t);\n })))).next((() => {\n if (s) {\n let t = gs();\n const s = [];\n return Rt.forEach(i, ((i, r) => {\n var o;\n N(\"IndexedDbIndexManager\", `Using index ${o = i, `id=${o.indexId}|cg=${o.collectionGroup}|f=${o.fields.map((t => `${t.fieldPath}:${t.kind}`)).join(\",\")}`} to execute ${$n(e)}`);\n const u = function(t, e) {\n const n = ft(e);\n if (void 0 === n) return null;\n for (const e of Bn(t, n.fieldPath)) switch (e.op) {\n case \"array-contains-any\" /* Operator.ARRAY_CONTAINS_ANY */ :\n return e.value.arrayValue.values || [];\n\n case \"array-contains\" /* Operator.ARRAY_CONTAINS */ :\n return [ e.value ];\n // Remaining filters are not array filters.\n }\n return null;\n }\n /**\n * Returns the list of values that are used in != or NOT_IN filters. Returns\n * `null` if there are no such filters.\n */ (r, i), c = function(t, e) {\n const n = new Map;\n for (const s of dt(e)) for (const e of Bn(t, s.fieldPath)) switch (e.op) {\n case \"==\" /* Operator.EQUAL */ :\n case \"in\" /* Operator.IN */ :\n // Encode equality prefix, which is encoded in the index value before\n // the inequality (e.g. `a == 'a' && b != 'b'` is encoded to\n // `value != 'ab'`).\n n.set(s.fieldPath.canonicalString(), e.value);\n break;\n\n case \"not-in\" /* Operator.NOT_IN */ :\n case \"!=\" /* Operator.NOT_EQUAL */ :\n // NotIn/NotEqual is always a suffix. There cannot be any remaining\n // segments and hence we can return early here.\n return n.set(s.fieldPath.canonicalString(), e.value), Array.from(n.values());\n // Remaining filters cannot be used as notIn bounds.\n }\n return null;\n }\n /**\n * Returns a lower bound of field values that can be used as a starting point to\n * scan the index defined by `fieldIndex`. Returns `MIN_VALUE` if no lower bound\n * exists.\n */ (r, i), a = function(t, e) {\n const n = [];\n let s = !0;\n // For each segment, retrieve a lower bound if there is a suitable filter or\n // startAt.\n for (const i of dt(e)) {\n const e = 0 /* IndexKind.ASCENDING */ === i.kind ? Ln(t, i.fieldPath, t.startAt) : qn(t, i.fieldPath, t.startAt);\n n.push(e.value), s && (s = e.inclusive);\n }\n return new hn(n, s);\n }\n /**\n * Returns an upper bound of field values that can be used as an ending point\n * when scanning the index defined by `fieldIndex`. Returns `MAX_VALUE` if no\n * upper bound exists.\n */ (r, i), h = function(t, e) {\n const n = [];\n let s = !0;\n // For each segment, retrieve an upper bound if there is a suitable filter or\n // endAt.\n for (const i of dt(e)) {\n const e = 0 /* IndexKind.ASCENDING */ === i.kind ? qn(t, i.fieldPath, t.endAt) : Ln(t, i.fieldPath, t.endAt);\n n.push(e.value), s && (s = e.inclusive);\n }\n return new hn(n, s);\n }(r, i), l = this.hn(i, r, a), f = this.hn(i, r, h), d = this.ln(i, r, c), w = this.fn(i.indexId, u, l, a.inclusive, f, h.inclusive, d);\n return Rt.forEach(w, (i => n.H(i, e.limit).next((e => {\n e.forEach((e => {\n const n = ht.fromSegments(e.documentKey);\n t.has(n) || (t = t.add(n), s.push(n));\n }));\n }))));\n })).next((() => s));\n }\n return Rt.resolve(null);\n }));\n }\n cn(t) {\n let e = this.un.get(t);\n if (e) return e;\n if (0 === t.filters.length) e = [ t ]; else {\n e = Br(gn.create(t.filters, \"and\" /* CompositeOperator.AND */)).map((e => Mn(t.path, t.collectionGroup, t.orderBy, e.getFilters(), t.limit, t.startAt, t.endAt)));\n }\n return this.un.set(t, e), e;\n }\n /**\n * Constructs a key range query on `DbIndexEntryStore` that unions all\n * bounds.\n */ fn(t, e, n, s, i, r, o) {\n // The number of total index scans we union together. This is similar to a\n // distributed normal form, but adapted for array values. We create a single\n // index range per value in an ARRAY_CONTAINS or ARRAY_CONTAINS_ANY filter\n // combined with the values from the query bounds.\n const u = (null != e ? e.length : 1) * Math.max(n.length, i.length), c = u / (null != e ? e.length : 1), a = [];\n for (let h = 0; h < u; ++h) {\n const u = e ? this.dn(e[h / c]) : Hr, l = this.wn(t, u, n[h % c], s), f = this._n(t, u, i[h % c], r), d = o.map((e => this.wn(t, u, e, \n /* inclusive= */ !0)));\n a.push(...this.createRange(l, f, d));\n }\n return a;\n }\n /** Generates the lower bound for `arrayValue` and `directionalValue`. */ wn(t, e, n, s) {\n const i = new kr(t, ht.empty(), e, n);\n return s ? i : i.Je();\n }\n /** Generates the upper bound for `arrayValue` and `directionalValue`. */ _n(t, e, n, s) {\n const i = new kr(t, ht.empty(), e, n);\n return s ? i.Je() : i;\n }\n an(t, e) {\n const n = new Or(e), s = null != e.collectionGroup ? e.collectionGroup : e.path.lastSegment();\n return this.getFieldIndexes(t, s).next((t => {\n // Return the index with the most number of segments.\n let e = null;\n for (const s of t) {\n n.tn(s) && (!e || s.fields.length > e.fields.length) && (e = s);\n }\n return e;\n }));\n }\n getIndexType(t, e) {\n let n = 2 /* IndexType.FULL */;\n const s = this.cn(e);\n return Rt.forEach(s, (e => this.an(t, e).next((t => {\n t ? 0 /* IndexType.NONE */ !== n && t.fields.length < function(t) {\n let e = new Ee(at.comparator), n = !1;\n for (const s of t.filters) for (const t of s.getFlattenedFilters()) \n // __name__ is not an explicit segment of any index, so we don't need to\n // count it.\n t.field.isKeyField() || (\n // ARRAY_CONTAINS or ARRAY_CONTAINS_ANY filters must be counted separately.\n // For instance, it is possible to have an index for \"a ARRAY a ASC\". Even\n // though these are on the same field, they should be counted as two\n // separate segments in an index.\n \"array-contains\" /* Operator.ARRAY_CONTAINS */ === t.op || \"array-contains-any\" /* Operator.ARRAY_CONTAINS_ANY */ === t.op ? n = !0 : e = e.add(t.field));\n for (const n of t.orderBy) \n // __name__ is not an explicit segment of any index, so we don't need to\n // count it.\n n.field.isKeyField() || (e = e.add(n.field));\n return e.size + (n ? 1 : 0);\n }(e) && (n = 1 /* IndexType.PARTIAL */) : n = 0 /* IndexType.NONE */;\n })))).next((() => \n // OR queries have more than one sub-target (one sub-target per DNF term). We currently consider\n // OR queries that have a `limit` to have a partial index. For such queries we perform sorting\n // and apply the limit in memory as a post-processing step.\n function(t) {\n return null !== t.limit;\n }(e) && s.length > 1 && 2 /* IndexType.FULL */ === n ? 1 /* IndexType.PARTIAL */ : n));\n }\n /**\n * Returns the byte encoded form of the directional values in the field index.\n * Returns `null` if the document does not have all fields specified in the\n * index.\n */ mn(t, e) {\n const n = new Nr;\n for (const s of dt(t)) {\n const t = e.data.field(s.fieldPath);\n if (null == t) return null;\n const i = n.He(s.kind);\n br.Ve._e(t, i);\n }\n return n.Qe();\n }\n /** Encodes a single value to the ascending index format. */ dn(t) {\n const e = new Nr;\n return br.Ve._e(t, e.He(0 /* IndexKind.ASCENDING */)), e.Qe();\n }\n /**\n * Returns an encoded form of the document key that sorts based on the key\n * ordering of the field index.\n */ gn(t, e) {\n const n = new Nr;\n return br.Ve._e(We(this.databaseId, e), n.He(function(t) {\n const e = dt(t);\n return 0 === e.length ? 0 /* IndexKind.ASCENDING */ : e[e.length - 1].kind;\n }(t))), n.Qe();\n }\n /**\n * Encodes the given field values according to the specification in `target`.\n * For IN queries, a list of possible values is returned.\n */ ln(t, e, n) {\n if (null === n) return [];\n let s = [];\n s.push(new Nr);\n let i = 0;\n for (const r of dt(t)) {\n const t = n[i++];\n for (const n of s) if (this.yn(e, r.fieldPath) && Je(t)) s = this.pn(s, r, t); else {\n const e = n.He(r.kind);\n br.Ve._e(t, e);\n }\n }\n return this.In(s);\n }\n /**\n * Encodes the given bounds according to the specification in `target`. For IN\n * queries, a list of possible values is returned.\n */ hn(t, e, n) {\n return this.ln(t, e, n.position);\n }\n /** Returns the byte representation for the provided encoders. */ In(t) {\n const e = [];\n for (let n = 0; n < t.length; ++n) e[n] = t[n].Qe();\n return e;\n }\n /**\n * Creates a separate encoder for each element of an array.\n *\n * The method appends each value to all existing encoders (e.g. filter(\"a\",\n * \"==\", \"a1\").filter(\"b\", \"in\", [\"b1\", \"b2\"]) becomes [\"a1,b1\", \"a1,b2\"]). A\n * list of new encoders is returned.\n */ pn(t, e, n) {\n const s = [ ...t ], i = [];\n for (const t of n.arrayValue.values || []) for (const n of s) {\n const s = new Nr;\n s.seed(n.Qe()), br.Ve._e(t, s.He(e.kind)), i.push(s);\n }\n return i;\n }\n yn(t, e) {\n return !!t.filters.find((t => t instanceof mn && t.field.isEqual(e) && (\"in\" /* Operator.IN */ === t.op || \"not-in\" /* Operator.NOT_IN */ === t.op)));\n }\n getFieldIndexes(t, e) {\n const n = Zr(t), s = to(t);\n return (e ? n.j(\"collectionGroupIndex\", IDBKeyRange.bound(e, e)) : n.j()).next((t => {\n const e = [];\n return Rt.forEach(t, (t => s.get([ t.indexId, this.uid ]).next((n => {\n e.push(function(t, e) {\n const n = e ? new gt(e.sequenceNumber, new It(wr(e.readTime), new ht(Gt(e.documentKey)), e.largestBatchId)) : gt.empty(), s = t.fields.map((([t, e]) => new _t(at.fromServerFormat(t), e)));\n return new lt(t.indexId, t.collectionGroup, s, n);\n }(t, n));\n })))).next((() => e));\n }));\n }\n getNextCollectionGroupToUpdate(t) {\n return this.getFieldIndexes(t).next((t => 0 === t.length ? null : (t.sort(((t, e) => {\n const n = t.indexState.sequenceNumber - e.indexState.sequenceNumber;\n return 0 !== n ? n : et(t.collectionGroup, e.collectionGroup);\n })), t[0].collectionGroup)));\n }\n updateCollectionGroup(t, e, n) {\n const s = Zr(t), i = to(t);\n return this.Tn(t).next((t => s.j(\"collectionGroupIndex\", IDBKeyRange.bound(e, e)).next((e => Rt.forEach(e, (e => i.put(Tr(e.indexId, this.user, t, n))))))));\n }\n updateIndexEntries(t, e) {\n // Porting Note: `getFieldIndexes()` on Web does not cache index lookups as\n // it could be used across different IndexedDB transactions. As any cached\n // data might be invalidated by other multi-tab clients, we can only trust\n // data within a single IndexedDB transaction. We therefore add a cache\n // here.\n const n = new Map;\n return Rt.forEach(e, ((e, s) => {\n const i = n.get(e.collectionGroup);\n return (i ? Rt.resolve(i) : this.getFieldIndexes(t, e.collectionGroup)).next((i => (n.set(e.collectionGroup, i), \n Rt.forEach(i, (n => this.En(t, e, n).next((e => {\n const i = this.An(s, n);\n return e.isEqual(i) ? Rt.resolve() : this.vn(t, s, n, e, i);\n })))))));\n }));\n }\n Rn(t, e, n, s) {\n return Xr(t).put({\n indexId: s.indexId,\n uid: this.uid,\n arrayValue: s.arrayValue,\n directionalValue: s.directionalValue,\n orderedDocumentKey: this.gn(n, e.key),\n documentKey: e.key.path.toArray()\n });\n }\n Pn(t, e, n, s) {\n return Xr(t).delete([ s.indexId, this.uid, s.arrayValue, s.directionalValue, this.gn(n, e.key), e.key.path.toArray() ]);\n }\n En(t, e, n) {\n const s = Xr(t);\n let i = new Ee(Mr);\n return s.X({\n index: \"documentKeyIndex\",\n range: IDBKeyRange.only([ n.indexId, this.uid, this.gn(n, e) ])\n }, ((t, s) => {\n i = i.add(new kr(n.indexId, e, s.arrayValue, s.directionalValue));\n })).next((() => i));\n }\n /** Creates the index entries for the given document. */ An(t, e) {\n let n = new Ee(Mr);\n const s = this.mn(e, t);\n if (null == s) return n;\n const i = ft(e);\n if (null != i) {\n const r = t.data.field(i.fieldPath);\n if (Je(r)) for (const i of r.arrayValue.values || []) n = n.add(new kr(e.indexId, t.key, this.dn(i), s));\n } else n = n.add(new kr(e.indexId, t.key, Hr, s));\n return n;\n }\n /**\n * Updates the index entries for the provided document by deleting entries\n * that are no longer referenced in `newEntries` and adding all newly added\n * entries.\n */ vn(t, e, n, s, i) {\n N(\"IndexedDbIndexManager\", \"Updating index entries for document '%s'\", e.key);\n const r = [];\n return function(t, e, n, s, i) {\n const r = t.getIterator(), o = e.getIterator();\n let u = ve(r), c = ve(o);\n // Walk through the two sets at the same time, using the ordering defined by\n // `comparator`.\n for (;u || c; ) {\n let t = !1, e = !1;\n if (u && c) {\n const s = n(u, c);\n s < 0 ? \n // The element was removed if the next element in our ordered\n // walkthrough is only in `before`.\n e = !0 : s > 0 && (\n // The element was added if the next element in our ordered walkthrough\n // is only in `after`.\n t = !0);\n } else null != u ? e = !0 : t = !0;\n t ? (s(c), c = ve(o)) : e ? (i(u), u = ve(r)) : (u = ve(r), c = ve(o));\n }\n }(s, i, Mr, (\n /* onAdd= */ s => {\n r.push(this.Rn(t, e, n, s));\n }), (\n /* onRemove= */ s => {\n r.push(this.Pn(t, e, n, s));\n })), Rt.waitFor(r);\n }\n Tn(t) {\n let e = 1;\n return to(t).X({\n index: \"sequenceNumberIndex\",\n reverse: !0,\n range: IDBKeyRange.upperBound([ this.uid, Number.MAX_SAFE_INTEGER ])\n }, ((t, n, s) => {\n s.done(), e = n.sequenceNumber + 1;\n })).next((() => e));\n }\n /**\n * Returns a new set of IDB ranges that splits the existing range and excludes\n * any values that match the `notInValue` from these ranges. As an example,\n * '[foo > 2 && foo != 3]` becomes `[foo > 2 && < 3, foo > 3]`.\n */ createRange(t, e, n) {\n // The notIn values need to be sorted and unique so that we can return a\n // sorted set of non-overlapping ranges.\n n = n.sort(((t, e) => Mr(t, e))).filter(((t, e, n) => !e || 0 !== Mr(t, n[e - 1])));\n const s = [];\n s.push(t);\n for (const i of n) {\n const n = Mr(i, t), r = Mr(i, e);\n if (0 === n) \n // `notInValue` is the lower bound. We therefore need to raise the bound\n // to the next value.\n s[0] = t.Je(); else if (n > 0 && r < 0) \n // `notInValue` is in the middle of the range\n s.push(i), s.push(i.Je()); else if (r > 0) \n // `notInValue` (and all following values) are out of the range\n break;\n }\n s.push(e);\n const i = [];\n for (let t = 0; t < s.length; t += 2) {\n // If we encounter two bounds that will create an unmatchable key range,\n // then we return an empty set of key ranges.\n if (this.bn(s[t], s[t + 1])) return [];\n const e = [ s[t].indexId, this.uid, s[t].arrayValue, s[t].directionalValue, Hr, [] ], n = [ s[t + 1].indexId, this.uid, s[t + 1].arrayValue, s[t + 1].directionalValue, Hr, [] ];\n i.push(IDBKeyRange.bound(e, n));\n }\n return i;\n }\n bn(t, e) {\n // If lower bound is greater than the upper bound, then the key\n // range can never be matched.\n return Mr(t, e) > 0;\n }\n getMinOffsetFromCollectionGroup(t, e) {\n return this.getFieldIndexes(t, e).next(eo);\n }\n getMinOffset(t, e) {\n return Rt.mapArray(this.cn(e), (e => this.an(t, e).next((t => t || O())))).next(eo);\n }\n}\n\n/**\n * Helper to get a typed SimpleDbStore for the collectionParents\n * document store.\n */ function Yr(t) {\n return _e(t, \"collectionParents\");\n}\n\n/**\n * Helper to get a typed SimpleDbStore for the index entry object store.\n */ function Xr(t) {\n return _e(t, \"indexEntries\");\n}\n\n/**\n * Helper to get a typed SimpleDbStore for the index configuration object store.\n */ function Zr(t) {\n return _e(t, \"indexConfiguration\");\n}\n\n/**\n * Helper to get a typed SimpleDbStore for the index state object store.\n */ function to(t) {\n return _e(t, \"indexState\");\n}\n\nfunction eo(t) {\n F(0 !== t.length);\n let e = t[0].indexState.offset, n = e.largestBatchId;\n for (let s = 1; s < t.length; s++) {\n const i = t[s].indexState.offset;\n Tt(i, e) < 0 && (e = i), n < i.largestBatchId && (n = i.largestBatchId);\n }\n return new It(e.readTime, e.documentKey, n);\n}\n\n/**\n * @license\n * Copyright 2018 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */ const no = {\n didRun: !1,\n sequenceNumbersCollected: 0,\n targetsRemoved: 0,\n documentsRemoved: 0\n};\n\nclass so {\n constructor(\n // When we attempt to collect, we will only do so if the cache size is greater than this\n // threshold. Passing `COLLECTION_DISABLED` here will cause collection to always be skipped.\n t, \n // The percentage of sequence numbers that we will attempt to collect\n e, \n // A cap on the total number of sequence numbers that will be collected. This prevents\n // us from collecting a huge number of sequence numbers if the cache has grown very large.\n n) {\n this.cacheSizeCollectionThreshold = t, this.percentileToCollect = e, this.maximumSequenceNumbersToCollect = n;\n }\n static withCacheSize(t) {\n return new so(t, so.DEFAULT_COLLECTION_PERCENTILE, so.DEFAULT_MAX_SEQUENCE_NUMBERS_TO_COLLECT);\n }\n}\n\n/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * Delete a mutation batch and the associated document mutations.\n * @returns A PersistencePromise of the document mutations that were removed.\n */\nfunction io(t, e, n) {\n const s = t.store(\"mutations\"), i = t.store(\"documentMutations\"), r = [], o = IDBKeyRange.only(n.batchId);\n let u = 0;\n const c = s.X({\n range: o\n }, ((t, e, n) => (u++, n.delete())));\n r.push(c.next((() => {\n F(1 === u);\n })));\n const a = [];\n for (const t of n.mutations) {\n const s = zt(e, t.key.path, n.batchId);\n r.push(i.delete(s)), a.push(t.key);\n }\n return Rt.waitFor(r).next((() => a));\n}\n\n/**\n * Returns an approximate size for the given document.\n */ function ro(t) {\n if (!t) return 0;\n let e;\n if (t.document) e = t.document; else if (t.unknownDocument) e = t.unknownDocument; else {\n if (!t.noDocument) throw O();\n e = t.noDocument;\n }\n return JSON.stringify(e).length;\n}\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/** A mutation queue for a specific user, backed by IndexedDB. */ so.DEFAULT_COLLECTION_PERCENTILE = 10, \nso.DEFAULT_MAX_SEQUENCE_NUMBERS_TO_COLLECT = 1e3, so.DEFAULT = new so(41943040, so.DEFAULT_COLLECTION_PERCENTILE, so.DEFAULT_MAX_SEQUENCE_NUMBERS_TO_COLLECT), \nso.DISABLED = new so(-1, 0, 0);\n\nclass oo {\n constructor(\n /**\n * The normalized userId (e.g. null UID => \"\" userId) used to store /\n * retrieve mutations.\n */\n t, e, n, s) {\n this.userId = t, this.serializer = e, this.indexManager = n, this.referenceDelegate = s, \n /**\n * Caches the document keys for pending mutation batches. If the mutation\n * has been removed from IndexedDb, the cached value may continue to\n * be used to retrieve the batch's document keys. To remove a cached value\n * locally, `removeCachedMutationKeys()` should be invoked either directly\n * or through `removeMutationBatches()`.\n *\n * With multi-tab, when the primary client acknowledges or rejects a mutation,\n * this cache is used by secondary clients to invalidate the local\n * view of the documents that were previously affected by the mutation.\n */\n // PORTING NOTE: Multi-tab only.\n this.Vn = {};\n }\n /**\n * Creates a new mutation queue for the given user.\n * @param user - The user for which to create a mutation queue.\n * @param serializer - The serializer to use when persisting to IndexedDb.\n */ static de(t, e, n, s) {\n // TODO(mcg): Figure out what constraints there are on userIDs\n // In particular, are there any reserved characters? are empty ids allowed?\n // For the moment store these together in the same mutations table assuming\n // that empty userIDs aren't allowed.\n F(\"\" !== t.uid);\n const i = t.isAuthenticated() ? t.uid : \"\";\n return new oo(i, e, n, s);\n }\n checkEmpty(t) {\n let e = !0;\n const n = IDBKeyRange.bound([ this.userId, Number.NEGATIVE_INFINITY ], [ this.userId, Number.POSITIVE_INFINITY ]);\n return co(t).X({\n index: \"userMutationsIndex\",\n range: n\n }, ((t, n, s) => {\n e = !1, s.done();\n })).next((() => e));\n }\n addMutationBatch(t, e, n, s) {\n const i = ao(t), r = co(t);\n // The IndexedDb implementation in Chrome (and Firefox) does not handle\n // compound indices that include auto-generated keys correctly. To ensure\n // that the index entry is added correctly in all browsers, we perform two\n // writes: The first write is used to retrieve the next auto-generated Batch\n // ID, and the second write populates the index and stores the actual\n // mutation batch.\n // See: https://bugs.chromium.org/p/chromium/issues/detail?id=701972\n // We write an empty object to obtain key\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n return r.add({}).next((o => {\n F(\"number\" == typeof o);\n const u = new Zs(o, e, n, s), c = function(t, e, n) {\n const s = n.baseMutations.map((e => ji(t.fe, e))), i = n.mutations.map((e => ji(t.fe, e)));\n return {\n userId: e,\n batchId: n.batchId,\n localWriteTimeMs: n.localWriteTime.toMillis(),\n baseMutations: s,\n mutations: i\n };\n }(this.serializer, this.userId, u), a = [];\n let h = new Ee(((t, e) => et(t.canonicalString(), e.canonicalString())));\n for (const t of s) {\n const e = zt(this.userId, t.key.path, o);\n h = h.add(t.key.path.popLast()), a.push(r.put(c)), a.push(i.put(e, Wt));\n }\n return h.forEach((e => {\n a.push(this.indexManager.addToCollectionParentIndex(t, e));\n })), t.addOnCommittedListener((() => {\n this.Vn[o] = u.keys();\n })), Rt.waitFor(a).next((() => u));\n }));\n }\n lookupMutationBatch(t, e) {\n return co(t).get(e).next((t => t ? (F(t.userId === this.userId), _r(this.serializer, t)) : null));\n }\n /**\n * Returns the document keys for the mutation batch with the given batchId.\n * For primary clients, this method returns `null` after\n * `removeMutationBatches()` has been called. Secondary clients return a\n * cached result until `removeCachedMutationKeys()` is invoked.\n */\n // PORTING NOTE: Multi-tab only.\n Sn(t, e) {\n return this.Vn[e] ? Rt.resolve(this.Vn[e]) : this.lookupMutationBatch(t, e).next((t => {\n if (t) {\n const n = t.keys();\n return this.Vn[e] = n, n;\n }\n return null;\n }));\n }\n getNextMutationBatchAfterBatchId(t, e) {\n const n = e + 1, s = IDBKeyRange.lowerBound([ this.userId, n ]);\n let i = null;\n return co(t).X({\n index: \"userMutationsIndex\",\n range: s\n }, ((t, e, s) => {\n e.userId === this.userId && (F(e.batchId >= n), i = _r(this.serializer, e)), s.done();\n })).next((() => i));\n }\n getHighestUnacknowledgedBatchId(t) {\n const e = IDBKeyRange.upperBound([ this.userId, Number.POSITIVE_INFINITY ]);\n let n = -1;\n return co(t).X({\n index: \"userMutationsIndex\",\n range: e,\n reverse: !0\n }, ((t, e, s) => {\n n = e.batchId, s.done();\n })).next((() => n));\n }\n getAllMutationBatches(t) {\n const e = IDBKeyRange.bound([ this.userId, -1 ], [ this.userId, Number.POSITIVE_INFINITY ]);\n return co(t).j(\"userMutationsIndex\", e).next((t => t.map((t => _r(this.serializer, t)))));\n }\n getAllMutationBatchesAffectingDocumentKey(t, e) {\n // Scan the document-mutation index starting with a prefix starting with\n // the given documentKey.\n const n = jt(this.userId, e.path), s = IDBKeyRange.lowerBound(n), i = [];\n return ao(t).X({\n range: s\n }, ((n, s, r) => {\n const [o, u, c] = n, a = Gt(u);\n // Only consider rows matching exactly the specific key of\n // interest. Note that because we order by path first, and we\n // order terminators before path separators, we'll encounter all\n // the index rows for documentKey contiguously. In particular, all\n // the rows for documentKey will occur before any rows for\n // documents nested in a subcollection beneath documentKey so we\n // can stop as soon as we hit any such row.\n if (o === this.userId && e.path.isEqual(a)) \n // Look up the mutation batch in the store.\n return co(t).get(c).next((t => {\n if (!t) throw O();\n F(t.userId === this.userId), i.push(_r(this.serializer, t));\n }));\n r.done();\n })).next((() => i));\n }\n getAllMutationBatchesAffectingDocumentKeys(t, e) {\n let n = new Ee(et);\n const s = [];\n return e.forEach((e => {\n const i = jt(this.userId, e.path), r = IDBKeyRange.lowerBound(i), o = ao(t).X({\n range: r\n }, ((t, s, i) => {\n const [r, o, u] = t, c = Gt(o);\n // Only consider rows matching exactly the specific key of\n // interest. Note that because we order by path first, and we\n // order terminators before path separators, we'll encounter all\n // the index rows for documentKey contiguously. In particular, all\n // the rows for documentKey will occur before any rows for\n // documents nested in a subcollection beneath documentKey so we\n // can stop as soon as we hit any such row.\n r === this.userId && e.path.isEqual(c) ? n = n.add(u) : i.done();\n }));\n s.push(o);\n })), Rt.waitFor(s).next((() => this.Dn(t, n)));\n }\n getAllMutationBatchesAffectingQuery(t, e) {\n const n = e.path, s = n.length + 1, i = jt(this.userId, n), r = IDBKeyRange.lowerBound(i);\n // Collect up unique batchIDs encountered during a scan of the index. Use a\n // SortedSet to accumulate batch IDs so they can be traversed in order in a\n // scan of the main table.\n let o = new Ee(et);\n return ao(t).X({\n range: r\n }, ((t, e, i) => {\n const [r, u, c] = t, a = Gt(u);\n r === this.userId && n.isPrefixOf(a) ? \n // Rows with document keys more than one segment longer than the\n // query path can't be matches. For example, a query on 'rooms'\n // can't match the document /rooms/abc/messages/xyx.\n // TODO(mcg): we'll need a different scanner when we implement\n // ancestor queries.\n a.length === s && (o = o.add(c)) : i.done();\n })).next((() => this.Dn(t, o)));\n }\n Dn(t, e) {\n const n = [], s = [];\n // TODO(rockwood): Implement this using iterate.\n return e.forEach((e => {\n s.push(co(t).get(e).next((t => {\n if (null === t) throw O();\n F(t.userId === this.userId), n.push(_r(this.serializer, t));\n })));\n })), Rt.waitFor(s).next((() => n));\n }\n removeMutationBatch(t, e) {\n return io(t.ht, this.userId, e).next((n => (t.addOnCommittedListener((() => {\n this.Cn(e.batchId);\n })), Rt.forEach(n, (e => this.referenceDelegate.markPotentiallyOrphaned(t, e))))));\n }\n /**\n * Clears the cached keys for a mutation batch. This method should be\n * called by secondary clients after they process mutation updates.\n *\n * Note that this method does not have to be called from primary clients as\n * the corresponding cache entries are cleared when an acknowledged or\n * rejected batch is removed from the mutation queue.\n */\n // PORTING NOTE: Multi-tab only\n Cn(t) {\n delete this.Vn[t];\n }\n performConsistencyCheck(t) {\n return this.checkEmpty(t).next((e => {\n if (!e) return Rt.resolve();\n // Verify that there are no entries in the documentMutations index if\n // the queue is empty.\n const n = IDBKeyRange.lowerBound([ this.userId ]);\n const s = [];\n return ao(t).X({\n range: n\n }, ((t, e, n) => {\n if (t[0] === this.userId) {\n const e = Gt(t[1]);\n s.push(e);\n } else n.done();\n })).next((() => {\n F(0 === s.length);\n }));\n }));\n }\n containsKey(t, e) {\n return uo(t, this.userId, e);\n }\n // PORTING NOTE: Multi-tab only (state is held in memory in other clients).\n /** Returns the mutation queue's metadata from IndexedDb. */\n xn(t) {\n return ho(t).get(this.userId).next((t => t || {\n userId: this.userId,\n lastAcknowledgedBatchId: -1,\n lastStreamToken: \"\"\n }));\n }\n}\n\n/**\n * @returns true if the mutation queue for the given user contains a pending\n * mutation for the given key.\n */ function uo(t, e, n) {\n const s = jt(e, n.path), i = s[1], r = IDBKeyRange.lowerBound(s);\n let o = !1;\n return ao(t).X({\n range: r,\n Y: !0\n }, ((t, n, s) => {\n const [r, u, /*batchID*/ c] = t;\n r === e && u === i && (o = !0), s.done();\n })).next((() => o));\n}\n\n/** Returns true if any mutation queue contains the given document. */\n/**\n * Helper to get a typed SimpleDbStore for the mutations object store.\n */\nfunction co(t) {\n return _e(t, \"mutations\");\n}\n\n/**\n * Helper to get a typed SimpleDbStore for the mutationQueues object store.\n */ function ao(t) {\n return _e(t, \"documentMutations\");\n}\n\n/**\n * Helper to get a typed SimpleDbStore for the mutationQueues object store.\n */ function ho(t) {\n return _e(t, \"mutationQueues\");\n}\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/** Offset to ensure non-overlapping target ids. */\n/**\n * Generates monotonically increasing target IDs for sending targets to the\n * watch stream.\n *\n * The client constructs two generators, one for the target cache, and one for\n * for the sync engine (to generate limbo documents targets). These\n * generators produce non-overlapping IDs (by using even and odd IDs\n * respectively).\n *\n * By separating the target ID space, the query cache can generate target IDs\n * that persist across client restarts, while sync engine can independently\n * generate in-memory target IDs that are transient and can be reused after a\n * restart.\n */\nclass lo {\n constructor(t) {\n this.Nn = t;\n }\n next() {\n return this.Nn += 2, this.Nn;\n }\n static kn() {\n // The target cache generator must return '2' in its first call to `next()`\n // as there is no differentiation in the protocol layer between an unset\n // number and the number '0'. If we were to sent a target with target ID\n // '0', the backend would consider it unset and replace it with its own ID.\n return new lo(0);\n }\n static Mn() {\n // Sync engine assigns target IDs for limbo document detection.\n return new lo(-1);\n }\n}\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */ class fo {\n constructor(t, e) {\n this.referenceDelegate = t, this.serializer = e;\n }\n // PORTING NOTE: We don't cache global metadata for the target cache, since\n // some of it (in particular `highestTargetId`) can be modified by secondary\n // tabs. We could perhaps be more granular (and e.g. still cache\n // `lastRemoteSnapshotVersion` in memory) but for simplicity we currently go\n // to IndexedDb whenever we need to read metadata. We can revisit if it turns\n // out to have a meaningful performance impact.\n allocateTargetId(t) {\n return this.$n(t).next((e => {\n const n = new lo(e.highestTargetId);\n return e.highestTargetId = n.next(), this.On(t, e).next((() => e.highestTargetId));\n }));\n }\n getLastRemoteSnapshotVersion(t) {\n return this.$n(t).next((t => rt.fromTimestamp(new it(t.lastRemoteSnapshotVersion.seconds, t.lastRemoteSnapshotVersion.nanoseconds))));\n }\n getHighestSequenceNumber(t) {\n return this.$n(t).next((t => t.highestListenSequenceNumber));\n }\n setTargetsMetadata(t, e, n) {\n return this.$n(t).next((s => (s.highestListenSequenceNumber = e, n && (s.lastRemoteSnapshotVersion = n.toTimestamp()), \n e > s.highestListenSequenceNumber && (s.highestListenSequenceNumber = e), this.On(t, s))));\n }\n addTargetData(t, e) {\n return this.Fn(t, e).next((() => this.$n(t).next((n => (n.targetCount += 1, this.Bn(e, n), \n this.On(t, n))))));\n }\n updateTargetData(t, e) {\n return this.Fn(t, e);\n }\n removeTargetData(t, e) {\n return this.removeMatchingKeysForTargetId(t, e.targetId).next((() => wo(t).delete(e.targetId))).next((() => this.$n(t))).next((e => (F(e.targetCount > 0), \n e.targetCount -= 1, this.On(t, e))));\n }\n /**\n * Drops any targets with sequence number less than or equal to the upper bound, excepting those\n * present in `activeTargetIds`. Document associations for the removed targets are also removed.\n * Returns the number of targets removed.\n */ removeTargets(t, e, n) {\n let s = 0;\n const i = [];\n return wo(t).X(((r, o) => {\n const u = mr(o);\n u.sequenceNumber <= e && null === n.get(u.targetId) && (s++, i.push(this.removeTargetData(t, u)));\n })).next((() => Rt.waitFor(i))).next((() => s));\n }\n /**\n * Call provided function with each `TargetData` that we have cached.\n */ forEachTarget(t, e) {\n return wo(t).X(((t, n) => {\n const s = mr(n);\n e(s);\n }));\n }\n $n(t) {\n return _o(t).get(\"targetGlobalKey\").next((t => (F(null !== t), t)));\n }\n On(t, e) {\n return _o(t).put(\"targetGlobalKey\", e);\n }\n Fn(t, e) {\n return wo(t).put(gr(this.serializer, e));\n }\n /**\n * In-place updates the provided metadata to account for values in the given\n * TargetData. Saving is done separately. Returns true if there were any\n * changes to the metadata.\n */ Bn(t, e) {\n let n = !1;\n return t.targetId > e.highestTargetId && (e.highestTargetId = t.targetId, n = !0), \n t.sequenceNumber > e.highestListenSequenceNumber && (e.highestListenSequenceNumber = t.sequenceNumber, \n n = !0), n;\n }\n getTargetCount(t) {\n return this.$n(t).next((t => t.targetCount));\n }\n getTargetData(t, e) {\n // Iterating by the canonicalId may yield more than one result because\n // canonicalId values are not required to be unique per target. This query\n // depends on the queryTargets index to be efficient.\n const n = $n(e), s = IDBKeyRange.bound([ n, Number.NEGATIVE_INFINITY ], [ n, Number.POSITIVE_INFINITY ]);\n let i = null;\n return wo(t).X({\n range: s,\n index: \"queryTargetsIndex\"\n }, ((t, n, s) => {\n const r = mr(n);\n // After finding a potential match, check that the target is\n // actually equal to the requested target.\n On(e, r.target) && (i = r, s.done());\n })).next((() => i));\n }\n addMatchingKeys(t, e, n) {\n // PORTING NOTE: The reverse index (documentsTargets) is maintained by\n // IndexedDb.\n const s = [], i = mo(t);\n return e.forEach((e => {\n const r = qt(e.path);\n s.push(i.put({\n targetId: n,\n path: r\n })), s.push(this.referenceDelegate.addReference(t, n, e));\n })), Rt.waitFor(s);\n }\n removeMatchingKeys(t, e, n) {\n // PORTING NOTE: The reverse index (documentsTargets) is maintained by\n // IndexedDb.\n const s = mo(t);\n return Rt.forEach(e, (e => {\n const i = qt(e.path);\n return Rt.waitFor([ s.delete([ n, i ]), this.referenceDelegate.removeReference(t, n, e) ]);\n }));\n }\n removeMatchingKeysForTargetId(t, e) {\n const n = mo(t), s = IDBKeyRange.bound([ e ], [ e + 1 ], \n /*lowerOpen=*/ !1, \n /*upperOpen=*/ !0);\n return n.delete(s);\n }\n getMatchingKeysForTargetId(t, e) {\n const n = IDBKeyRange.bound([ e ], [ e + 1 ], \n /*lowerOpen=*/ !1, \n /*upperOpen=*/ !0), s = mo(t);\n let i = gs();\n return s.X({\n range: n,\n Y: !0\n }, ((t, e, n) => {\n const s = Gt(t[1]), r = new ht(s);\n i = i.add(r);\n })).next((() => i));\n }\n containsKey(t, e) {\n const n = qt(e.path), s = IDBKeyRange.bound([ n ], [ st(n) ], \n /*lowerOpen=*/ !1, \n /*upperOpen=*/ !0);\n let i = 0;\n return mo(t).X({\n index: \"documentTargetsIndex\",\n Y: !0,\n range: s\n }, (([t, e], n, s) => {\n // Having a sentinel row for a document does not count as containing that document;\n // For the target cache, containing the document means the document is part of some\n // target.\n 0 !== t && (i++, s.done());\n })).next((() => i > 0));\n }\n /**\n * Looks up a TargetData entry by target ID.\n *\n * @param targetId - The target ID of the TargetData entry to look up.\n * @returns The cached TargetData entry, or null if the cache has no entry for\n * the target.\n */\n // PORTING NOTE: Multi-tab only.\n le(t, e) {\n return wo(t).get(e).next((t => t ? mr(t) : null));\n }\n}\n\n/**\n * Helper to get a typed SimpleDbStore for the queries object store.\n */ function wo(t) {\n return _e(t, \"targets\");\n}\n\n/**\n * Helper to get a typed SimpleDbStore for the target globals object store.\n */ function _o(t) {\n return _e(t, \"targetGlobal\");\n}\n\n/**\n * Helper to get a typed SimpleDbStore for the document target object store.\n */ function mo(t) {\n return _e(t, \"targetDocuments\");\n}\n\n/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */ function go([t, e], [n, s]) {\n const i = et(t, n);\n return 0 === i ? et(e, s) : i;\n}\n\n/**\n * Used to calculate the nth sequence number. Keeps a rolling buffer of the\n * lowest n values passed to `addElement`, and finally reports the largest of\n * them in `maxValue`.\n */ class yo {\n constructor(t) {\n this.Ln = t, this.buffer = new Ee(go), this.qn = 0;\n }\n Un() {\n return ++this.qn;\n }\n Kn(t) {\n const e = [ t, this.Un() ];\n if (this.buffer.size < this.Ln) this.buffer = this.buffer.add(e); else {\n const t = this.buffer.last();\n go(e, t) < 0 && (this.buffer = this.buffer.delete(t).add(e));\n }\n }\n get maxValue() {\n // Guaranteed to be non-empty. If we decide we are not collecting any\n // sequence numbers, nthSequenceNumber below short-circuits. If we have\n // decided that we are collecting n sequence numbers, it's because n is some\n // percentage of the existing sequence numbers. That means we should never\n // be in a situation where we are collecting sequence numbers but don't\n // actually have any.\n return this.buffer.last()[0];\n }\n}\n\n/**\n * This class is responsible for the scheduling of LRU garbage collection. It handles checking\n * whether or not GC is enabled, as well as which delay to use before the next run.\n */ class po {\n constructor(t, e, n) {\n this.garbageCollector = t, this.asyncQueue = e, this.localStore = n, this.Gn = null;\n }\n start() {\n -1 !== this.garbageCollector.params.cacheSizeCollectionThreshold && this.Qn(6e4);\n }\n stop() {\n this.Gn && (this.Gn.cancel(), this.Gn = null);\n }\n get started() {\n return null !== this.Gn;\n }\n Qn(t) {\n N(\"LruGarbageCollector\", `Garbage collection scheduled in ${t}ms`), this.Gn = this.asyncQueue.enqueueAfterDelay(\"lru_garbage_collection\" /* TimerId.LruGarbageCollection */ , t, (async () => {\n this.Gn = null;\n try {\n await this.localStore.collectGarbage(this.garbageCollector);\n } catch (t) {\n Dt(t) ? N(\"LruGarbageCollector\", \"Ignoring IndexedDB error during garbage collection: \", t) : await vt(t);\n }\n await this.Qn(3e5);\n }));\n }\n}\n\n/**\n * Implements the steps for LRU garbage collection.\n */ class Io {\n constructor(t, e) {\n this.jn = t, this.params = e;\n }\n calculateTargetCount(t, e) {\n return this.jn.zn(t).next((t => Math.floor(e / 100 * t)));\n }\n nthSequenceNumber(t, e) {\n if (0 === e) return Rt.resolve(Ot.ct);\n const n = new yo(e);\n return this.jn.forEachTarget(t, (t => n.Kn(t.sequenceNumber))).next((() => this.jn.Wn(t, (t => n.Kn(t))))).next((() => n.maxValue));\n }\n removeTargets(t, e, n) {\n return this.jn.removeTargets(t, e, n);\n }\n removeOrphanedDocuments(t, e) {\n return this.jn.removeOrphanedDocuments(t, e);\n }\n collect(t, e) {\n return -1 === this.params.cacheSizeCollectionThreshold ? (N(\"LruGarbageCollector\", \"Garbage collection skipped; disabled\"), \n Rt.resolve(no)) : this.getCacheSize(t).next((n => n < this.params.cacheSizeCollectionThreshold ? (N(\"LruGarbageCollector\", `Garbage collection skipped; Cache size ${n} is lower than threshold ${this.params.cacheSizeCollectionThreshold}`), \n no) : this.Hn(t, e)));\n }\n getCacheSize(t) {\n return this.jn.getCacheSize(t);\n }\n Hn(t, e) {\n let n, s, i, r, o, c, a;\n const h = Date.now();\n return this.calculateTargetCount(t, this.params.percentileToCollect).next((e => (\n // Cap at the configured max\n e > this.params.maximumSequenceNumbersToCollect ? (N(\"LruGarbageCollector\", `Capping sequence numbers to collect down to the maximum of ${this.params.maximumSequenceNumbersToCollect} from ${e}`), \n s = this.params.maximumSequenceNumbersToCollect) : s = e, r = Date.now(), this.nthSequenceNumber(t, s)))).next((s => (n = s, \n o = Date.now(), this.removeTargets(t, n, e)))).next((e => (i = e, c = Date.now(), \n this.removeOrphanedDocuments(t, n)))).next((t => {\n if (a = Date.now(), C() <= LogLevel.DEBUG) {\n N(\"LruGarbageCollector\", `LRU Garbage Collection\\n\\tCounted targets in ${r - h}ms\\n\\tDetermined least recently used ${s} in ` + (o - r) + \"ms\\n\" + `\\tRemoved ${i} targets in ` + (c - o) + \"ms\\n\" + `\\tRemoved ${t} documents in ` + (a - c) + \"ms\\n\" + `Total Duration: ${a - h}ms`);\n }\n return Rt.resolve({\n didRun: !0,\n sequenceNumbersCollected: s,\n targetsRemoved: i,\n documentsRemoved: t\n });\n }));\n }\n}\n\nfunction To(t, e) {\n return new Io(t, e);\n}\n\n/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/** Provides LRU functionality for IndexedDB persistence. */ class Eo {\n constructor(t, e) {\n this.db = t, this.garbageCollector = To(this, e);\n }\n zn(t) {\n const e = this.Jn(t);\n return this.db.getTargetCache().getTargetCount(t).next((t => e.next((e => t + e))));\n }\n Jn(t) {\n let e = 0;\n return this.Wn(t, (t => {\n e++;\n })).next((() => e));\n }\n forEachTarget(t, e) {\n return this.db.getTargetCache().forEachTarget(t, e);\n }\n Wn(t, e) {\n return this.Yn(t, ((t, n) => e(n)));\n }\n addReference(t, e, n) {\n return Ao(t, n);\n }\n removeReference(t, e, n) {\n return Ao(t, n);\n }\n removeTargets(t, e, n) {\n return this.db.getTargetCache().removeTargets(t, e, n);\n }\n markPotentiallyOrphaned(t, e) {\n return Ao(t, e);\n }\n /**\n * Returns true if anything would prevent this document from being garbage\n * collected, given that the document in question is not present in any\n * targets and has a sequence number less than or equal to the upper bound for\n * the collection run.\n */ Xn(t, e) {\n return function(t, e) {\n let n = !1;\n return ho(t).Z((s => uo(t, s, e).next((t => (t && (n = !0), Rt.resolve(!t)))))).next((() => n));\n }(t, e);\n }\n removeOrphanedDocuments(t, e) {\n const n = this.db.getRemoteDocumentCache().newChangeBuffer(), s = [];\n let i = 0;\n return this.Yn(t, ((r, o) => {\n if (o <= e) {\n const e = this.Xn(t, r).next((e => {\n if (!e) \n // Our size accounting requires us to read all documents before\n // removing them.\n return i++, n.getEntry(t, r).next((() => (n.removeEntry(r, rt.min()), mo(t).delete([ 0, qt(r.path) ]))));\n }));\n s.push(e);\n }\n })).next((() => Rt.waitFor(s))).next((() => n.apply(t))).next((() => i));\n }\n removeTarget(t, e) {\n const n = e.withSequenceNumber(t.currentSequenceNumber);\n return this.db.getTargetCache().updateTargetData(t, n);\n }\n updateLimboDocument(t, e) {\n return Ao(t, e);\n }\n /**\n * Call provided function for each document in the cache that is 'orphaned'. Orphaned\n * means not a part of any target, so the only entry in the target-document index for\n * that document will be the sentinel row (targetId 0), which will also have the sequence\n * number for the last time the document was accessed.\n */ Yn(t, e) {\n const n = mo(t);\n let s, i = Ot.ct;\n return n.X({\n index: \"documentTargetsIndex\"\n }, (([t, n], {path: r, sequenceNumber: o}) => {\n 0 === t ? (\n // if nextToReport is valid, report it, this is a new key so the\n // last one must not be a member of any targets.\n i !== Ot.ct && e(new ht(Gt(s)), i), \n // set nextToReport to be this sequence number. It's the next one we\n // might report, if we don't find any targets for this document.\n // Note that the sequence number must be defined when the targetId\n // is 0.\n i = o, s = r) : \n // set nextToReport to be invalid, we know we don't need to report\n // this one since we found a target for it.\n i = Ot.ct;\n })).next((() => {\n // Since we report sequence numbers after getting to the next key, we\n // need to check if the last key we iterated over was an orphaned\n // document and report it.\n i !== Ot.ct && e(new ht(Gt(s)), i);\n }));\n }\n getCacheSize(t) {\n return this.db.getRemoteDocumentCache().getSize(t);\n }\n}\n\nfunction Ao(t, e) {\n return mo(t).put(\n /**\n * @returns A value suitable for writing a sentinel row in the target-document\n * store.\n */\n function(t, e) {\n return {\n targetId: 0,\n path: qt(t.path),\n sequenceNumber: e\n };\n }(e, t.currentSequenceNumber));\n}\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * An in-memory buffer of entries to be written to a RemoteDocumentCache.\n * It can be used to batch up a set of changes to be written to the cache, but\n * additionally supports reading entries back with the `getEntry()` method,\n * falling back to the underlying RemoteDocumentCache if no entry is\n * buffered.\n *\n * Entries added to the cache *must* be read first. This is to facilitate\n * calculating the size delta of the pending changes.\n *\n * PORTING NOTE: This class was implemented then removed from other platforms.\n * If byte-counting ends up being needed on the other platforms, consider\n * porting this class as part of that implementation work.\n */ class vo {\n constructor() {\n // A mapping of document key to the new cache entry that should be written.\n this.changes = new os((t => t.toString()), ((t, e) => t.isEqual(e))), this.changesApplied = !1;\n }\n /**\n * Buffers a `RemoteDocumentCache.addEntry()` call.\n *\n * You can only modify documents that have already been retrieved via\n * `getEntry()/getEntries()` (enforced via IndexedDbs `apply()`).\n */ addEntry(t) {\n this.assertNotApplied(), this.changes.set(t.key, t);\n }\n /**\n * Buffers a `RemoteDocumentCache.removeEntry()` call.\n *\n * You can only remove documents that have already been retrieved via\n * `getEntry()/getEntries()` (enforced via IndexedDbs `apply()`).\n */ removeEntry(t, e) {\n this.assertNotApplied(), this.changes.set(t, an.newInvalidDocument(t).setReadTime(e));\n }\n /**\n * Looks up an entry in the cache. The buffered changes will first be checked,\n * and if no buffered change applies, this will forward to\n * `RemoteDocumentCache.getEntry()`.\n *\n * @param transaction - The transaction in which to perform any persistence\n * operations.\n * @param documentKey - The key of the entry to look up.\n * @returns The cached document or an invalid document if we have nothing\n * cached.\n */ getEntry(t, e) {\n this.assertNotApplied();\n const n = this.changes.get(e);\n return void 0 !== n ? Rt.resolve(n) : this.getFromCache(t, e);\n }\n /**\n * Looks up several entries in the cache, forwarding to\n * `RemoteDocumentCache.getEntry()`.\n *\n * @param transaction - The transaction in which to perform any persistence\n * operations.\n * @param documentKeys - The keys of the entries to look up.\n * @returns A map of cached documents, indexed by key. If an entry cannot be\n * found, the corresponding key will be mapped to an invalid document.\n */ getEntries(t, e) {\n return this.getAllFromCache(t, e);\n }\n /**\n * Applies buffered changes to the underlying RemoteDocumentCache, using\n * the provided transaction.\n */ apply(t) {\n return this.assertNotApplied(), this.changesApplied = !0, this.applyChanges(t);\n }\n /** Helper to assert this.changes is not null */ assertNotApplied() {}\n}\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * The RemoteDocumentCache for IndexedDb. To construct, invoke\n * `newIndexedDbRemoteDocumentCache()`.\n */ class Ro {\n constructor(t) {\n this.serializer = t;\n }\n setIndexManager(t) {\n this.indexManager = t;\n }\n /**\n * Adds the supplied entries to the cache.\n *\n * All calls of `addEntry` are required to go through the RemoteDocumentChangeBuffer\n * returned by `newChangeBuffer()` to ensure proper accounting of metadata.\n */ addEntry(t, e, n) {\n return So(t).put(n);\n }\n /**\n * Removes a document from the cache.\n *\n * All calls of `removeEntry` are required to go through the RemoteDocumentChangeBuffer\n * returned by `newChangeBuffer()` to ensure proper accounting of metadata.\n */ removeEntry(t, e, n) {\n return So(t).delete(\n /**\n * Returns a key that can be used for document lookups via the primary key of\n * the DbRemoteDocument object store.\n */\n function(t, e) {\n const n = t.path.toArray();\n return [ \n /* prefix path */ n.slice(0, n.length - 2), \n /* collection id */ n[n.length - 2], fr(e), \n /* document id */ n[n.length - 1] ];\n }\n /**\n * Returns a key that can be used for document lookups on the\n * `DbRemoteDocumentDocumentCollectionGroupIndex` index.\n */ (e, n));\n }\n /**\n * Updates the current cache size.\n *\n * Callers to `addEntry()` and `removeEntry()` *must* call this afterwards to update the\n * cache's metadata.\n */ updateMetadata(t, e) {\n return this.getMetadata(t).next((n => (n.byteSize += e, this.Zn(t, n))));\n }\n getEntry(t, e) {\n let n = an.newInvalidDocument(e);\n return So(t).X({\n index: \"documentKeyIndex\",\n range: IDBKeyRange.only(Do(e))\n }, ((t, s) => {\n n = this.ts(e, s);\n })).next((() => n));\n }\n /**\n * Looks up an entry in the cache.\n *\n * @param documentKey - The key of the entry to look up.\n * @returns The cached document entry and its size.\n */ es(t, e) {\n let n = {\n size: 0,\n document: an.newInvalidDocument(e)\n };\n return So(t).X({\n index: \"documentKeyIndex\",\n range: IDBKeyRange.only(Do(e))\n }, ((t, s) => {\n n = {\n document: this.ts(e, s),\n size: ro(s)\n };\n })).next((() => n));\n }\n getEntries(t, e) {\n let n = cs();\n return this.ns(t, e, ((t, e) => {\n const s = this.ts(t, e);\n n = n.insert(t, s);\n })).next((() => n));\n }\n /**\n * Looks up several entries in the cache.\n *\n * @param documentKeys - The set of keys entries to look up.\n * @returns A map of documents indexed by key and a map of sizes indexed by\n * key (zero if the document does not exist).\n */ ss(t, e) {\n let n = cs(), s = new pe(ht.comparator);\n return this.ns(t, e, ((t, e) => {\n const i = this.ts(t, e);\n n = n.insert(t, i), s = s.insert(t, ro(e));\n })).next((() => ({\n documents: n,\n rs: s\n })));\n }\n ns(t, e, n) {\n if (e.isEmpty()) return Rt.resolve();\n let s = new Ee(xo);\n e.forEach((t => s = s.add(t)));\n const i = IDBKeyRange.bound(Do(s.first()), Do(s.last())), r = s.getIterator();\n let o = r.getNext();\n return So(t).X({\n index: \"documentKeyIndex\",\n range: i\n }, ((t, e, s) => {\n const i = ht.fromSegments([ ...e.prefixPath, e.collectionGroup, e.documentId ]);\n // Go through keys not found in cache.\n for (;o && xo(o, i) < 0; ) n(o, null), o = r.getNext();\n o && o.isEqual(i) && (\n // Key found in cache.\n n(o, e), o = r.hasNext() ? r.getNext() : null), \n // Skip to the next key (if there is one).\n o ? s.G(Do(o)) : s.done();\n })).next((() => {\n // The rest of the keys are not in the cache. One case where `iterate`\n // above won't go through them is when the cache is empty.\n for (;o; ) n(o, null), o = r.hasNext() ? r.getNext() : null;\n }));\n }\n getDocumentsMatchingQuery(t, e, n, s) {\n const i = e.path, r = [ i.popLast().toArray(), i.lastSegment(), fr(n.readTime), n.documentKey.path.isEmpty() ? \"\" : n.documentKey.path.lastSegment() ], o = [ i.popLast().toArray(), i.lastSegment(), [ Number.MAX_SAFE_INTEGER, Number.MAX_SAFE_INTEGER ], \"\" ];\n return So(t).j(IDBKeyRange.bound(r, o, !0)).next((t => {\n let n = cs();\n for (const i of t) {\n const t = this.ts(ht.fromSegments(i.prefixPath.concat(i.collectionGroup, i.documentId)), i);\n t.isFoundDocument() && (ns(e, t) || s.has(t.key)) && (\n // Either the document matches the given query, or it is mutated.\n n = n.insert(t.key, t));\n }\n return n;\n }));\n }\n getAllFromCollectionGroup(t, e, n, s) {\n let i = cs();\n const r = Co(e, n), o = Co(e, It.max());\n return So(t).X({\n index: \"collectionGroupIndex\",\n range: IDBKeyRange.bound(r, o, !0)\n }, ((t, e, n) => {\n const r = this.ts(ht.fromSegments(e.prefixPath.concat(e.collectionGroup, e.documentId)), e);\n i = i.insert(r.key, r), i.size === s && n.done();\n })).next((() => i));\n }\n newChangeBuffer(t) {\n return new bo(this, !!t && t.trackRemovals);\n }\n getSize(t) {\n return this.getMetadata(t).next((t => t.byteSize));\n }\n getMetadata(t) {\n return Vo(t).get(\"remoteDocumentGlobalKey\").next((t => (F(!!t), t)));\n }\n Zn(t, e) {\n return Vo(t).put(\"remoteDocumentGlobalKey\", e);\n }\n /**\n * Decodes `dbRemoteDoc` and returns the document (or an invalid document if\n * the document corresponds to the format used for sentinel deletes).\n */ ts(t, e) {\n if (e) {\n const t = hr(this.serializer, e);\n // Whether the document is a sentinel removal and should only be used in the\n // `getNewDocumentChanges()`\n if (!(t.isNoDocument() && t.version.isEqual(rt.min()))) return t;\n }\n return an.newInvalidDocument(t);\n }\n}\n\n/** Creates a new IndexedDbRemoteDocumentCache. */ function Po(t) {\n return new Ro(t);\n}\n\n/**\n * Handles the details of adding and updating documents in the IndexedDbRemoteDocumentCache.\n *\n * Unlike the MemoryRemoteDocumentChangeBuffer, the IndexedDb implementation computes the size\n * delta for all submitted changes. This avoids having to re-read all documents from IndexedDb\n * when we apply the changes.\n */ class bo extends vo {\n /**\n * @param documentCache - The IndexedDbRemoteDocumentCache to apply the changes to.\n * @param trackRemovals - Whether to create sentinel deletes that can be tracked by\n * `getNewDocumentChanges()`.\n */\n constructor(t, e) {\n super(), this.os = t, this.trackRemovals = e, \n // A map of document sizes and read times prior to applying the changes in\n // this buffer.\n this.us = new os((t => t.toString()), ((t, e) => t.isEqual(e)));\n }\n applyChanges(t) {\n const e = [];\n let n = 0, s = new Ee(((t, e) => et(t.canonicalString(), e.canonicalString())));\n return this.changes.forEach(((i, r) => {\n const o = this.us.get(i);\n if (e.push(this.os.removeEntry(t, i, o.readTime)), r.isValidDocument()) {\n const u = lr(this.os.serializer, r);\n s = s.add(i.path.popLast());\n const c = ro(u);\n n += c - o.size, e.push(this.os.addEntry(t, i, u));\n } else if (n -= o.size, this.trackRemovals) {\n // In order to track removals, we store a \"sentinel delete\" in the\n // RemoteDocumentCache. This entry is represented by a NoDocument\n // with a version of 0 and ignored by `maybeDecodeDocument()` but\n // preserved in `getNewDocumentChanges()`.\n const n = lr(this.os.serializer, r.convertToNoDocument(rt.min()));\n e.push(this.os.addEntry(t, i, n));\n }\n })), s.forEach((n => {\n e.push(this.os.indexManager.addToCollectionParentIndex(t, n));\n })), e.push(this.os.updateMetadata(t, n)), Rt.waitFor(e);\n }\n getFromCache(t, e) {\n // Record the size of everything we load from the cache so we can compute a delta later.\n return this.os.es(t, e).next((t => (this.us.set(e, {\n size: t.size,\n readTime: t.document.readTime\n }), t.document)));\n }\n getAllFromCache(t, e) {\n // Record the size of everything we load from the cache so we can compute\n // a delta later.\n return this.os.ss(t, e).next((({documents: t, rs: e}) => (\n // Note: `getAllFromCache` returns two maps instead of a single map from\n // keys to `DocumentSizeEntry`s. This is to allow returning the\n // `MutableDocumentMap` directly, without a conversion.\n e.forEach(((e, n) => {\n this.us.set(e, {\n size: n,\n readTime: t.get(e).readTime\n });\n })), t)));\n }\n}\n\nfunction Vo(t) {\n return _e(t, \"remoteDocumentGlobal\");\n}\n\n/**\n * Helper to get a typed SimpleDbStore for the remoteDocuments object store.\n */ function So(t) {\n return _e(t, \"remoteDocumentsV14\");\n}\n\n/**\n * Returns a key that can be used for document lookups on the\n * `DbRemoteDocumentDocumentKeyIndex` index.\n */ function Do(t) {\n const e = t.path.toArray();\n return [ \n /* prefix path */ e.slice(0, e.length - 2), \n /* collection id */ e[e.length - 2], \n /* document id */ e[e.length - 1] ];\n}\n\nfunction Co(t, e) {\n const n = e.documentKey.path.toArray();\n return [ \n /* collection id */ t, fr(e.readTime), \n /* prefix path */ n.slice(0, n.length - 2), \n /* document id */ n.length > 0 ? n[n.length - 1] : \"\" ];\n}\n\n/**\n * Comparator that compares document keys according to the primary key sorting\n * used by the `DbRemoteDocumentDocument` store (by prefix path, collection id\n * and then document ID).\n *\n * Visible for testing.\n */ function xo(t, e) {\n const n = t.path.toArray(), s = e.path.toArray();\n // The ordering is based on https://chromium.googlesource.com/chromium/blink/+/fe5c21fef94dae71c1c3344775b8d8a7f7e6d9ec/Source/modules/indexeddb/IDBKey.cpp#74\n let i = 0;\n for (let t = 0; t < n.length - 2 && t < s.length - 2; ++t) if (i = et(n[t], s[t]), \n i) return i;\n return i = et(n.length, s.length), i || (i = et(n[n.length - 2], s[s.length - 2]), \n i || et(n[n.length - 1], s[s.length - 1]));\n}\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * Schema Version for the Web client:\n * 1. Initial version including Mutation Queue, Query Cache, and Remote\n * Document Cache\n * 2. Used to ensure a targetGlobal object exists and add targetCount to it. No\n * longer required because migration 3 unconditionally clears it.\n * 3. Dropped and re-created Query Cache to deal with cache corruption related\n * to limbo resolution. Addresses\n * https://github.com/firebase/firebase-ios-sdk/issues/1548\n * 4. Multi-Tab Support.\n * 5. Removal of held write acks.\n * 6. Create document global for tracking document cache size.\n * 7. Ensure every cached document has a sentinel row with a sequence number.\n * 8. Add collection-parent index for Collection Group queries.\n * 9. Change RemoteDocumentChanges store to be keyed by readTime rather than\n * an auto-incrementing ID. This is required for Index-Free queries.\n * 10. Rewrite the canonical IDs to the explicit Protobuf-based format.\n * 11. Add bundles and named_queries for bundle support.\n * 12. Add document overlays.\n * 13. Rewrite the keys of the remote document cache to allow for efficient\n * document lookup via `getAll()`.\n * 14. Add overlays.\n * 15. Add indexing support.\n */\n/**\n * @license\n * Copyright 2022 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * Represents a local view (overlay) of a document, and the fields that are\n * locally mutated.\n */\nclass No {\n constructor(t, \n /**\n * The fields that are locally mutated by patch mutations.\n *\n * If the overlayed\tdocument is from set or delete mutations, this is `null`.\n * If there is no overlay (mutation) for the document, this is an empty `FieldMask`.\n */\n e) {\n this.overlayedDocument = t, this.mutatedFields = e;\n }\n}\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * A readonly view of the local state of all documents we're tracking (i.e. we\n * have a cached version in remoteDocumentCache or local mutations for the\n * document). The view is computed by applying the mutations in the\n * MutationQueue to the RemoteDocumentCache.\n */ class ko {\n constructor(t, e, n, s) {\n this.remoteDocumentCache = t, this.mutationQueue = e, this.documentOverlayCache = n, \n this.indexManager = s;\n }\n /**\n * Get the local view of the document identified by `key`.\n *\n * @returns Local view of the document or null if we don't have any cached\n * state for it.\n */ getDocument(t, e) {\n let n = null;\n return this.documentOverlayCache.getOverlay(t, e).next((s => (n = s, this.remoteDocumentCache.getEntry(t, e)))).next((t => (null !== n && Ks(n.mutation, t, Re.empty(), it.now()), \n t)));\n }\n /**\n * Gets the local view of the documents identified by `keys`.\n *\n * If we don't have cached state for a document in `keys`, a NoDocument will\n * be stored for that key in the resulting set.\n */ getDocuments(t, e) {\n return this.remoteDocumentCache.getEntries(t, e).next((e => this.getLocalViewOfDocuments(t, e, gs()).next((() => e))));\n }\n /**\n * Similar to `getDocuments`, but creates the local view from the given\n * `baseDocs` without retrieving documents from the local store.\n *\n * @param transaction - The transaction this operation is scoped to.\n * @param docs - The documents to apply local mutations to get the local views.\n * @param existenceStateChanged - The set of document keys whose existence state\n * is changed. This is useful to determine if some documents overlay needs\n * to be recalculated.\n */ getLocalViewOfDocuments(t, e, n = gs()) {\n const s = fs();\n return this.populateOverlays(t, s, e).next((() => this.computeViews(t, e, s, n).next((t => {\n let e = hs();\n return t.forEach(((t, n) => {\n e = e.insert(t, n.overlayedDocument);\n })), e;\n }))));\n }\n /**\n * Gets the overlayed documents for the given document map, which will include\n * the local view of those documents and a `FieldMask` indicating which fields\n * are mutated locally, `null` if overlay is a Set or Delete mutation.\n */ getOverlayedDocuments(t, e) {\n const n = fs();\n return this.populateOverlays(t, n, e).next((() => this.computeViews(t, e, n, gs())));\n }\n /**\n * Fetches the overlays for {@code docs} and adds them to provided overlay map\n * if the map does not already contain an entry for the given document key.\n */ populateOverlays(t, e, n) {\n const s = [];\n return n.forEach((t => {\n e.has(t) || s.push(t);\n })), this.documentOverlayCache.getOverlays(t, s).next((t => {\n t.forEach(((t, n) => {\n e.set(t, n);\n }));\n }));\n }\n /**\n * Computes the local view for the given documents.\n *\n * @param docs - The documents to compute views for. It also has the base\n * version of the documents.\n * @param overlays - The overlays that need to be applied to the given base\n * version of the documents.\n * @param existenceStateChanged - A set of documents whose existence states\n * might have changed. This is used to determine if we need to re-calculate\n * overlays from mutation queues.\n * @return A map represents the local documents view.\n */ computeViews(t, e, n, s) {\n let i = cs();\n const r = ws(), o = ws();\n return e.forEach(((t, e) => {\n const o = n.get(e.key);\n // Recalculate an overlay if the document's existence state changed due to\n // a remote event *and* the overlay is a PatchMutation. This is because\n // document existence state can change if some patch mutation's\n // preconditions are met.\n // NOTE: we recalculate when `overlay` is undefined as well, because there\n // might be a patch mutation whose precondition does not match before the\n // change (hence overlay is undefined), but would now match.\n s.has(e.key) && (void 0 === o || o.mutation instanceof zs) ? i = i.insert(e.key, e) : void 0 !== o ? (r.set(e.key, o.mutation.getFieldMask()), \n Ks(o.mutation, e, o.mutation.getFieldMask(), it.now())) : \n // no overlay exists\n // Using EMPTY to indicate there is no overlay for the document.\n r.set(e.key, Re.empty());\n })), this.recalculateAndSaveOverlays(t, i).next((t => (t.forEach(((t, e) => r.set(t, e))), \n e.forEach(((t, e) => {\n var n;\n return o.set(t, new No(e, null !== (n = r.get(t)) && void 0 !== n ? n : null));\n })), o)));\n }\n recalculateAndSaveOverlays(t, e) {\n const n = ws();\n // A reverse lookup map from batch id to the documents within that batch.\n let s = new pe(((t, e) => t - e)), i = gs();\n return this.mutationQueue.getAllMutationBatchesAffectingDocumentKeys(t, e).next((t => {\n for (const i of t) i.keys().forEach((t => {\n const r = e.get(t);\n if (null === r) return;\n let o = n.get(t) || Re.empty();\n o = i.applyToLocalView(r, o), n.set(t, o);\n const u = (s.get(i.batchId) || gs()).add(t);\n s = s.insert(i.batchId, u);\n }));\n })).next((() => {\n const r = [], o = s.getReverseIterator();\n // Iterate in descending order of batch IDs, and skip documents that are\n // already saved.\n for (;o.hasNext(); ) {\n const s = o.getNext(), u = s.key, c = s.value, a = ds();\n c.forEach((t => {\n if (!i.has(t)) {\n const s = qs(e.get(t), n.get(t));\n null !== s && a.set(t, s), i = i.add(t);\n }\n })), r.push(this.documentOverlayCache.saveOverlays(t, u, a));\n }\n return Rt.waitFor(r);\n })).next((() => n));\n }\n /**\n * Recalculates overlays by reading the documents from remote document cache\n * first, and saves them after they are calculated.\n */ recalculateAndSaveOverlaysForDocumentKeys(t, e) {\n return this.remoteDocumentCache.getEntries(t, e).next((e => this.recalculateAndSaveOverlays(t, e)));\n }\n /**\n * Performs a query against the local view of all documents.\n *\n * @param transaction - The persistence transaction.\n * @param query - The query to match documents against.\n * @param offset - Read time and key to start scanning by (exclusive).\n */ getDocumentsMatchingQuery(t, e, n) {\n /**\n * Returns whether the query matches a single document by path (rather than a\n * collection).\n */\n return function(t) {\n return ht.isDocumentKey(t.path) && null === t.collectionGroup && 0 === t.filters.length;\n }(e) ? this.getDocumentsMatchingDocumentQuery(t, e.path) : Wn(e) ? this.getDocumentsMatchingCollectionGroupQuery(t, e, n) : this.getDocumentsMatchingCollectionQuery(t, e, n);\n }\n /**\n * Given a collection group, returns the next documents that follow the provided offset, along\n * with an updated batch ID.\n *\n *

The documents returned by this method are ordered by remote version from the provided\n * offset. If there are no more remote documents after the provided offset, documents with\n * mutations in order of batch id from the offset are returned. Since all documents in a batch are\n * returned together, the total number of documents returned can exceed {@code count}.\n *\n * @param transaction\n * @param collectionGroup The collection group for the documents.\n * @param offset The offset to index into.\n * @param count The number of documents to return\n * @return A LocalWriteResult with the documents that follow the provided offset and the last processed batch id.\n */ getNextDocuments(t, e, n, s) {\n return this.remoteDocumentCache.getAllFromCollectionGroup(t, e, n, s).next((i => {\n const r = s - i.size > 0 ? this.documentOverlayCache.getOverlaysForCollectionGroup(t, e, n.largestBatchId, s - i.size) : Rt.resolve(fs());\n // The callsite will use the largest batch ID together with the latest read time to create\n // a new index offset. Since we only process batch IDs if all remote documents have been read,\n // no overlay will increase the overall read time. This is why we only need to special case\n // the batch id.\n let o = -1, u = i;\n return r.next((e => Rt.forEach(e, ((e, n) => (o < n.largestBatchId && (o = n.largestBatchId), \n i.get(e) ? Rt.resolve() : this.remoteDocumentCache.getEntry(t, e).next((t => {\n u = u.insert(e, t);\n }))))).next((() => this.populateOverlays(t, e, i))).next((() => this.computeViews(t, u, e, gs()))).next((t => ({\n batchId: o,\n changes: ls(t)\n })))));\n }));\n }\n getDocumentsMatchingDocumentQuery(t, e) {\n // Just do a simple document lookup.\n return this.getDocument(t, new ht(e)).next((t => {\n let e = hs();\n return t.isFoundDocument() && (e = e.insert(t.key, t)), e;\n }));\n }\n getDocumentsMatchingCollectionGroupQuery(t, e, n) {\n const s = e.collectionGroup;\n let i = hs();\n return this.indexManager.getCollectionParents(t, s).next((r => Rt.forEach(r, (r => {\n const o = function(t, e) {\n return new Un(e, \n /*collectionGroup=*/ null, t.explicitOrderBy.slice(), t.filters.slice(), t.limit, t.limitType, t.startAt, t.endAt);\n }(e, r.child(s));\n return this.getDocumentsMatchingCollectionQuery(t, o, n).next((t => {\n t.forEach(((t, e) => {\n i = i.insert(t, e);\n }));\n }));\n })).next((() => i))));\n }\n getDocumentsMatchingCollectionQuery(t, e, n) {\n // Query the remote documents and overlay mutations.\n let s;\n return this.documentOverlayCache.getOverlaysForCollection(t, e.path, n.largestBatchId).next((i => (s = i, \n this.remoteDocumentCache.getDocumentsMatchingQuery(t, e, n, s)))).next((t => {\n // As documents might match the query because of their overlay we need to\n // include documents for all overlays in the initial document set.\n s.forEach(((e, n) => {\n const s = n.getKey();\n null === t.get(s) && (t = t.insert(s, an.newInvalidDocument(s)));\n }));\n // Apply the overlays and match against the query.\n let n = hs();\n return t.forEach(((t, i) => {\n const r = s.get(t);\n void 0 !== r && Ks(r.mutation, i, Re.empty(), it.now()), \n // Finally, insert the documents that still match the query\n ns(e, i) && (n = n.insert(t, i));\n })), n;\n }));\n }\n}\n\n/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */ class Mo {\n constructor(t) {\n this.serializer = t, this.cs = new Map, this.hs = new Map;\n }\n getBundleMetadata(t, e) {\n return Rt.resolve(this.cs.get(e));\n }\n saveBundleMetadata(t, e) {\n /** Decodes a BundleMetadata proto into a BundleMetadata object. */\n var n;\n return this.cs.set(e.id, {\n id: (n = e).id,\n version: n.version,\n createTime: Ni(n.createTime)\n }), Rt.resolve();\n }\n getNamedQuery(t, e) {\n return Rt.resolve(this.hs.get(e));\n }\n saveNamedQuery(t, e) {\n return this.hs.set(e.name, function(t) {\n return {\n name: t.name,\n query: yr(t.bundledQuery),\n readTime: Ni(t.readTime)\n };\n }(e)), Rt.resolve();\n }\n}\n\n/**\n * @license\n * Copyright 2022 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * An in-memory implementation of DocumentOverlayCache.\n */ class $o {\n constructor() {\n // A map sorted by DocumentKey, whose value is a pair of the largest batch id\n // for the overlay and the overlay itself.\n this.overlays = new pe(ht.comparator), this.ls = new Map;\n }\n getOverlay(t, e) {\n return Rt.resolve(this.overlays.get(e));\n }\n getOverlays(t, e) {\n const n = fs();\n return Rt.forEach(e, (e => this.getOverlay(t, e).next((t => {\n null !== t && n.set(e, t);\n })))).next((() => n));\n }\n saveOverlays(t, e, n) {\n return n.forEach(((n, s) => {\n this.we(t, e, s);\n })), Rt.resolve();\n }\n removeOverlaysForBatchId(t, e, n) {\n const s = this.ls.get(n);\n return void 0 !== s && (s.forEach((t => this.overlays = this.overlays.remove(t))), \n this.ls.delete(n)), Rt.resolve();\n }\n getOverlaysForCollection(t, e, n) {\n const s = fs(), i = e.length + 1, r = new ht(e.child(\"\")), o = this.overlays.getIteratorFrom(r);\n for (;o.hasNext(); ) {\n const t = o.getNext().value, r = t.getKey();\n if (!e.isPrefixOf(r.path)) break;\n // Documents from sub-collections\n r.path.length === i && (t.largestBatchId > n && s.set(t.getKey(), t));\n }\n return Rt.resolve(s);\n }\n getOverlaysForCollectionGroup(t, e, n, s) {\n let i = new pe(((t, e) => t - e));\n const r = this.overlays.getIterator();\n for (;r.hasNext(); ) {\n const t = r.getNext().value;\n if (t.getKey().getCollectionGroup() === e && t.largestBatchId > n) {\n let e = i.get(t.largestBatchId);\n null === e && (e = fs(), i = i.insert(t.largestBatchId, e)), e.set(t.getKey(), t);\n }\n }\n const o = fs(), u = i.getIterator();\n for (;u.hasNext(); ) {\n if (u.getNext().value.forEach(((t, e) => o.set(t, e))), o.size() >= s) break;\n }\n return Rt.resolve(o);\n }\n we(t, e, n) {\n // Remove the association of the overlay to its batch id.\n const s = this.overlays.get(n.key);\n if (null !== s) {\n const t = this.ls.get(s.largestBatchId).delete(n.key);\n this.ls.set(s.largestBatchId, t);\n }\n this.overlays = this.overlays.insert(n.key, new ei(e, n));\n // Create the association of this overlay to the given largestBatchId.\n let i = this.ls.get(e);\n void 0 === i && (i = gs(), this.ls.set(e, i)), this.ls.set(e, i.add(n.key));\n }\n}\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * A collection of references to a document from some kind of numbered entity\n * (either a target ID or batch ID). As references are added to or removed from\n * the set corresponding events are emitted to a registered garbage collector.\n *\n * Each reference is represented by a DocumentReference object. Each of them\n * contains enough information to uniquely identify the reference. They are all\n * stored primarily in a set sorted by key. A document is considered garbage if\n * there's no references in that set (this can be efficiently checked thanks to\n * sorting by key).\n *\n * ReferenceSet also keeps a secondary set that contains references sorted by\n * IDs. This one is used to efficiently implement removal of all references by\n * some target ID.\n */ class Oo {\n constructor() {\n // A set of outstanding references to a document sorted by key.\n this.fs = new Ee(Fo.ds), \n // A set of outstanding references to a document sorted by target id.\n this.ws = new Ee(Fo._s);\n }\n /** Returns true if the reference set contains no references. */ isEmpty() {\n return this.fs.isEmpty();\n }\n /** Adds a reference to the given document key for the given ID. */ addReference(t, e) {\n const n = new Fo(t, e);\n this.fs = this.fs.add(n), this.ws = this.ws.add(n);\n }\n /** Add references to the given document keys for the given ID. */ gs(t, e) {\n t.forEach((t => this.addReference(t, e)));\n }\n /**\n * Removes a reference to the given document key for the given\n * ID.\n */ removeReference(t, e) {\n this.ys(new Fo(t, e));\n }\n ps(t, e) {\n t.forEach((t => this.removeReference(t, e)));\n }\n /**\n * Clears all references with a given ID. Calls removeRef() for each key\n * removed.\n */ Is(t) {\n const e = new ht(new ut([])), n = new Fo(e, t), s = new Fo(e, t + 1), i = [];\n return this.ws.forEachInRange([ n, s ], (t => {\n this.ys(t), i.push(t.key);\n })), i;\n }\n Ts() {\n this.fs.forEach((t => this.ys(t)));\n }\n ys(t) {\n this.fs = this.fs.delete(t), this.ws = this.ws.delete(t);\n }\n Es(t) {\n const e = new ht(new ut([])), n = new Fo(e, t), s = new Fo(e, t + 1);\n let i = gs();\n return this.ws.forEachInRange([ n, s ], (t => {\n i = i.add(t.key);\n })), i;\n }\n containsKey(t) {\n const e = new Fo(t, 0), n = this.fs.firstAfterOrEqual(e);\n return null !== n && t.isEqual(n.key);\n }\n}\n\nclass Fo {\n constructor(t, e) {\n this.key = t, this.As = e;\n }\n /** Compare by key then by ID */ static ds(t, e) {\n return ht.comparator(t.key, e.key) || et(t.As, e.As);\n }\n /** Compare by ID then by key */ static _s(t, e) {\n return et(t.As, e.As) || ht.comparator(t.key, e.key);\n }\n}\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */ class Bo {\n constructor(t, e) {\n this.indexManager = t, this.referenceDelegate = e, \n /**\n * The set of all mutations that have been sent but not yet been applied to\n * the backend.\n */\n this.mutationQueue = [], \n /** Next value to use when assigning sequential IDs to each mutation batch. */\n this.vs = 1, \n /** An ordered mapping between documents and the mutations batch IDs. */\n this.Rs = new Ee(Fo.ds);\n }\n checkEmpty(t) {\n return Rt.resolve(0 === this.mutationQueue.length);\n }\n addMutationBatch(t, e, n, s) {\n const i = this.vs;\n this.vs++, this.mutationQueue.length > 0 && this.mutationQueue[this.mutationQueue.length - 1];\n const r = new Zs(i, e, n, s);\n this.mutationQueue.push(r);\n // Track references by document key and index collection parents.\n for (const e of s) this.Rs = this.Rs.add(new Fo(e.key, i)), this.indexManager.addToCollectionParentIndex(t, e.key.path.popLast());\n return Rt.resolve(r);\n }\n lookupMutationBatch(t, e) {\n return Rt.resolve(this.Ps(e));\n }\n getNextMutationBatchAfterBatchId(t, e) {\n const n = e + 1, s = this.bs(n), i = s < 0 ? 0 : s;\n // The requested batchId may still be out of range so normalize it to the\n // start of the queue.\n return Rt.resolve(this.mutationQueue.length > i ? this.mutationQueue[i] : null);\n }\n getHighestUnacknowledgedBatchId() {\n return Rt.resolve(0 === this.mutationQueue.length ? -1 : this.vs - 1);\n }\n getAllMutationBatches(t) {\n return Rt.resolve(this.mutationQueue.slice());\n }\n getAllMutationBatchesAffectingDocumentKey(t, e) {\n const n = new Fo(e, 0), s = new Fo(e, Number.POSITIVE_INFINITY), i = [];\n return this.Rs.forEachInRange([ n, s ], (t => {\n const e = this.Ps(t.As);\n i.push(e);\n })), Rt.resolve(i);\n }\n getAllMutationBatchesAffectingDocumentKeys(t, e) {\n let n = new Ee(et);\n return e.forEach((t => {\n const e = new Fo(t, 0), s = new Fo(t, Number.POSITIVE_INFINITY);\n this.Rs.forEachInRange([ e, s ], (t => {\n n = n.add(t.As);\n }));\n })), Rt.resolve(this.Vs(n));\n }\n getAllMutationBatchesAffectingQuery(t, e) {\n // Use the query path as a prefix for testing if a document matches the\n // query.\n const n = e.path, s = n.length + 1;\n // Construct a document reference for actually scanning the index. Unlike\n // the prefix the document key in this reference must have an even number of\n // segments. The empty segment can be used a suffix of the query path\n // because it precedes all other segments in an ordered traversal.\n let i = n;\n ht.isDocumentKey(i) || (i = i.child(\"\"));\n const r = new Fo(new ht(i), 0);\n // Find unique batchIDs referenced by all documents potentially matching the\n // query.\n let o = new Ee(et);\n return this.Rs.forEachWhile((t => {\n const e = t.key.path;\n return !!n.isPrefixOf(e) && (\n // Rows with document keys more than one segment longer than the query\n // path can't be matches. For example, a query on 'rooms' can't match\n // the document /rooms/abc/messages/xyx.\n // TODO(mcg): we'll need a different scanner when we implement\n // ancestor queries.\n e.length === s && (o = o.add(t.As)), !0);\n }), r), Rt.resolve(this.Vs(o));\n }\n Vs(t) {\n // Construct an array of matching batches, sorted by batchID to ensure that\n // multiple mutations affecting the same document key are applied in order.\n const e = [];\n return t.forEach((t => {\n const n = this.Ps(t);\n null !== n && e.push(n);\n })), e;\n }\n removeMutationBatch(t, e) {\n F(0 === this.Ss(e.batchId, \"removed\")), this.mutationQueue.shift();\n let n = this.Rs;\n return Rt.forEach(e.mutations, (s => {\n const i = new Fo(s.key, e.batchId);\n return n = n.delete(i), this.referenceDelegate.markPotentiallyOrphaned(t, s.key);\n })).next((() => {\n this.Rs = n;\n }));\n }\n Cn(t) {\n // No-op since the memory mutation queue does not maintain a separate cache.\n }\n containsKey(t, e) {\n const n = new Fo(e, 0), s = this.Rs.firstAfterOrEqual(n);\n return Rt.resolve(e.isEqual(s && s.key));\n }\n performConsistencyCheck(t) {\n return this.mutationQueue.length, Rt.resolve();\n }\n /**\n * Finds the index of the given batchId in the mutation queue and asserts that\n * the resulting index is within the bounds of the queue.\n *\n * @param batchId - The batchId to search for\n * @param action - A description of what the caller is doing, phrased in passive\n * form (e.g. \"acknowledged\" in a routine that acknowledges batches).\n */ Ss(t, e) {\n return this.bs(t);\n }\n /**\n * Finds the index of the given batchId in the mutation queue. This operation\n * is O(1).\n *\n * @returns The computed index of the batch with the given batchId, based on\n * the state of the queue. Note this index can be negative if the requested\n * batchId has already been remvoed from the queue or past the end of the\n * queue if the batchId is larger than the last added batch.\n */ bs(t) {\n if (0 === this.mutationQueue.length) \n // As an index this is past the end of the queue\n return 0;\n // Examine the front of the queue to figure out the difference between the\n // batchId and indexes in the array. Note that since the queue is ordered\n // by batchId, if the first batch has a larger batchId then the requested\n // batchId doesn't exist in the queue.\n return t - this.mutationQueue[0].batchId;\n }\n /**\n * A version of lookupMutationBatch that doesn't return a promise, this makes\n * other functions that uses this code easier to read and more efficent.\n */ Ps(t) {\n const e = this.bs(t);\n if (e < 0 || e >= this.mutationQueue.length) return null;\n return this.mutationQueue[e];\n }\n}\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * The memory-only RemoteDocumentCache for IndexedDb. To construct, invoke\n * `newMemoryRemoteDocumentCache()`.\n */\nclass Lo {\n /**\n * @param sizer - Used to assess the size of a document. For eager GC, this is\n * expected to just return 0 to avoid unnecessarily doing the work of\n * calculating the size.\n */\n constructor(t) {\n this.Ds = t, \n /** Underlying cache of documents and their read times. */\n this.docs = new pe(ht.comparator), \n /** Size of all cached documents. */\n this.size = 0;\n }\n setIndexManager(t) {\n this.indexManager = t;\n }\n /**\n * Adds the supplied entry to the cache and updates the cache size as appropriate.\n *\n * All calls of `addEntry` are required to go through the RemoteDocumentChangeBuffer\n * returned by `newChangeBuffer()`.\n */ addEntry(t, e) {\n const n = e.key, s = this.docs.get(n), i = s ? s.size : 0, r = this.Ds(e);\n return this.docs = this.docs.insert(n, {\n document: e.mutableCopy(),\n size: r\n }), this.size += r - i, this.indexManager.addToCollectionParentIndex(t, n.path.popLast());\n }\n /**\n * Removes the specified entry from the cache and updates the cache size as appropriate.\n *\n * All calls of `removeEntry` are required to go through the RemoteDocumentChangeBuffer\n * returned by `newChangeBuffer()`.\n */ removeEntry(t) {\n const e = this.docs.get(t);\n e && (this.docs = this.docs.remove(t), this.size -= e.size);\n }\n getEntry(t, e) {\n const n = this.docs.get(e);\n return Rt.resolve(n ? n.document.mutableCopy() : an.newInvalidDocument(e));\n }\n getEntries(t, e) {\n let n = cs();\n return e.forEach((t => {\n const e = this.docs.get(t);\n n = n.insert(t, e ? e.document.mutableCopy() : an.newInvalidDocument(t));\n })), Rt.resolve(n);\n }\n getDocumentsMatchingQuery(t, e, n, s) {\n let i = cs();\n // Documents are ordered by key, so we can use a prefix scan to narrow down\n // the documents we need to match the query against.\n const r = e.path, o = new ht(r.child(\"\")), u = this.docs.getIteratorFrom(o);\n for (;u.hasNext(); ) {\n const {key: t, value: {document: o}} = u.getNext();\n if (!r.isPrefixOf(t.path)) break;\n t.path.length > r.length + 1 || (Tt(pt(o), n) <= 0 || (s.has(o.key) || ns(e, o)) && (i = i.insert(o.key, o.mutableCopy())));\n }\n return Rt.resolve(i);\n }\n getAllFromCollectionGroup(t, e, n, s) {\n // This method should only be called from the IndexBackfiller if persistence\n // is enabled.\n O();\n }\n Cs(t, e) {\n return Rt.forEach(this.docs, (t => e(t)));\n }\n newChangeBuffer(t) {\n // `trackRemovals` is ignores since the MemoryRemoteDocumentCache keeps\n // a separate changelog and does not need special handling for removals.\n return new qo(this);\n }\n getSize(t) {\n return Rt.resolve(this.size);\n }\n}\n\n/**\n * Creates a new memory-only RemoteDocumentCache.\n *\n * @param sizer - Used to assess the size of a document. For eager GC, this is\n * expected to just return 0 to avoid unnecessarily doing the work of\n * calculating the size.\n */\n/**\n * Handles the details of adding and updating documents in the MemoryRemoteDocumentCache.\n */\nclass qo extends vo {\n constructor(t) {\n super(), this.os = t;\n }\n applyChanges(t) {\n const e = [];\n return this.changes.forEach(((n, s) => {\n s.isValidDocument() ? e.push(this.os.addEntry(t, s)) : this.os.removeEntry(n);\n })), Rt.waitFor(e);\n }\n getFromCache(t, e) {\n return this.os.getEntry(t, e);\n }\n getAllFromCache(t, e) {\n return this.os.getEntries(t, e);\n }\n}\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */ class Uo {\n constructor(t) {\n this.persistence = t, \n /**\n * Maps a target to the data about that target\n */\n this.xs = new os((t => $n(t)), On), \n /** The last received snapshot version. */\n this.lastRemoteSnapshotVersion = rt.min(), \n /** The highest numbered target ID encountered. */\n this.highestTargetId = 0, \n /** The highest sequence number encountered. */\n this.Ns = 0, \n /**\n * A ordered bidirectional mapping between documents and the remote target\n * IDs.\n */\n this.ks = new Oo, this.targetCount = 0, this.Ms = lo.kn();\n }\n forEachTarget(t, e) {\n return this.xs.forEach(((t, n) => e(n))), Rt.resolve();\n }\n getLastRemoteSnapshotVersion(t) {\n return Rt.resolve(this.lastRemoteSnapshotVersion);\n }\n getHighestSequenceNumber(t) {\n return Rt.resolve(this.Ns);\n }\n allocateTargetId(t) {\n return this.highestTargetId = this.Ms.next(), Rt.resolve(this.highestTargetId);\n }\n setTargetsMetadata(t, e, n) {\n return n && (this.lastRemoteSnapshotVersion = n), e > this.Ns && (this.Ns = e), \n Rt.resolve();\n }\n Fn(t) {\n this.xs.set(t.target, t);\n const e = t.targetId;\n e > this.highestTargetId && (this.Ms = new lo(e), this.highestTargetId = e), t.sequenceNumber > this.Ns && (this.Ns = t.sequenceNumber);\n }\n addTargetData(t, e) {\n return this.Fn(e), this.targetCount += 1, Rt.resolve();\n }\n updateTargetData(t, e) {\n return this.Fn(e), Rt.resolve();\n }\n removeTargetData(t, e) {\n return this.xs.delete(e.target), this.ks.Is(e.targetId), this.targetCount -= 1, \n Rt.resolve();\n }\n removeTargets(t, e, n) {\n let s = 0;\n const i = [];\n return this.xs.forEach(((r, o) => {\n o.sequenceNumber <= e && null === n.get(o.targetId) && (this.xs.delete(r), i.push(this.removeMatchingKeysForTargetId(t, o.targetId)), \n s++);\n })), Rt.waitFor(i).next((() => s));\n }\n getTargetCount(t) {\n return Rt.resolve(this.targetCount);\n }\n getTargetData(t, e) {\n const n = this.xs.get(e) || null;\n return Rt.resolve(n);\n }\n addMatchingKeys(t, e, n) {\n return this.ks.gs(e, n), Rt.resolve();\n }\n removeMatchingKeys(t, e, n) {\n this.ks.ps(e, n);\n const s = this.persistence.referenceDelegate, i = [];\n return s && e.forEach((e => {\n i.push(s.markPotentiallyOrphaned(t, e));\n })), Rt.waitFor(i);\n }\n removeMatchingKeysForTargetId(t, e) {\n return this.ks.Is(e), Rt.resolve();\n }\n getMatchingKeysForTargetId(t, e) {\n const n = this.ks.Es(e);\n return Rt.resolve(n);\n }\n containsKey(t, e) {\n return Rt.resolve(this.ks.containsKey(e));\n }\n}\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * A memory-backed instance of Persistence. Data is stored only in RAM and\n * not persisted across sessions.\n */\nclass Ko {\n /**\n * The constructor accepts a factory for creating a reference delegate. This\n * allows both the delegate and this instance to have strong references to\n * each other without having nullable fields that would then need to be\n * checked or asserted on every access.\n */\n constructor(t, e) {\n this.$s = {}, this.overlays = {}, this.Os = new Ot(0), this.Fs = !1, this.Fs = !0, \n this.referenceDelegate = t(this), this.Bs = new Uo(this);\n this.indexManager = new zr, this.remoteDocumentCache = function(t) {\n return new Lo(t);\n }((t => this.referenceDelegate.Ls(t))), this.serializer = new ar(e), this.qs = new Mo(this.serializer);\n }\n start() {\n return Promise.resolve();\n }\n shutdown() {\n // No durable state to ensure is closed on shutdown.\n return this.Fs = !1, Promise.resolve();\n }\n get started() {\n return this.Fs;\n }\n setDatabaseDeletedListener() {\n // No op.\n }\n setNetworkEnabled() {\n // No op.\n }\n getIndexManager(t) {\n // We do not currently support indices for memory persistence, so we can\n // return the same shared instance of the memory index manager.\n return this.indexManager;\n }\n getDocumentOverlayCache(t) {\n let e = this.overlays[t.toKey()];\n return e || (e = new $o, this.overlays[t.toKey()] = e), e;\n }\n getMutationQueue(t, e) {\n let n = this.$s[t.toKey()];\n return n || (n = new Bo(e, this.referenceDelegate), this.$s[t.toKey()] = n), n;\n }\n getTargetCache() {\n return this.Bs;\n }\n getRemoteDocumentCache() {\n return this.remoteDocumentCache;\n }\n getBundleCache() {\n return this.qs;\n }\n runTransaction(t, e, n) {\n N(\"MemoryPersistence\", \"Starting transaction:\", t);\n const s = new Go(this.Os.next());\n return this.referenceDelegate.Us(), n(s).next((t => this.referenceDelegate.Ks(s).next((() => t)))).toPromise().then((t => (s.raiseOnCommittedEvent(), \n t)));\n }\n Gs(t, e) {\n return Rt.or(Object.values(this.$s).map((n => () => n.containsKey(t, e))));\n }\n}\n\n/**\n * Memory persistence is not actually transactional, but future implementations\n * may have transaction-scoped state.\n */ class Go extends At {\n constructor(t) {\n super(), this.currentSequenceNumber = t;\n }\n}\n\nclass Qo {\n constructor(t) {\n this.persistence = t, \n /** Tracks all documents that are active in Query views. */\n this.Qs = new Oo, \n /** The list of documents that are potentially GCed after each transaction. */\n this.js = null;\n }\n static zs(t) {\n return new Qo(t);\n }\n get Ws() {\n if (this.js) return this.js;\n throw O();\n }\n addReference(t, e, n) {\n return this.Qs.addReference(n, e), this.Ws.delete(n.toString()), Rt.resolve();\n }\n removeReference(t, e, n) {\n return this.Qs.removeReference(n, e), this.Ws.add(n.toString()), Rt.resolve();\n }\n markPotentiallyOrphaned(t, e) {\n return this.Ws.add(e.toString()), Rt.resolve();\n }\n removeTarget(t, e) {\n this.Qs.Is(e.targetId).forEach((t => this.Ws.add(t.toString())));\n const n = this.persistence.getTargetCache();\n return n.getMatchingKeysForTargetId(t, e.targetId).next((t => {\n t.forEach((t => this.Ws.add(t.toString())));\n })).next((() => n.removeTargetData(t, e)));\n }\n Us() {\n this.js = new Set;\n }\n Ks(t) {\n // Remove newly orphaned documents.\n const e = this.persistence.getRemoteDocumentCache().newChangeBuffer();\n return Rt.forEach(this.Ws, (n => {\n const s = ht.fromPath(n);\n return this.Hs(t, s).next((t => {\n t || e.removeEntry(s, rt.min());\n }));\n })).next((() => (this.js = null, e.apply(t))));\n }\n updateLimboDocument(t, e) {\n return this.Hs(t, e).next((t => {\n t ? this.Ws.delete(e.toString()) : this.Ws.add(e.toString());\n }));\n }\n Ls(t) {\n // For eager GC, we don't care about the document size, there are no size thresholds.\n return 0;\n }\n Hs(t, e) {\n return Rt.or([ () => Rt.resolve(this.Qs.containsKey(e)), () => this.persistence.getTargetCache().containsKey(t, e), () => this.persistence.Gs(t, e) ]);\n }\n}\n\nclass jo {\n constructor(t, e) {\n this.persistence = t, this.Js = new os((t => qt(t.path)), ((t, e) => t.isEqual(e))), \n this.garbageCollector = To(this, e);\n }\n static zs(t, e) {\n return new jo(t, e);\n }\n // No-ops, present so memory persistence doesn't have to care which delegate\n // it has.\n Us() {}\n Ks(t) {\n return Rt.resolve();\n }\n forEachTarget(t, e) {\n return this.persistence.getTargetCache().forEachTarget(t, e);\n }\n zn(t) {\n const e = this.Jn(t);\n return this.persistence.getTargetCache().getTargetCount(t).next((t => e.next((e => t + e))));\n }\n Jn(t) {\n let e = 0;\n return this.Wn(t, (t => {\n e++;\n })).next((() => e));\n }\n Wn(t, e) {\n return Rt.forEach(this.Js, ((n, s) => this.Xn(t, n, s).next((t => t ? Rt.resolve() : e(s)))));\n }\n removeTargets(t, e, n) {\n return this.persistence.getTargetCache().removeTargets(t, e, n);\n }\n removeOrphanedDocuments(t, e) {\n let n = 0;\n const s = this.persistence.getRemoteDocumentCache(), i = s.newChangeBuffer();\n return s.Cs(t, (s => this.Xn(t, s, e).next((t => {\n t || (n++, i.removeEntry(s, rt.min()));\n })))).next((() => i.apply(t))).next((() => n));\n }\n markPotentiallyOrphaned(t, e) {\n return this.Js.set(e, t.currentSequenceNumber), Rt.resolve();\n }\n removeTarget(t, e) {\n const n = e.withSequenceNumber(t.currentSequenceNumber);\n return this.persistence.getTargetCache().updateTargetData(t, n);\n }\n addReference(t, e, n) {\n return this.Js.set(n, t.currentSequenceNumber), Rt.resolve();\n }\n removeReference(t, e, n) {\n return this.Js.set(n, t.currentSequenceNumber), Rt.resolve();\n }\n updateLimboDocument(t, e) {\n return this.Js.set(e, t.currentSequenceNumber), Rt.resolve();\n }\n Ls(t) {\n let e = t.key.toString().length;\n return t.isFoundDocument() && (e += ze(t.data.value)), e;\n }\n Xn(t, e, n) {\n return Rt.or([ () => this.persistence.Gs(t, e), () => this.persistence.getTargetCache().containsKey(t, e), () => {\n const t = this.Js.get(e);\n return Rt.resolve(void 0 !== t && t > n);\n } ]);\n }\n getCacheSize(t) {\n return this.persistence.getRemoteDocumentCache().getSize(t);\n }\n}\n\n/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/** Performs database creation and schema upgrades. */ class zo {\n constructor(t) {\n this.serializer = t;\n }\n /**\n * Performs database creation and schema upgrades.\n *\n * Note that in production, this method is only ever used to upgrade the schema\n * to SCHEMA_VERSION. Different values of toVersion are only used for testing\n * and local feature development.\n */ O(t, e, n, s) {\n const i = new Pt(\"createOrUpgrade\", e);\n n < 1 && s >= 1 && (function(t) {\n t.createObjectStore(\"owner\");\n }(t), function(t) {\n t.createObjectStore(\"mutationQueues\", {\n keyPath: \"userId\"\n });\n t.createObjectStore(\"mutations\", {\n keyPath: \"batchId\",\n autoIncrement: !0\n }).createIndex(\"userMutationsIndex\", Qt, {\n unique: !0\n }), t.createObjectStore(\"documentMutations\");\n }\n /**\n * Upgrade function to migrate the 'mutations' store from V1 to V3. Loads\n * and rewrites all data.\n */ (t), Wo(t), function(t) {\n t.createObjectStore(\"remoteDocuments\");\n }(t));\n // Migration 2 to populate the targetGlobal object no longer needed since\n // migration 3 unconditionally clears it.\n let r = Rt.resolve();\n return n < 3 && s >= 3 && (\n // Brand new clients don't need to drop and recreate--only clients that\n // potentially have corrupt data.\n 0 !== n && (!function(t) {\n t.deleteObjectStore(\"targetDocuments\"), t.deleteObjectStore(\"targets\"), t.deleteObjectStore(\"targetGlobal\");\n }(t), Wo(t)), r = r.next((() => \n /**\n * Creates the target global singleton row.\n *\n * @param txn - The version upgrade transaction for indexeddb\n */\n function(t) {\n const e = t.store(\"targetGlobal\"), n = {\n highestTargetId: 0,\n highestListenSequenceNumber: 0,\n lastRemoteSnapshotVersion: rt.min().toTimestamp(),\n targetCount: 0\n };\n return e.put(\"targetGlobalKey\", n);\n }(i)))), n < 4 && s >= 4 && (0 !== n && (\n // Schema version 3 uses auto-generated keys to generate globally unique\n // mutation batch IDs (this was previously ensured internally by the\n // client). To migrate to the new schema, we have to read all mutations\n // and write them back out. We preserve the existing batch IDs to guarantee\n // consistency with other object stores. Any further mutation batch IDs will\n // be auto-generated.\n r = r.next((() => function(t, e) {\n return e.store(\"mutations\").j().next((n => {\n t.deleteObjectStore(\"mutations\");\n t.createObjectStore(\"mutations\", {\n keyPath: \"batchId\",\n autoIncrement: !0\n }).createIndex(\"userMutationsIndex\", Qt, {\n unique: !0\n });\n const s = e.store(\"mutations\"), i = n.map((t => s.put(t)));\n return Rt.waitFor(i);\n }));\n }(t, i)))), r = r.next((() => {\n !function(t) {\n t.createObjectStore(\"clientMetadata\", {\n keyPath: \"clientId\"\n });\n }(t);\n }))), n < 5 && s >= 5 && (r = r.next((() => this.Ys(i)))), n < 6 && s >= 6 && (r = r.next((() => (function(t) {\n t.createObjectStore(\"remoteDocumentGlobal\");\n }(t), this.Xs(i))))), n < 7 && s >= 7 && (r = r.next((() => this.Zs(i)))), n < 8 && s >= 8 && (r = r.next((() => this.ti(t, i)))), \n n < 9 && s >= 9 && (r = r.next((() => {\n // Multi-Tab used to manage its own changelog, but this has been moved\n // to the DbRemoteDocument object store itself. Since the previous change\n // log only contained transient data, we can drop its object store.\n !function(t) {\n t.objectStoreNames.contains(\"remoteDocumentChanges\") && t.deleteObjectStore(\"remoteDocumentChanges\");\n }(t);\n // Note: Schema version 9 used to create a read time index for the\n // RemoteDocumentCache. This is now done with schema version 13.\n }))), n < 10 && s >= 10 && (r = r.next((() => this.ei(i)))), n < 11 && s >= 11 && (r = r.next((() => {\n !function(t) {\n t.createObjectStore(\"bundles\", {\n keyPath: \"bundleId\"\n });\n }(t), function(t) {\n t.createObjectStore(\"namedQueries\", {\n keyPath: \"name\"\n });\n }(t);\n }))), n < 12 && s >= 12 && (r = r.next((() => {\n !function(t) {\n const e = t.createObjectStore(\"documentOverlays\", {\n keyPath: oe\n });\n e.createIndex(\"collectionPathOverlayIndex\", ue, {\n unique: !1\n }), e.createIndex(\"collectionGroupOverlayIndex\", ce, {\n unique: !1\n });\n }(t);\n }))), n < 13 && s >= 13 && (r = r.next((() => function(t) {\n const e = t.createObjectStore(\"remoteDocumentsV14\", {\n keyPath: Ht\n });\n e.createIndex(\"documentKeyIndex\", Jt), e.createIndex(\"collectionGroupIndex\", Yt);\n }(t))).next((() => this.ni(t, i))).next((() => t.deleteObjectStore(\"remoteDocuments\")))), \n n < 14 && s >= 14 && (r = r.next((() => this.si(t, i)))), n < 15 && s >= 15 && (r = r.next((() => function(t) {\n t.createObjectStore(\"indexConfiguration\", {\n keyPath: \"indexId\",\n autoIncrement: !0\n }).createIndex(\"collectionGroupIndex\", \"collectionGroup\", {\n unique: !1\n });\n t.createObjectStore(\"indexState\", {\n keyPath: ne\n }).createIndex(\"sequenceNumberIndex\", se, {\n unique: !1\n });\n t.createObjectStore(\"indexEntries\", {\n keyPath: ie\n }).createIndex(\"documentKeyIndex\", re, {\n unique: !1\n });\n }(t)))), r;\n }\n Xs(t) {\n let e = 0;\n return t.store(\"remoteDocuments\").X(((t, n) => {\n e += ro(n);\n })).next((() => {\n const n = {\n byteSize: e\n };\n return t.store(\"remoteDocumentGlobal\").put(\"remoteDocumentGlobalKey\", n);\n }));\n }\n Ys(t) {\n const e = t.store(\"mutationQueues\"), n = t.store(\"mutations\");\n return e.j().next((e => Rt.forEach(e, (e => {\n const s = IDBKeyRange.bound([ e.userId, -1 ], [ e.userId, e.lastAcknowledgedBatchId ]);\n return n.j(\"userMutationsIndex\", s).next((n => Rt.forEach(n, (n => {\n F(n.userId === e.userId);\n const s = _r(this.serializer, n);\n return io(t, e.userId, s).next((() => {}));\n }))));\n }))));\n }\n /**\n * Ensures that every document in the remote document cache has a corresponding sentinel row\n * with a sequence number. Missing rows are given the most recently used sequence number.\n */ Zs(t) {\n const e = t.store(\"targetDocuments\"), n = t.store(\"remoteDocuments\");\n return t.store(\"targetGlobal\").get(\"targetGlobalKey\").next((t => {\n const s = [];\n return n.X(((n, i) => {\n const r = new ut(n), o = function(t) {\n return [ 0, qt(t) ];\n }(r);\n s.push(e.get(o).next((n => n ? Rt.resolve() : (n => e.put({\n targetId: 0,\n path: qt(n),\n sequenceNumber: t.highestListenSequenceNumber\n }))(r))));\n })).next((() => Rt.waitFor(s)));\n }));\n }\n ti(t, e) {\n // Create the index.\n t.createObjectStore(\"collectionParents\", {\n keyPath: ee\n });\n const n = e.store(\"collectionParents\"), s = new Wr, i = t => {\n if (s.add(t)) {\n const e = t.lastSegment(), s = t.popLast();\n return n.put({\n collectionId: e,\n parent: qt(s)\n });\n }\n };\n // Helper to add an index entry iff we haven't already written it.\n // Index existing remote documents.\n return e.store(\"remoteDocuments\").X({\n Y: !0\n }, ((t, e) => {\n const n = new ut(t);\n return i(n.popLast());\n })).next((() => e.store(\"documentMutations\").X({\n Y: !0\n }, (([t, e, n], s) => {\n const r = Gt(e);\n return i(r.popLast());\n }))));\n }\n ei(t) {\n const e = t.store(\"targets\");\n return e.X(((t, n) => {\n const s = mr(n), i = gr(this.serializer, s);\n return e.put(i);\n }));\n }\n ni(t, e) {\n const n = e.store(\"remoteDocuments\"), s = [];\n return n.X(((t, n) => {\n const i = e.store(\"remoteDocumentsV14\"), r = (o = n, o.document ? new ht(ut.fromString(o.document.name).popFirst(5)) : o.noDocument ? ht.fromSegments(o.noDocument.path) : o.unknownDocument ? ht.fromSegments(o.unknownDocument.path) : O()).path.toArray();\n var o;\n /**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */ const u = {\n prefixPath: r.slice(0, r.length - 2),\n collectionGroup: r[r.length - 2],\n documentId: r[r.length - 1],\n readTime: n.readTime || [ 0, 0 ],\n unknownDocument: n.unknownDocument,\n noDocument: n.noDocument,\n document: n.document,\n hasCommittedMutations: !!n.hasCommittedMutations\n };\n s.push(i.put(u));\n })).next((() => Rt.waitFor(s)));\n }\n si(t, e) {\n const n = e.store(\"mutations\"), s = Po(this.serializer), i = new Ko(Qo.zs, this.serializer.fe);\n return n.j().next((t => {\n const n = new Map;\n return t.forEach((t => {\n var e;\n let s = null !== (e = n.get(t.userId)) && void 0 !== e ? e : gs();\n _r(this.serializer, t).keys().forEach((t => s = s.add(t))), n.set(t.userId, s);\n })), Rt.forEach(n, ((t, n) => {\n const r = new V(n), o = Rr.de(this.serializer, r), u = i.getIndexManager(r), c = oo.de(r, this.serializer, u, i.referenceDelegate);\n return new ko(s, c, o, u).recalculateAndSaveOverlaysForDocumentKeys(new we(e, Ot.ct), t).next();\n }));\n }));\n }\n}\n\nfunction Wo(t) {\n t.createObjectStore(\"targetDocuments\", {\n keyPath: Zt\n }).createIndex(\"documentTargetsIndex\", te, {\n unique: !0\n });\n // NOTE: This is unique only because the TargetId is the suffix.\n t.createObjectStore(\"targets\", {\n keyPath: \"targetId\"\n }).createIndex(\"queryTargetsIndex\", Xt, {\n unique: !0\n }), t.createObjectStore(\"targetGlobal\");\n}\n\nconst Ho = \"Failed to obtain exclusive access to the persistence layer. To allow shared access, multi-tab synchronization has to be enabled in all tabs. If you are using `experimentalForceOwningTab:true`, make sure that only one tab has persistence enabled at any given time.\";\n\n/**\n * Oldest acceptable age in milliseconds for client metadata before the client\n * is considered inactive and its associated data is garbage collected.\n */\n/**\n * An IndexedDB-backed instance of Persistence. Data is stored persistently\n * across sessions.\n *\n * On Web only, the Firestore SDKs support shared access to its persistence\n * layer. This allows multiple browser tabs to read and write to IndexedDb and\n * to synchronize state even without network connectivity. Shared access is\n * currently optional and not enabled unless all clients invoke\n * `enablePersistence()` with `{synchronizeTabs:true}`.\n *\n * In multi-tab mode, if multiple clients are active at the same time, the SDK\n * will designate one client as the “primary client”. An effort is made to pick\n * a visible, network-connected and active client, and this client is\n * responsible for letting other clients know about its presence. The primary\n * client writes a unique client-generated identifier (the client ID) to\n * IndexedDb’s “owner” store every 4 seconds. If the primary client fails to\n * update this entry, another client can acquire the lease and take over as\n * primary.\n *\n * Some persistence operations in the SDK are designated as primary-client only\n * operations. This includes the acknowledgment of mutations and all updates of\n * remote documents. The effects of these operations are written to persistence\n * and then broadcast to other tabs via LocalStorage (see\n * `WebStorageSharedClientState`), which then refresh their state from\n * persistence.\n *\n * Similarly, the primary client listens to notifications sent by secondary\n * clients to discover persistence changes written by secondary clients, such as\n * the addition of new mutations and query targets.\n *\n * If multi-tab is not enabled and another tab already obtained the primary\n * lease, IndexedDbPersistence enters a failed state and all subsequent\n * operations will automatically fail.\n *\n * Additionally, there is an optimization so that when a tab is closed, the\n * primary lease is released immediately (this is especially important to make\n * sure that a refreshed tab is able to immediately re-acquire the primary\n * lease). Unfortunately, IndexedDB cannot be reliably used in window.unload\n * since it is an asynchronous API. So in addition to attempting to give up the\n * lease, the leaseholder writes its client ID to a \"zombiedClient\" entry in\n * LocalStorage which acts as an indicator that another tab should go ahead and\n * take the primary lease immediately regardless of the current lease timestamp.\n *\n * TODO(b/114226234): Remove `synchronizeTabs` section when multi-tab is no\n * longer optional.\n */\nclass Jo {\n constructor(\n /**\n * Whether to synchronize the in-memory state of multiple tabs and share\n * access to local persistence.\n */\n t, e, n, s, i, r, o, u, c, \n /**\n * If set to true, forcefully obtains database access. Existing tabs will\n * no longer be able to access IndexedDB.\n */\n a, h = 15) {\n if (this.allowTabSynchronization = t, this.persistenceKey = e, this.clientId = n, \n this.ii = i, this.window = r, this.document = o, this.ri = c, this.oi = a, this.ui = h, \n this.Os = null, this.Fs = !1, this.isPrimary = !1, this.networkEnabled = !0, \n /** Our window.unload handler, if registered. */\n this.ci = null, this.inForeground = !1, \n /** Our 'visibilitychange' listener if registered. */\n this.ai = null, \n /** The client metadata refresh task. */\n this.hi = null, \n /** The last time we garbage collected the client metadata object store. */\n this.li = Number.NEGATIVE_INFINITY, \n /** A listener to notify on primary state changes. */\n this.fi = t => Promise.resolve(), !Jo.D()) throw new U(q.UNIMPLEMENTED, \"This platform is either missing IndexedDB or is known to have an incomplete implementation. Offline persistence has been disabled.\");\n this.referenceDelegate = new Eo(this, s), this.di = e + \"main\", this.serializer = new ar(u), \n this.wi = new bt(this.di, this.ui, new zo(this.serializer)), this.Bs = new fo(this.referenceDelegate, this.serializer), \n this.remoteDocumentCache = Po(this.serializer), this.qs = new Er, this.window && this.window.localStorage ? this._i = this.window.localStorage : (this._i = null, \n !1 === a && k(\"IndexedDbPersistence\", \"LocalStorage is unavailable. As a result, persistence may not work reliably. In particular enablePersistence() could fail immediately after refreshing the page.\"));\n }\n /**\n * Attempt to start IndexedDb persistence.\n *\n * @returns Whether persistence was enabled.\n */ start() {\n // NOTE: This is expected to fail sometimes (in the case of another tab\n // already having the persistence lock), so it's the first thing we should\n // do.\n return this.mi().then((() => {\n if (!this.isPrimary && !this.allowTabSynchronization) \n // Fail `start()` if `synchronizeTabs` is disabled and we cannot\n // obtain the primary lease.\n throw new U(q.FAILED_PRECONDITION, Ho);\n return this.gi(), this.yi(), this.pi(), this.runTransaction(\"getHighestListenSequenceNumber\", \"readonly\", (t => this.Bs.getHighestSequenceNumber(t)));\n })).then((t => {\n this.Os = new Ot(t, this.ri);\n })).then((() => {\n this.Fs = !0;\n })).catch((t => (this.wi && this.wi.close(), Promise.reject(t))));\n }\n /**\n * Registers a listener that gets called when the primary state of the\n * instance changes. Upon registering, this listener is invoked immediately\n * with the current primary state.\n *\n * PORTING NOTE: This is only used for Web multi-tab.\n */ Ii(t) {\n return this.fi = async e => {\n if (this.started) return t(e);\n }, t(this.isPrimary);\n }\n /**\n * Registers a listener that gets called when the database receives a\n * version change event indicating that it has deleted.\n *\n * PORTING NOTE: This is only used for Web multi-tab.\n */ setDatabaseDeletedListener(t) {\n this.wi.B((async e => {\n // Check if an attempt is made to delete IndexedDB.\n null === e.newVersion && await t();\n }));\n }\n /**\n * Adjusts the current network state in the client's metadata, potentially\n * affecting the primary lease.\n *\n * PORTING NOTE: This is only used for Web multi-tab.\n */ setNetworkEnabled(t) {\n this.networkEnabled !== t && (this.networkEnabled = t, \n // Schedule a primary lease refresh for immediate execution. The eventual\n // lease update will be propagated via `primaryStateListener`.\n this.ii.enqueueAndForget((async () => {\n this.started && await this.mi();\n })));\n }\n /**\n * Updates the client metadata in IndexedDb and attempts to either obtain or\n * extend the primary lease for the local client. Asynchronously notifies the\n * primary state listener if the client either newly obtained or released its\n * primary lease.\n */ mi() {\n return this.runTransaction(\"updateClientMetadataAndTryBecomePrimary\", \"readwrite\", (t => Xo(t).put({\n clientId: this.clientId,\n updateTimeMs: Date.now(),\n networkEnabled: this.networkEnabled,\n inForeground: this.inForeground\n }).next((() => {\n if (this.isPrimary) return this.Ti(t).next((t => {\n t || (this.isPrimary = !1, this.ii.enqueueRetryable((() => this.fi(!1))));\n }));\n })).next((() => this.Ei(t))).next((e => this.isPrimary && !e ? this.Ai(t).next((() => !1)) : !!e && this.vi(t).next((() => !0)))))).catch((t => {\n if (Dt(t)) \n // Proceed with the existing state. Any subsequent access to\n // IndexedDB will verify the lease.\n return N(\"IndexedDbPersistence\", \"Failed to extend owner lease: \", t), this.isPrimary;\n if (!this.allowTabSynchronization) throw t;\n return N(\"IndexedDbPersistence\", \"Releasing owner lease after error during lease refresh\", t), \n /* isPrimary= */ !1;\n })).then((t => {\n this.isPrimary !== t && this.ii.enqueueRetryable((() => this.fi(t))), this.isPrimary = t;\n }));\n }\n Ti(t) {\n return Yo(t).get(\"owner\").next((t => Rt.resolve(this.Ri(t))));\n }\n Pi(t) {\n return Xo(t).delete(this.clientId);\n }\n /**\n * If the garbage collection threshold has passed, prunes the\n * RemoteDocumentChanges and the ClientMetadata store based on the last update\n * time of all clients.\n */ async bi() {\n if (this.isPrimary && !this.Vi(this.li, 18e5)) {\n this.li = Date.now();\n const t = await this.runTransaction(\"maybeGarbageCollectMultiClientState\", \"readwrite-primary\", (t => {\n const e = _e(t, \"clientMetadata\");\n return e.j().next((t => {\n const n = this.Si(t, 18e5), s = t.filter((t => -1 === n.indexOf(t)));\n // Delete metadata for clients that are no longer considered active.\n return Rt.forEach(s, (t => e.delete(t.clientId))).next((() => s));\n }));\n })).catch((() => []));\n // Delete potential leftover entries that may continue to mark the\n // inactive clients as zombied in LocalStorage.\n // Ideally we'd delete the IndexedDb and LocalStorage zombie entries for\n // the client atomically, but we can't. So we opt to delete the IndexedDb\n // entries first to avoid potentially reviving a zombied client.\n if (this._i) for (const e of t) this._i.removeItem(this.Di(e.clientId));\n }\n }\n /**\n * Schedules a recurring timer to update the client metadata and to either\n * extend or acquire the primary lease if the client is eligible.\n */ pi() {\n this.hi = this.ii.enqueueAfterDelay(\"client_metadata_refresh\" /* TimerId.ClientMetadataRefresh */ , 4e3, (() => this.mi().then((() => this.bi())).then((() => this.pi()))));\n }\n /** Checks whether `client` is the local client. */ Ri(t) {\n return !!t && t.ownerId === this.clientId;\n }\n /**\n * Evaluate the state of all active clients and determine whether the local\n * client is or can act as the holder of the primary lease. Returns whether\n * the client is eligible for the lease, but does not actually acquire it.\n * May return 'false' even if there is no active leaseholder and another\n * (foreground) client should become leaseholder instead.\n */ Ei(t) {\n if (this.oi) return Rt.resolve(!0);\n return Yo(t).get(\"owner\").next((e => {\n // A client is eligible for the primary lease if:\n // - its network is enabled and the client's tab is in the foreground.\n // - its network is enabled and no other client's tab is in the\n // foreground.\n // - every clients network is disabled and the client's tab is in the\n // foreground.\n // - every clients network is disabled and no other client's tab is in\n // the foreground.\n // - the `forceOwningTab` setting was passed in.\n if (null !== e && this.Vi(e.leaseTimestampMs, 5e3) && !this.Ci(e.ownerId)) {\n if (this.Ri(e) && this.networkEnabled) return !0;\n if (!this.Ri(e)) {\n if (!e.allowTabSynchronization) \n // Fail the `canActAsPrimary` check if the current leaseholder has\n // not opted into multi-tab synchronization. If this happens at\n // client startup, we reject the Promise returned by\n // `enablePersistence()` and the user can continue to use Firestore\n // with in-memory persistence.\n // If this fails during a lease refresh, we will instead block the\n // AsyncQueue from executing further operations. Note that this is\n // acceptable since mixing & matching different `synchronizeTabs`\n // settings is not supported.\n // TODO(b/114226234): Remove this check when `synchronizeTabs` can\n // no longer be turned off.\n throw new U(q.FAILED_PRECONDITION, Ho);\n return !1;\n }\n }\n return !(!this.networkEnabled || !this.inForeground) || Xo(t).j().next((t => void 0 === this.Si(t, 5e3).find((t => {\n if (this.clientId !== t.clientId) {\n const e = !this.networkEnabled && t.networkEnabled, n = !this.inForeground && t.inForeground, s = this.networkEnabled === t.networkEnabled;\n if (e || n && s) return !0;\n }\n return !1;\n }))));\n })).next((t => (this.isPrimary !== t && N(\"IndexedDbPersistence\", `Client ${t ? \"is\" : \"is not\"} eligible for a primary lease.`), \n t)));\n }\n async shutdown() {\n // The shutdown() operations are idempotent and can be called even when\n // start() aborted (e.g. because it couldn't acquire the persistence lease).\n this.Fs = !1, this.xi(), this.hi && (this.hi.cancel(), this.hi = null), this.Ni(), \n this.ki(), \n // Use `SimpleDb.runTransaction` directly to avoid failing if another tab\n // has obtained the primary lease.\n await this.wi.runTransaction(\"shutdown\", \"readwrite\", [ \"owner\", \"clientMetadata\" ], (t => {\n const e = new we(t, Ot.ct);\n return this.Ai(e).next((() => this.Pi(e)));\n })), this.wi.close(), \n // Remove the entry marking the client as zombied from LocalStorage since\n // we successfully deleted its metadata from IndexedDb.\n this.Mi();\n }\n /**\n * Returns clients that are not zombied and have an updateTime within the\n * provided threshold.\n */ Si(t, e) {\n return t.filter((t => this.Vi(t.updateTimeMs, e) && !this.Ci(t.clientId)));\n }\n /**\n * Returns the IDs of the clients that are currently active. If multi-tab\n * is not supported, returns an array that only contains the local client's\n * ID.\n *\n * PORTING NOTE: This is only used for Web multi-tab.\n */ $i() {\n return this.runTransaction(\"getActiveClients\", \"readonly\", (t => Xo(t).j().next((t => this.Si(t, 18e5).map((t => t.clientId))))));\n }\n get started() {\n return this.Fs;\n }\n getMutationQueue(t, e) {\n return oo.de(t, this.serializer, e, this.referenceDelegate);\n }\n getTargetCache() {\n return this.Bs;\n }\n getRemoteDocumentCache() {\n return this.remoteDocumentCache;\n }\n getIndexManager(t) {\n return new Jr(t, this.serializer.fe.databaseId);\n }\n getDocumentOverlayCache(t) {\n return Rr.de(this.serializer, t);\n }\n getBundleCache() {\n return this.qs;\n }\n runTransaction(t, e, n) {\n N(\"IndexedDbPersistence\", \"Starting transaction:\", t);\n const s = \"readonly\" === e ? \"readonly\" : \"readwrite\", i = 15 === (r = this.ui) ? de : 14 === r ? fe : 13 === r ? le : 12 === r ? he : 11 === r ? ae : void O();\n /** Returns the object stores for the provided schema. */\n var r;\n let o;\n // Do all transactions as readwrite against all object stores, since we\n // are the only reader/writer.\n return this.wi.runTransaction(t, s, i, (s => (o = new we(s, this.Os ? this.Os.next() : Ot.ct), \n \"readwrite-primary\" === e ? this.Ti(o).next((t => !!t || this.Ei(o))).next((e => {\n if (!e) throw k(`Failed to obtain primary lease for action '${t}'.`), this.isPrimary = !1, \n this.ii.enqueueRetryable((() => this.fi(!1))), new U(q.FAILED_PRECONDITION, Et);\n return n(o);\n })).next((t => this.vi(o).next((() => t)))) : this.Oi(o).next((() => n(o)))))).then((t => (o.raiseOnCommittedEvent(), \n t)));\n }\n /**\n * Verifies that the current tab is the primary leaseholder or alternatively\n * that the leaseholder has opted into multi-tab synchronization.\n */\n // TODO(b/114226234): Remove this check when `synchronizeTabs` can no longer\n // be turned off.\n Oi(t) {\n return Yo(t).get(\"owner\").next((t => {\n if (null !== t && this.Vi(t.leaseTimestampMs, 5e3) && !this.Ci(t.ownerId) && !this.Ri(t) && !(this.oi || this.allowTabSynchronization && t.allowTabSynchronization)) throw new U(q.FAILED_PRECONDITION, Ho);\n }));\n }\n /**\n * Obtains or extends the new primary lease for the local client. This\n * method does not verify that the client is eligible for this lease.\n */ vi(t) {\n const e = {\n ownerId: this.clientId,\n allowTabSynchronization: this.allowTabSynchronization,\n leaseTimestampMs: Date.now()\n };\n return Yo(t).put(\"owner\", e);\n }\n static D() {\n return bt.D();\n }\n /** Checks the primary lease and removes it if we are the current primary. */ Ai(t) {\n const e = Yo(t);\n return e.get(\"owner\").next((t => this.Ri(t) ? (N(\"IndexedDbPersistence\", \"Releasing primary lease.\"), \n e.delete(\"owner\")) : Rt.resolve()));\n }\n /** Verifies that `updateTimeMs` is within `maxAgeMs`. */ Vi(t, e) {\n const n = Date.now();\n return !(t < n - e) && (!(t > n) || (k(`Detected an update time that is in the future: ${t} > ${n}`), \n !1));\n }\n gi() {\n null !== this.document && \"function\" == typeof this.document.addEventListener && (this.ai = () => {\n this.ii.enqueueAndForget((() => (this.inForeground = \"visible\" === this.document.visibilityState, \n this.mi())));\n }, this.document.addEventListener(\"visibilitychange\", this.ai), this.inForeground = \"visible\" === this.document.visibilityState);\n }\n Ni() {\n this.ai && (this.document.removeEventListener(\"visibilitychange\", this.ai), this.ai = null);\n }\n /**\n * Attaches a window.unload handler that will synchronously write our\n * clientId to a \"zombie client id\" location in LocalStorage. This can be used\n * by tabs trying to acquire the primary lease to determine that the lease\n * is no longer valid even if the timestamp is recent. This is particularly\n * important for the refresh case (so the tab correctly re-acquires the\n * primary lease). LocalStorage is used for this rather than IndexedDb because\n * it is a synchronous API and so can be used reliably from an unload\n * handler.\n */ yi() {\n var t;\n \"function\" == typeof (null === (t = this.window) || void 0 === t ? void 0 : t.addEventListener) && (this.ci = () => {\n // Note: In theory, this should be scheduled on the AsyncQueue since it\n // accesses internal state. We execute this code directly during shutdown\n // to make sure it gets a chance to run.\n this.xi();\n const t = /(?:Version|Mobile)\\/1[456]/;\n isSafari() && (navigator.appVersion.match(t) || navigator.userAgent.match(t)) && \n // On Safari 14, 15, and 16, we do not run any cleanup actions as it might\n // trigger a bug that prevents Safari from re-opening IndexedDB during\n // the next page load.\n // See https://bugs.webkit.org/show_bug.cgi?id=226547\n this.ii.enterRestrictedMode(/* purgeExistingTasks= */ !0), this.ii.enqueueAndForget((() => this.shutdown()));\n }, this.window.addEventListener(\"pagehide\", this.ci));\n }\n ki() {\n this.ci && (this.window.removeEventListener(\"pagehide\", this.ci), this.ci = null);\n }\n /**\n * Returns whether a client is \"zombied\" based on its LocalStorage entry.\n * Clients become zombied when their tab closes without running all of the\n * cleanup logic in `shutdown()`.\n */ Ci(t) {\n var e;\n try {\n const n = null !== (null === (e = this._i) || void 0 === e ? void 0 : e.getItem(this.Di(t)));\n return N(\"IndexedDbPersistence\", `Client '${t}' ${n ? \"is\" : \"is not\"} zombied in LocalStorage`), \n n;\n } catch (t) {\n // Gracefully handle if LocalStorage isn't working.\n return k(\"IndexedDbPersistence\", \"Failed to get zombied client id.\", t), !1;\n }\n }\n /**\n * Record client as zombied (a client that had its tab closed). Zombied\n * clients are ignored during primary tab selection.\n */ xi() {\n if (this._i) try {\n this._i.setItem(this.Di(this.clientId), String(Date.now()));\n } catch (t) {\n // Gracefully handle if LocalStorage isn't available / working.\n k(\"Failed to set zombie client id.\", t);\n }\n }\n /** Removes the zombied client entry if it exists. */ Mi() {\n if (this._i) try {\n this._i.removeItem(this.Di(this.clientId));\n } catch (t) {\n // Ignore\n }\n }\n Di(t) {\n return `firestore_zombie_${this.persistenceKey}_${t}`;\n }\n}\n\n/**\n * Helper to get a typed SimpleDbStore for the primary client object store.\n */ function Yo(t) {\n return _e(t, \"owner\");\n}\n\n/**\n * Helper to get a typed SimpleDbStore for the client metadata object store.\n */ function Xo(t) {\n return _e(t, \"clientMetadata\");\n}\n\n/**\n * Generates a string used as a prefix when storing data in IndexedDB and\n * LocalStorage.\n */ function Zo(t, e) {\n // Use two different prefix formats:\n // * firestore / persistenceKey / projectID . databaseID / ...\n // * firestore / persistenceKey / projectID / ...\n // projectIDs are DNS-compatible names and cannot contain dots\n // so there's no danger of collisions.\n let n = t.projectId;\n return t.isDefaultDatabase || (n += \".\" + t.database), \"firestore/\" + e + \"/\" + n + \"/\";\n}\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * A set of changes to what documents are currently in view and out of view for\n * a given query. These changes are sent to the LocalStore by the View (via\n * the SyncEngine) and are used to pin / unpin documents as appropriate.\n */\nclass tu {\n constructor(t, e, n, s) {\n this.targetId = t, this.fromCache = e, this.Fi = n, this.Bi = s;\n }\n static Li(t, e) {\n let n = gs(), s = gs();\n for (const t of e.docChanges) switch (t.type) {\n case 0 /* ChangeType.Added */ :\n n = n.add(t.doc.key);\n break;\n\n case 1 /* ChangeType.Removed */ :\n s = s.add(t.doc.key);\n // do nothing\n }\n return new tu(t, e.fromCache, n, s);\n }\n}\n\n/**\n * @license\n * Copyright 2019 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * The Firestore query engine.\n *\n * Firestore queries can be executed in three modes. The Query Engine determines\n * what mode to use based on what data is persisted. The mode only determines\n * the runtime complexity of the query - the result set is equivalent across all\n * implementations.\n *\n * The Query engine will use indexed-based execution if a user has configured\n * any index that can be used to execute query (via `setIndexConfiguration()`).\n * Otherwise, the engine will try to optimize the query by re-using a previously\n * persisted query result. If that is not possible, the query will be executed\n * via a full collection scan.\n *\n * Index-based execution is the default when available. The query engine\n * supports partial indexed execution and merges the result from the index\n * lookup with documents that have not yet been indexed. The index evaluation\n * matches the backend's format and as such, the SDK can use indexing for all\n * queries that the backend supports.\n *\n * If no index exists, the query engine tries to take advantage of the target\n * document mapping in the TargetCache. These mappings exists for all queries\n * that have been synced with the backend at least once and allow the query\n * engine to only read documents that previously matched a query plus any\n * documents that were edited after the query was last listened to.\n *\n * There are some cases when this optimization is not guaranteed to produce\n * the same results as full collection scans. In these cases, query\n * processing falls back to full scans. These cases are:\n *\n * - Limit queries where a document that matched the query previously no longer\n * matches the query.\n *\n * - Limit queries where a document edit may cause the document to sort below\n * another document that is in the local cache.\n *\n * - Queries that have never been CURRENT or free of limbo documents.\n */ class eu {\n constructor() {\n this.qi = !1;\n }\n /** Sets the document view to query against. */ initialize(t, e) {\n this.Ui = t, this.indexManager = e, this.qi = !0;\n }\n /** Returns all local documents matching the specified query. */ getDocumentsMatchingQuery(t, e, n, s) {\n return this.Ki(t, e).next((i => i || this.Gi(t, e, s, n))).next((n => n || this.Qi(t, e)));\n }\n /**\n * Performs an indexed query that evaluates the query based on a collection's\n * persisted index values. Returns `null` if an index is not available.\n */ Ki(t, e) {\n if (Qn(e)) \n // Queries that match all documents don't benefit from using\n // key-based lookups. It is more efficient to scan all documents in a\n // collection, rather than to perform individual lookups.\n return Rt.resolve(null);\n let n = Jn(e);\n return this.indexManager.getIndexType(t, n).next((s => 0 /* IndexType.NONE */ === s ? null : (null !== e.limit && 1 /* IndexType.PARTIAL */ === s && (\n // We cannot apply a limit for targets that are served using a partial\n // index. If a partial index will be used to serve the target, the\n // query may return a superset of documents that match the target\n // (e.g. if the index doesn't include all the target's filters), or\n // may return the correct set of documents in the wrong order (e.g. if\n // the index doesn't include a segment for one of the orderBys).\n // Therefore, a limit should not be applied in such cases.\n e = Xn(e, null, \"F\" /* LimitType.First */), n = Jn(e)), this.indexManager.getDocumentsMatchingTarget(t, n).next((s => {\n const i = gs(...s);\n return this.Ui.getDocuments(t, i).next((s => this.indexManager.getMinOffset(t, n).next((n => {\n const r = this.ji(e, s);\n return this.zi(e, r, i, n.readTime) ? this.Ki(t, Xn(e, null, \"F\" /* LimitType.First */)) : this.Wi(t, r, e, n);\n }))));\n })))));\n }\n /**\n * Performs a query based on the target's persisted query mapping. Returns\n * `null` if the mapping is not available or cannot be used.\n */ Gi(t, e, n, s) {\n return Qn(e) || s.isEqual(rt.min()) ? this.Qi(t, e) : this.Ui.getDocuments(t, n).next((i => {\n const r = this.ji(e, i);\n return this.zi(e, r, n, s) ? this.Qi(t, e) : (C() <= LogLevel.DEBUG && N(\"QueryEngine\", \"Re-using previous result from %s to execute query: %s\", s.toString(), es(e)), \n this.Wi(t, r, e, yt(s, -1)));\n }));\n // Queries that have never seen a snapshot without limbo free documents\n // should also be run as a full collection scan.\n }\n /** Applies the query filter and sorting to the provided documents. */ ji(t, e) {\n // Sort the documents and re-apply the query filter since previously\n // matching documents do not necessarily still match the query.\n let n = new Ee(is(t));\n return e.forEach(((e, s) => {\n ns(t, s) && (n = n.add(s));\n })), n;\n }\n /**\n * Determines if a limit query needs to be refilled from cache, making it\n * ineligible for index-free execution.\n *\n * @param query - The query.\n * @param sortedPreviousResults - The documents that matched the query when it\n * was last synchronized, sorted by the query's comparator.\n * @param remoteKeys - The document keys that matched the query at the last\n * snapshot.\n * @param limboFreeSnapshotVersion - The version of the snapshot when the\n * query was last synchronized.\n */ zi(t, e, n, s) {\n if (null === t.limit) \n // Queries without limits do not need to be refilled.\n return !1;\n if (n.size !== e.size) \n // The query needs to be refilled if a previously matching document no\n // longer matches.\n return !0;\n // Limit queries are not eligible for index-free query execution if there is\n // a potential that an older document from cache now sorts before a document\n // that was previously part of the limit. This, however, can only happen if\n // the document at the edge of the limit goes out of limit.\n // If a document that is not the limit boundary sorts differently,\n // the boundary of the limit itself did not change and documents from cache\n // will continue to be \"rejected\" by this boundary. Therefore, we can ignore\n // any modifications that don't affect the last document.\n const i = \"F\" /* LimitType.First */ === t.limitType ? e.last() : e.first();\n return !!i && (i.hasPendingWrites || i.version.compareTo(s) > 0);\n }\n Qi(t, e) {\n return C() <= LogLevel.DEBUG && N(\"QueryEngine\", \"Using full collection scan to execute query:\", es(e)), \n this.Ui.getDocumentsMatchingQuery(t, e, It.min());\n }\n /**\n * Combines the results from an indexed execution with the remaining documents\n * that have not yet been indexed.\n */ Wi(t, e, n, s) {\n // Retrieve all results for documents that were updated since the offset.\n return this.Ui.getDocumentsMatchingQuery(t, n, s).next((t => (\n // Merge with existing results\n e.forEach((e => {\n t = t.insert(e.key, e);\n })), t)));\n }\n}\n\n/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * Implements `LocalStore` interface.\n *\n * Note: some field defined in this class might have public access level, but\n * the class is not exported so they are only accessible from this module.\n * This is useful to implement optional features (like bundles) in free\n * functions, such that they are tree-shakeable.\n */\nclass nu {\n constructor(\n /** Manages our in-memory or durable persistence. */\n t, e, n, s) {\n this.persistence = t, this.Hi = e, this.serializer = s, \n /**\n * Maps a targetID to data about its target.\n *\n * PORTING NOTE: We are using an immutable data structure on Web to make re-runs\n * of `applyRemoteEvent()` idempotent.\n */\n this.Ji = new pe(et), \n /** Maps a target to its targetID. */\n // TODO(wuandy): Evaluate if TargetId can be part of Target.\n this.Yi = new os((t => $n(t)), On), \n /**\n * A per collection group index of the last read time processed by\n * `getNewDocumentChanges()`.\n *\n * PORTING NOTE: This is only used for multi-tab synchronization.\n */\n this.Xi = new Map, this.Zi = t.getRemoteDocumentCache(), this.Bs = t.getTargetCache(), \n this.qs = t.getBundleCache(), this.tr(n);\n }\n tr(t) {\n // TODO(indexing): Add spec tests that test these components change after a\n // user change\n this.documentOverlayCache = this.persistence.getDocumentOverlayCache(t), this.indexManager = this.persistence.getIndexManager(t), \n this.mutationQueue = this.persistence.getMutationQueue(t, this.indexManager), this.localDocuments = new ko(this.Zi, this.mutationQueue, this.documentOverlayCache, this.indexManager), \n this.Zi.setIndexManager(this.indexManager), this.Hi.initialize(this.localDocuments, this.indexManager);\n }\n collectGarbage(t) {\n return this.persistence.runTransaction(\"Collect garbage\", \"readwrite-primary\", (e => t.collect(e, this.Ji)));\n }\n}\n\nfunction su(\n/** Manages our in-memory or durable persistence. */\nt, e, n, s) {\n return new nu(t, e, n, s);\n}\n\n/**\n * Tells the LocalStore that the currently authenticated user has changed.\n *\n * In response the local store switches the mutation queue to the new user and\n * returns any resulting document changes.\n */\n// PORTING NOTE: Android and iOS only return the documents affected by the\n// change.\nasync function iu(t, e) {\n const n = L(t);\n return await n.persistence.runTransaction(\"Handle user change\", \"readonly\", (t => {\n // Swap out the mutation queue, grabbing the pending mutation batches\n // before and after.\n let s;\n return n.mutationQueue.getAllMutationBatches(t).next((i => (s = i, n.tr(e), n.mutationQueue.getAllMutationBatches(t)))).next((e => {\n const i = [], r = [];\n // Union the old/new changed keys.\n let o = gs();\n for (const t of s) {\n i.push(t.batchId);\n for (const e of t.mutations) o = o.add(e.key);\n }\n for (const t of e) {\n r.push(t.batchId);\n for (const e of t.mutations) o = o.add(e.key);\n }\n // Return the set of all (potentially) changed documents and the list\n // of mutation batch IDs that were affected by change.\n return n.localDocuments.getDocuments(t, o).next((t => ({\n er: t,\n removedBatchIds: i,\n addedBatchIds: r\n })));\n }));\n }));\n}\n\n/* Accepts locally generated Mutations and commit them to storage. */\n/**\n * Acknowledges the given batch.\n *\n * On the happy path when a batch is acknowledged, the local store will\n *\n * + remove the batch from the mutation queue;\n * + apply the changes to the remote document cache;\n * + recalculate the latency compensated view implied by those changes (there\n * may be mutations in the queue that affect the documents but haven't been\n * acknowledged yet); and\n * + give the changed documents back the sync engine\n *\n * @returns The resulting (modified) documents.\n */\nfunction ru(t, e) {\n const n = L(t);\n return n.persistence.runTransaction(\"Acknowledge batch\", \"readwrite-primary\", (t => {\n const s = e.batch.keys(), i = n.Zi.newChangeBuffer({\n trackRemovals: !0\n });\n return function(t, e, n, s) {\n const i = n.batch, r = i.keys();\n let o = Rt.resolve();\n return r.forEach((t => {\n o = o.next((() => s.getEntry(e, t))).next((e => {\n const r = n.docVersions.get(t);\n F(null !== r), e.version.compareTo(r) < 0 && (i.applyToRemoteDocument(e, n), e.isValidDocument() && (\n // We use the commitVersion as the readTime rather than the\n // document's updateTime since the updateTime is not advanced\n // for updates that do not modify the underlying document.\n e.setReadTime(n.commitVersion), s.addEntry(e)));\n }));\n })), o.next((() => t.mutationQueue.removeMutationBatch(e, i)));\n }\n /** Returns the local view of the documents affected by a mutation batch. */\n // PORTING NOTE: Multi-Tab only.\n (n, t, e, i).next((() => i.apply(t))).next((() => n.mutationQueue.performConsistencyCheck(t))).next((() => n.documentOverlayCache.removeOverlaysForBatchId(t, s, e.batch.batchId))).next((() => n.localDocuments.recalculateAndSaveOverlaysForDocumentKeys(t, function(t) {\n let e = gs();\n for (let n = 0; n < t.mutationResults.length; ++n) {\n t.mutationResults[n].transformResults.length > 0 && (e = e.add(t.batch.mutations[n].key));\n }\n return e;\n }\n /**\n * Removes mutations from the MutationQueue for the specified batch;\n * LocalDocuments will be recalculated.\n *\n * @returns The resulting modified documents.\n */ (e)))).next((() => n.localDocuments.getDocuments(t, s)));\n }));\n}\n\n/**\n * Returns the last consistent snapshot processed (used by the RemoteStore to\n * determine whether to buffer incoming snapshots from the backend).\n */\nfunction ou(t) {\n const e = L(t);\n return e.persistence.runTransaction(\"Get last remote snapshot version\", \"readonly\", (t => e.Bs.getLastRemoteSnapshotVersion(t)));\n}\n\n/**\n * Updates the \"ground-state\" (remote) documents. We assume that the remote\n * event reflects any write batches that have been acknowledged or rejected\n * (i.e. we do not re-apply local mutations to updates from this event).\n *\n * LocalDocuments are re-calculated if there are remaining mutations in the\n * queue.\n */ function uu(t, e) {\n const n = L(t), s = e.snapshotVersion;\n let i = n.Ji;\n return n.persistence.runTransaction(\"Apply remote event\", \"readwrite-primary\", (t => {\n const r = n.Zi.newChangeBuffer({\n trackRemovals: !0\n });\n // Reset newTargetDataByTargetMap in case this transaction gets re-run.\n i = n.Ji;\n const o = [];\n e.targetChanges.forEach(((r, u) => {\n const c = i.get(u);\n if (!c) return;\n // Only update the remote keys if the target is still active. This\n // ensures that we can persist the updated target data along with\n // the updated assignment.\n o.push(n.Bs.removeMatchingKeys(t, r.removedDocuments, u).next((() => n.Bs.addMatchingKeys(t, r.addedDocuments, u))));\n let a = c.withSequenceNumber(t.currentSequenceNumber);\n null !== e.targetMismatches.get(u) ? a = a.withResumeToken(Ve.EMPTY_BYTE_STRING, rt.min()).withLastLimboFreeSnapshotVersion(rt.min()) : r.resumeToken.approximateByteSize() > 0 && (a = a.withResumeToken(r.resumeToken, s)), \n i = i.insert(u, a), \n // Update the target data if there are target changes (or if\n // sufficient time has passed since the last update).\n /**\n * Returns true if the newTargetData should be persisted during an update of\n * an active target. TargetData should always be persisted when a target is\n * being released and should not call this function.\n *\n * While the target is active, TargetData updates can be omitted when nothing\n * about the target has changed except metadata like the resume token or\n * snapshot version. Occasionally it's worth the extra write to prevent these\n * values from getting too stale after a crash, but this doesn't have to be\n * too frequent.\n */\n function(t, e, n) {\n // Always persist target data if we don't already have a resume token.\n if (0 === t.resumeToken.approximateByteSize()) return !0;\n // Don't allow resume token changes to be buffered indefinitely. This\n // allows us to be reasonably up-to-date after a crash and avoids needing\n // to loop over all active queries on shutdown. Especially in the browser\n // we may not get time to do anything interesting while the current tab is\n // closing.\n if (e.snapshotVersion.toMicroseconds() - t.snapshotVersion.toMicroseconds() >= 3e8) return !0;\n // Otherwise if the only thing that has changed about a target is its resume\n // token it's not worth persisting. Note that the RemoteStore keeps an\n // in-memory view of the currently active targets which includes the current\n // resume token, so stream failure or user changes will still use an\n // up-to-date resume token regardless of what we do here.\n return n.addedDocuments.size + n.modifiedDocuments.size + n.removedDocuments.size > 0;\n }\n /**\n * Notifies local store of the changed views to locally pin documents.\n */ (c, a, r) && o.push(n.Bs.updateTargetData(t, a));\n }));\n let u = cs(), c = gs();\n // HACK: The only reason we allow a null snapshot version is so that we\n // can synthesize remote events when we get permission denied errors while\n // trying to resolve the state of a locally cached document that is in\n // limbo.\n if (e.documentUpdates.forEach((s => {\n e.resolvedLimboDocuments.has(s) && o.push(n.persistence.referenceDelegate.updateLimboDocument(t, s));\n })), \n // Each loop iteration only affects its \"own\" doc, so it's safe to get all\n // the remote documents in advance in a single call.\n o.push(cu(t, r, e.documentUpdates).next((t => {\n u = t.nr, c = t.sr;\n }))), !s.isEqual(rt.min())) {\n const e = n.Bs.getLastRemoteSnapshotVersion(t).next((e => n.Bs.setTargetsMetadata(t, t.currentSequenceNumber, s)));\n o.push(e);\n }\n return Rt.waitFor(o).next((() => r.apply(t))).next((() => n.localDocuments.getLocalViewOfDocuments(t, u, c))).next((() => u));\n })).then((t => (n.Ji = i, t)));\n}\n\n/**\n * Populates document change buffer with documents from backend or a bundle.\n * Returns the document changes resulting from applying those documents, and\n * also a set of documents whose existence state are changed as a result.\n *\n * @param txn - Transaction to use to read existing documents from storage.\n * @param documentBuffer - Document buffer to collect the resulted changes to be\n * applied to storage.\n * @param documents - Documents to be applied.\n */ function cu(t, e, n) {\n let s = gs(), i = gs();\n return n.forEach((t => s = s.add(t))), e.getEntries(t, s).next((t => {\n let s = cs();\n return n.forEach(((n, r) => {\n const o = t.get(n);\n // Check if see if there is a existence state change for this document.\n r.isFoundDocument() !== o.isFoundDocument() && (i = i.add(n)), \n // Note: The order of the steps below is important, since we want\n // to ensure that rejected limbo resolutions (which fabricate\n // NoDocuments with SnapshotVersion.min()) never add documents to\n // cache.\n r.isNoDocument() && r.version.isEqual(rt.min()) ? (\n // NoDocuments with SnapshotVersion.min() are used in manufactured\n // events. We remove these documents from cache since we lost\n // access.\n e.removeEntry(n, r.readTime), s = s.insert(n, r)) : !o.isValidDocument() || r.version.compareTo(o.version) > 0 || 0 === r.version.compareTo(o.version) && o.hasPendingWrites ? (e.addEntry(r), \n s = s.insert(n, r)) : N(\"LocalStore\", \"Ignoring outdated watch update for \", n, \". Current version:\", o.version, \" Watch version:\", r.version);\n })), {\n nr: s,\n sr: i\n };\n }));\n}\n\n/**\n * Gets the mutation batch after the passed in batchId in the mutation queue\n * or null if empty.\n * @param afterBatchId - If provided, the batch to search after.\n * @returns The next mutation or null if there wasn't one.\n */\nfunction au(t, e) {\n const n = L(t);\n return n.persistence.runTransaction(\"Get next mutation batch\", \"readonly\", (t => (void 0 === e && (e = -1), \n n.mutationQueue.getNextMutationBatchAfterBatchId(t, e))));\n}\n\n/**\n * Reads the current value of a Document with a given key or null if not\n * found - used for testing.\n */\n/**\n * Assigns the given target an internal ID so that its results can be pinned so\n * they don't get GC'd. A target must be allocated in the local store before\n * the store can be used to manage its view.\n *\n * Allocating an already allocated `Target` will return the existing `TargetData`\n * for that `Target`.\n */\nfunction hu(t, e) {\n const n = L(t);\n return n.persistence.runTransaction(\"Allocate target\", \"readwrite\", (t => {\n let s;\n return n.Bs.getTargetData(t, e).next((i => i ? (\n // This target has been listened to previously, so reuse the\n // previous targetID.\n // TODO(mcg): freshen last accessed date?\n s = i, Rt.resolve(s)) : n.Bs.allocateTargetId(t).next((i => (s = new cr(e, i, \"TargetPurposeListen\" /* TargetPurpose.Listen */ , t.currentSequenceNumber), \n n.Bs.addTargetData(t, s).next((() => s)))))));\n })).then((t => {\n // If Multi-Tab is enabled, the existing target data may be newer than\n // the in-memory data\n const s = n.Ji.get(t.targetId);\n return (null === s || t.snapshotVersion.compareTo(s.snapshotVersion) > 0) && (n.Ji = n.Ji.insert(t.targetId, t), \n n.Yi.set(e, t.targetId)), t;\n }));\n}\n\n/**\n * Returns the TargetData as seen by the LocalStore, including updates that may\n * have not yet been persisted to the TargetCache.\n */\n// Visible for testing.\n/**\n * Unpins all the documents associated with the given target. If\n * `keepPersistedTargetData` is set to false and Eager GC enabled, the method\n * directly removes the associated target data from the target cache.\n *\n * Releasing a non-existing `Target` is a no-op.\n */\n// PORTING NOTE: `keepPersistedTargetData` is multi-tab only.\nasync function lu(t, e, n) {\n const s = L(t), i = s.Ji.get(e), r = n ? \"readwrite\" : \"readwrite-primary\";\n try {\n n || await s.persistence.runTransaction(\"Release target\", r, (t => s.persistence.referenceDelegate.removeTarget(t, i)));\n } catch (t) {\n if (!Dt(t)) throw t;\n // All `releaseTarget` does is record the final metadata state for the\n // target, but we've been recording this periodically during target\n // activity. If we lose this write this could cause a very slight\n // difference in the order of target deletion during GC, but we\n // don't define exact LRU semantics so this is acceptable.\n N(\"LocalStore\", `Failed to update sequence numbers for target ${e}: ${t}`);\n }\n s.Ji = s.Ji.remove(e), s.Yi.delete(i.target);\n}\n\n/**\n * Runs the specified query against the local store and returns the results,\n * potentially taking advantage of query data from previous executions (such\n * as the set of remote keys).\n *\n * @param usePreviousResults - Whether results from previous executions can\n * be used to optimize this query execution.\n */ function fu(t, e, n) {\n const s = L(t);\n let i = rt.min(), r = gs();\n return s.persistence.runTransaction(\"Execute query\", \"readonly\", (t => function(t, e, n) {\n const s = L(t), i = s.Yi.get(n);\n return void 0 !== i ? Rt.resolve(s.Ji.get(i)) : s.Bs.getTargetData(e, n);\n }(s, t, Jn(e)).next((e => {\n if (e) return i = e.lastLimboFreeSnapshotVersion, s.Bs.getMatchingKeysForTargetId(t, e.targetId).next((t => {\n r = t;\n }));\n })).next((() => s.Hi.getDocumentsMatchingQuery(t, e, n ? i : rt.min(), n ? r : gs()))).next((t => (_u(s, ss(e), t), \n {\n documents: t,\n ir: r\n })))));\n}\n\n// PORTING NOTE: Multi-Tab only.\nfunction du(t, e) {\n const n = L(t), s = L(n.Bs), i = n.Ji.get(e);\n return i ? Promise.resolve(i.target) : n.persistence.runTransaction(\"Get target data\", \"readonly\", (t => s.le(t, e).next((t => t ? t.target : null))));\n}\n\n/**\n * Returns the set of documents that have been updated since the last call.\n * If this is the first call, returns the set of changes since client\n * initialization. Further invocations will return document that have changed\n * since the prior call.\n */\n// PORTING NOTE: Multi-Tab only.\nfunction wu(t, e) {\n const n = L(t), s = n.Xi.get(e) || rt.min();\n // Get the current maximum read time for the collection. This should always\n // exist, but to reduce the chance for regressions we default to\n // SnapshotVersion.Min()\n // TODO(indexing): Consider removing the default value.\n return n.persistence.runTransaction(\"Get new document changes\", \"readonly\", (t => n.Zi.getAllFromCollectionGroup(t, e, yt(s, -1), \n /* limit= */ Number.MAX_SAFE_INTEGER))).then((t => (_u(n, e, t), t)));\n}\n\n/** Sets the collection group's maximum read time from the given documents. */\n// PORTING NOTE: Multi-Tab only.\nfunction _u(t, e, n) {\n let s = t.Xi.get(e) || rt.min();\n n.forEach(((t, e) => {\n e.readTime.compareTo(s) > 0 && (s = e.readTime);\n })), t.Xi.set(e, s);\n}\n\n/**\n * Creates a new target using the given bundle name, which will be used to\n * hold the keys of all documents from the bundle in query-document mappings.\n * This ensures that the loaded documents do not get garbage collected\n * right away.\n */\n/**\n * Applies the documents from a bundle to the \"ground-state\" (remote)\n * documents.\n *\n * LocalDocuments are re-calculated if there are remaining mutations in the\n * queue.\n */\nasync function mu(t, e, n, s) {\n const i = L(t);\n let r = gs(), o = cs();\n for (const t of n) {\n const n = e.rr(t.metadata.name);\n t.document && (r = r.add(n));\n const s = e.ur(t);\n s.setReadTime(e.cr(t.metadata.readTime)), o = o.insert(n, s);\n }\n const u = i.Zi.newChangeBuffer({\n trackRemovals: !0\n }), c = await hu(i, function(t) {\n // It is OK that the path used for the query is not valid, because this will\n // not be read and queried.\n return Jn(Gn(ut.fromString(`__bundle__/docs/${t}`)));\n }(s));\n // Allocates a target to hold all document keys from the bundle, such that\n // they will not get garbage collected right away.\n return i.persistence.runTransaction(\"Apply bundle documents\", \"readwrite\", (t => cu(t, u, o).next((e => (u.apply(t), \n e))).next((e => i.Bs.removeMatchingKeysForTargetId(t, c.targetId).next((() => i.Bs.addMatchingKeys(t, r, c.targetId))).next((() => i.localDocuments.getLocalViewOfDocuments(t, e.nr, e.sr))).next((() => e.nr))))));\n}\n\n/**\n * Returns a promise of a boolean to indicate if the given bundle has already\n * been loaded and the create time is newer than the current loading bundle.\n */\n/**\n * Saves the given `NamedQuery` to local persistence.\n */\nasync function gu(t, e, n = gs()) {\n // Allocate a target for the named query such that it can be resumed\n // from associated read time if users use it to listen.\n // NOTE: this also means if no corresponding target exists, the new target\n // will remain active and will not get collected, unless users happen to\n // unlisten the query somehow.\n const s = await hu(t, Jn(yr(e.bundledQuery))), i = L(t);\n return i.persistence.runTransaction(\"Save named query\", \"readwrite\", (t => {\n const r = Ni(e.readTime);\n // Simply save the query itself if it is older than what the SDK already\n // has.\n if (s.snapshotVersion.compareTo(r) >= 0) return i.qs.saveNamedQuery(t, e);\n // Update existing target data because the query from the bundle is newer.\n const o = s.withResumeToken(Ve.EMPTY_BYTE_STRING, r);\n return i.Ji = i.Ji.insert(o.targetId, o), i.Bs.updateTargetData(t, o).next((() => i.Bs.removeMatchingKeysForTargetId(t, s.targetId))).next((() => i.Bs.addMatchingKeys(t, n, s.targetId))).next((() => i.qs.saveNamedQuery(t, e)));\n }));\n}\n\n/** Assembles the key for a client state in WebStorage */\nfunction yu(t, e) {\n return `firestore_clients_${t}_${e}`;\n}\n\n// The format of the WebStorage key that stores the mutation state is:\n// firestore_mutations__\n// (for unauthenticated users)\n// or: firestore_mutations___\n\n// 'user_uid' is last to avoid needing to escape '_' characters that it might\n// contain.\n/** Assembles the key for a mutation batch in WebStorage */\nfunction pu(t, e, n) {\n let s = `firestore_mutations_${t}_${n}`;\n return e.isAuthenticated() && (s += `_${e.uid}`), s;\n}\n\n// The format of the WebStorage key that stores a query target's metadata is:\n// firestore_targets__\n/** Assembles the key for a query state in WebStorage */\nfunction Iu(t, e) {\n return `firestore_targets_${t}_${e}`;\n}\n\n// The WebStorage prefix that stores the primary tab's online state. The\n// format of the key is:\n// firestore_online_state_\n/**\n * Holds the state of a mutation batch, including its user ID, batch ID and\n * whether the batch is 'pending', 'acknowledged' or 'rejected'.\n */\n// Visible for testing\nclass Tu {\n constructor(t, e, n, s) {\n this.user = t, this.batchId = e, this.state = n, this.error = s;\n }\n /**\n * Parses a MutationMetadata from its JSON representation in WebStorage.\n * Logs a warning and returns null if the format of the data is not valid.\n */ static ar(t, e, n) {\n const s = JSON.parse(n);\n let i, r = \"object\" == typeof s && -1 !== [ \"pending\", \"acknowledged\", \"rejected\" ].indexOf(s.state) && (void 0 === s.error || \"object\" == typeof s.error);\n return r && s.error && (r = \"string\" == typeof s.error.message && \"string\" == typeof s.error.code, \n r && (i = new U(s.error.code, s.error.message))), r ? new Tu(t, e, s.state, i) : (k(\"SharedClientState\", `Failed to parse mutation state for ID '${e}': ${n}`), \n null);\n }\n hr() {\n const t = {\n state: this.state,\n updateTimeMs: Date.now()\n };\n return this.error && (t.error = {\n code: this.error.code,\n message: this.error.message\n }), JSON.stringify(t);\n }\n}\n\n/**\n * Holds the state of a query target, including its target ID and whether the\n * target is 'not-current', 'current' or 'rejected'.\n */\n// Visible for testing\nclass Eu {\n constructor(t, e, n) {\n this.targetId = t, this.state = e, this.error = n;\n }\n /**\n * Parses a QueryTargetMetadata from its JSON representation in WebStorage.\n * Logs a warning and returns null if the format of the data is not valid.\n */ static ar(t, e) {\n const n = JSON.parse(e);\n let s, i = \"object\" == typeof n && -1 !== [ \"not-current\", \"current\", \"rejected\" ].indexOf(n.state) && (void 0 === n.error || \"object\" == typeof n.error);\n return i && n.error && (i = \"string\" == typeof n.error.message && \"string\" == typeof n.error.code, \n i && (s = new U(n.error.code, n.error.message))), i ? new Eu(t, n.state, s) : (k(\"SharedClientState\", `Failed to parse target state for ID '${t}': ${e}`), \n null);\n }\n hr() {\n const t = {\n state: this.state,\n updateTimeMs: Date.now()\n };\n return this.error && (t.error = {\n code: this.error.code,\n message: this.error.message\n }), JSON.stringify(t);\n }\n}\n\n/**\n * This class represents the immutable ClientState for a client read from\n * WebStorage, containing the list of active query targets.\n */ class Au {\n constructor(t, e) {\n this.clientId = t, this.activeTargetIds = e;\n }\n /**\n * Parses a RemoteClientState from the JSON representation in WebStorage.\n * Logs a warning and returns null if the format of the data is not valid.\n */ static ar(t, e) {\n const n = JSON.parse(e);\n let s = \"object\" == typeof n && n.activeTargetIds instanceof Array, i = ps();\n for (let t = 0; s && t < n.activeTargetIds.length; ++t) s = Lt(n.activeTargetIds[t]), \n i = i.add(n.activeTargetIds[t]);\n return s ? new Au(t, i) : (k(\"SharedClientState\", `Failed to parse client data for instance '${t}': ${e}`), \n null);\n }\n}\n\n/**\n * This class represents the online state for all clients participating in\n * multi-tab. The online state is only written to by the primary client, and\n * used in secondary clients to update their query views.\n */ class vu {\n constructor(t, e) {\n this.clientId = t, this.onlineState = e;\n }\n /**\n * Parses a SharedOnlineState from its JSON representation in WebStorage.\n * Logs a warning and returns null if the format of the data is not valid.\n */ static ar(t) {\n const e = JSON.parse(t);\n return \"object\" == typeof e && -1 !== [ \"Unknown\", \"Online\", \"Offline\" ].indexOf(e.onlineState) && \"string\" == typeof e.clientId ? new vu(e.clientId, e.onlineState) : (k(\"SharedClientState\", `Failed to parse online state: ${t}`), \n null);\n }\n}\n\n/**\n * Metadata state of the local client. Unlike `RemoteClientState`, this class is\n * mutable and keeps track of all pending mutations, which allows us to\n * update the range of pending mutation batch IDs as new mutations are added or\n * removed.\n *\n * The data in `LocalClientState` is not read from WebStorage and instead\n * updated via its instance methods. The updated state can be serialized via\n * `toWebStorageJSON()`.\n */\n// Visible for testing.\nclass Ru {\n constructor() {\n this.activeTargetIds = ps();\n }\n lr(t) {\n this.activeTargetIds = this.activeTargetIds.add(t);\n }\n dr(t) {\n this.activeTargetIds = this.activeTargetIds.delete(t);\n }\n /**\n * Converts this entry into a JSON-encoded format we can use for WebStorage.\n * Does not encode `clientId` as it is part of the key in WebStorage.\n */ hr() {\n const t = {\n activeTargetIds: this.activeTargetIds.toArray(),\n updateTimeMs: Date.now()\n };\n return JSON.stringify(t);\n }\n}\n\n/**\n * `WebStorageSharedClientState` uses WebStorage (window.localStorage) as the\n * backing store for the SharedClientState. It keeps track of all active\n * clients and supports modifications of the local client's data.\n */ class Pu {\n constructor(t, e, n, s, i) {\n this.window = t, this.ii = e, this.persistenceKey = n, this.wr = s, this.syncEngine = null, \n this.onlineStateHandler = null, this.sequenceNumberHandler = null, this._r = this.mr.bind(this), \n this.gr = new pe(et), this.started = !1, \n /**\n * Captures WebStorage events that occur before `start()` is called. These\n * events are replayed once `WebStorageSharedClientState` is started.\n */\n this.yr = [];\n // Escape the special characters mentioned here:\n // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions\n const r = n.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\");\n this.storage = this.window.localStorage, this.currentUser = i, this.pr = yu(this.persistenceKey, this.wr), \n this.Ir = \n /** Assembles the key for the current sequence number. */\n function(t) {\n return `firestore_sequence_number_${t}`;\n }\n /**\n * @license\n * Copyright 2018 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */ (this.persistenceKey), this.gr = this.gr.insert(this.wr, new Ru), this.Tr = new RegExp(`^firestore_clients_${r}_([^_]*)$`), \n this.Er = new RegExp(`^firestore_mutations_${r}_(\\\\d+)(?:_(.*))?$`), this.Ar = new RegExp(`^firestore_targets_${r}_(\\\\d+)$`), \n this.vr = \n /** Assembles the key for the online state of the primary tab. */\n function(t) {\n return `firestore_online_state_${t}`;\n }\n // The WebStorage prefix that plays as a event to indicate the remote documents\n // might have changed due to some secondary tabs loading a bundle.\n // format of the key is:\n // firestore_bundle_loaded_v2_\n // The version ending with \"v2\" stores the list of modified collection groups.\n (this.persistenceKey), this.Rr = function(t) {\n return `firestore_bundle_loaded_v2_${t}`;\n }\n // The WebStorage key prefix for the key that stores the last sequence number allocated. The key\n // looks like 'firestore_sequence_number_'.\n (this.persistenceKey), \n // Rather than adding the storage observer during start(), we add the\n // storage observer during initialization. This ensures that we collect\n // events before other components populate their initial state (during their\n // respective start() calls). Otherwise, we might for example miss a\n // mutation that is added after LocalStore's start() processed the existing\n // mutations but before we observe WebStorage events.\n this.window.addEventListener(\"storage\", this._r);\n }\n /** Returns 'true' if WebStorage is available in the current environment. */ static D(t) {\n return !(!t || !t.localStorage);\n }\n async start() {\n // Retrieve the list of existing clients to backfill the data in\n // SharedClientState.\n const t = await this.syncEngine.$i();\n for (const e of t) {\n if (e === this.wr) continue;\n const t = this.getItem(yu(this.persistenceKey, e));\n if (t) {\n const n = Au.ar(e, t);\n n && (this.gr = this.gr.insert(n.clientId, n));\n }\n }\n this.Pr();\n // Check if there is an existing online state and call the callback handler\n // if applicable.\n const e = this.storage.getItem(this.vr);\n if (e) {\n const t = this.br(e);\n t && this.Vr(t);\n }\n for (const t of this.yr) this.mr(t);\n this.yr = [], \n // Register a window unload hook to remove the client metadata entry from\n // WebStorage even if `shutdown()` was not called.\n this.window.addEventListener(\"pagehide\", (() => this.shutdown())), this.started = !0;\n }\n writeSequenceNumber(t) {\n this.setItem(this.Ir, JSON.stringify(t));\n }\n getAllActiveQueryTargets() {\n return this.Sr(this.gr);\n }\n isActiveQueryTarget(t) {\n let e = !1;\n return this.gr.forEach(((n, s) => {\n s.activeTargetIds.has(t) && (e = !0);\n })), e;\n }\n addPendingMutation(t) {\n this.Dr(t, \"pending\");\n }\n updateMutationState(t, e, n) {\n this.Dr(t, e, n), \n // Once a final mutation result is observed by other clients, they no longer\n // access the mutation's metadata entry. Since WebStorage replays events\n // in order, it is safe to delete the entry right after updating it.\n this.Cr(t);\n }\n addLocalQueryTarget(t) {\n let e = \"not-current\";\n // Lookup an existing query state if the target ID was already registered\n // by another tab\n if (this.isActiveQueryTarget(t)) {\n const n = this.storage.getItem(Iu(this.persistenceKey, t));\n if (n) {\n const s = Eu.ar(t, n);\n s && (e = s.state);\n }\n }\n return this.Nr.lr(t), this.Pr(), e;\n }\n removeLocalQueryTarget(t) {\n this.Nr.dr(t), this.Pr();\n }\n isLocalQueryTarget(t) {\n return this.Nr.activeTargetIds.has(t);\n }\n clearQueryState(t) {\n this.removeItem(Iu(this.persistenceKey, t));\n }\n updateQueryState(t, e, n) {\n this.kr(t, e, n);\n }\n handleUserChange(t, e, n) {\n e.forEach((t => {\n this.Cr(t);\n })), this.currentUser = t, n.forEach((t => {\n this.addPendingMutation(t);\n }));\n }\n setOnlineState(t) {\n this.Mr(t);\n }\n notifyBundleLoaded(t) {\n this.$r(t);\n }\n shutdown() {\n this.started && (this.window.removeEventListener(\"storage\", this._r), this.removeItem(this.pr), \n this.started = !1);\n }\n getItem(t) {\n const e = this.storage.getItem(t);\n return N(\"SharedClientState\", \"READ\", t, e), e;\n }\n setItem(t, e) {\n N(\"SharedClientState\", \"SET\", t, e), this.storage.setItem(t, e);\n }\n removeItem(t) {\n N(\"SharedClientState\", \"REMOVE\", t), this.storage.removeItem(t);\n }\n mr(t) {\n // Note: The function is typed to take Event to be interface-compatible with\n // `Window.addEventListener`.\n const e = t;\n if (e.storageArea === this.storage) {\n if (N(\"SharedClientState\", \"EVENT\", e.key, e.newValue), e.key === this.pr) return void k(\"Received WebStorage notification for local change. Another client might have garbage-collected our state\");\n this.ii.enqueueRetryable((async () => {\n if (this.started) {\n if (null !== e.key) if (this.Tr.test(e.key)) {\n if (null == e.newValue) {\n const t = this.Or(e.key);\n return this.Fr(t, null);\n }\n {\n const t = this.Br(e.key, e.newValue);\n if (t) return this.Fr(t.clientId, t);\n }\n } else if (this.Er.test(e.key)) {\n if (null !== e.newValue) {\n const t = this.Lr(e.key, e.newValue);\n if (t) return this.qr(t);\n }\n } else if (this.Ar.test(e.key)) {\n if (null !== e.newValue) {\n const t = this.Ur(e.key, e.newValue);\n if (t) return this.Kr(t);\n }\n } else if (e.key === this.vr) {\n if (null !== e.newValue) {\n const t = this.br(e.newValue);\n if (t) return this.Vr(t);\n }\n } else if (e.key === this.Ir) {\n const t = function(t) {\n let e = Ot.ct;\n if (null != t) try {\n const n = JSON.parse(t);\n F(\"number\" == typeof n), e = n;\n } catch (t) {\n k(\"SharedClientState\", \"Failed to read sequence number from WebStorage\", t);\n }\n return e;\n }\n /**\n * `MemorySharedClientState` is a simple implementation of SharedClientState for\n * clients using memory persistence. The state in this class remains fully\n * isolated and no synchronization is performed.\n */ (e.newValue);\n t !== Ot.ct && this.sequenceNumberHandler(t);\n } else if (e.key === this.Rr) {\n const t = this.Gr(e.newValue);\n await Promise.all(t.map((t => this.syncEngine.Qr(t))));\n }\n } else this.yr.push(e);\n }));\n }\n }\n get Nr() {\n return this.gr.get(this.wr);\n }\n Pr() {\n this.setItem(this.pr, this.Nr.hr());\n }\n Dr(t, e, n) {\n const s = new Tu(this.currentUser, t, e, n), i = pu(this.persistenceKey, this.currentUser, t);\n this.setItem(i, s.hr());\n }\n Cr(t) {\n const e = pu(this.persistenceKey, this.currentUser, t);\n this.removeItem(e);\n }\n Mr(t) {\n const e = {\n clientId: this.wr,\n onlineState: t\n };\n this.storage.setItem(this.vr, JSON.stringify(e));\n }\n kr(t, e, n) {\n const s = Iu(this.persistenceKey, t), i = new Eu(t, e, n);\n this.setItem(s, i.hr());\n }\n $r(t) {\n const e = JSON.stringify(Array.from(t));\n this.setItem(this.Rr, e);\n }\n /**\n * Parses a client state key in WebStorage. Returns null if the key does not\n * match the expected key format.\n */ Or(t) {\n const e = this.Tr.exec(t);\n return e ? e[1] : null;\n }\n /**\n * Parses a client state in WebStorage. Returns 'null' if the value could not\n * be parsed.\n */ Br(t, e) {\n const n = this.Or(t);\n return Au.ar(n, e);\n }\n /**\n * Parses a mutation batch state in WebStorage. Returns 'null' if the value\n * could not be parsed.\n */ Lr(t, e) {\n const n = this.Er.exec(t), s = Number(n[1]), i = void 0 !== n[2] ? n[2] : null;\n return Tu.ar(new V(i), s, e);\n }\n /**\n * Parses a query target state from WebStorage. Returns 'null' if the value\n * could not be parsed.\n */ Ur(t, e) {\n const n = this.Ar.exec(t), s = Number(n[1]);\n return Eu.ar(s, e);\n }\n /**\n * Parses an online state from WebStorage. Returns 'null' if the value\n * could not be parsed.\n */ br(t) {\n return vu.ar(t);\n }\n Gr(t) {\n return JSON.parse(t);\n }\n async qr(t) {\n if (t.user.uid === this.currentUser.uid) return this.syncEngine.jr(t.batchId, t.state, t.error);\n N(\"SharedClientState\", `Ignoring mutation for non-active user ${t.user.uid}`);\n }\n Kr(t) {\n return this.syncEngine.zr(t.targetId, t.state, t.error);\n }\n Fr(t, e) {\n const n = e ? this.gr.insert(t, e) : this.gr.remove(t), s = this.Sr(this.gr), i = this.Sr(n), r = [], o = [];\n return i.forEach((t => {\n s.has(t) || r.push(t);\n })), s.forEach((t => {\n i.has(t) || o.push(t);\n })), this.syncEngine.Wr(r, o).then((() => {\n this.gr = n;\n }));\n }\n Vr(t) {\n // We check whether the client that wrote this online state is still active\n // by comparing its client ID to the list of clients kept active in\n // IndexedDb. If a client does not update their IndexedDb client state\n // within 5 seconds, it is considered inactive and we don't emit an online\n // state event.\n this.gr.get(t.clientId) && this.onlineStateHandler(t.onlineState);\n }\n Sr(t) {\n let e = ps();\n return t.forEach(((t, n) => {\n e = e.unionWith(n.activeTargetIds);\n })), e;\n }\n}\n\nclass bu {\n constructor() {\n this.Hr = new Ru, this.Jr = {}, this.onlineStateHandler = null, this.sequenceNumberHandler = null;\n }\n addPendingMutation(t) {\n // No op.\n }\n updateMutationState(t, e, n) {\n // No op.\n }\n addLocalQueryTarget(t) {\n return this.Hr.lr(t), this.Jr[t] || \"not-current\";\n }\n updateQueryState(t, e, n) {\n this.Jr[t] = e;\n }\n removeLocalQueryTarget(t) {\n this.Hr.dr(t);\n }\n isLocalQueryTarget(t) {\n return this.Hr.activeTargetIds.has(t);\n }\n clearQueryState(t) {\n delete this.Jr[t];\n }\n getAllActiveQueryTargets() {\n return this.Hr.activeTargetIds;\n }\n isActiveQueryTarget(t) {\n return this.Hr.activeTargetIds.has(t);\n }\n start() {\n return this.Hr = new Ru, Promise.resolve();\n }\n handleUserChange(t, e, n) {\n // No op.\n }\n setOnlineState(t) {\n // No op.\n }\n shutdown() {}\n writeSequenceNumber(t) {}\n notifyBundleLoaded(t) {\n // No op.\n }\n}\n\n/**\n * @license\n * Copyright 2019 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */ class Vu {\n Yr(t) {\n // No-op.\n }\n shutdown() {\n // No-op.\n }\n}\n\n/**\n * @license\n * Copyright 2019 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n// References to `window` are guarded by BrowserConnectivityMonitor.isAvailable()\n/* eslint-disable no-restricted-globals */\n/**\n * Browser implementation of ConnectivityMonitor.\n */\nclass Su {\n constructor() {\n this.Xr = () => this.Zr(), this.eo = () => this.no(), this.so = [], this.io();\n }\n Yr(t) {\n this.so.push(t);\n }\n shutdown() {\n window.removeEventListener(\"online\", this.Xr), window.removeEventListener(\"offline\", this.eo);\n }\n io() {\n window.addEventListener(\"online\", this.Xr), window.addEventListener(\"offline\", this.eo);\n }\n Zr() {\n N(\"ConnectivityMonitor\", \"Network connectivity changed: AVAILABLE\");\n for (const t of this.so) t(0 /* NetworkStatus.AVAILABLE */);\n }\n no() {\n N(\"ConnectivityMonitor\", \"Network connectivity changed: UNAVAILABLE\");\n for (const t of this.so) t(1 /* NetworkStatus.UNAVAILABLE */);\n }\n // TODO(chenbrian): Consider passing in window either into this component or\n // here for testing via FakeWindow.\n /** Checks that all used attributes of window are available. */\n static D() {\n return \"undefined\" != typeof window && void 0 !== window.addEventListener && void 0 !== window.removeEventListener;\n }\n}\n\n/**\n * @license\n * Copyright 2023 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * The value returned from the most recent invocation of\n * `generateUniqueDebugId()`, or null if it has never been invoked.\n */ let Du = null;\n\n/**\n * Generates and returns an initial value for `lastUniqueDebugId`.\n *\n * The returned value is randomly selected from a range of integers that are\n * represented as 8 hexadecimal digits. This means that (within reason) any\n * numbers generated by incrementing the returned number by 1 will also be\n * represented by 8 hexadecimal digits. This leads to all \"IDs\" having the same\n * length when converted to a hexadecimal string, making reading logs containing\n * these IDs easier to follow. And since the return value is randomly selected\n * it will help to differentiate between logs from different executions.\n */\n/**\n * Generates and returns a unique ID as a hexadecimal string.\n *\n * The returned ID is intended to be used in debug logging messages to help\n * correlate log messages that may be spatially separated in the logs, but\n * logically related. For example, a network connection could include the same\n * \"debug ID\" string in all of its log messages to help trace a specific\n * connection over time.\n *\n * @return the 10-character generated ID (e.g. \"0xa1b2c3d4\").\n */\nfunction Cu() {\n return null === Du ? Du = 268435456 + Math.round(2147483648 * Math.random()) : Du++, \n \"0x\" + Du.toString(16);\n}\n\n/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */ const xu = {\n BatchGetDocuments: \"batchGet\",\n Commit: \"commit\",\n RunQuery: \"runQuery\",\n RunAggregationQuery: \"runAggregationQuery\"\n};\n\n/**\n * Maps RPC names to the corresponding REST endpoint name.\n *\n * We use array notation to avoid mangling.\n */\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * Provides a simple helper class that implements the Stream interface to\n * bridge to other implementations that are streams but do not implement the\n * interface. The stream callbacks are invoked with the callOn... methods.\n */\nclass Nu {\n constructor(t) {\n this.ro = t.ro, this.oo = t.oo;\n }\n uo(t) {\n this.co = t;\n }\n ao(t) {\n this.ho = t;\n }\n onMessage(t) {\n this.lo = t;\n }\n close() {\n this.oo();\n }\n send(t) {\n this.ro(t);\n }\n fo() {\n this.co();\n }\n wo(t) {\n this.ho(t);\n }\n _o(t) {\n this.lo(t);\n }\n}\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */ const ku = \"WebChannelConnection\";\n\nclass Mu extends \n/**\n * Base class for all Rest-based connections to the backend (WebChannel and\n * HTTP).\n */\nclass {\n constructor(t) {\n this.databaseInfo = t, this.databaseId = t.databaseId;\n const e = t.ssl ? \"https\" : \"http\";\n this.mo = e + \"://\" + t.host, this.yo = \"projects/\" + this.databaseId.projectId + \"/databases/\" + this.databaseId.database + \"/documents\";\n }\n get po() {\n // Both `invokeRPC()` and `invokeStreamingRPC()` use their `path` arguments to determine\n // where to run the query, and expect the `request` to NOT specify the \"path\".\n return !1;\n }\n Io(t, e, n, s, i) {\n const r = Cu(), o = this.To(t, e);\n N(\"RestConnection\", `Sending RPC '${t}' ${r}:`, o, n);\n const u = {};\n return this.Eo(u, s, i), this.Ao(t, o, u, n).then((e => (N(\"RestConnection\", `Received RPC '${t}' ${r}: `, e), \n e)), (e => {\n throw M(\"RestConnection\", `RPC '${t}' ${r} failed with error: `, e, \"url: \", o, \"request:\", n), \n e;\n }));\n }\n vo(t, e, n, s, i, r) {\n // The REST API automatically aggregates all of the streamed results, so we\n // can just use the normal invoke() method.\n return this.Io(t, e, n, s, i);\n }\n /**\n * Modifies the headers for a request, adding any authorization token if\n * present and any additional headers for the request.\n */ Eo(t, e, n) {\n t[\"X-Goog-Api-Client\"] = \"gl-js/ fire/\" + S, \n // Content-Type: text/plain will avoid preflight requests which might\n // mess with CORS and redirects by proxies. If we add custom headers\n // we will need to change this code to potentially use the $httpOverwrite\n // parameter supported by ESF to avoid triggering preflight requests.\n t[\"Content-Type\"] = \"text/plain\", this.databaseInfo.appId && (t[\"X-Firebase-GMPID\"] = this.databaseInfo.appId), \n e && e.headers.forEach(((e, n) => t[n] = e)), n && n.headers.forEach(((e, n) => t[n] = e));\n }\n To(t, e) {\n const n = xu[t];\n return `${this.mo}/v1/${e}:${n}`;\n }\n} {\n constructor(t) {\n super(t), this.forceLongPolling = t.forceLongPolling, this.autoDetectLongPolling = t.autoDetectLongPolling, \n this.useFetchStreams = t.useFetchStreams, this.longPollingOptions = t.longPollingOptions;\n }\n Ao(t, e, n, s) {\n const i = Cu();\n return new Promise(((r, o) => {\n const u = new XhrIo;\n u.setWithCredentials(!0), u.listenOnce(EventType.COMPLETE, (() => {\n try {\n switch (u.getLastErrorCode()) {\n case ErrorCode.NO_ERROR:\n const e = u.getResponseJson();\n N(ku, `XHR for RPC '${t}' ${i} received:`, JSON.stringify(e)), r(e);\n break;\n\n case ErrorCode.TIMEOUT:\n N(ku, `RPC '${t}' ${i} timed out`), o(new U(q.DEADLINE_EXCEEDED, \"Request time out\"));\n break;\n\n case ErrorCode.HTTP_ERROR:\n const n = u.getStatus();\n if (N(ku, `RPC '${t}' ${i} failed with status:`, n, \"response text:\", u.getResponseText()), \n n > 0) {\n let t = u.getResponseJson();\n Array.isArray(t) && (t = t[0]);\n const e = null == t ? void 0 : t.error;\n if (e && e.status && e.message) {\n const t = function(t) {\n const e = t.toLowerCase().replace(/_/g, \"-\");\n return Object.values(q).indexOf(e) >= 0 ? e : q.UNKNOWN;\n }(e.status);\n o(new U(t, e.message));\n } else o(new U(q.UNKNOWN, \"Server responded with status \" + u.getStatus()));\n } else \n // If we received an HTTP_ERROR but there's no status code,\n // it's most probably a connection issue\n o(new U(q.UNAVAILABLE, \"Connection failed.\"));\n break;\n\n default:\n O();\n }\n } finally {\n N(ku, `RPC '${t}' ${i} completed.`);\n }\n }));\n const c = JSON.stringify(s);\n N(ku, `RPC '${t}' ${i} sending request:`, s), u.send(e, \"POST\", c, n, 15);\n }));\n }\n Ro(t, e, n) {\n const s = Cu(), i = [ this.mo, \"/\", \"google.firestore.v1.Firestore\", \"/\", t, \"/channel\" ], r = createWebChannelTransport(), o = getStatEventTarget(), u = {\n // Required for backend stickiness, routing behavior is based on this\n // parameter.\n httpSessionIdParam: \"gsessionid\",\n initMessageHeaders: {},\n messageUrlParams: {\n // This param is used to improve routing and project isolation by the\n // backend and must be included in every request.\n database: `projects/${this.databaseId.projectId}/databases/${this.databaseId.database}`\n },\n sendRawJson: !0,\n supportsCrossDomainXhr: !0,\n internalChannelParams: {\n // Override the default timeout (randomized between 10-20 seconds) since\n // a large write batch on a slow internet connection may take a long\n // time to send to the backend. Rather than have WebChannel impose a\n // tight timeout which could lead to infinite timeouts and retries, we\n // set it very large (5-10 minutes) and rely on the browser's builtin\n // timeouts to kick in if the request isn't working.\n forwardChannelRequestTimeoutMs: 6e5\n },\n forceLongPolling: this.forceLongPolling,\n detectBufferingProxy: this.autoDetectLongPolling\n }, c = this.longPollingOptions.timeoutSeconds;\n void 0 !== c && (u.longPollingTimeout = Math.round(1e3 * c)), this.useFetchStreams && (u.xmlHttpFactory = new FetchXmlHttpFactory({})), \n this.Eo(u.initMessageHeaders, e, n), \n // Sending the custom headers we just added to request.initMessageHeaders\n // (Authorization, etc.) will trigger the browser to make a CORS preflight\n // request because the XHR will no longer meet the criteria for a \"simple\"\n // CORS request:\n // https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS#Simple_requests\n // Therefore to avoid the CORS preflight request (an extra network\n // roundtrip), we use the encodeInitMessageHeaders option to specify that\n // the headers should instead be encoded in the request's POST payload,\n // which is recognized by the webchannel backend.\n u.encodeInitMessageHeaders = !0;\n const a = i.join(\"\");\n N(ku, `Creating RPC '${t}' stream ${s}: ${a}`, u);\n const h = r.createWebChannel(a, u);\n // WebChannel supports sending the first message with the handshake - saving\n // a network round trip. However, it will have to call send in the same\n // JS event loop as open. In order to enforce this, we delay actually\n // opening the WebChannel until send is called. Whether we have called\n // open is tracked with this variable.\n let l = !1, f = !1;\n // A flag to determine whether the stream was closed (by us or through an\n // error/close event) to avoid delivering multiple close events or sending\n // on a closed stream\n const d = new Nu({\n ro: e => {\n f ? N(ku, `Not sending because RPC '${t}' stream ${s} is closed:`, e) : (l || (N(ku, `Opening RPC '${t}' stream ${s} transport.`), \n h.open(), l = !0), N(ku, `RPC '${t}' stream ${s} sending:`, e), h.send(e));\n },\n oo: () => h.close()\n }), w = (t, e, n) => {\n // TODO(dimond): closure typing seems broken because WebChannel does\n // not implement goog.events.Listenable\n t.listen(e, (t => {\n try {\n n(t);\n } catch (t) {\n setTimeout((() => {\n throw t;\n }), 0);\n }\n }));\n };\n // Closure events are guarded and exceptions are swallowed, so catch any\n // exception and rethrow using a setTimeout so they become visible again.\n // Note that eventually this function could go away if we are confident\n // enough the code is exception free.\n return w(h, WebChannel.EventType.OPEN, (() => {\n f || N(ku, `RPC '${t}' stream ${s} transport opened.`);\n })), w(h, WebChannel.EventType.CLOSE, (() => {\n f || (f = !0, N(ku, `RPC '${t}' stream ${s} transport closed`), d.wo());\n })), w(h, WebChannel.EventType.ERROR, (e => {\n f || (f = !0, M(ku, `RPC '${t}' stream ${s} transport errored:`, e), d.wo(new U(q.UNAVAILABLE, \"The operation could not be completed\")));\n })), w(h, WebChannel.EventType.MESSAGE, (e => {\n var n;\n if (!f) {\n const i = e.data[0];\n F(!!i);\n // TODO(b/35143891): There is a bug in One Platform that caused errors\n // (and only errors) to be wrapped in an extra array. To be forward\n // compatible with the bug we need to check either condition. The latter\n // can be removed once the fix has been rolled out.\n // Use any because msgData.error is not typed.\n const r = i, o = r.error || (null === (n = r[0]) || void 0 === n ? void 0 : n.error);\n if (o) {\n N(ku, `RPC '${t}' stream ${s} received error:`, o);\n // error.status will be a string like 'OK' or 'NOT_FOUND'.\n const e = o.status;\n let n = \n /**\n * Maps an error Code from a GRPC status identifier like 'NOT_FOUND'.\n *\n * @returns The Code equivalent to the given status string or undefined if\n * there is no match.\n */\n function(t) {\n // lookup by string\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const e = ii[t];\n if (void 0 !== e) return ui(e);\n }(e), i = o.message;\n void 0 === n && (n = q.INTERNAL, i = \"Unknown error status: \" + e + \" with message \" + o.message), \n // Mark closed so no further events are propagated\n f = !0, d.wo(new U(n, i)), h.close();\n } else N(ku, `RPC '${t}' stream ${s} received:`, i), d._o(i);\n }\n })), w(o, Event.STAT_EVENT, (e => {\n e.stat === Stat.PROXY ? N(ku, `RPC '${t}' stream ${s} detected buffering proxy`) : e.stat === Stat.NOPROXY && N(ku, `RPC '${t}' stream ${s} detected no buffering proxy`);\n })), setTimeout((() => {\n // Technically we could/should wait for the WebChannel opened event,\n // but because we want to send the first message with the WebChannel\n // handshake we pretend the channel opened here (asynchronously), and\n // then delay the actual open until the first message is sent.\n d.fo();\n }), 0), d;\n }\n}\n\n/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/** Initializes the WebChannelConnection for the browser. */\n/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/** The Platform's 'window' implementation or null if not available. */\nfunction $u() {\n // `window` is not always available, e.g. in ReactNative and WebWorkers.\n // eslint-disable-next-line no-restricted-globals\n return \"undefined\" != typeof window ? window : null;\n}\n\n/** The Platform's 'document' implementation or null if not available. */ function Ou() {\n // `document` is not always available, e.g. in ReactNative and WebWorkers.\n // eslint-disable-next-line no-restricted-globals\n return \"undefined\" != typeof document ? document : null;\n}\n\n/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */ function Fu(t) {\n return new Vi(t, /* useProto3Json= */ !0);\n}\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * A helper for running delayed tasks following an exponential backoff curve\n * between attempts.\n *\n * Each delay is made up of a \"base\" delay which follows the exponential\n * backoff curve, and a +/- 50% \"jitter\" that is calculated and added to the\n * base delay. This prevents clients from accidentally synchronizing their\n * delays causing spikes of load to the backend.\n */\nclass Bu {\n constructor(\n /**\n * The AsyncQueue to run backoff operations on.\n */\n t, \n /**\n * The ID to use when scheduling backoff operations on the AsyncQueue.\n */\n e, \n /**\n * The initial delay (used as the base delay on the first retry attempt).\n * Note that jitter will still be applied, so the actual delay could be as\n * little as 0.5*initialDelayMs.\n */\n n = 1e3\n /**\n * The multiplier to use to determine the extended base delay after each\n * attempt.\n */ , s = 1.5\n /**\n * The maximum base delay after which no further backoff is performed.\n * Note that jitter will still be applied, so the actual delay could be as\n * much as 1.5*maxDelayMs.\n */ , i = 6e4) {\n this.ii = t, this.timerId = e, this.Po = n, this.bo = s, this.Vo = i, this.So = 0, \n this.Do = null, \n /** The last backoff attempt, as epoch milliseconds. */\n this.Co = Date.now(), this.reset();\n }\n /**\n * Resets the backoff delay.\n *\n * The very next backoffAndWait() will have no delay. If it is called again\n * (i.e. due to an error), initialDelayMs (plus jitter) will be used, and\n * subsequent ones will increase according to the backoffFactor.\n */ reset() {\n this.So = 0;\n }\n /**\n * Resets the backoff delay to the maximum delay (e.g. for use after a\n * RESOURCE_EXHAUSTED error).\n */ xo() {\n this.So = this.Vo;\n }\n /**\n * Returns a promise that resolves after currentDelayMs, and increases the\n * delay for any subsequent attempts. If there was a pending backoff operation\n * already, it will be canceled.\n */ No(t) {\n // Cancel any pending backoff operation.\n this.cancel();\n // First schedule using the current base (which may be 0 and should be\n // honored as such).\n const e = Math.floor(this.So + this.ko()), n = Math.max(0, Date.now() - this.Co), s = Math.max(0, e - n);\n // Guard against lastAttemptTime being in the future due to a clock change.\n s > 0 && N(\"ExponentialBackoff\", `Backing off for ${s} ms (base delay: ${this.So} ms, delay with jitter: ${e} ms, last attempt: ${n} ms ago)`), \n this.Do = this.ii.enqueueAfterDelay(this.timerId, s, (() => (this.Co = Date.now(), \n t()))), \n // Apply backoff factor to determine next delay and ensure it is within\n // bounds.\n this.So *= this.bo, this.So < this.Po && (this.So = this.Po), this.So > this.Vo && (this.So = this.Vo);\n }\n Mo() {\n null !== this.Do && (this.Do.skipDelay(), this.Do = null);\n }\n cancel() {\n null !== this.Do && (this.Do.cancel(), this.Do = null);\n }\n /** Returns a random value in the range [-currentBaseMs/2, currentBaseMs/2] */ ko() {\n return (Math.random() - .5) * this.So;\n }\n}\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * A PersistentStream is an abstract base class that represents a streaming RPC\n * to the Firestore backend. It's built on top of the connections own support\n * for streaming RPCs, and adds several critical features for our clients:\n *\n * - Exponential backoff on failure\n * - Authentication via CredentialsProvider\n * - Dispatching all callbacks into the shared worker queue\n * - Closing idle streams after 60 seconds of inactivity\n *\n * Subclasses of PersistentStream implement serialization of models to and\n * from the JSON representation of the protocol buffers for a specific\n * streaming RPC.\n *\n * ## Starting and Stopping\n *\n * Streaming RPCs are stateful and need to be start()ed before messages can\n * be sent and received. The PersistentStream will call the onOpen() function\n * of the listener once the stream is ready to accept requests.\n *\n * Should a start() fail, PersistentStream will call the registered onClose()\n * listener with a FirestoreError indicating what went wrong.\n *\n * A PersistentStream can be started and stopped repeatedly.\n *\n * Generic types:\n * SendType: The type of the outgoing message of the underlying\n * connection stream\n * ReceiveType: The type of the incoming message of the underlying\n * connection stream\n * ListenerType: The type of the listener that will be used for callbacks\n */\nclass Lu {\n constructor(t, e, n, s, i, r, o, u) {\n this.ii = t, this.$o = n, this.Oo = s, this.connection = i, this.authCredentialsProvider = r, \n this.appCheckCredentialsProvider = o, this.listener = u, this.state = 0 /* PersistentStreamState.Initial */ , \n /**\n * A close count that's incremented every time the stream is closed; used by\n * getCloseGuardedDispatcher() to invalidate callbacks that happen after\n * close.\n */\n this.Fo = 0, this.Bo = null, this.Lo = null, this.stream = null, this.qo = new Bu(t, e);\n }\n /**\n * Returns true if start() has been called and no error has occurred. True\n * indicates the stream is open or in the process of opening (which\n * encompasses respecting backoff, getting auth tokens, and starting the\n * actual RPC). Use isOpen() to determine if the stream is open and ready for\n * outbound requests.\n */ Uo() {\n return 1 /* PersistentStreamState.Starting */ === this.state || 5 /* PersistentStreamState.Backoff */ === this.state || this.Ko();\n }\n /**\n * Returns true if the underlying RPC is open (the onOpen() listener has been\n * called) and the stream is ready for outbound requests.\n */ Ko() {\n return 2 /* PersistentStreamState.Open */ === this.state || 3 /* PersistentStreamState.Healthy */ === this.state;\n }\n /**\n * Starts the RPC. Only allowed if isStarted() returns false. The stream is\n * not immediately ready for use: onOpen() will be invoked when the RPC is\n * ready for outbound requests, at which point isOpen() will return true.\n *\n * When start returns, isStarted() will return true.\n */ start() {\n 4 /* PersistentStreamState.Error */ !== this.state ? this.auth() : this.Go();\n }\n /**\n * Stops the RPC. This call is idempotent and allowed regardless of the\n * current isStarted() state.\n *\n * When stop returns, isStarted() and isOpen() will both return false.\n */ async stop() {\n this.Uo() && await this.close(0 /* PersistentStreamState.Initial */);\n }\n /**\n * After an error the stream will usually back off on the next attempt to\n * start it. If the error warrants an immediate restart of the stream, the\n * sender can use this to indicate that the receiver should not back off.\n *\n * Each error will call the onClose() listener. That function can decide to\n * inhibit backoff if required.\n */ Qo() {\n this.state = 0 /* PersistentStreamState.Initial */ , this.qo.reset();\n }\n /**\n * Marks this stream as idle. If no further actions are performed on the\n * stream for one minute, the stream will automatically close itself and\n * notify the stream's onClose() handler with Status.OK. The stream will then\n * be in a !isStarted() state, requiring the caller to start the stream again\n * before further use.\n *\n * Only streams that are in state 'Open' can be marked idle, as all other\n * states imply pending network operations.\n */ jo() {\n // Starts the idle time if we are in state 'Open' and are not yet already\n // running a timer (in which case the previous idle timeout still applies).\n this.Ko() && null === this.Bo && (this.Bo = this.ii.enqueueAfterDelay(this.$o, 6e4, (() => this.zo())));\n }\n /** Sends a message to the underlying stream. */ Wo(t) {\n this.Ho(), this.stream.send(t);\n }\n /** Called by the idle timer when the stream should close due to inactivity. */ async zo() {\n if (this.Ko()) \n // When timing out an idle stream there's no reason to force the stream into backoff when\n // it restarts so set the stream state to Initial instead of Error.\n return this.close(0 /* PersistentStreamState.Initial */);\n }\n /** Marks the stream as active again. */ Ho() {\n this.Bo && (this.Bo.cancel(), this.Bo = null);\n }\n /** Cancels the health check delayed operation. */ Jo() {\n this.Lo && (this.Lo.cancel(), this.Lo = null);\n }\n /**\n * Closes the stream and cleans up as necessary:\n *\n * * closes the underlying GRPC stream;\n * * calls the onClose handler with the given 'error';\n * * sets internal stream state to 'finalState';\n * * adjusts the backoff timer based on the error\n *\n * A new stream can be opened by calling start().\n *\n * @param finalState - the intended state of the stream after closing.\n * @param error - the error the connection was closed with.\n */ async close(t, e) {\n // Cancel any outstanding timers (they're guaranteed not to execute).\n this.Ho(), this.Jo(), this.qo.cancel(), \n // Invalidates any stream-related callbacks (e.g. from auth or the\n // underlying stream), guaranteeing they won't execute.\n this.Fo++, 4 /* PersistentStreamState.Error */ !== t ? \n // If this is an intentional close ensure we don't delay our next connection attempt.\n this.qo.reset() : e && e.code === q.RESOURCE_EXHAUSTED ? (\n // Log the error. (Probably either 'quota exceeded' or 'max queue length reached'.)\n k(e.toString()), k(\"Using maximum backoff delay to prevent overloading the backend.\"), \n this.qo.xo()) : e && e.code === q.UNAUTHENTICATED && 3 /* PersistentStreamState.Healthy */ !== this.state && (\n // \"unauthenticated\" error means the token was rejected. This should rarely\n // happen since both Auth and AppCheck ensure a sufficient TTL when we\n // request a token. If a user manually resets their system clock this can\n // fail, however. In this case, we should get a Code.UNAUTHENTICATED error\n // before we received the first message and we need to invalidate the token\n // to ensure that we fetch a new token.\n this.authCredentialsProvider.invalidateToken(), this.appCheckCredentialsProvider.invalidateToken()), \n // Clean up the underlying stream because we are no longer interested in events.\n null !== this.stream && (this.Yo(), this.stream.close(), this.stream = null), \n // This state must be assigned before calling onClose() to allow the callback to\n // inhibit backoff or otherwise manipulate the state in its non-started state.\n this.state = t, \n // Notify the listener that the stream closed.\n await this.listener.ao(e);\n }\n /**\n * Can be overridden to perform additional cleanup before the stream is closed.\n * Calling super.tearDown() is not required.\n */ Yo() {}\n auth() {\n this.state = 1 /* PersistentStreamState.Starting */;\n const t = this.Xo(this.Fo), e = this.Fo;\n // TODO(mikelehen): Just use dispatchIfNotClosed, but see TODO below.\n Promise.all([ this.authCredentialsProvider.getToken(), this.appCheckCredentialsProvider.getToken() ]).then((([t, n]) => {\n // Stream can be stopped while waiting for authentication.\n // TODO(mikelehen): We really should just use dispatchIfNotClosed\n // and let this dispatch onto the queue, but that opened a spec test can\n // of worms that I don't want to deal with in this PR.\n this.Fo === e && \n // Normally we'd have to schedule the callback on the AsyncQueue.\n // However, the following calls are safe to be called outside the\n // AsyncQueue since they don't chain asynchronous calls\n this.Zo(t, n);\n }), (e => {\n t((() => {\n const t = new U(q.UNKNOWN, \"Fetching auth token failed: \" + e.message);\n return this.tu(t);\n }));\n }));\n }\n Zo(t, e) {\n const n = this.Xo(this.Fo);\n this.stream = this.eu(t, e), this.stream.uo((() => {\n n((() => (this.state = 2 /* PersistentStreamState.Open */ , this.Lo = this.ii.enqueueAfterDelay(this.Oo, 1e4, (() => (this.Ko() && (this.state = 3 /* PersistentStreamState.Healthy */), \n Promise.resolve()))), this.listener.uo())));\n })), this.stream.ao((t => {\n n((() => this.tu(t)));\n })), this.stream.onMessage((t => {\n n((() => this.onMessage(t)));\n }));\n }\n Go() {\n this.state = 5 /* PersistentStreamState.Backoff */ , this.qo.No((async () => {\n this.state = 0 /* PersistentStreamState.Initial */ , this.start();\n }));\n }\n // Visible for tests\n tu(t) {\n // In theory the stream could close cleanly, however, in our current model\n // we never expect this to happen because if we stop a stream ourselves,\n // this callback will never be called. To prevent cases where we retry\n // without a backoff accidentally, we set the stream to error in all cases.\n return N(\"PersistentStream\", `close with error: ${t}`), this.stream = null, this.close(4 /* PersistentStreamState.Error */ , t);\n }\n /**\n * Returns a \"dispatcher\" function that dispatches operations onto the\n * AsyncQueue but only runs them if closeCount remains unchanged. This allows\n * us to turn auth / stream callbacks into no-ops if the stream is closed /\n * re-opened, etc.\n */ Xo(t) {\n return e => {\n this.ii.enqueueAndForget((() => this.Fo === t ? e() : (N(\"PersistentStream\", \"stream callback skipped by getCloseGuardedDispatcher.\"), \n Promise.resolve())));\n };\n }\n}\n\n/**\n * A PersistentStream that implements the Listen RPC.\n *\n * Once the Listen stream has called the onOpen() listener, any number of\n * listen() and unlisten() calls can be made to control what changes will be\n * sent from the server for ListenResponses.\n */ class qu extends Lu {\n constructor(t, e, n, s, i, r) {\n super(t, \"listen_stream_connection_backoff\" /* TimerId.ListenStreamConnectionBackoff */ , \"listen_stream_idle\" /* TimerId.ListenStreamIdle */ , \"health_check_timeout\" /* TimerId.HealthCheckTimeout */ , e, n, s, r), \n this.serializer = i;\n }\n eu(t, e) {\n return this.connection.Ro(\"Listen\", t, e);\n }\n onMessage(t) {\n // A successful response means the stream is healthy\n this.qo.reset();\n const e = Qi(this.serializer, t), n = function(t) {\n // We have only reached a consistent snapshot for the entire stream if there\n // is a read_time set and it applies to all targets (i.e. the list of\n // targets is empty). The backend is guaranteed to send such responses.\n if (!(\"targetChange\" in t)) return rt.min();\n const e = t.targetChange;\n return e.targetIds && e.targetIds.length ? rt.min() : e.readTime ? Ni(e.readTime) : rt.min();\n }(t);\n return this.listener.nu(e, n);\n }\n /**\n * Registers interest in the results of the given target. If the target\n * includes a resumeToken it will be included in the request. Results that\n * affect the target will be streamed back as WatchChange messages that\n * reference the targetId.\n */ su(t) {\n const e = {};\n e.database = Li(this.serializer), e.addTarget = function(t, e) {\n let n;\n const s = e.target;\n if (n = Fn(s) ? {\n documents: Hi(t, s)\n } : {\n query: Ji(t, s)\n }, n.targetId = e.targetId, e.resumeToken.approximateByteSize() > 0) {\n n.resumeToken = Ci(t, e.resumeToken);\n const s = Si(t, e.expectedCount);\n null !== s && (n.expectedCount = s);\n } else if (e.snapshotVersion.compareTo(rt.min()) > 0) {\n // TODO(wuandy): Consider removing above check because it is most likely true.\n // Right now, many tests depend on this behaviour though (leaving min() out\n // of serialization).\n n.readTime = Di(t, e.snapshotVersion.toTimestamp());\n const s = Si(t, e.expectedCount);\n null !== s && (n.expectedCount = s);\n }\n return n;\n }(this.serializer, t);\n const n = Xi(this.serializer, t);\n n && (e.labels = n), this.Wo(e);\n }\n /**\n * Unregisters interest in the results of the target associated with the\n * given targetId.\n */ iu(t) {\n const e = {};\n e.database = Li(this.serializer), e.removeTarget = t, this.Wo(e);\n }\n}\n\n/**\n * A Stream that implements the Write RPC.\n *\n * The Write RPC requires the caller to maintain special streamToken\n * state in between calls, to help the server understand which responses the\n * client has processed by the time the next request is made. Every response\n * will contain a streamToken; this value must be passed to the next\n * request.\n *\n * After calling start() on this stream, the next request must be a handshake,\n * containing whatever streamToken is on hand. Once a response to this\n * request is received, all pending mutations may be submitted. When\n * submitting multiple batches of mutations at the same time, it's\n * okay to use the same streamToken for the calls to writeMutations.\n *\n * TODO(b/33271235): Use proto types\n */ class Uu extends Lu {\n constructor(t, e, n, s, i, r) {\n super(t, \"write_stream_connection_backoff\" /* TimerId.WriteStreamConnectionBackoff */ , \"write_stream_idle\" /* TimerId.WriteStreamIdle */ , \"health_check_timeout\" /* TimerId.HealthCheckTimeout */ , e, n, s, r), \n this.serializer = i, this.ru = !1;\n }\n /**\n * Tracks whether or not a handshake has been successfully exchanged and\n * the stream is ready to accept mutations.\n */ get ou() {\n return this.ru;\n }\n // Override of PersistentStream.start\n start() {\n this.ru = !1, this.lastStreamToken = void 0, super.start();\n }\n Yo() {\n this.ru && this.uu([]);\n }\n eu(t, e) {\n return this.connection.Ro(\"Write\", t, e);\n }\n onMessage(t) {\n if (\n // Always capture the last stream token.\n F(!!t.streamToken), this.lastStreamToken = t.streamToken, this.ru) {\n // A successful first write response means the stream is healthy,\n // Note, that we could consider a successful handshake healthy, however,\n // the write itself might be causing an error we want to back off from.\n this.qo.reset();\n const e = Wi(t.writeResults, t.commitTime), n = Ni(t.commitTime);\n return this.listener.cu(n, e);\n }\n // The first response is always the handshake response\n return F(!t.writeResults || 0 === t.writeResults.length), this.ru = !0, this.listener.au();\n }\n /**\n * Sends an initial streamToken to the server, performing the handshake\n * required to make the StreamingWrite RPC work. Subsequent\n * calls should wait until onHandshakeComplete was called.\n */ hu() {\n // TODO(dimond): Support stream resumption. We intentionally do not set the\n // stream token on the handshake, ignoring any stream token we might have.\n const t = {};\n t.database = Li(this.serializer), this.Wo(t);\n }\n /** Sends a group of mutations to the Firestore backend to apply. */ uu(t) {\n const e = {\n streamToken: this.lastStreamToken,\n writes: t.map((t => ji(this.serializer, t)))\n };\n this.Wo(e);\n }\n}\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * Datastore and its related methods are a wrapper around the external Google\n * Cloud Datastore grpc API, which provides an interface that is more convenient\n * for the rest of the client SDK architecture to consume.\n */\n/**\n * An implementation of Datastore that exposes additional state for internal\n * consumption.\n */\nclass Ku extends class {} {\n constructor(t, e, n, s) {\n super(), this.authCredentials = t, this.appCheckCredentials = e, this.connection = n, \n this.serializer = s, this.lu = !1;\n }\n fu() {\n if (this.lu) throw new U(q.FAILED_PRECONDITION, \"The client has already been terminated.\");\n }\n /** Invokes the provided RPC with auth and AppCheck tokens. */ Io(t, e, n) {\n return this.fu(), Promise.all([ this.authCredentials.getToken(), this.appCheckCredentials.getToken() ]).then((([s, i]) => this.connection.Io(t, e, n, s, i))).catch((t => {\n throw \"FirebaseError\" === t.name ? (t.code === q.UNAUTHENTICATED && (this.authCredentials.invalidateToken(), \n this.appCheckCredentials.invalidateToken()), t) : new U(q.UNKNOWN, t.toString());\n }));\n }\n /** Invokes the provided RPC with streamed results with auth and AppCheck tokens. */ vo(t, e, n, s) {\n return this.fu(), Promise.all([ this.authCredentials.getToken(), this.appCheckCredentials.getToken() ]).then((([i, r]) => this.connection.vo(t, e, n, i, r, s))).catch((t => {\n throw \"FirebaseError\" === t.name ? (t.code === q.UNAUTHENTICATED && (this.authCredentials.invalidateToken(), \n this.appCheckCredentials.invalidateToken()), t) : new U(q.UNKNOWN, t.toString());\n }));\n }\n terminate() {\n this.lu = !0;\n }\n}\n\n// TODO(firestorexp): Make sure there is only one Datastore instance per\n// firestore-exp client.\nasync function Gu(t, e, n) {\n var s;\n const i = L(t), {request: r, du: o} = function(t, e, n) {\n const s = Ji(t, e), i = {}, r = [];\n let o = 0;\n return n.forEach((t => {\n // Map all client-side aliases to a unique short-form\n // alias. This avoids issues with client-side aliases that\n // exceed the 1500-byte string size limit.\n const e = \"aggregate_\" + o++;\n i[e] = t.alias, \"count\" === t.yt ? r.push({\n alias: e,\n count: {}\n }) : \"avg\" === t.yt ? r.push({\n alias: e,\n avg: {\n field: sr(t.fieldPath)\n }\n }) : \"sum\" === t.yt && r.push({\n alias: e,\n sum: {\n field: sr(t.fieldPath)\n }\n });\n })), {\n request: {\n structuredAggregationQuery: {\n aggregations: r,\n structuredQuery: s.structuredQuery\n },\n parent: s.parent\n },\n du: i\n };\n }(i.serializer, Jn(e), n), u = r.parent;\n i.connection.po || delete r.parent;\n const c = (await i.vo(\"RunAggregationQuery\", u, r, /*expectedResponseCount=*/ 1)).filter((t => !!t.result));\n // Omit RunAggregationQueryResponse that only contain readTimes.\n F(1 === c.length);\n // Remap the short-form aliases that were sent to the server\n // to the client-side aliases. Users will access the results\n // using the client-side alias.\n const a = null === (s = c[0].result) || void 0 === s ? void 0 : s.aggregateFields;\n return Object.keys(a).reduce(((t, e) => (t[o[e]] = a[e], t)), {});\n}\n\n/**\n * A component used by the RemoteStore to track the OnlineState (that is,\n * whether or not the client as a whole should be considered to be online or\n * offline), implementing the appropriate heuristics.\n *\n * In particular, when the client is trying to connect to the backend, we\n * allow up to MAX_WATCH_STREAM_FAILURES within ONLINE_STATE_TIMEOUT_MS for\n * a connection to succeed. If we have too many failures or the timeout elapses,\n * then we set the OnlineState to Offline, and the client will behave as if\n * it is offline (get()s will return cached data, etc.).\n */\nclass Qu {\n constructor(t, e) {\n this.asyncQueue = t, this.onlineStateHandler = e, \n /** The current OnlineState. */\n this.state = \"Unknown\" /* OnlineState.Unknown */ , \n /**\n * A count of consecutive failures to open the stream. If it reaches the\n * maximum defined by MAX_WATCH_STREAM_FAILURES, we'll set the OnlineState to\n * Offline.\n */\n this.wu = 0, \n /**\n * A timer that elapses after ONLINE_STATE_TIMEOUT_MS, at which point we\n * transition from OnlineState.Unknown to OnlineState.Offline without waiting\n * for the stream to actually fail (MAX_WATCH_STREAM_FAILURES times).\n */\n this._u = null, \n /**\n * Whether the client should log a warning message if it fails to connect to\n * the backend (initially true, cleared after a successful stream, or if we've\n * logged the message already).\n */\n this.mu = !0;\n }\n /**\n * Called by RemoteStore when a watch stream is started (including on each\n * backoff attempt).\n *\n * If this is the first attempt, it sets the OnlineState to Unknown and starts\n * the onlineStateTimer.\n */ gu() {\n 0 === this.wu && (this.yu(\"Unknown\" /* OnlineState.Unknown */), this._u = this.asyncQueue.enqueueAfterDelay(\"online_state_timeout\" /* TimerId.OnlineStateTimeout */ , 1e4, (() => (this._u = null, \n this.pu(\"Backend didn't respond within 10 seconds.\"), this.yu(\"Offline\" /* OnlineState.Offline */), \n Promise.resolve()))));\n }\n /**\n * Updates our OnlineState as appropriate after the watch stream reports a\n * failure. The first failure moves us to the 'Unknown' state. We then may\n * allow multiple failures (based on MAX_WATCH_STREAM_FAILURES) before we\n * actually transition to the 'Offline' state.\n */ Iu(t) {\n \"Online\" /* OnlineState.Online */ === this.state ? this.yu(\"Unknown\" /* OnlineState.Unknown */) : (this.wu++, \n this.wu >= 1 && (this.Tu(), this.pu(`Connection failed 1 times. Most recent error: ${t.toString()}`), \n this.yu(\"Offline\" /* OnlineState.Offline */)));\n }\n /**\n * Explicitly sets the OnlineState to the specified state.\n *\n * Note that this resets our timers / failure counters, etc. used by our\n * Offline heuristics, so must not be used in place of\n * handleWatchStreamStart() and handleWatchStreamFailure().\n */ set(t) {\n this.Tu(), this.wu = 0, \"Online\" /* OnlineState.Online */ === t && (\n // We've connected to watch at least once. Don't warn the developer\n // about being offline going forward.\n this.mu = !1), this.yu(t);\n }\n yu(t) {\n t !== this.state && (this.state = t, this.onlineStateHandler(t));\n }\n pu(t) {\n const e = `Could not reach Cloud Firestore backend. ${t}\\nThis typically indicates that your device does not have a healthy Internet connection at the moment. The client will operate in offline mode until it is able to successfully connect to the backend.`;\n this.mu ? (k(e), this.mu = !1) : N(\"OnlineStateTracker\", e);\n }\n Tu() {\n null !== this._u && (this._u.cancel(), this._u = null);\n }\n}\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */ class ju {\n constructor(\n /**\n * The local store, used to fill the write pipeline with outbound mutations.\n */\n t, \n /** The client-side proxy for interacting with the backend. */\n e, n, s, i) {\n this.localStore = t, this.datastore = e, this.asyncQueue = n, this.remoteSyncer = {}, \n /**\n * A list of up to MAX_PENDING_WRITES writes that we have fetched from the\n * LocalStore via fillWritePipeline() and have or will send to the write\n * stream.\n *\n * Whenever writePipeline.length > 0 the RemoteStore will attempt to start or\n * restart the write stream. When the stream is established the writes in the\n * pipeline will be sent in order.\n *\n * Writes remain in writePipeline until they are acknowledged by the backend\n * and thus will automatically be re-sent if the stream is interrupted /\n * restarted before they're acknowledged.\n *\n * Write responses from the backend are linked to their originating request\n * purely based on order, and so we can just shift() writes from the front of\n * the writePipeline as we receive responses.\n */\n this.Eu = [], \n /**\n * A mapping of watched targets that the client cares about tracking and the\n * user has explicitly called a 'listen' for this target.\n *\n * These targets may or may not have been sent to or acknowledged by the\n * server. On re-establishing the listen stream, these targets should be sent\n * to the server. The targets removed with unlistens are removed eagerly\n * without waiting for confirmation from the listen stream.\n */\n this.Au = new Map, \n /**\n * A set of reasons for why the RemoteStore may be offline. If empty, the\n * RemoteStore may start its network connections.\n */\n this.vu = new Set, \n /**\n * Event handlers that get called when the network is disabled or enabled.\n *\n * PORTING NOTE: These functions are used on the Web client to create the\n * underlying streams (to support tree-shakeable streams). On Android and iOS,\n * the streams are created during construction of RemoteStore.\n */\n this.Ru = [], this.Pu = i, this.Pu.Yr((t => {\n n.enqueueAndForget((async () => {\n // Porting Note: Unlike iOS, `restartNetwork()` is called even when the\n // network becomes unreachable as we don't have any other way to tear\n // down our streams.\n ec(this) && (N(\"RemoteStore\", \"Restarting streams for network reachability change.\"), \n await async function(t) {\n const e = L(t);\n e.vu.add(4 /* OfflineCause.ConnectivityChange */), await Wu(e), e.bu.set(\"Unknown\" /* OnlineState.Unknown */), \n e.vu.delete(4 /* OfflineCause.ConnectivityChange */), await zu(e);\n }(this));\n }));\n })), this.bu = new Qu(n, s);\n }\n}\n\nasync function zu(t) {\n if (ec(t)) for (const e of t.Ru) await e(/* enabled= */ !0);\n}\n\n/**\n * Temporarily disables the network. The network can be re-enabled using\n * enableNetwork().\n */ async function Wu(t) {\n for (const e of t.Ru) await e(/* enabled= */ !1);\n}\n\n/**\n * Starts new listen for the given target. Uses resume token if provided. It\n * is a no-op if the target of given `TargetData` is already being listened to.\n */\nfunction Hu(t, e) {\n const n = L(t);\n n.Au.has(e.targetId) || (\n // Mark this as something the client is currently listening for.\n n.Au.set(e.targetId, e), tc(n) ? \n // The listen will be sent in onWatchStreamOpen\n Zu(n) : pc(n).Ko() && Yu(n, e));\n}\n\n/**\n * Removes the listen from server. It is a no-op if the given target id is\n * not being listened to.\n */ function Ju(t, e) {\n const n = L(t), s = pc(n);\n n.Au.delete(e), s.Ko() && Xu(n, e), 0 === n.Au.size && (s.Ko() ? s.jo() : ec(n) && \n // Revert to OnlineState.Unknown if the watch stream is not open and we\n // have no listeners, since without any listens to send we cannot\n // confirm if the stream is healthy and upgrade to OnlineState.Online.\n n.bu.set(\"Unknown\" /* OnlineState.Unknown */));\n}\n\n/**\n * We need to increment the the expected number of pending responses we're due\n * from watch so we wait for the ack to process any messages from this target.\n */ function Yu(t, e) {\n if (t.Vu.qt(e.targetId), e.resumeToken.approximateByteSize() > 0 || e.snapshotVersion.compareTo(rt.min()) > 0) {\n const n = t.remoteSyncer.getRemoteKeysForTarget(e.targetId).size;\n e = e.withExpectedCount(n);\n }\n pc(t).su(e);\n}\n\n/**\n * We need to increment the expected number of pending responses we're due\n * from watch so we wait for the removal on the server before we process any\n * messages from this target.\n */ function Xu(t, e) {\n t.Vu.qt(e), pc(t).iu(e);\n}\n\nfunction Zu(t) {\n t.Vu = new Ei({\n getRemoteKeysForTarget: e => t.remoteSyncer.getRemoteKeysForTarget(e),\n le: e => t.Au.get(e) || null,\n ue: () => t.datastore.serializer.databaseId\n }), pc(t).start(), t.bu.gu();\n}\n\n/**\n * Returns whether the watch stream should be started because it's necessary\n * and has not yet been started.\n */ function tc(t) {\n return ec(t) && !pc(t).Uo() && t.Au.size > 0;\n}\n\nfunction ec(t) {\n return 0 === L(t).vu.size;\n}\n\nfunction nc(t) {\n t.Vu = void 0;\n}\n\nasync function sc(t) {\n t.Au.forEach(((e, n) => {\n Yu(t, e);\n }));\n}\n\nasync function ic(t, e) {\n nc(t), \n // If we still need the watch stream, retry the connection.\n tc(t) ? (t.bu.Iu(e), Zu(t)) : \n // No need to restart watch stream because there are no active targets.\n // The online state is set to unknown because there is no active attempt\n // at establishing a connection\n t.bu.set(\"Unknown\" /* OnlineState.Unknown */);\n}\n\nasync function rc(t, e, n) {\n if (\n // Mark the client as online since we got a message from the server\n t.bu.set(\"Online\" /* OnlineState.Online */), e instanceof Ii && 2 /* WatchTargetChangeState.Removed */ === e.state && e.cause) \n // There was an error on a target, don't wait for a consistent snapshot\n // to raise events\n try {\n await \n /** Handles an error on a target */\n async function(t, e) {\n const n = e.cause;\n for (const s of e.targetIds) \n // A watched target might have been removed already.\n t.Au.has(s) && (await t.remoteSyncer.rejectListen(s, n), t.Au.delete(s), t.Vu.removeTarget(s));\n }\n /**\n * Attempts to fill our write pipeline with writes from the LocalStore.\n *\n * Called internally to bootstrap or refill the write pipeline and by\n * SyncEngine whenever there are new mutations to process.\n *\n * Starts the write stream if necessary.\n */ (t, e);\n } catch (n) {\n N(\"RemoteStore\", \"Failed to remove targets %s: %s \", e.targetIds.join(\",\"), n), \n await oc(t, n);\n } else if (e instanceof yi ? t.Vu.Ht(e) : e instanceof pi ? t.Vu.ne(e) : t.Vu.Xt(e), \n !n.isEqual(rt.min())) try {\n const e = await ou(t.localStore);\n n.compareTo(e) >= 0 && \n // We have received a target change with a global snapshot if the snapshot\n // version is not equal to SnapshotVersion.min().\n await \n /**\n * Takes a batch of changes from the Datastore, repackages them as a\n * RemoteEvent, and passes that on to the listener, which is typically the\n * SyncEngine.\n */\n function(t, e) {\n const n = t.Vu.ce(e);\n // Update in-memory resume tokens. LocalStore will update the\n // persistent view of these when applying the completed RemoteEvent.\n return n.targetChanges.forEach(((n, s) => {\n if (n.resumeToken.approximateByteSize() > 0) {\n const i = t.Au.get(s);\n // A watched target might have been removed already.\n i && t.Au.set(s, i.withResumeToken(n.resumeToken, e));\n }\n })), \n // Re-establish listens for the targets that have been invalidated by\n // existence filter mismatches.\n n.targetMismatches.forEach(((e, n) => {\n const s = t.Au.get(e);\n if (!s) \n // A watched target might have been removed already.\n return;\n // Clear the resume token for the target, since we're in a known mismatch\n // state.\n t.Au.set(e, s.withResumeToken(Ve.EMPTY_BYTE_STRING, s.snapshotVersion)), \n // Cause a hard reset by unwatching and rewatching immediately, but\n // deliberately don't send a resume token so that we get a full update.\n Xu(t, e);\n // Mark the target we send as being on behalf of an existence filter\n // mismatch, but don't actually retain that in listenTargets. This ensures\n // that we flag the first re-listen this way without impacting future\n // listens of this target (that might happen e.g. on reconnect).\n const i = new cr(s.target, e, n, s.sequenceNumber);\n Yu(t, i);\n })), t.remoteSyncer.applyRemoteEvent(n);\n }(t, n);\n } catch (e) {\n N(\"RemoteStore\", \"Failed to raise snapshot:\", e), await oc(t, e);\n }\n}\n\n/**\n * Recovery logic for IndexedDB errors that takes the network offline until\n * `op` succeeds. Retries are scheduled with backoff using\n * `enqueueRetryable()`. If `op()` is not provided, IndexedDB access is\n * validated via a generic operation.\n *\n * The returned Promise is resolved once the network is disabled and before\n * any retry attempt.\n */ async function oc(t, e, n) {\n if (!Dt(e)) throw e;\n t.vu.add(1 /* OfflineCause.IndexedDbFailed */), \n // Disable network and raise offline snapshots\n await Wu(t), t.bu.set(\"Offline\" /* OnlineState.Offline */), n || (\n // Use a simple read operation to determine if IndexedDB recovered.\n // Ideally, we would expose a health check directly on SimpleDb, but\n // RemoteStore only has access to persistence through LocalStore.\n n = () => ou(t.localStore)), \n // Probe IndexedDB periodically and re-enable network\n t.asyncQueue.enqueueRetryable((async () => {\n N(\"RemoteStore\", \"Retrying IndexedDB access\"), await n(), t.vu.delete(1 /* OfflineCause.IndexedDbFailed */), \n await zu(t);\n }));\n}\n\n/**\n * Executes `op`. If `op` fails, takes the network offline until `op`\n * succeeds. Returns after the first attempt.\n */ function uc(t, e) {\n return e().catch((n => oc(t, n, e)));\n}\n\nasync function cc(t) {\n const e = L(t), n = Ic(e);\n let s = e.Eu.length > 0 ? e.Eu[e.Eu.length - 1].batchId : -1;\n for (;ac(e); ) try {\n const t = await au(e.localStore, s);\n if (null === t) {\n 0 === e.Eu.length && n.jo();\n break;\n }\n s = t.batchId, hc(e, t);\n } catch (t) {\n await oc(e, t);\n }\n lc(e) && fc(e);\n}\n\n/**\n * Returns true if we can add to the write pipeline (i.e. the network is\n * enabled and the write pipeline is not full).\n */ function ac(t) {\n return ec(t) && t.Eu.length < 10;\n}\n\n/**\n * Queues additional writes to be sent to the write stream, sending them\n * immediately if the write stream is established.\n */ function hc(t, e) {\n t.Eu.push(e);\n const n = Ic(t);\n n.Ko() && n.ou && n.uu(e.mutations);\n}\n\nfunction lc(t) {\n return ec(t) && !Ic(t).Uo() && t.Eu.length > 0;\n}\n\nfunction fc(t) {\n Ic(t).start();\n}\n\nasync function dc(t) {\n Ic(t).hu();\n}\n\nasync function wc(t) {\n const e = Ic(t);\n // Send the write pipeline now that the stream is established.\n for (const n of t.Eu) e.uu(n.mutations);\n}\n\nasync function _c(t, e, n) {\n const s = t.Eu.shift(), i = ti.from(s, e, n);\n await uc(t, (() => t.remoteSyncer.applySuccessfulWrite(i))), \n // It's possible that with the completion of this mutation another\n // slot has freed up.\n await cc(t);\n}\n\nasync function mc(t, e) {\n // If the write stream closed after the write handshake completes, a write\n // operation failed and we fail the pending operation.\n e && Ic(t).ou && \n // This error affects the actual write.\n await async function(t, e) {\n // Only handle permanent errors here. If it's transient, just let the retry\n // logic kick in.\n if (n = e.code, oi(n) && n !== q.ABORTED) {\n // This was a permanent error, the request itself was the problem\n // so it's not going to succeed if we resend it.\n const n = t.Eu.shift();\n // In this case it's also unlikely that the server itself is melting\n // down -- this was just a bad request so inhibit backoff on the next\n // restart.\n Ic(t).Qo(), await uc(t, (() => t.remoteSyncer.rejectFailedWrite(n.batchId, e))), \n // It's possible that with the completion of this mutation\n // another slot has freed up.\n await cc(t);\n }\n var n;\n }(t, e), \n // The write stream might have been started by refilling the write\n // pipeline for failed writes\n lc(t) && fc(t);\n}\n\nasync function gc(t, e) {\n const n = L(t);\n n.asyncQueue.verifyOperationInProgress(), N(\"RemoteStore\", \"RemoteStore received new credentials\");\n const s = ec(n);\n // Tear down and re-create our network streams. This will ensure we get a\n // fresh auth token for the new user and re-fill the write pipeline with\n // new mutations from the LocalStore (since mutations are per-user).\n n.vu.add(3 /* OfflineCause.CredentialChange */), await Wu(n), s && \n // Don't set the network status to Unknown if we are offline.\n n.bu.set(\"Unknown\" /* OnlineState.Unknown */), await n.remoteSyncer.handleCredentialChange(e), \n n.vu.delete(3 /* OfflineCause.CredentialChange */), await zu(n);\n}\n\n/**\n * Toggles the network state when the client gains or loses its primary lease.\n */ async function yc(t, e) {\n const n = L(t);\n e ? (n.vu.delete(2 /* OfflineCause.IsSecondary */), await zu(n)) : e || (n.vu.add(2 /* OfflineCause.IsSecondary */), \n await Wu(n), n.bu.set(\"Unknown\" /* OnlineState.Unknown */));\n}\n\n/**\n * If not yet initialized, registers the WatchStream and its network state\n * callback with `remoteStoreImpl`. Returns the existing stream if one is\n * already available.\n *\n * PORTING NOTE: On iOS and Android, the WatchStream gets registered on startup.\n * This is not done on Web to allow it to be tree-shaken.\n */ function pc(t) {\n return t.Su || (\n // Create stream (but note that it is not started yet).\n t.Su = function(t, e, n) {\n const s = L(t);\n return s.fu(), new qu(e, s.connection, s.authCredentials, s.appCheckCredentials, s.serializer, n);\n }\n /**\n * @license\n * Copyright 2018 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */ (t.datastore, t.asyncQueue, {\n uo: sc.bind(null, t),\n ao: ic.bind(null, t),\n nu: rc.bind(null, t)\n }), t.Ru.push((async e => {\n e ? (t.Su.Qo(), tc(t) ? Zu(t) : t.bu.set(\"Unknown\" /* OnlineState.Unknown */)) : (await t.Su.stop(), \n nc(t));\n }))), t.Su;\n}\n\n/**\n * If not yet initialized, registers the WriteStream and its network state\n * callback with `remoteStoreImpl`. Returns the existing stream if one is\n * already available.\n *\n * PORTING NOTE: On iOS and Android, the WriteStream gets registered on startup.\n * This is not done on Web to allow it to be tree-shaken.\n */ function Ic(t) {\n return t.Du || (\n // Create stream (but note that it is not started yet).\n t.Du = function(t, e, n) {\n const s = L(t);\n return s.fu(), new Uu(e, s.connection, s.authCredentials, s.appCheckCredentials, s.serializer, n);\n }(t.datastore, t.asyncQueue, {\n uo: dc.bind(null, t),\n ao: mc.bind(null, t),\n au: wc.bind(null, t),\n cu: _c.bind(null, t)\n }), t.Ru.push((async e => {\n e ? (t.Du.Qo(), \n // This will start the write stream if necessary.\n await cc(t)) : (await t.Du.stop(), t.Eu.length > 0 && (N(\"RemoteStore\", `Stopping write stream with ${t.Eu.length} pending writes`), \n t.Eu = []));\n }))), t.Du;\n}\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * Represents an operation scheduled to be run in the future on an AsyncQueue.\n *\n * It is created via DelayedOperation.createAndSchedule().\n *\n * Supports cancellation (via cancel()) and early execution (via skipDelay()).\n *\n * Note: We implement `PromiseLike` instead of `Promise`, as the `Promise` type\n * in newer versions of TypeScript defines `finally`, which is not available in\n * IE.\n */\nclass Tc {\n constructor(t, e, n, s, i) {\n this.asyncQueue = t, this.timerId = e, this.targetTimeMs = n, this.op = s, this.removalCallback = i, \n this.deferred = new K, this.then = this.deferred.promise.then.bind(this.deferred.promise), \n // It's normal for the deferred promise to be canceled (due to cancellation)\n // and so we attach a dummy catch callback to avoid\n // 'UnhandledPromiseRejectionWarning' log spam.\n this.deferred.promise.catch((t => {}));\n }\n /**\n * Creates and returns a DelayedOperation that has been scheduled to be\n * executed on the provided asyncQueue after the provided delayMs.\n *\n * @param asyncQueue - The queue to schedule the operation on.\n * @param id - A Timer ID identifying the type of operation this is.\n * @param delayMs - The delay (ms) before the operation should be scheduled.\n * @param op - The operation to run.\n * @param removalCallback - A callback to be called synchronously once the\n * operation is executed or canceled, notifying the AsyncQueue to remove it\n * from its delayedOperations list.\n * PORTING NOTE: This exists to prevent making removeDelayedOperation() and\n * the DelayedOperation class public.\n */ static createAndSchedule(t, e, n, s, i) {\n const r = Date.now() + n, o = new Tc(t, e, r, s, i);\n return o.start(n), o;\n }\n /**\n * Starts the timer. This is called immediately after construction by\n * createAndSchedule().\n */ start(t) {\n this.timerHandle = setTimeout((() => this.handleDelayElapsed()), t);\n }\n /**\n * Queues the operation to run immediately (if it hasn't already been run or\n * canceled).\n */ skipDelay() {\n return this.handleDelayElapsed();\n }\n /**\n * Cancels the operation if it hasn't already been executed or canceled. The\n * promise will be rejected.\n *\n * As long as the operation has not yet been run, calling cancel() provides a\n * guarantee that the operation will not be run.\n */ cancel(t) {\n null !== this.timerHandle && (this.clearTimeout(), this.deferred.reject(new U(q.CANCELLED, \"Operation cancelled\" + (t ? \": \" + t : \"\"))));\n }\n handleDelayElapsed() {\n this.asyncQueue.enqueueAndForget((() => null !== this.timerHandle ? (this.clearTimeout(), \n this.op().then((t => this.deferred.resolve(t)))) : Promise.resolve()));\n }\n clearTimeout() {\n null !== this.timerHandle && (this.removalCallback(this), clearTimeout(this.timerHandle), \n this.timerHandle = null);\n }\n}\n\n/**\n * Returns a FirestoreError that can be surfaced to the user if the provided\n * error is an IndexedDbTransactionError. Re-throws the error otherwise.\n */ function Ec(t, e) {\n if (k(\"AsyncQueue\", `${e}: ${t}`), Dt(t)) return new U(q.UNAVAILABLE, `${e}: ${t}`);\n throw t;\n}\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * DocumentSet is an immutable (copy-on-write) collection that holds documents\n * in order specified by the provided comparator. We always add a document key\n * comparator on top of what is provided to guarantee document equality based on\n * the key.\n */ class Ac {\n /** The default ordering is by key if the comparator is omitted */\n constructor(t) {\n // We are adding document key comparator to the end as it's the only\n // guaranteed unique property of a document.\n this.comparator = t ? (e, n) => t(e, n) || ht.comparator(e.key, n.key) : (t, e) => ht.comparator(t.key, e.key), \n this.keyedMap = hs(), this.sortedSet = new pe(this.comparator);\n }\n /**\n * Returns an empty copy of the existing DocumentSet, using the same\n * comparator.\n */ static emptySet(t) {\n return new Ac(t.comparator);\n }\n has(t) {\n return null != this.keyedMap.get(t);\n }\n get(t) {\n return this.keyedMap.get(t);\n }\n first() {\n return this.sortedSet.minKey();\n }\n last() {\n return this.sortedSet.maxKey();\n }\n isEmpty() {\n return this.sortedSet.isEmpty();\n }\n /**\n * Returns the index of the provided key in the document set, or -1 if the\n * document key is not present in the set;\n */ indexOf(t) {\n const e = this.keyedMap.get(t);\n return e ? this.sortedSet.indexOf(e) : -1;\n }\n get size() {\n return this.sortedSet.size;\n }\n /** Iterates documents in order defined by \"comparator\" */ forEach(t) {\n this.sortedSet.inorderTraversal(((e, n) => (t(e), !1)));\n }\n /** Inserts or updates a document with the same key */ add(t) {\n // First remove the element if we have it.\n const e = this.delete(t.key);\n return e.copy(e.keyedMap.insert(t.key, t), e.sortedSet.insert(t, null));\n }\n /** Deletes a document with a given key */ delete(t) {\n const e = this.get(t);\n return e ? this.copy(this.keyedMap.remove(t), this.sortedSet.remove(e)) : this;\n }\n isEqual(t) {\n if (!(t instanceof Ac)) return !1;\n if (this.size !== t.size) return !1;\n const e = this.sortedSet.getIterator(), n = t.sortedSet.getIterator();\n for (;e.hasNext(); ) {\n const t = e.getNext().key, s = n.getNext().key;\n if (!t.isEqual(s)) return !1;\n }\n return !0;\n }\n toString() {\n const t = [];\n return this.forEach((e => {\n t.push(e.toString());\n })), 0 === t.length ? \"DocumentSet ()\" : \"DocumentSet (\\n \" + t.join(\" \\n\") + \"\\n)\";\n }\n copy(t, e) {\n const n = new Ac;\n return n.comparator = this.comparator, n.keyedMap = t, n.sortedSet = e, n;\n }\n}\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * DocumentChangeSet keeps track of a set of changes to docs in a query, merging\n * duplicate events for the same doc.\n */ class vc {\n constructor() {\n this.Cu = new pe(ht.comparator);\n }\n track(t) {\n const e = t.doc.key, n = this.Cu.get(e);\n n ? \n // Merge the new change with the existing change.\n 0 /* ChangeType.Added */ !== t.type && 3 /* ChangeType.Metadata */ === n.type ? this.Cu = this.Cu.insert(e, t) : 3 /* ChangeType.Metadata */ === t.type && 1 /* ChangeType.Removed */ !== n.type ? this.Cu = this.Cu.insert(e, {\n type: n.type,\n doc: t.doc\n }) : 2 /* ChangeType.Modified */ === t.type && 2 /* ChangeType.Modified */ === n.type ? this.Cu = this.Cu.insert(e, {\n type: 2 /* ChangeType.Modified */ ,\n doc: t.doc\n }) : 2 /* ChangeType.Modified */ === t.type && 0 /* ChangeType.Added */ === n.type ? this.Cu = this.Cu.insert(e, {\n type: 0 /* ChangeType.Added */ ,\n doc: t.doc\n }) : 1 /* ChangeType.Removed */ === t.type && 0 /* ChangeType.Added */ === n.type ? this.Cu = this.Cu.remove(e) : 1 /* ChangeType.Removed */ === t.type && 2 /* ChangeType.Modified */ === n.type ? this.Cu = this.Cu.insert(e, {\n type: 1 /* ChangeType.Removed */ ,\n doc: n.doc\n }) : 0 /* ChangeType.Added */ === t.type && 1 /* ChangeType.Removed */ === n.type ? this.Cu = this.Cu.insert(e, {\n type: 2 /* ChangeType.Modified */ ,\n doc: t.doc\n }) : \n // This includes these cases, which don't make sense:\n // Added->Added\n // Removed->Removed\n // Modified->Added\n // Removed->Modified\n // Metadata->Added\n // Removed->Metadata\n O() : this.Cu = this.Cu.insert(e, t);\n }\n xu() {\n const t = [];\n return this.Cu.inorderTraversal(((e, n) => {\n t.push(n);\n })), t;\n }\n}\n\nclass Rc {\n constructor(t, e, n, s, i, r, o, u, c) {\n this.query = t, this.docs = e, this.oldDocs = n, this.docChanges = s, this.mutatedKeys = i, \n this.fromCache = r, this.syncStateChanged = o, this.excludesMetadataChanges = u, \n this.hasCachedResults = c;\n }\n /** Returns a view snapshot as if all documents in the snapshot were added. */ static fromInitialDocuments(t, e, n, s, i) {\n const r = [];\n return e.forEach((t => {\n r.push({\n type: 0 /* ChangeType.Added */ ,\n doc: t\n });\n })), new Rc(t, e, Ac.emptySet(e), r, n, s, \n /* syncStateChanged= */ !0, \n /* excludesMetadataChanges= */ !1, i);\n }\n get hasPendingWrites() {\n return !this.mutatedKeys.isEmpty();\n }\n isEqual(t) {\n if (!(this.fromCache === t.fromCache && this.hasCachedResults === t.hasCachedResults && this.syncStateChanged === t.syncStateChanged && this.mutatedKeys.isEqual(t.mutatedKeys) && Zn(this.query, t.query) && this.docs.isEqual(t.docs) && this.oldDocs.isEqual(t.oldDocs))) return !1;\n const e = this.docChanges, n = t.docChanges;\n if (e.length !== n.length) return !1;\n for (let t = 0; t < e.length; t++) if (e[t].type !== n[t].type || !e[t].doc.isEqual(n[t].doc)) return !1;\n return !0;\n }\n}\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * Holds the listeners and the last received ViewSnapshot for a query being\n * tracked by EventManager.\n */ class Pc {\n constructor() {\n this.Nu = void 0, this.listeners = [];\n }\n}\n\nclass bc {\n constructor() {\n this.queries = new os((t => ts(t)), Zn), this.onlineState = \"Unknown\" /* OnlineState.Unknown */ , \n this.ku = new Set;\n }\n}\n\nasync function Vc(t, e) {\n const n = L(t), s = e.query;\n let i = !1, r = n.queries.get(s);\n if (r || (i = !0, r = new Pc), i) try {\n r.Nu = await n.onListen(s);\n } catch (t) {\n const n = Ec(t, `Initialization of query '${es(e.query)}' failed`);\n return void e.onError(n);\n }\n if (n.queries.set(s, r), r.listeners.push(e), \n // Run global snapshot listeners if a consistent snapshot has been emitted.\n e.Mu(n.onlineState), r.Nu) {\n e.$u(r.Nu) && xc(n);\n }\n}\n\nasync function Sc(t, e) {\n const n = L(t), s = e.query;\n let i = !1;\n const r = n.queries.get(s);\n if (r) {\n const t = r.listeners.indexOf(e);\n t >= 0 && (r.listeners.splice(t, 1), i = 0 === r.listeners.length);\n }\n if (i) return n.queries.delete(s), n.onUnlisten(s);\n}\n\nfunction Dc(t, e) {\n const n = L(t);\n let s = !1;\n for (const t of e) {\n const e = t.query, i = n.queries.get(e);\n if (i) {\n for (const e of i.listeners) e.$u(t) && (s = !0);\n i.Nu = t;\n }\n }\n s && xc(n);\n}\n\nfunction Cc(t, e, n) {\n const s = L(t), i = s.queries.get(e);\n if (i) for (const t of i.listeners) t.onError(n);\n // Remove all listeners. NOTE: We don't need to call syncEngine.unlisten()\n // after an error.\n s.queries.delete(e);\n}\n\n// Call all global snapshot listeners that have been set.\nfunction xc(t) {\n t.ku.forEach((t => {\n t.next();\n }));\n}\n\n/**\n * QueryListener takes a series of internal view snapshots and determines\n * when to raise the event.\n *\n * It uses an Observer to dispatch events.\n */ class Nc {\n constructor(t, e, n) {\n this.query = t, this.Ou = e, \n /**\n * Initial snapshots (e.g. from cache) may not be propagated to the wrapped\n * observer. This flag is set to true once we've actually raised an event.\n */\n this.Fu = !1, this.Bu = null, this.onlineState = \"Unknown\" /* OnlineState.Unknown */ , \n this.options = n || {};\n }\n /**\n * Applies the new ViewSnapshot to this listener, raising a user-facing event\n * if applicable (depending on what changed, whether the user has opted into\n * metadata-only changes, etc.). Returns true if a user-facing event was\n * indeed raised.\n */ $u(t) {\n if (!this.options.includeMetadataChanges) {\n // Remove the metadata only changes.\n const e = [];\n for (const n of t.docChanges) 3 /* ChangeType.Metadata */ !== n.type && e.push(n);\n t = new Rc(t.query, t.docs, t.oldDocs, e, t.mutatedKeys, t.fromCache, t.syncStateChanged, \n /* excludesMetadataChanges= */ !0, t.hasCachedResults);\n }\n let e = !1;\n return this.Fu ? this.Lu(t) && (this.Ou.next(t), e = !0) : this.qu(t, this.onlineState) && (this.Uu(t), \n e = !0), this.Bu = t, e;\n }\n onError(t) {\n this.Ou.error(t);\n }\n /** Returns whether a snapshot was raised. */ Mu(t) {\n this.onlineState = t;\n let e = !1;\n return this.Bu && !this.Fu && this.qu(this.Bu, t) && (this.Uu(this.Bu), e = !0), \n e;\n }\n qu(t, e) {\n // Always raise the first event when we're synced\n if (!t.fromCache) return !0;\n // NOTE: We consider OnlineState.Unknown as online (it should become Offline\n // or Online if we wait long enough).\n const n = \"Offline\" /* OnlineState.Offline */ !== e;\n // Don't raise the event if we're online, aren't synced yet (checked\n // above) and are waiting for a sync.\n return (!this.options.Ku || !n) && (!t.docs.isEmpty() || t.hasCachedResults || \"Offline\" /* OnlineState.Offline */ === e);\n // Raise data from cache if we have any documents, have cached results before,\n // or we are offline.\n }\n Lu(t) {\n // We don't need to handle includeDocumentMetadataChanges here because\n // the Metadata only changes have already been stripped out if needed.\n // At this point the only changes we will see are the ones we should\n // propagate.\n if (t.docChanges.length > 0) return !0;\n const e = this.Bu && this.Bu.hasPendingWrites !== t.hasPendingWrites;\n return !(!t.syncStateChanged && !e) && !0 === this.options.includeMetadataChanges;\n // Generally we should have hit one of the cases above, but it's possible\n // to get here if there were only metadata docChanges and they got\n // stripped out.\n }\n Uu(t) {\n t = Rc.fromInitialDocuments(t.query, t.docs, t.mutatedKeys, t.fromCache, t.hasCachedResults), \n this.Fu = !0, this.Ou.next(t);\n }\n}\n\n/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * A complete element in the bundle stream, together with the byte length it\n * occupies in the stream.\n */ class kc {\n constructor(t, \n // How many bytes this element takes to store in the bundle.\n e) {\n this.Gu = t, this.byteLength = e;\n }\n Qu() {\n return \"metadata\" in this.Gu;\n }\n}\n\n/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * Helper to convert objects from bundles to model objects in the SDK.\n */ class Mc {\n constructor(t) {\n this.serializer = t;\n }\n rr(t) {\n return Oi(this.serializer, t);\n }\n /**\n * Converts a BundleDocument to a MutableDocument.\n */ ur(t) {\n return t.metadata.exists ? Ki(this.serializer, t.document, !1) : an.newNoDocument(this.rr(t.metadata.name), this.cr(t.metadata.readTime));\n }\n cr(t) {\n return Ni(t);\n }\n}\n\n/**\n * A class to process the elements from a bundle, load them into local\n * storage and provide progress update while loading.\n */ class $c {\n constructor(t, e, n) {\n this.ju = t, this.localStore = e, this.serializer = n, \n /** Batched queries to be saved into storage */\n this.queries = [], \n /** Batched documents to be saved into storage */\n this.documents = [], \n /** The collection groups affected by this bundle. */\n this.collectionGroups = new Set, this.progress = Oc(t);\n }\n /**\n * Adds an element from the bundle to the loader.\n *\n * Returns a new progress if adding the element leads to a new progress,\n * otherwise returns null.\n */ zu(t) {\n this.progress.bytesLoaded += t.byteLength;\n let e = this.progress.documentsLoaded;\n if (t.Gu.namedQuery) this.queries.push(t.Gu.namedQuery); else if (t.Gu.documentMetadata) {\n this.documents.push({\n metadata: t.Gu.documentMetadata\n }), t.Gu.documentMetadata.exists || ++e;\n const n = ut.fromString(t.Gu.documentMetadata.name);\n this.collectionGroups.add(n.get(n.length - 2));\n } else t.Gu.document && (this.documents[this.documents.length - 1].document = t.Gu.document, \n ++e);\n return e !== this.progress.documentsLoaded ? (this.progress.documentsLoaded = e, \n Object.assign({}, this.progress)) : null;\n }\n Wu(t) {\n const e = new Map, n = new Mc(this.serializer);\n for (const s of t) if (s.metadata.queries) {\n const t = n.rr(s.metadata.name);\n for (const n of s.metadata.queries) {\n const s = (e.get(n) || gs()).add(t);\n e.set(n, s);\n }\n }\n return e;\n }\n /**\n * Update the progress to 'Success' and return the updated progress.\n */ async complete() {\n const t = await mu(this.localStore, new Mc(this.serializer), this.documents, this.ju.id), e = this.Wu(this.documents);\n for (const t of this.queries) await gu(this.localStore, t, e.get(t.name));\n return this.progress.taskState = \"Success\", {\n progress: this.progress,\n Hu: this.collectionGroups,\n Ju: t\n };\n }\n}\n\n/**\n * Returns a `LoadBundleTaskProgress` representing the initial progress of\n * loading a bundle.\n */ function Oc(t) {\n return {\n taskState: \"Running\",\n documentsLoaded: 0,\n bytesLoaded: 0,\n totalDocuments: t.totalDocuments,\n totalBytes: t.totalBytes\n };\n}\n\n/**\n * Returns a `LoadBundleTaskProgress` representing the progress that the loading\n * has succeeded.\n */\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nclass Fc {\n constructor(t) {\n this.key = t;\n }\n}\n\nclass Bc {\n constructor(t) {\n this.key = t;\n }\n}\n\n/**\n * View is responsible for computing the final merged truth of what docs are in\n * a query. It gets notified of local and remote changes to docs, and applies\n * the query filters and limits to determine the most correct possible results.\n */ class Lc {\n constructor(t, \n /** Documents included in the remote target */\n e) {\n this.query = t, this.Yu = e, this.Xu = null, this.hasCachedResults = !1, \n /**\n * A flag whether the view is current with the backend. A view is considered\n * current after it has seen the current flag from the backend and did not\n * lose consistency within the watch stream (e.g. because of an existence\n * filter mismatch).\n */\n this.current = !1, \n /** Documents in the view but not in the remote target */\n this.Zu = gs(), \n /** Document Keys that have local changes */\n this.mutatedKeys = gs(), this.tc = is(t), this.ec = new Ac(this.tc);\n }\n /**\n * The set of remote documents that the server has told us belongs to the target associated with\n * this view.\n */ get nc() {\n return this.Yu;\n }\n /**\n * Iterates over a set of doc changes, applies the query limit, and computes\n * what the new results should be, what the changes were, and whether we may\n * need to go back to the local cache for more results. Does not make any\n * changes to the view.\n * @param docChanges - The doc changes to apply to this view.\n * @param previousChanges - If this is being called with a refill, then start\n * with this set of docs and changes instead of the current view.\n * @returns a new set of docs, changes, and refill flag.\n */ sc(t, e) {\n const n = e ? e.ic : new vc, s = e ? e.ec : this.ec;\n let i = e ? e.mutatedKeys : this.mutatedKeys, r = s, o = !1;\n // Track the last doc in a (full) limit. This is necessary, because some\n // update (a delete, or an update moving a doc past the old limit) might\n // mean there is some other document in the local cache that either should\n // come (1) between the old last limit doc and the new last document, in the\n // case of updates, or (2) after the new last document, in the case of\n // deletes. So we keep this doc at the old limit to compare the updates to.\n // Note that this should never get used in a refill (when previousChanges is\n // set), because there will only be adds -- no deletes or updates.\n const u = \"F\" /* LimitType.First */ === this.query.limitType && s.size === this.query.limit ? s.last() : null, c = \"L\" /* LimitType.Last */ === this.query.limitType && s.size === this.query.limit ? s.first() : null;\n // Drop documents out to meet limit/limitToLast requirement.\n if (t.inorderTraversal(((t, e) => {\n const a = s.get(t), h = ns(this.query, e) ? e : null, l = !!a && this.mutatedKeys.has(a.key), f = !!h && (h.hasLocalMutations || \n // We only consider committed mutations for documents that were\n // mutated during the lifetime of the view.\n this.mutatedKeys.has(h.key) && h.hasCommittedMutations);\n let d = !1;\n // Calculate change\n if (a && h) {\n a.data.isEqual(h.data) ? l !== f && (n.track({\n type: 3 /* ChangeType.Metadata */ ,\n doc: h\n }), d = !0) : this.rc(a, h) || (n.track({\n type: 2 /* ChangeType.Modified */ ,\n doc: h\n }), d = !0, (u && this.tc(h, u) > 0 || c && this.tc(h, c) < 0) && (\n // This doc moved from inside the limit to outside the limit.\n // That means there may be some other doc in the local cache\n // that should be included instead.\n o = !0));\n } else !a && h ? (n.track({\n type: 0 /* ChangeType.Added */ ,\n doc: h\n }), d = !0) : a && !h && (n.track({\n type: 1 /* ChangeType.Removed */ ,\n doc: a\n }), d = !0, (u || c) && (\n // A doc was removed from a full limit query. We'll need to\n // requery from the local cache to see if we know about some other\n // doc that should be in the results.\n o = !0));\n d && (h ? (r = r.add(h), i = f ? i.add(t) : i.delete(t)) : (r = r.delete(t), i = i.delete(t)));\n })), null !== this.query.limit) for (;r.size > this.query.limit; ) {\n const t = \"F\" /* LimitType.First */ === this.query.limitType ? r.last() : r.first();\n r = r.delete(t.key), i = i.delete(t.key), n.track({\n type: 1 /* ChangeType.Removed */ ,\n doc: t\n });\n }\n return {\n ec: r,\n ic: n,\n zi: o,\n mutatedKeys: i\n };\n }\n rc(t, e) {\n // We suppress the initial change event for documents that were modified as\n // part of a write acknowledgment (e.g. when the value of a server transform\n // is applied) as Watch will send us the same document again.\n // By suppressing the event, we only raise two user visible events (one with\n // `hasPendingWrites` and the final state of the document) instead of three\n // (one with `hasPendingWrites`, the modified document with\n // `hasPendingWrites` and the final state of the document).\n return t.hasLocalMutations && e.hasCommittedMutations && !e.hasLocalMutations;\n }\n /**\n * Updates the view with the given ViewDocumentChanges and optionally updates\n * limbo docs and sync state from the provided target change.\n * @param docChanges - The set of changes to make to the view's docs.\n * @param updateLimboDocuments - Whether to update limbo documents based on\n * this change.\n * @param targetChange - A target change to apply for computing limbo docs and\n * sync state.\n * @returns A new ViewChange with the given docs, changes, and sync state.\n */\n // PORTING NOTE: The iOS/Android clients always compute limbo document changes.\n applyChanges(t, e, n) {\n const s = this.ec;\n this.ec = t.ec, this.mutatedKeys = t.mutatedKeys;\n // Sort changes based on type and query comparator\n const i = t.ic.xu();\n i.sort(((t, e) => function(t, e) {\n const n = t => {\n switch (t) {\n case 0 /* ChangeType.Added */ :\n return 1;\n\n case 2 /* ChangeType.Modified */ :\n case 3 /* ChangeType.Metadata */ :\n // A metadata change is converted to a modified change at the public\n // api layer. Since we sort by document key and then change type,\n // metadata and modified changes must be sorted equivalently.\n return 2;\n\n case 1 /* ChangeType.Removed */ :\n return 0;\n\n default:\n return O();\n }\n };\n return n(t) - n(e);\n }\n /**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */ (t.type, e.type) || this.tc(t.doc, e.doc))), this.oc(n);\n const r = e ? this.uc() : [], o = 0 === this.Zu.size && this.current ? 1 /* SyncState.Synced */ : 0 /* SyncState.Local */ , u = o !== this.Xu;\n if (this.Xu = o, 0 !== i.length || u) {\n return {\n snapshot: new Rc(this.query, t.ec, s, i, t.mutatedKeys, 0 /* SyncState.Local */ === o, u, \n /* excludesMetadataChanges= */ !1, !!n && n.resumeToken.approximateByteSize() > 0),\n cc: r\n };\n }\n // no changes\n return {\n cc: r\n };\n }\n /**\n * Applies an OnlineState change to the view, potentially generating a\n * ViewChange if the view's syncState changes as a result.\n */ Mu(t) {\n return this.current && \"Offline\" /* OnlineState.Offline */ === t ? (\n // If we're offline, set `current` to false and then call applyChanges()\n // to refresh our syncState and generate a ViewChange as appropriate. We\n // are guaranteed to get a new TargetChange that sets `current` back to\n // true once the client is back online.\n this.current = !1, this.applyChanges({\n ec: this.ec,\n ic: new vc,\n mutatedKeys: this.mutatedKeys,\n zi: !1\n }, \n /* updateLimboDocuments= */ !1)) : {\n cc: []\n };\n }\n /**\n * Returns whether the doc for the given key should be in limbo.\n */ ac(t) {\n // If the remote end says it's part of this query, it's not in limbo.\n return !this.Yu.has(t) && (\n // The local store doesn't think it's a result, so it shouldn't be in limbo.\n !!this.ec.has(t) && !this.ec.get(t).hasLocalMutations);\n }\n /**\n * Updates syncedDocuments, current, and limbo docs based on the given change.\n * Returns the list of changes to which docs are in limbo.\n */ oc(t) {\n t && (t.addedDocuments.forEach((t => this.Yu = this.Yu.add(t))), t.modifiedDocuments.forEach((t => {})), \n t.removedDocuments.forEach((t => this.Yu = this.Yu.delete(t))), this.current = t.current);\n }\n uc() {\n // We can only determine limbo documents when we're in-sync with the server.\n if (!this.current) return [];\n // TODO(klimt): Do this incrementally so that it's not quadratic when\n // updating many documents.\n const t = this.Zu;\n this.Zu = gs(), this.ec.forEach((t => {\n this.ac(t.key) && (this.Zu = this.Zu.add(t.key));\n }));\n // Diff the new limbo docs with the old limbo docs.\n const e = [];\n return t.forEach((t => {\n this.Zu.has(t) || e.push(new Bc(t));\n })), this.Zu.forEach((n => {\n t.has(n) || e.push(new Fc(n));\n })), e;\n }\n /**\n * Update the in-memory state of the current view with the state read from\n * persistence.\n *\n * We update the query view whenever a client's primary status changes:\n * - When a client transitions from primary to secondary, it can miss\n * LocalStorage updates and its query views may temporarily not be\n * synchronized with the state on disk.\n * - For secondary to primary transitions, the client needs to update the list\n * of `syncedDocuments` since secondary clients update their query views\n * based purely on synthesized RemoteEvents.\n *\n * @param queryResult.documents - The documents that match the query according\n * to the LocalStore.\n * @param queryResult.remoteKeys - The keys of the documents that match the\n * query according to the backend.\n *\n * @returns The ViewChange that resulted from this synchronization.\n */\n // PORTING NOTE: Multi-tab only.\n hc(t) {\n this.Yu = t.ir, this.Zu = gs();\n const e = this.sc(t.documents);\n return this.applyChanges(e, /*updateLimboDocuments=*/ !0);\n }\n /**\n * Returns a view snapshot as if this query was just listened to. Contains\n * a document add for every existing document and the `fromCache` and\n * `hasPendingWrites` status of the already established view.\n */\n // PORTING NOTE: Multi-tab only.\n lc() {\n return Rc.fromInitialDocuments(this.query, this.ec, this.mutatedKeys, 0 /* SyncState.Local */ === this.Xu, this.hasCachedResults);\n }\n}\n\n/**\n * QueryView contains all of the data that SyncEngine needs to keep track of for\n * a particular query.\n */\nclass qc {\n constructor(\n /**\n * The query itself.\n */\n t, \n /**\n * The target number created by the client that is used in the watch\n * stream to identify this query.\n */\n e, \n /**\n * The view is responsible for computing the final merged truth of what\n * docs are in the query. It gets notified of local and remote changes,\n * and applies the query filters and limits to determine the most correct\n * possible results.\n */\n n) {\n this.query = t, this.targetId = e, this.view = n;\n }\n}\n\n/** Tracks a limbo resolution. */ class Uc {\n constructor(t) {\n this.key = t, \n /**\n * Set to true once we've received a document. This is used in\n * getRemoteKeysForTarget() and ultimately used by WatchChangeAggregator to\n * decide whether it needs to manufacture a delete event for the target once\n * the target is CURRENT.\n */\n this.fc = !1;\n }\n}\n\n/**\n * An implementation of `SyncEngine` coordinating with other parts of SDK.\n *\n * The parts of SyncEngine that act as a callback to RemoteStore need to be\n * registered individually. This is done in `syncEngineWrite()` and\n * `syncEngineListen()` (as well as `applyPrimaryState()`) as these methods\n * serve as entry points to RemoteStore's functionality.\n *\n * Note: some field defined in this class might have public access level, but\n * the class is not exported so they are only accessible from this module.\n * This is useful to implement optional features (like bundles) in free\n * functions, such that they are tree-shakeable.\n */ class Kc {\n constructor(t, e, n, \n // PORTING NOTE: Manages state synchronization in multi-tab environments.\n s, i, r) {\n this.localStore = t, this.remoteStore = e, this.eventManager = n, this.sharedClientState = s, \n this.currentUser = i, this.maxConcurrentLimboResolutions = r, this.dc = {}, this.wc = new os((t => ts(t)), Zn), \n this._c = new Map, \n /**\n * The keys of documents that are in limbo for which we haven't yet started a\n * limbo resolution query. The strings in this set are the result of calling\n * `key.path.canonicalString()` where `key` is a `DocumentKey` object.\n *\n * The `Set` type was chosen because it provides efficient lookup and removal\n * of arbitrary elements and it also maintains insertion order, providing the\n * desired queue-like FIFO semantics.\n */\n this.mc = new Set, \n /**\n * Keeps track of the target ID for each document that is in limbo with an\n * active target.\n */\n this.gc = new pe(ht.comparator), \n /**\n * Keeps track of the information about an active limbo resolution for each\n * active target ID that was started for the purpose of limbo resolution.\n */\n this.yc = new Map, this.Ic = new Oo, \n /** Stores user completion handlers, indexed by User and BatchId. */\n this.Tc = {}, \n /** Stores user callbacks waiting for all pending writes to be acknowledged. */\n this.Ec = new Map, this.Ac = lo.Mn(), this.onlineState = \"Unknown\" /* OnlineState.Unknown */ , \n // The primary state is set to `true` or `false` immediately after Firestore\n // startup. In the interim, a client should only be considered primary if\n // `isPrimary` is true.\n this.vc = void 0;\n }\n get isPrimaryClient() {\n return !0 === this.vc;\n }\n}\n\n/**\n * Initiates the new listen, resolves promise when listen enqueued to the\n * server. All the subsequent view snapshots or errors are sent to the\n * subscribed handlers. Returns the initial snapshot.\n */\nasync function Gc(t, e) {\n const n = pa(t);\n let s, i;\n const r = n.wc.get(e);\n if (r) \n // PORTING NOTE: With Multi-Tab Web, it is possible that a query view\n // already exists when EventManager calls us for the first time. This\n // happens when the primary tab is already listening to this query on\n // behalf of another tab and the user of the primary also starts listening\n // to the query. EventManager will not have an assigned target ID in this\n // case and calls `listen` to obtain this ID.\n s = r.targetId, n.sharedClientState.addLocalQueryTarget(s), i = r.view.lc(); else {\n const t = await hu(n.localStore, Jn(e)), r = n.sharedClientState.addLocalQueryTarget(t.targetId);\n s = t.targetId, i = await Qc(n, e, s, \"current\" === r, t.resumeToken), n.isPrimaryClient && Hu(n.remoteStore, t);\n }\n return i;\n}\n\n/**\n * Registers a view for a previously unknown query and computes its initial\n * snapshot.\n */ async function Qc(t, e, n, s, i) {\n // PORTING NOTE: On Web only, we inject the code that registers new Limbo\n // targets based on view changes. This allows us to only depend on Limbo\n // changes when user code includes queries.\n t.Rc = (e, n, s) => async function(t, e, n, s) {\n let i = e.view.sc(n);\n i.zi && (\n // The query has a limit and some docs were removed, so we need\n // to re-run the query against the local store to make sure we\n // didn't lose any good docs that had been past the limit.\n i = await fu(t.localStore, e.query, \n /* usePreviousResults= */ !1).then((({documents: t}) => e.view.sc(t, i))));\n const r = s && s.targetChanges.get(e.targetId), o = e.view.applyChanges(i, \n /* updateLimboDocuments= */ t.isPrimaryClient, r);\n return ia(t, e.targetId, o.cc), o.snapshot;\n }(t, e, n, s);\n const r = await fu(t.localStore, e, \n /* usePreviousResults= */ !0), o = new Lc(e, r.ir), u = o.sc(r.documents), c = gi.createSynthesizedTargetChangeForCurrentChange(n, s && \"Offline\" /* OnlineState.Offline */ !== t.onlineState, i), a = o.applyChanges(u, \n /* updateLimboDocuments= */ t.isPrimaryClient, c);\n ia(t, n, a.cc);\n const h = new qc(e, n, o);\n return t.wc.set(e, h), t._c.has(n) ? t._c.get(n).push(e) : t._c.set(n, [ e ]), a.snapshot;\n}\n\n/** Stops listening to the query. */ async function jc(t, e) {\n const n = L(t), s = n.wc.get(e), i = n._c.get(s.targetId);\n if (i.length > 1) return n._c.set(s.targetId, i.filter((t => !Zn(t, e)))), void n.wc.delete(e);\n // No other queries are mapped to the target, clean up the query and the target.\n if (n.isPrimaryClient) {\n // We need to remove the local query target first to allow us to verify\n // whether any other client is still interested in this target.\n n.sharedClientState.removeLocalQueryTarget(s.targetId);\n n.sharedClientState.isActiveQueryTarget(s.targetId) || await lu(n.localStore, s.targetId, \n /*keepPersistedTargetData=*/ !1).then((() => {\n n.sharedClientState.clearQueryState(s.targetId), Ju(n.remoteStore, s.targetId), \n na(n, s.targetId);\n })).catch(vt);\n } else na(n, s.targetId), await lu(n.localStore, s.targetId, \n /*keepPersistedTargetData=*/ !0);\n}\n\n/**\n * Initiates the write of local mutation batch which involves adding the\n * writes to the mutation queue, notifying the remote store about new\n * mutations and raising events for any changes this write caused.\n *\n * The promise returned by this call is resolved when the above steps\n * have completed, *not* when the write was acked by the backend. The\n * userCallback is resolved once the write was acked/rejected by the\n * backend (or failed locally for any other reason).\n */ async function zc(t, e, n) {\n const s = Ia(t);\n try {\n const t = await function(t, e) {\n const n = L(t), s = it.now(), i = e.reduce(((t, e) => t.add(e.key)), gs());\n let r, o;\n return n.persistence.runTransaction(\"Locally write mutations\", \"readwrite\", (t => {\n // Figure out which keys do not have a remote version in the cache, this\n // is needed to create the right overlay mutation: if no remote version\n // presents, we do not need to create overlays as patch mutations.\n // TODO(Overlay): Is there a better way to determine this? Using the\n // document version does not work because local mutations set them back\n // to 0.\n let u = cs(), c = gs();\n return n.Zi.getEntries(t, i).next((t => {\n u = t, u.forEach(((t, e) => {\n e.isValidDocument() || (c = c.add(t));\n }));\n })).next((() => n.localDocuments.getOverlayedDocuments(t, u))).next((i => {\n r = i;\n // For non-idempotent mutations (such as `FieldValue.increment()`),\n // we record the base state in a separate patch mutation. This is\n // later used to guarantee consistent values and prevents flicker\n // even if the backend sends us an update that already includes our\n // transform.\n const o = [];\n for (const t of e) {\n const e = Gs(t, r.get(t.key).overlayedDocument);\n null != e && \n // NOTE: The base state should only be applied if there's some\n // existing document to override, so use a Precondition of\n // exists=true\n o.push(new zs(t.key, e, cn(e.value.mapValue), Fs.exists(!0)));\n }\n return n.mutationQueue.addMutationBatch(t, s, o, e);\n })).next((e => {\n o = e;\n const s = e.applyToLocalDocumentSet(r, c);\n return n.documentOverlayCache.saveOverlays(t, e.batchId, s);\n }));\n })).then((() => ({\n batchId: o.batchId,\n changes: ls(r)\n })));\n }(s.localStore, e);\n s.sharedClientState.addPendingMutation(t.batchId), function(t, e, n) {\n let s = t.Tc[t.currentUser.toKey()];\n s || (s = new pe(et));\n s = s.insert(e, n), t.Tc[t.currentUser.toKey()] = s;\n }\n /**\n * Resolves or rejects the user callback for the given batch and then discards\n * it.\n */ (s, t.batchId, n), await ua(s, t.changes), await cc(s.remoteStore);\n } catch (t) {\n // If we can't persist the mutation, we reject the user callback and\n // don't send the mutation. The user can then retry the write.\n const e = Ec(t, \"Failed to persist write\");\n n.reject(e);\n }\n}\n\n/**\n * Applies one remote event to the sync engine, notifying any views of the\n * changes, and releasing any pending mutation batches that would become\n * visible because of the snapshot version the remote event contains.\n */ async function Wc(t, e) {\n const n = L(t);\n try {\n const t = await uu(n.localStore, e);\n // Update `receivedDocument` as appropriate for any limbo targets.\n e.targetChanges.forEach(((t, e) => {\n const s = n.yc.get(e);\n s && (\n // Since this is a limbo resolution lookup, it's for a single document\n // and it could be added, modified, or removed, but not a combination.\n F(t.addedDocuments.size + t.modifiedDocuments.size + t.removedDocuments.size <= 1), \n t.addedDocuments.size > 0 ? s.fc = !0 : t.modifiedDocuments.size > 0 ? F(s.fc) : t.removedDocuments.size > 0 && (F(s.fc), \n s.fc = !1));\n })), await ua(n, t, e);\n } catch (t) {\n await vt(t);\n }\n}\n\n/**\n * Applies an OnlineState change to the sync engine and notifies any views of\n * the change.\n */ function Hc(t, e, n) {\n const s = L(t);\n // If we are the secondary client, we explicitly ignore the remote store's\n // online state (the local client may go offline, even though the primary\n // tab remains online) and only apply the primary tab's online state from\n // SharedClientState.\n if (s.isPrimaryClient && 0 /* OnlineStateSource.RemoteStore */ === n || !s.isPrimaryClient && 1 /* OnlineStateSource.SharedClientState */ === n) {\n const t = [];\n s.wc.forEach(((n, s) => {\n const i = s.view.Mu(e);\n i.snapshot && t.push(i.snapshot);\n })), function(t, e) {\n const n = L(t);\n n.onlineState = e;\n let s = !1;\n n.queries.forEach(((t, n) => {\n for (const t of n.listeners) \n // Run global snapshot listeners if a consistent snapshot has been emitted.\n t.Mu(e) && (s = !0);\n })), s && xc(n);\n }(s.eventManager, e), t.length && s.dc.nu(t), s.onlineState = e, s.isPrimaryClient && s.sharedClientState.setOnlineState(e);\n }\n}\n\n/**\n * Rejects the listen for the given targetID. This can be triggered by the\n * backend for any active target.\n *\n * @param syncEngine - The sync engine implementation.\n * @param targetId - The targetID corresponds to one previously initiated by the\n * user as part of TargetData passed to listen() on RemoteStore.\n * @param err - A description of the condition that has forced the rejection.\n * Nearly always this will be an indication that the user is no longer\n * authorized to see the data matching the target.\n */ async function Jc(t, e, n) {\n const s = L(t);\n // PORTING NOTE: Multi-tab only.\n s.sharedClientState.updateQueryState(e, \"rejected\", n);\n const i = s.yc.get(e), r = i && i.key;\n if (r) {\n // TODO(klimt): We really only should do the following on permission\n // denied errors, but we don't have the cause code here.\n // It's a limbo doc. Create a synthetic event saying it was deleted.\n // This is kind of a hack. Ideally, we would have a method in the local\n // store to purge a document. However, it would be tricky to keep all of\n // the local store's invariants with another method.\n let t = new pe(ht.comparator);\n // TODO(b/217189216): This limbo document should ideally have a read time,\n // so that it is picked up by any read-time based scans. The backend,\n // however, does not send a read time for target removals.\n t = t.insert(r, an.newNoDocument(r, rt.min()));\n const n = gs().add(r), i = new mi(rt.min(), \n /* targetChanges= */ new Map, \n /* targetMismatches= */ new pe(et), t, n);\n await Wc(s, i), \n // Since this query failed, we won't want to manually unlisten to it.\n // We only remove it from bookkeeping after we successfully applied the\n // RemoteEvent. If `applyRemoteEvent()` throws, we want to re-listen to\n // this query when the RemoteStore restarts the Watch stream, which should\n // re-trigger the target failure.\n s.gc = s.gc.remove(r), s.yc.delete(e), oa(s);\n } else await lu(s.localStore, e, \n /* keepPersistedTargetData */ !1).then((() => na(s, e, n))).catch(vt);\n}\n\nasync function Yc(t, e) {\n const n = L(t), s = e.batch.batchId;\n try {\n const t = await ru(n.localStore, e);\n // The local store may or may not be able to apply the write result and\n // raise events immediately (depending on whether the watcher is caught\n // up), so we raise user callbacks first so that they consistently happen\n // before listen events.\n ea(n, s, /*error=*/ null), ta(n, s), n.sharedClientState.updateMutationState(s, \"acknowledged\"), \n await ua(n, t);\n } catch (t) {\n await vt(t);\n }\n}\n\nasync function Xc(t, e, n) {\n const s = L(t);\n try {\n const t = await function(t, e) {\n const n = L(t);\n return n.persistence.runTransaction(\"Reject batch\", \"readwrite-primary\", (t => {\n let s;\n return n.mutationQueue.lookupMutationBatch(t, e).next((e => (F(null !== e), s = e.keys(), \n n.mutationQueue.removeMutationBatch(t, e)))).next((() => n.mutationQueue.performConsistencyCheck(t))).next((() => n.documentOverlayCache.removeOverlaysForBatchId(t, s, e))).next((() => n.localDocuments.recalculateAndSaveOverlaysForDocumentKeys(t, s))).next((() => n.localDocuments.getDocuments(t, s)));\n }));\n }\n /**\n * Returns the largest (latest) batch id in mutation queue that is pending\n * server response.\n *\n * Returns `BATCHID_UNKNOWN` if the queue is empty.\n */ (s.localStore, e);\n // The local store may or may not be able to apply the write result and\n // raise events immediately (depending on whether the watcher is caught up),\n // so we raise user callbacks first so that they consistently happen before\n // listen events.\n ea(s, e, n), ta(s, e), s.sharedClientState.updateMutationState(e, \"rejected\", n), \n await ua(s, t);\n } catch (n) {\n await vt(n);\n }\n}\n\n/**\n * Registers a user callback that resolves when all pending mutations at the moment of calling\n * are acknowledged .\n */ async function Zc(t, e) {\n const n = L(t);\n ec(n.remoteStore) || N(\"SyncEngine\", \"The network is disabled. The task returned by 'awaitPendingWrites()' will not complete until the network is enabled.\");\n try {\n const t = await function(t) {\n const e = L(t);\n return e.persistence.runTransaction(\"Get highest unacknowledged batch id\", \"readonly\", (t => e.mutationQueue.getHighestUnacknowledgedBatchId(t)));\n }(n.localStore);\n if (-1 === t) \n // Trigger the callback right away if there is no pending writes at the moment.\n return void e.resolve();\n const s = n.Ec.get(t) || [];\n s.push(e), n.Ec.set(t, s);\n } catch (t) {\n const n = Ec(t, \"Initialization of waitForPendingWrites() operation failed\");\n e.reject(n);\n }\n}\n\n/**\n * Triggers the callbacks that are waiting for this batch id to get acknowledged by server,\n * if there are any.\n */ function ta(t, e) {\n (t.Ec.get(e) || []).forEach((t => {\n t.resolve();\n })), t.Ec.delete(e);\n}\n\n/** Reject all outstanding callbacks waiting for pending writes to complete. */ function ea(t, e, n) {\n const s = L(t);\n let i = s.Tc[s.currentUser.toKey()];\n // NOTE: Mutations restored from persistence won't have callbacks, so it's\n // okay for there to be no callback for this ID.\n if (i) {\n const t = i.get(e);\n t && (n ? t.reject(n) : t.resolve(), i = i.remove(e)), s.Tc[s.currentUser.toKey()] = i;\n }\n}\n\nfunction na(t, e, n = null) {\n t.sharedClientState.removeLocalQueryTarget(e);\n for (const s of t._c.get(e)) t.wc.delete(s), n && t.dc.Pc(s, n);\n if (t._c.delete(e), t.isPrimaryClient) {\n t.Ic.Is(e).forEach((e => {\n t.Ic.containsKey(e) || \n // We removed the last reference for this key\n sa(t, e);\n }));\n }\n}\n\nfunction sa(t, e) {\n t.mc.delete(e.path.canonicalString());\n // It's possible that the target already got removed because the query failed. In that case,\n // the key won't exist in `limboTargetsByKey`. Only do the cleanup if we still have the target.\n const n = t.gc.get(e);\n null !== n && (Ju(t.remoteStore, n), t.gc = t.gc.remove(e), t.yc.delete(n), oa(t));\n}\n\nfunction ia(t, e, n) {\n for (const s of n) if (s instanceof Fc) t.Ic.addReference(s.key, e), ra(t, s); else if (s instanceof Bc) {\n N(\"SyncEngine\", \"Document no longer in limbo: \" + s.key), t.Ic.removeReference(s.key, e);\n t.Ic.containsKey(s.key) || \n // We removed the last reference for this key\n sa(t, s.key);\n } else O();\n}\n\nfunction ra(t, e) {\n const n = e.key, s = n.path.canonicalString();\n t.gc.get(n) || t.mc.has(s) || (N(\"SyncEngine\", \"New document in limbo: \" + n), t.mc.add(s), \n oa(t));\n}\n\n/**\n * Starts listens for documents in limbo that are enqueued for resolution,\n * subject to a maximum number of concurrent resolutions.\n *\n * Without bounding the number of concurrent resolutions, the server can fail\n * with \"resource exhausted\" errors which can lead to pathological client\n * behavior as seen in https://github.com/firebase/firebase-js-sdk/issues/2683.\n */ function oa(t) {\n for (;t.mc.size > 0 && t.gc.size < t.maxConcurrentLimboResolutions; ) {\n const e = t.mc.values().next().value;\n t.mc.delete(e);\n const n = new ht(ut.fromString(e)), s = t.Ac.next();\n t.yc.set(s, new Uc(n)), t.gc = t.gc.insert(n, s), Hu(t.remoteStore, new cr(Jn(Gn(n.path)), s, \"TargetPurposeLimboResolution\" /* TargetPurpose.LimboResolution */ , Ot.ct));\n }\n}\n\nasync function ua(t, e, n) {\n const s = L(t), i = [], r = [], o = [];\n s.wc.isEmpty() || (s.wc.forEach(((t, u) => {\n o.push(s.Rc(u, e, n).then((t => {\n // Update views if there are actual changes.\n if (\n // If there are changes, or we are handling a global snapshot, notify\n // secondary clients to update query state.\n (t || n) && s.isPrimaryClient && s.sharedClientState.updateQueryState(u.targetId, (null == t ? void 0 : t.fromCache) ? \"not-current\" : \"current\"), \n t) {\n i.push(t);\n const e = tu.Li(u.targetId, t);\n r.push(e);\n }\n })));\n })), await Promise.all(o), s.dc.nu(i), await async function(t, e) {\n const n = L(t);\n try {\n await n.persistence.runTransaction(\"notifyLocalViewChanges\", \"readwrite\", (t => Rt.forEach(e, (e => Rt.forEach(e.Fi, (s => n.persistence.referenceDelegate.addReference(t, e.targetId, s))).next((() => Rt.forEach(e.Bi, (s => n.persistence.referenceDelegate.removeReference(t, e.targetId, s)))))))));\n } catch (t) {\n if (!Dt(t)) throw t;\n // If `notifyLocalViewChanges` fails, we did not advance the sequence\n // number for the documents that were included in this transaction.\n // This might trigger them to be deleted earlier than they otherwise\n // would have, but it should not invalidate the integrity of the data.\n N(\"LocalStore\", \"Failed to update sequence numbers: \" + t);\n }\n for (const t of e) {\n const e = t.targetId;\n if (!t.fromCache) {\n const t = n.Ji.get(e), s = t.snapshotVersion, i = t.withLastLimboFreeSnapshotVersion(s);\n // Advance the last limbo free snapshot version\n n.Ji = n.Ji.insert(e, i);\n }\n }\n }(s.localStore, r));\n}\n\nasync function ca(t, e) {\n const n = L(t);\n if (!n.currentUser.isEqual(e)) {\n N(\"SyncEngine\", \"User change. New user:\", e.toKey());\n const t = await iu(n.localStore, e);\n n.currentUser = e, \n // Fails tasks waiting for pending writes requested by previous user.\n function(t, e) {\n t.Ec.forEach((t => {\n t.forEach((t => {\n t.reject(new U(q.CANCELLED, e));\n }));\n })), t.Ec.clear();\n }(n, \"'waitForPendingWrites' promise is rejected due to a user change.\"), \n // TODO(b/114226417): Consider calling this only in the primary tab.\n n.sharedClientState.handleUserChange(e, t.removedBatchIds, t.addedBatchIds), await ua(n, t.er);\n }\n}\n\nfunction aa(t, e) {\n const n = L(t), s = n.yc.get(e);\n if (s && s.fc) return gs().add(s.key);\n {\n let t = gs();\n const s = n._c.get(e);\n if (!s) return t;\n for (const e of s) {\n const s = n.wc.get(e);\n t = t.unionWith(s.view.nc);\n }\n return t;\n }\n}\n\n/**\n * Reconcile the list of synced documents in an existing view with those\n * from persistence.\n */ async function ha(t, e) {\n const n = L(t), s = await fu(n.localStore, e.query, \n /* usePreviousResults= */ !0), i = e.view.hc(s);\n return n.isPrimaryClient && ia(n, e.targetId, i.cc), i;\n}\n\n/**\n * Retrieves newly changed documents from remote document cache and raises\n * snapshots if needed.\n */\n// PORTING NOTE: Multi-Tab only.\nasync function la(t, e) {\n const n = L(t);\n return wu(n.localStore, e).then((t => ua(n, t)));\n}\n\n/** Applies a mutation state to an existing batch. */\n// PORTING NOTE: Multi-Tab only.\nasync function fa(t, e, n, s) {\n const i = L(t), r = await function(t, e) {\n const n = L(t), s = L(n.mutationQueue);\n return n.persistence.runTransaction(\"Lookup mutation documents\", \"readonly\", (t => s.Sn(t, e).next((e => e ? n.localDocuments.getDocuments(t, e) : Rt.resolve(null)))));\n }\n // PORTING NOTE: Multi-Tab only.\n (i.localStore, e);\n null !== r ? (\"pending\" === n ? \n // If we are the primary client, we need to send this write to the\n // backend. Secondary clients will ignore these writes since their remote\n // connection is disabled.\n await cc(i.remoteStore) : \"acknowledged\" === n || \"rejected\" === n ? (\n // NOTE: Both these methods are no-ops for batches that originated from\n // other clients.\n ea(i, e, s || null), ta(i, e), function(t, e) {\n L(L(t).mutationQueue).Cn(e);\n }\n // PORTING NOTE: Multi-Tab only.\n (i.localStore, e)) : O(), await ua(i, r)) : \n // A throttled tab may not have seen the mutation before it was completed\n // and removed from the mutation queue, in which case we won't have cached\n // the affected documents. In this case we can safely ignore the update\n // since that means we didn't apply the mutation locally at all (if we\n // had, we would have cached the affected documents), and so we will just\n // see any resulting document changes via normal remote document updates\n // as applicable.\n N(\"SyncEngine\", \"Cannot apply mutation batch with id: \" + e);\n}\n\n/** Applies a query target change from a different tab. */\n// PORTING NOTE: Multi-Tab only.\nasync function da(t, e) {\n const n = L(t);\n if (pa(n), Ia(n), !0 === e && !0 !== n.vc) {\n // Secondary tabs only maintain Views for their local listeners and the\n // Views internal state may not be 100% populated (in particular\n // secondary tabs don't track syncedDocuments, the set of documents the\n // server considers to be in the target). So when a secondary becomes\n // primary, we need to need to make sure that all views for all targets\n // match the state on disk.\n const t = n.sharedClientState.getAllActiveQueryTargets(), e = await wa(n, t.toArray());\n n.vc = !0, await yc(n.remoteStore, !0);\n for (const t of e) Hu(n.remoteStore, t);\n } else if (!1 === e && !1 !== n.vc) {\n const t = [];\n let e = Promise.resolve();\n n._c.forEach(((s, i) => {\n n.sharedClientState.isLocalQueryTarget(i) ? t.push(i) : e = e.then((() => (na(n, i), \n lu(n.localStore, i, \n /*keepPersistedTargetData=*/ !0)))), Ju(n.remoteStore, i);\n })), await e, await wa(n, t), \n // PORTING NOTE: Multi-Tab only.\n function(t) {\n const e = L(t);\n e.yc.forEach(((t, n) => {\n Ju(e.remoteStore, n);\n })), e.Ic.Ts(), e.yc = new Map, e.gc = new pe(ht.comparator);\n }\n /**\n * Reconcile the query views of the provided query targets with the state from\n * persistence. Raises snapshots for any changes that affect the local\n * client and returns the updated state of all target's query data.\n *\n * @param syncEngine - The sync engine implementation\n * @param targets - the list of targets with views that need to be recomputed\n * @param transitionToPrimary - `true` iff the tab transitions from a secondary\n * tab to a primary tab\n */\n // PORTING NOTE: Multi-Tab only.\n (n), n.vc = !1, await yc(n.remoteStore, !1);\n }\n}\n\nasync function wa(t, e, n) {\n const s = L(t), i = [], r = [];\n for (const t of e) {\n let e;\n const n = s._c.get(t);\n if (n && 0 !== n.length) {\n // For queries that have a local View, we fetch their current state\n // from LocalStore (as the resume token and the snapshot version\n // might have changed) and reconcile their views with the persisted\n // state (the list of syncedDocuments may have gotten out of sync).\n e = await hu(s.localStore, Jn(n[0]));\n for (const t of n) {\n const e = s.wc.get(t), n = await ha(s, e);\n n.snapshot && r.push(n.snapshot);\n }\n } else {\n // For queries that never executed on this client, we need to\n // allocate the target in LocalStore and initialize a new View.\n const n = await du(s.localStore, t);\n e = await hu(s.localStore, n), await Qc(s, _a(n), t, \n /*current=*/ !1, e.resumeToken);\n }\n i.push(e);\n }\n return s.dc.nu(r), i;\n}\n\n/**\n * Creates a `Query` object from the specified `Target`. There is no way to\n * obtain the original `Query`, so we synthesize a `Query` from the `Target`\n * object.\n *\n * The synthesized result might be different from the original `Query`, but\n * since the synthesized `Query` should return the same results as the\n * original one (only the presentation of results might differ), the potential\n * difference will not cause issues.\n */\n// PORTING NOTE: Multi-Tab only.\nfunction _a(t) {\n return Kn(t.path, t.collectionGroup, t.orderBy, t.filters, t.limit, \"F\" /* LimitType.First */ , t.startAt, t.endAt);\n}\n\n/** Returns the IDs of the clients that are currently active. */\n// PORTING NOTE: Multi-Tab only.\nfunction ma(t) {\n const e = L(t);\n return L(L(e.localStore).persistence).$i();\n}\n\n/** Applies a query target change from a different tab. */\n// PORTING NOTE: Multi-Tab only.\nasync function ga(t, e, n, s) {\n const i = L(t);\n if (i.vc) \n // If we receive a target state notification via WebStorage, we are\n // either already secondary or another tab has taken the primary lease.\n return void N(\"SyncEngine\", \"Ignoring unexpected query state notification.\");\n const r = i._c.get(e);\n if (r && r.length > 0) switch (n) {\n case \"current\":\n case \"not-current\":\n {\n const t = await wu(i.localStore, ss(r[0])), s = mi.createSynthesizedRemoteEventForCurrentChange(e, \"current\" === n, Ve.EMPTY_BYTE_STRING);\n await ua(i, t, s);\n break;\n }\n\n case \"rejected\":\n await lu(i.localStore, e, \n /* keepPersistedTargetData */ !0), na(i, e, s);\n break;\n\n default:\n O();\n }\n}\n\n/** Adds or removes Watch targets for queries from different tabs. */ async function ya(t, e, n) {\n const s = pa(t);\n if (s.vc) {\n for (const t of e) {\n if (s._c.has(t)) {\n // A target might have been added in a previous attempt\n N(\"SyncEngine\", \"Adding an already active target \" + t);\n continue;\n }\n const e = await du(s.localStore, t), n = await hu(s.localStore, e);\n await Qc(s, _a(e), n.targetId, \n /*current=*/ !1, n.resumeToken), Hu(s.remoteStore, n);\n }\n for (const t of n) \n // Check that the target is still active since the target might have been\n // removed if it has been rejected by the backend.\n s._c.has(t) && \n // Release queries that are still active.\n await lu(s.localStore, t, \n /* keepPersistedTargetData */ !1).then((() => {\n Ju(s.remoteStore, t), na(s, t);\n })).catch(vt);\n }\n}\n\nfunction pa(t) {\n const e = L(t);\n return e.remoteStore.remoteSyncer.applyRemoteEvent = Wc.bind(null, e), e.remoteStore.remoteSyncer.getRemoteKeysForTarget = aa.bind(null, e), \n e.remoteStore.remoteSyncer.rejectListen = Jc.bind(null, e), e.dc.nu = Dc.bind(null, e.eventManager), \n e.dc.Pc = Cc.bind(null, e.eventManager), e;\n}\n\nfunction Ia(t) {\n const e = L(t);\n return e.remoteStore.remoteSyncer.applySuccessfulWrite = Yc.bind(null, e), e.remoteStore.remoteSyncer.rejectFailedWrite = Xc.bind(null, e), \n e;\n}\n\n/**\n * Loads a Firestore bundle into the SDK. The returned promise resolves when\n * the bundle finished loading.\n *\n * @param syncEngine - SyncEngine to use.\n * @param bundleReader - Bundle to load into the SDK.\n * @param task - LoadBundleTask used to update the loading progress to public API.\n */ function Ta(t, e, n) {\n const s = L(t);\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\n (\n /** Loads a bundle and returns the list of affected collection groups. */\n async function(t, e, n) {\n try {\n const s = await e.getMetadata();\n if (await function(t, e) {\n const n = L(t), s = Ni(e.createTime);\n return n.persistence.runTransaction(\"hasNewerBundle\", \"readonly\", (t => n.qs.getBundleMetadata(t, e.id))).then((t => !!t && t.createTime.compareTo(s) >= 0));\n }\n /**\n * Saves the given `BundleMetadata` to local persistence.\n */ (t.localStore, s)) return await e.close(), n._completeWith(function(t) {\n return {\n taskState: \"Success\",\n documentsLoaded: t.totalDocuments,\n bytesLoaded: t.totalBytes,\n totalDocuments: t.totalDocuments,\n totalBytes: t.totalBytes\n };\n }(s)), Promise.resolve(new Set);\n n._updateProgress(Oc(s));\n const i = new $c(s, t.localStore, e.serializer);\n let r = await e.bc();\n for (;r; ) {\n const t = await i.zu(r);\n t && n._updateProgress(t), r = await e.bc();\n }\n const o = await i.complete();\n return await ua(t, o.Ju, \n /* remoteEvent */ void 0), \n // Save metadata, so loading the same bundle will skip.\n await function(t, e) {\n const n = L(t);\n return n.persistence.runTransaction(\"Save bundle\", \"readwrite\", (t => n.qs.saveBundleMetadata(t, e)));\n }\n /**\n * Returns a promise of a `NamedQuery` associated with given query name. Promise\n * resolves to undefined if no persisted data can be found.\n */ (t.localStore, s), n._completeWith(o.progress), Promise.resolve(o.Hu);\n } catch (t) {\n return M(\"SyncEngine\", `Loading bundle failed with ${t}`), n._failWith(t), Promise.resolve(new Set);\n }\n }\n /**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n /**\n * Provides all components needed for Firestore with in-memory persistence.\n * Uses EagerGC garbage collection.\n */)(s, e, n).then((t => {\n s.sharedClientState.notifyBundleLoaded(t);\n }));\n}\n\nclass Ea {\n constructor() {\n this.synchronizeTabs = !1;\n }\n async initialize(t) {\n this.serializer = Fu(t.databaseInfo.databaseId), this.sharedClientState = this.createSharedClientState(t), \n this.persistence = this.createPersistence(t), await this.persistence.start(), this.localStore = this.createLocalStore(t), \n this.gcScheduler = this.createGarbageCollectionScheduler(t, this.localStore), this.indexBackfillerScheduler = this.createIndexBackfillerScheduler(t, this.localStore);\n }\n createGarbageCollectionScheduler(t, e) {\n return null;\n }\n createIndexBackfillerScheduler(t, e) {\n return null;\n }\n createLocalStore(t) {\n return su(this.persistence, new eu, t.initialUser, this.serializer);\n }\n createPersistence(t) {\n return new Ko(Qo.zs, this.serializer);\n }\n createSharedClientState(t) {\n return new bu;\n }\n async terminate() {\n this.gcScheduler && this.gcScheduler.stop(), await this.sharedClientState.shutdown(), \n await this.persistence.shutdown();\n }\n}\n\nclass Aa extends Ea {\n constructor(t) {\n super(), this.cacheSizeBytes = t;\n }\n createGarbageCollectionScheduler(t, e) {\n F(this.persistence.referenceDelegate instanceof jo);\n const n = this.persistence.referenceDelegate.garbageCollector;\n return new po(n, t.asyncQueue, e);\n }\n createPersistence(t) {\n const e = void 0 !== this.cacheSizeBytes ? so.withCacheSize(this.cacheSizeBytes) : so.DEFAULT;\n return new Ko((t => jo.zs(t, e)), this.serializer);\n }\n}\n\n/**\n * Provides all components needed for Firestore with IndexedDB persistence.\n */ class va extends Ea {\n constructor(t, e, n) {\n super(), this.Vc = t, this.cacheSizeBytes = e, this.forceOwnership = n, this.synchronizeTabs = !1;\n }\n async initialize(t) {\n await super.initialize(t), await this.Vc.initialize(this, t), \n // Enqueue writes from a previous session\n await Ia(this.Vc.syncEngine), await cc(this.Vc.remoteStore), \n // NOTE: This will immediately call the listener, so we make sure to\n // set it after localStore / remoteStore are started.\n await this.persistence.Ii((() => (this.gcScheduler && !this.gcScheduler.started && this.gcScheduler.start(), \n this.indexBackfillerScheduler && !this.indexBackfillerScheduler.started && this.indexBackfillerScheduler.start(), \n Promise.resolve())));\n }\n createLocalStore(t) {\n return su(this.persistence, new eu, t.initialUser, this.serializer);\n }\n createGarbageCollectionScheduler(t, e) {\n const n = this.persistence.referenceDelegate.garbageCollector;\n return new po(n, t.asyncQueue, e);\n }\n createIndexBackfillerScheduler(t, e) {\n const n = new $t(e, this.persistence);\n return new Mt(t.asyncQueue, n);\n }\n createPersistence(t) {\n const e = Zo(t.databaseInfo.databaseId, t.databaseInfo.persistenceKey), n = void 0 !== this.cacheSizeBytes ? so.withCacheSize(this.cacheSizeBytes) : so.DEFAULT;\n return new Jo(this.synchronizeTabs, e, t.clientId, n, t.asyncQueue, $u(), Ou(), this.serializer, this.sharedClientState, !!this.forceOwnership);\n }\n createSharedClientState(t) {\n return new bu;\n }\n}\n\n/**\n * Provides all components needed for Firestore with multi-tab IndexedDB\n * persistence.\n *\n * In the legacy client, this provider is used to provide both multi-tab and\n * non-multi-tab persistence since we cannot tell at build time whether\n * `synchronizeTabs` will be enabled.\n */ class Ra extends va {\n constructor(t, e) {\n super(t, e, /* forceOwnership= */ !1), this.Vc = t, this.cacheSizeBytes = e, this.synchronizeTabs = !0;\n }\n async initialize(t) {\n await super.initialize(t);\n const e = this.Vc.syncEngine;\n this.sharedClientState instanceof Pu && (this.sharedClientState.syncEngine = {\n jr: fa.bind(null, e),\n zr: ga.bind(null, e),\n Wr: ya.bind(null, e),\n $i: ma.bind(null, e),\n Qr: la.bind(null, e)\n }, await this.sharedClientState.start()), \n // NOTE: This will immediately call the listener, so we make sure to\n // set it after localStore / remoteStore are started.\n await this.persistence.Ii((async t => {\n await da(this.Vc.syncEngine, t), this.gcScheduler && (t && !this.gcScheduler.started ? this.gcScheduler.start() : t || this.gcScheduler.stop()), \n this.indexBackfillerScheduler && (t && !this.indexBackfillerScheduler.started ? this.indexBackfillerScheduler.start() : t || this.indexBackfillerScheduler.stop());\n }));\n }\n createSharedClientState(t) {\n const e = $u();\n if (!Pu.D(e)) throw new U(q.UNIMPLEMENTED, \"IndexedDB persistence is only available on platforms that support LocalStorage.\");\n const n = Zo(t.databaseInfo.databaseId, t.databaseInfo.persistenceKey);\n return new Pu(e, t.asyncQueue, n, t.clientId, t.initialUser);\n }\n}\n\n/**\n * Initializes and wires the components that are needed to interface with the\n * network.\n */ class Pa {\n async initialize(t, e) {\n this.localStore || (this.localStore = t.localStore, this.sharedClientState = t.sharedClientState, \n this.datastore = this.createDatastore(e), this.remoteStore = this.createRemoteStore(e), \n this.eventManager = this.createEventManager(e), this.syncEngine = this.createSyncEngine(e, \n /* startAsPrimary=*/ !t.synchronizeTabs), this.sharedClientState.onlineStateHandler = t => Hc(this.syncEngine, t, 1 /* OnlineStateSource.SharedClientState */), \n this.remoteStore.remoteSyncer.handleCredentialChange = ca.bind(null, this.syncEngine), \n await yc(this.remoteStore, this.syncEngine.isPrimaryClient));\n }\n createEventManager(t) {\n return new bc;\n }\n createDatastore(t) {\n const e = Fu(t.databaseInfo.databaseId), n = (s = t.databaseInfo, new Mu(s));\n var s;\n /** Return the Platform-specific connectivity monitor. */ return function(t, e, n, s) {\n return new Ku(t, e, n, s);\n }(t.authCredentials, t.appCheckCredentials, n, e);\n }\n createRemoteStore(t) {\n return e = this.localStore, n = this.datastore, s = t.asyncQueue, i = t => Hc(this.syncEngine, t, 0 /* OnlineStateSource.RemoteStore */), \n r = Su.D() ? new Su : new Vu, new ju(e, n, s, i, r);\n var e, n, s, i, r;\n /** Re-enables the network. Idempotent. */ }\n createSyncEngine(t, e) {\n return function(t, e, n, \n // PORTING NOTE: Manages state synchronization in multi-tab environments.\n s, i, r, o) {\n const u = new Kc(t, e, n, s, i, r);\n return o && (u.vc = !0), u;\n }(this.localStore, this.remoteStore, this.eventManager, this.sharedClientState, t.initialUser, t.maxConcurrentLimboResolutions, e);\n }\n terminate() {\n return async function(t) {\n const e = L(t);\n N(\"RemoteStore\", \"RemoteStore shutting down.\"), e.vu.add(5 /* OfflineCause.Shutdown */), \n await Wu(e), e.Pu.shutdown(), \n // Set the OnlineState to Unknown (rather than Offline) to avoid potentially\n // triggering spurious listener events with cached data, etc.\n e.bu.set(\"Unknown\" /* OnlineState.Unknown */);\n }(this.remoteStore);\n }\n}\n\n/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * How many bytes to read each time when `ReadableStreamReader.read()` is\n * called. Only applicable for byte streams that we control (e.g. those backed\n * by an UInt8Array).\n */\n/**\n * Builds a `ByteStreamReader` from a UInt8Array.\n * @param source - The data source to use.\n * @param bytesPerRead - How many bytes each `read()` from the returned reader\n * will read.\n */\nfunction ba(t, e = 10240) {\n let n = 0;\n // The TypeScript definition for ReadableStreamReader changed. We use\n // `any` here to allow this code to compile with different versions.\n // See https://github.com/microsoft/TypeScript/issues/42970\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n return {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n async read() {\n if (n < t.byteLength) {\n const s = {\n value: t.slice(n, n + e),\n done: !1\n };\n return n += e, s;\n }\n return {\n done: !0\n };\n },\n async cancel() {},\n releaseLock() {},\n closed: Promise.resolve()\n };\n}\n\n/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * On web, a `ReadableStream` is wrapped around by a `ByteStreamReader`.\n */\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/*\n * A wrapper implementation of Observer that will dispatch events\n * asynchronously. To allow immediate silencing, a mute call is added which\n * causes events scheduled to no longer be raised.\n */\nclass Va {\n constructor(t) {\n this.observer = t, \n /**\n * When set to true, will not raise future events. Necessary to deal with\n * async detachment of listener.\n */\n this.muted = !1;\n }\n next(t) {\n this.observer.next && this.Sc(this.observer.next, t);\n }\n error(t) {\n this.observer.error ? this.Sc(this.observer.error, t) : k(\"Uncaught Error in snapshot listener:\", t.toString());\n }\n Dc() {\n this.muted = !0;\n }\n Sc(t, e) {\n this.muted || setTimeout((() => {\n this.muted || t(e);\n }), 0);\n }\n}\n\n/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * A class representing a bundle.\n *\n * Takes a bundle stream or buffer, and presents abstractions to read bundled\n * elements out of the underlying content.\n */ class Sa {\n constructor(\n /** The reader to read from underlying binary bundle data source. */\n t, e) {\n this.Cc = t, this.serializer = e, \n /** Cached bundle metadata. */\n this.metadata = new K, \n /**\n * Internal buffer to hold bundle content, accumulating incomplete element\n * content.\n */\n this.buffer = new Uint8Array, this.xc = new TextDecoder(\"utf-8\"), \n // Read the metadata (which is the first element).\n this.Nc().then((t => {\n t && t.Qu() ? this.metadata.resolve(t.Gu.metadata) : this.metadata.reject(new Error(`The first element of the bundle is not a metadata, it is\\n ${JSON.stringify(null == t ? void 0 : t.Gu)}`));\n }), (t => this.metadata.reject(t)));\n }\n close() {\n return this.Cc.cancel();\n }\n async getMetadata() {\n return this.metadata.promise;\n }\n async bc() {\n // Makes sure metadata is read before proceeding.\n return await this.getMetadata(), this.Nc();\n }\n /**\n * Reads from the head of internal buffer, and pulling more data from\n * underlying stream if a complete element cannot be found, until an\n * element(including the prefixed length and the JSON string) is found.\n *\n * Once a complete element is read, it is dropped from internal buffer.\n *\n * Returns either the bundled element, or null if we have reached the end of\n * the stream.\n */ async Nc() {\n const t = await this.kc();\n if (null === t) return null;\n const e = this.xc.decode(t), n = Number(e);\n isNaN(n) && this.Mc(`length string (${e}) is not valid number`);\n const s = await this.$c(n);\n return new kc(JSON.parse(s), t.length + n);\n }\n /** First index of '{' from the underlying buffer. */ Oc() {\n return this.buffer.findIndex((t => t === \"{\".charCodeAt(0)));\n }\n /**\n * Reads from the beginning of the internal buffer, until the first '{', and\n * return the content.\n *\n * If reached end of the stream, returns a null.\n */ async kc() {\n for (;this.Oc() < 0; ) {\n if (await this.Fc()) break;\n }\n // Broke out of the loop because underlying stream is closed, and there\n // happens to be no more data to process.\n if (0 === this.buffer.length) return null;\n const t = this.Oc();\n // Broke out of the loop because underlying stream is closed, but still\n // cannot find an open bracket.\n t < 0 && this.Mc(\"Reached the end of bundle when a length string is expected.\");\n const e = this.buffer.slice(0, t);\n // Update the internal buffer to drop the read length.\n return this.buffer = this.buffer.slice(t), e;\n }\n /**\n * Reads from a specified position from the internal buffer, for a specified\n * number of bytes, pulling more data from the underlying stream if needed.\n *\n * Returns a string decoded from the read bytes.\n */ async $c(t) {\n for (;this.buffer.length < t; ) {\n await this.Fc() && this.Mc(\"Reached the end of bundle when more is expected.\");\n }\n const e = this.xc.decode(this.buffer.slice(0, t));\n // Update the internal buffer to drop the read json string.\n return this.buffer = this.buffer.slice(t), e;\n }\n Mc(t) {\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\n throw this.Cc.cancel(), new Error(`Invalid bundle format: ${t}`);\n }\n /**\n * Pulls more data from underlying stream to internal buffer.\n * Returns a boolean indicating whether the stream is finished.\n */ async Fc() {\n const t = await this.Cc.read();\n if (!t.done) {\n const e = new Uint8Array(this.buffer.length + t.value.length);\n e.set(this.buffer), e.set(t.value, this.buffer.length), this.buffer = e;\n }\n return t.done;\n }\n}\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * Internal transaction object responsible for accumulating the mutations to\n * perform and the base versions for any documents read.\n */\nclass Da {\n constructor(t) {\n this.datastore = t, \n // The version of each document that was read during this transaction.\n this.readVersions = new Map, this.mutations = [], this.committed = !1, \n /**\n * A deferred usage error that occurred previously in this transaction that\n * will cause the transaction to fail once it actually commits.\n */\n this.lastWriteError = null, \n /**\n * Set of documents that have been written in the transaction.\n *\n * When there's more than one write to the same key in a transaction, any\n * writes after the first are handled differently.\n */\n this.writtenDocs = new Set;\n }\n async lookup(t) {\n if (this.ensureCommitNotCalled(), this.mutations.length > 0) throw new U(q.INVALID_ARGUMENT, \"Firestore transactions require all reads to be executed before all writes.\");\n const e = await async function(t, e) {\n const n = L(t), s = Li(n.serializer) + \"/documents\", i = {\n documents: e.map((t => $i(n.serializer, t)))\n }, r = await n.vo(\"BatchGetDocuments\", s, i, e.length), o = new Map;\n r.forEach((t => {\n const e = Gi(n.serializer, t);\n o.set(e.key.toString(), e);\n }));\n const u = [];\n return e.forEach((t => {\n const e = o.get(t.toString());\n F(!!e), u.push(e);\n })), u;\n }(this.datastore, t);\n return e.forEach((t => this.recordVersion(t))), e;\n }\n set(t, e) {\n this.write(e.toMutation(t, this.precondition(t))), this.writtenDocs.add(t.toString());\n }\n update(t, e) {\n try {\n this.write(e.toMutation(t, this.preconditionForUpdate(t)));\n } catch (t) {\n this.lastWriteError = t;\n }\n this.writtenDocs.add(t.toString());\n }\n delete(t) {\n this.write(new Ys(t, this.precondition(t))), this.writtenDocs.add(t.toString());\n }\n async commit() {\n if (this.ensureCommitNotCalled(), this.lastWriteError) throw this.lastWriteError;\n const t = this.readVersions;\n // For each mutation, note that the doc was written.\n this.mutations.forEach((e => {\n t.delete(e.key.toString());\n })), \n // For each document that was read but not written to, we want to perform\n // a `verify` operation.\n t.forEach(((t, e) => {\n const n = ht.fromPath(e);\n this.mutations.push(new Xs(n, this.precondition(n)));\n })), await async function(t, e) {\n const n = L(t), s = Li(n.serializer) + \"/documents\", i = {\n writes: e.map((t => ji(n.serializer, t)))\n };\n await n.Io(\"Commit\", s, i);\n }(this.datastore, this.mutations), this.committed = !0;\n }\n recordVersion(t) {\n let e;\n if (t.isFoundDocument()) e = t.version; else {\n if (!t.isNoDocument()) throw O();\n // Represent a deleted doc using SnapshotVersion.min().\n e = rt.min();\n }\n const n = this.readVersions.get(t.key.toString());\n if (n) {\n if (!e.isEqual(n)) \n // This transaction will fail no matter what.\n throw new U(q.ABORTED, \"Document version changed between two reads.\");\n } else this.readVersions.set(t.key.toString(), e);\n }\n /**\n * Returns the version of this document when it was read in this transaction,\n * as a precondition, or no precondition if it was not read.\n */ precondition(t) {\n const e = this.readVersions.get(t.toString());\n return !this.writtenDocs.has(t.toString()) && e ? e.isEqual(rt.min()) ? Fs.exists(!1) : Fs.updateTime(e) : Fs.none();\n }\n /**\n * Returns the precondition for a document if the operation is an update.\n */ preconditionForUpdate(t) {\n const e = this.readVersions.get(t.toString());\n // The first time a document is written, we want to take into account the\n // read time and existence\n if (!this.writtenDocs.has(t.toString()) && e) {\n if (e.isEqual(rt.min())) \n // The document doesn't exist, so fail the transaction.\n // This has to be validated locally because you can't send a\n // precondition that a document does not exist without changing the\n // semantics of the backend write to be an insert. This is the reverse\n // of what we want, since we want to assert that the document doesn't\n // exist but then send the update and have it fail. Since we can't\n // express that to the backend, we have to validate locally.\n // Note: this can change once we can send separate verify writes in the\n // transaction.\n throw new U(q.INVALID_ARGUMENT, \"Can't update a document that doesn't exist.\");\n // Document exists, base precondition on document update time.\n return Fs.updateTime(e);\n }\n // Document was not read, so we just use the preconditions for a blind\n // update.\n return Fs.exists(!0);\n }\n write(t) {\n this.ensureCommitNotCalled(), this.mutations.push(t);\n }\n ensureCommitNotCalled() {}\n}\n\n/**\n * @license\n * Copyright 2019 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * TransactionRunner encapsulates the logic needed to run and retry transactions\n * with backoff.\n */ class Ca {\n constructor(t, e, n, s, i) {\n this.asyncQueue = t, this.datastore = e, this.options = n, this.updateFunction = s, \n this.deferred = i, this.Bc = n.maxAttempts, this.qo = new Bu(this.asyncQueue, \"transaction_retry\" /* TimerId.TransactionRetry */);\n }\n /** Runs the transaction and sets the result on deferred. */ run() {\n this.Bc -= 1, this.Lc();\n }\n Lc() {\n this.qo.No((async () => {\n const t = new Da(this.datastore), e = this.qc(t);\n e && e.then((e => {\n this.asyncQueue.enqueueAndForget((() => t.commit().then((() => {\n this.deferred.resolve(e);\n })).catch((t => {\n this.Uc(t);\n }))));\n })).catch((t => {\n this.Uc(t);\n }));\n }));\n }\n qc(t) {\n try {\n const e = this.updateFunction(t);\n return !Ft(e) && e.catch && e.then ? e : (this.deferred.reject(Error(\"Transaction callback must return a Promise\")), \n null);\n } catch (t) {\n // Do not retry errors thrown by user provided updateFunction.\n return this.deferred.reject(t), null;\n }\n }\n Uc(t) {\n this.Bc > 0 && this.Kc(t) ? (this.Bc -= 1, this.asyncQueue.enqueueAndForget((() => (this.Lc(), \n Promise.resolve())))) : this.deferred.reject(t);\n }\n Kc(t) {\n if (\"FirebaseError\" === t.name) {\n // In transactions, the backend will fail outdated reads with FAILED_PRECONDITION and\n // non-matching document versions with ABORTED. These errors should be retried.\n const e = t.code;\n return \"aborted\" === e || \"failed-precondition\" === e || \"already-exists\" === e || !oi(e);\n }\n return !1;\n }\n}\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * FirestoreClient is a top-level class that constructs and owns all of the //\n * pieces of the client SDK architecture. It is responsible for creating the //\n * async queue that is shared by all of the other components in the system. //\n */\nclass xa {\n constructor(t, e, \n /**\n * Asynchronous queue responsible for all of our internal processing. When\n * we get incoming work from the user (via public API) or the network\n * (incoming GRPC messages), we should always schedule onto this queue.\n * This ensures all of our work is properly serialized (e.g. we don't\n * start processing a new operation while the previous one is waiting for\n * an async I/O to complete).\n */\n n, s) {\n this.authCredentials = t, this.appCheckCredentials = e, this.asyncQueue = n, this.databaseInfo = s, \n this.user = V.UNAUTHENTICATED, this.clientId = tt.A(), this.authCredentialListener = () => Promise.resolve(), \n this.appCheckCredentialListener = () => Promise.resolve(), this.authCredentials.start(n, (async t => {\n N(\"FirestoreClient\", \"Received user=\", t.uid), await this.authCredentialListener(t), \n this.user = t;\n })), this.appCheckCredentials.start(n, (t => (N(\"FirestoreClient\", \"Received new app check token=\", t), \n this.appCheckCredentialListener(t, this.user))));\n }\n async getConfiguration() {\n return {\n asyncQueue: this.asyncQueue,\n databaseInfo: this.databaseInfo,\n clientId: this.clientId,\n authCredentials: this.authCredentials,\n appCheckCredentials: this.appCheckCredentials,\n initialUser: this.user,\n maxConcurrentLimboResolutions: 100\n };\n }\n setCredentialChangeListener(t) {\n this.authCredentialListener = t;\n }\n setAppCheckTokenChangeListener(t) {\n this.appCheckCredentialListener = t;\n }\n /**\n * Checks that the client has not been terminated. Ensures that other methods on //\n * this class cannot be called after the client is terminated. //\n */ verifyNotTerminated() {\n if (this.asyncQueue.isShuttingDown) throw new U(q.FAILED_PRECONDITION, \"The client has already been terminated.\");\n }\n terminate() {\n this.asyncQueue.enterRestrictedMode();\n const t = new K;\n return this.asyncQueue.enqueueAndForgetEvenWhileRestricted((async () => {\n try {\n this._onlineComponents && await this._onlineComponents.terminate(), this._offlineComponents && await this._offlineComponents.terminate(), \n // The credentials provider must be terminated after shutting down the\n // RemoteStore as it will prevent the RemoteStore from retrieving auth\n // tokens.\n this.authCredentials.shutdown(), this.appCheckCredentials.shutdown(), t.resolve();\n } catch (e) {\n const n = Ec(e, \"Failed to shutdown persistence\");\n t.reject(n);\n }\n })), t.promise;\n }\n}\n\nasync function Na(t, e) {\n t.asyncQueue.verifyOperationInProgress(), N(\"FirestoreClient\", \"Initializing OfflineComponentProvider\");\n const n = await t.getConfiguration();\n await e.initialize(n);\n let s = n.initialUser;\n t.setCredentialChangeListener((async t => {\n s.isEqual(t) || (await iu(e.localStore, t), s = t);\n })), \n // When a user calls clearPersistence() in one client, all other clients\n // need to be terminated to allow the delete to succeed.\n e.persistence.setDatabaseDeletedListener((() => t.terminate())), t._offlineComponents = e;\n}\n\nasync function ka(t, e) {\n t.asyncQueue.verifyOperationInProgress();\n const n = await $a(t);\n N(\"FirestoreClient\", \"Initializing OnlineComponentProvider\");\n const s = await t.getConfiguration();\n await e.initialize(n, s), \n // The CredentialChangeListener of the online component provider takes\n // precedence over the offline component provider.\n t.setCredentialChangeListener((t => gc(e.remoteStore, t))), t.setAppCheckTokenChangeListener(((t, n) => gc(e.remoteStore, n))), \n t._onlineComponents = e;\n}\n\n/**\n * Decides whether the provided error allows us to gracefully disable\n * persistence (as opposed to crashing the client).\n */ function Ma(t) {\n return \"FirebaseError\" === t.name ? t.code === q.FAILED_PRECONDITION || t.code === q.UNIMPLEMENTED : !(\"undefined\" != typeof DOMException && t instanceof DOMException) || (\n // When the browser is out of quota we could get either quota exceeded\n // or an aborted error depending on whether the error happened during\n // schema migration.\n 22 === t.code || 20 === t.code || \n // Firefox Private Browsing mode disables IndexedDb and returns\n // INVALID_STATE for any usage.\n 11 === t.code);\n}\n\nasync function $a(t) {\n if (!t._offlineComponents) if (t._uninitializedComponentsProvider) {\n N(\"FirestoreClient\", \"Using user provided OfflineComponentProvider\");\n try {\n await Na(t, t._uninitializedComponentsProvider._offline);\n } catch (e) {\n const n = e;\n if (!Ma(n)) throw n;\n M(\"Error using user provided cache. Falling back to memory cache: \" + n), await Na(t, new Ea);\n }\n } else N(\"FirestoreClient\", \"Using default OfflineComponentProvider\"), await Na(t, new Ea);\n return t._offlineComponents;\n}\n\nasync function Oa(t) {\n return t._onlineComponents || (t._uninitializedComponentsProvider ? (N(\"FirestoreClient\", \"Using user provided OnlineComponentProvider\"), \n await ka(t, t._uninitializedComponentsProvider._online)) : (N(\"FirestoreClient\", \"Using default OnlineComponentProvider\"), \n await ka(t, new Pa))), t._onlineComponents;\n}\n\nfunction Fa(t) {\n return $a(t).then((t => t.persistence));\n}\n\nfunction Ba(t) {\n return $a(t).then((t => t.localStore));\n}\n\nfunction La(t) {\n return Oa(t).then((t => t.remoteStore));\n}\n\nfunction qa(t) {\n return Oa(t).then((t => t.syncEngine));\n}\n\nfunction Ua(t) {\n return Oa(t).then((t => t.datastore));\n}\n\nasync function Ka(t) {\n const e = await Oa(t), n = e.eventManager;\n return n.onListen = Gc.bind(null, e.syncEngine), n.onUnlisten = jc.bind(null, e.syncEngine), \n n;\n}\n\n/** Enables the network connection and re-enqueues all pending operations. */ function Ga(t) {\n return t.asyncQueue.enqueue((async () => {\n const e = await Fa(t), n = await La(t);\n return e.setNetworkEnabled(!0), function(t) {\n const e = L(t);\n return e.vu.delete(0 /* OfflineCause.UserDisabled */), zu(e);\n }(n);\n }));\n}\n\n/** Disables the network connection. Pending operations will not complete. */ function Qa(t) {\n return t.asyncQueue.enqueue((async () => {\n const e = await Fa(t), n = await La(t);\n return e.setNetworkEnabled(!1), async function(t) {\n const e = L(t);\n e.vu.add(0 /* OfflineCause.UserDisabled */), await Wu(e), \n // Set the OnlineState to Offline so get()s return from cache, etc.\n e.bu.set(\"Offline\" /* OnlineState.Offline */);\n }(n);\n }));\n}\n\n/**\n * Returns a Promise that resolves when all writes that were pending at the time\n * this method was called received server acknowledgement. An acknowledgement\n * can be either acceptance or rejection.\n */ function ja(t, e) {\n const n = new K;\n return t.asyncQueue.enqueueAndForget((async () => async function(t, e, n) {\n try {\n const s = await function(t, e) {\n const n = L(t);\n return n.persistence.runTransaction(\"read document\", \"readonly\", (t => n.localDocuments.getDocument(t, e)));\n }(t, e);\n s.isFoundDocument() ? n.resolve(s) : s.isNoDocument() ? n.resolve(null) : n.reject(new U(q.UNAVAILABLE, \"Failed to get document from cache. (However, this document may exist on the server. Run again without setting 'source' in the GetOptions to attempt to retrieve the document from the server.)\"));\n } catch (t) {\n const s = Ec(t, `Failed to get document '${e} from cache`);\n n.reject(s);\n }\n }\n /**\n * Retrieves a latency-compensated document from the backend via a\n * SnapshotListener.\n */ (await Ba(t), e, n))), n.promise;\n}\n\nfunction za(t, e, n = {}) {\n const s = new K;\n return t.asyncQueue.enqueueAndForget((async () => function(t, e, n, s, i) {\n const r = new Va({\n next: r => {\n // Remove query first before passing event to user to avoid\n // user actions affecting the now stale query.\n e.enqueueAndForget((() => Sc(t, o)));\n const u = r.docs.has(n);\n !u && r.fromCache ? \n // TODO(dimond): If we're online and the document doesn't\n // exist then we resolve with a doc.exists set to false. If\n // we're offline however, we reject the Promise in this\n // case. Two options: 1) Cache the negative response from\n // the server so we can deliver that even when you're\n // offline 2) Actually reject the Promise in the online case\n // if the document doesn't exist.\n i.reject(new U(q.UNAVAILABLE, \"Failed to get document because the client is offline.\")) : u && r.fromCache && s && \"server\" === s.source ? i.reject(new U(q.UNAVAILABLE, 'Failed to get document from server. (However, this document does exist in the local cache. Run again without setting source to \"server\" to retrieve the cached document.)')) : i.resolve(r);\n },\n error: t => i.reject(t)\n }), o = new Nc(Gn(n.path), r, {\n includeMetadataChanges: !0,\n Ku: !0\n });\n return Vc(t, o);\n }(await Ka(t), t.asyncQueue, e, n, s))), s.promise;\n}\n\nfunction Wa(t, e) {\n const n = new K;\n return t.asyncQueue.enqueueAndForget((async () => async function(t, e, n) {\n try {\n const s = await fu(t, e, \n /* usePreviousResults= */ !0), i = new Lc(e, s.ir), r = i.sc(s.documents), o = i.applyChanges(r, \n /* updateLimboDocuments= */ !1);\n n.resolve(o.snapshot);\n } catch (t) {\n const s = Ec(t, `Failed to execute query '${e} against cache`);\n n.reject(s);\n }\n }\n /**\n * Retrieves a latency-compensated query snapshot from the backend via a\n * SnapshotListener.\n */ (await Ba(t), e, n))), n.promise;\n}\n\nfunction Ha(t, e, n = {}) {\n const s = new K;\n return t.asyncQueue.enqueueAndForget((async () => function(t, e, n, s, i) {\n const r = new Va({\n next: n => {\n // Remove query first before passing event to user to avoid\n // user actions affecting the now stale query.\n e.enqueueAndForget((() => Sc(t, o))), n.fromCache && \"server\" === s.source ? i.reject(new U(q.UNAVAILABLE, 'Failed to get documents from server. (However, these documents may exist in the local cache. Run again without setting source to \"server\" to retrieve the cached documents.)')) : i.resolve(n);\n },\n error: t => i.reject(t)\n }), o = new Nc(n, r, {\n includeMetadataChanges: !0,\n Ku: !0\n });\n return Vc(t, o);\n }(await Ka(t), t.asyncQueue, e, n, s))), s.promise;\n}\n\nfunction Ja(t, e) {\n const n = new Va(e);\n return t.asyncQueue.enqueueAndForget((async () => function(t, e) {\n L(t).ku.add(e), \n // Immediately fire an initial event, indicating all existing listeners\n // are in-sync.\n e.next();\n }(await Ka(t), n))), () => {\n n.Dc(), t.asyncQueue.enqueueAndForget((async () => function(t, e) {\n L(t).ku.delete(e);\n }(await Ka(t), n)));\n };\n}\n\n/**\n * Takes an updateFunction in which a set of reads and writes can be performed\n * atomically. In the updateFunction, the client can read and write values\n * using the supplied transaction object. After the updateFunction, all\n * changes will be committed. If a retryable error occurs (ex: some other\n * client has changed any of the data referenced), then the updateFunction\n * will be called again after a backoff. If the updateFunction still fails\n * after all retries, then the transaction will be rejected.\n *\n * The transaction object passed to the updateFunction contains methods for\n * accessing documents and collections. Unlike other datastore access, data\n * accessed with the transaction will not reflect local changes that have not\n * been committed. For this reason, it is required that all reads are\n * performed before any writes. Transactions must be performed while online.\n */ function Ya(t, e, n, s) {\n const i = function(t, e) {\n let n;\n n = \"string\" == typeof t ? hi().encode(t) : t;\n return function(t, e) {\n return new Sa(t, e);\n }(function(t, e) {\n if (t instanceof Uint8Array) return ba(t, e);\n if (t instanceof ArrayBuffer) return ba(new Uint8Array(t), e);\n if (t instanceof ReadableStream) return t.getReader();\n throw new Error(\"Source of `toByteStreamReader` has to be a ArrayBuffer or ReadableStream\");\n }(n), e);\n }(n, Fu(e));\n t.asyncQueue.enqueueAndForget((async () => {\n Ta(await qa(t), i, s);\n }));\n}\n\nfunction Xa(t, e) {\n return t.asyncQueue.enqueue((async () => function(t, e) {\n const n = L(t);\n return n.persistence.runTransaction(\"Get named query\", \"readonly\", (t => n.qs.getNamedQuery(t, e)));\n }(await Ba(t), e)));\n}\n\nfunction Za(t, e) {\n return t.asyncQueue.enqueue((async () => async function(t, e) {\n const n = L(t), s = n.indexManager, i = [];\n return n.persistence.runTransaction(\"Configure indexes\", \"readwrite\", (t => s.getFieldIndexes(t).next((n => \n /**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n /**\n * Compares two array for equality using comparator. The method computes the\n * intersection and invokes `onAdd` for every element that is in `after` but not\n * `before`. `onRemove` is invoked for every element in `before` but missing\n * from `after`.\n *\n * The method creates a copy of both `before` and `after` and runs in O(n log\n * n), where n is the size of the two lists.\n *\n * @param before - The elements that exist in the original array.\n * @param after - The elements to diff against the original array.\n * @param comparator - The comparator for the elements in before and after.\n * @param onAdd - A function to invoke for every element that is part of `\n * after` but not `before`.\n * @param onRemove - A function to invoke for every element that is part of\n * `before` but not `after`.\n */\n function(t, e, n, s, i) {\n t = [ ...t ], e = [ ...e ], t.sort(n), e.sort(n);\n const r = t.length, o = e.length;\n let u = 0, c = 0;\n for (;u < o && c < r; ) {\n const r = n(t[c], e[u]);\n r < 0 ? \n // The element was removed if the next element in our ordered\n // walkthrough is only in `before`.\n i(t[c++]) : r > 0 ? \n // The element was added if the next element in our ordered walkthrough\n // is only in `after`.\n s(e[u++]) : (u++, c++);\n }\n for (;u < o; ) s(e[u++]);\n for (;c < r; ) i(t[c++]);\n }(n, e, wt, (e => {\n i.push(s.addFieldIndex(t, e));\n }), (e => {\n i.push(s.deleteFieldIndex(t, e));\n })))).next((() => Rt.waitFor(i)))));\n }\n /**\n * @license\n * Copyright 2019 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n // The format of the LocalStorage key that stores the client state is:\n // firestore_clients__\n (await Ba(t), e)));\n}\n\n/**\n * @license\n * Copyright 2023 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * Compares two `ExperimentalLongPollingOptions` objects for equality.\n */\n/**\n * Creates and returns a new `ExperimentalLongPollingOptions` with the same\n * option values as the given instance.\n */\nfunction th(t) {\n const e = {};\n return void 0 !== t.timeoutSeconds && (e.timeoutSeconds = t.timeoutSeconds), e;\n}\n\n/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */ const eh = new Map;\n\n/**\n * An instance map that ensures only one Datastore exists per Firestore\n * instance.\n */\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nfunction nh(t, e, n) {\n if (!n) throw new U(q.INVALID_ARGUMENT, `Function ${t}() cannot be called with an empty ${e}.`);\n}\n\n/**\n * Validates that two boolean options are not set at the same time.\n * @internal\n */ function sh(t, e, n, s) {\n if (!0 === e && !0 === s) throw new U(q.INVALID_ARGUMENT, `${t} and ${n} cannot be used together.`);\n}\n\n/**\n * Validates that `path` refers to a document (indicated by the fact it contains\n * an even numbers of segments).\n */ function ih(t) {\n if (!ht.isDocumentKey(t)) throw new U(q.INVALID_ARGUMENT, `Invalid document reference. Document references must have an even number of segments, but ${t} has ${t.length}.`);\n}\n\n/**\n * Validates that `path` refers to a collection (indicated by the fact it\n * contains an odd numbers of segments).\n */ function rh(t) {\n if (ht.isDocumentKey(t)) throw new U(q.INVALID_ARGUMENT, `Invalid collection reference. Collection references must have an odd number of segments, but ${t} has ${t.length}.`);\n}\n\n/**\n * Returns true if it's a non-null object without a custom prototype\n * (i.e. excludes Array, Date, etc.).\n */\n/** Returns a string describing the type / value of the provided input. */\nfunction oh(t) {\n if (void 0 === t) return \"undefined\";\n if (null === t) return \"null\";\n if (\"string\" == typeof t) return t.length > 20 && (t = `${t.substring(0, 20)}...`), \n JSON.stringify(t);\n if (\"number\" == typeof t || \"boolean\" == typeof t) return \"\" + t;\n if (\"object\" == typeof t) {\n if (t instanceof Array) return \"an array\";\n {\n const e = \n /** try to get the constructor name for an object. */\n function(t) {\n if (t.constructor) return t.constructor.name;\n return null;\n }\n /**\n * Casts `obj` to `T`, optionally unwrapping Compat types to expose the\n * underlying instance. Throws if `obj` is not an instance of `T`.\n *\n * This cast is used in the Lite and Full SDK to verify instance types for\n * arguments passed to the public API.\n * @internal\n */ (t);\n return e ? `a custom ${e} object` : \"an object\";\n }\n }\n return \"function\" == typeof t ? \"a function\" : O();\n}\n\nfunction uh(t, \n// eslint-disable-next-line @typescript-eslint/no-explicit-any\ne) {\n if (\"_delegate\" in t && (\n // Unwrap Compat types\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n t = t._delegate), !(t instanceof e)) {\n if (e.name === t.constructor.name) throw new U(q.INVALID_ARGUMENT, \"Type does not match the expected instance. Did you pass a reference from a different Firestore SDK?\");\n {\n const n = oh(t);\n throw new U(q.INVALID_ARGUMENT, `Expected type '${e.name}', but it was: ${n}`);\n }\n }\n return t;\n}\n\nfunction ch(t, e) {\n if (e <= 0) throw new U(q.INVALID_ARGUMENT, `Function ${t}() requires a positive number, but it was: ${e}.`);\n}\n\n/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n// settings() defaults:\n/**\n * A concrete type describing all the values that can be applied via a\n * user-supplied `FirestoreSettings` object. This is a separate type so that\n * defaults can be supplied and the value can be checked for equality.\n */\nclass ah {\n constructor(t) {\n var e, n;\n if (void 0 === t.host) {\n if (void 0 !== t.ssl) throw new U(q.INVALID_ARGUMENT, \"Can't provide ssl option if host option is not set\");\n this.host = \"firestore.googleapis.com\", this.ssl = true;\n } else this.host = t.host, this.ssl = null === (e = t.ssl) || void 0 === e || e;\n if (this.credentials = t.credentials, this.ignoreUndefinedProperties = !!t.ignoreUndefinedProperties, \n this.cache = t.localCache, void 0 === t.cacheSizeBytes) this.cacheSizeBytes = 41943040; else {\n if (-1 !== t.cacheSizeBytes && t.cacheSizeBytes < 1048576) throw new U(q.INVALID_ARGUMENT, \"cacheSizeBytes must be at least 1048576\");\n this.cacheSizeBytes = t.cacheSizeBytes;\n }\n sh(\"experimentalForceLongPolling\", t.experimentalForceLongPolling, \"experimentalAutoDetectLongPolling\", t.experimentalAutoDetectLongPolling), \n this.experimentalForceLongPolling = !!t.experimentalForceLongPolling, this.experimentalForceLongPolling ? this.experimentalAutoDetectLongPolling = !1 : void 0 === t.experimentalAutoDetectLongPolling ? this.experimentalAutoDetectLongPolling = true : \n // For backwards compatibility, coerce the value to boolean even though\n // the TypeScript compiler has narrowed the type to boolean already.\n // noinspection PointlessBooleanExpressionJS\n this.experimentalAutoDetectLongPolling = !!t.experimentalAutoDetectLongPolling, \n this.experimentalLongPollingOptions = th(null !== (n = t.experimentalLongPollingOptions) && void 0 !== n ? n : {}), \n function(t) {\n if (void 0 !== t.timeoutSeconds) {\n if (isNaN(t.timeoutSeconds)) throw new U(q.INVALID_ARGUMENT, `invalid long polling timeout: ${t.timeoutSeconds} (must not be NaN)`);\n if (t.timeoutSeconds < 5) throw new U(q.INVALID_ARGUMENT, `invalid long polling timeout: ${t.timeoutSeconds} (minimum allowed value is 5)`);\n if (t.timeoutSeconds > 30) throw new U(q.INVALID_ARGUMENT, `invalid long polling timeout: ${t.timeoutSeconds} (maximum allowed value is 30)`);\n }\n }\n /**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n /**\n * The Cloud Firestore service interface.\n *\n * Do not call this constructor directly. Instead, use {@link (getFirestore:1)}.\n */ (this.experimentalLongPollingOptions), this.useFetchStreams = !!t.useFetchStreams;\n }\n isEqual(t) {\n return this.host === t.host && this.ssl === t.ssl && this.credentials === t.credentials && this.cacheSizeBytes === t.cacheSizeBytes && this.experimentalForceLongPolling === t.experimentalForceLongPolling && this.experimentalAutoDetectLongPolling === t.experimentalAutoDetectLongPolling && (e = this.experimentalLongPollingOptions, \n n = t.experimentalLongPollingOptions, e.timeoutSeconds === n.timeoutSeconds) && this.ignoreUndefinedProperties === t.ignoreUndefinedProperties && this.useFetchStreams === t.useFetchStreams;\n var e, n;\n }\n}\n\nclass hh {\n /** @hideconstructor */\n constructor(t, e, n, s) {\n this._authCredentials = t, this._appCheckCredentials = e, this._databaseId = n, \n this._app = s, \n /**\n * Whether it's a Firestore or Firestore Lite instance.\n */\n this.type = \"firestore-lite\", this._persistenceKey = \"(lite)\", this._settings = new ah({}), \n this._settingsFrozen = !1;\n }\n /**\n * The {@link @firebase/app#FirebaseApp} associated with this `Firestore` service\n * instance.\n */ get app() {\n if (!this._app) throw new U(q.FAILED_PRECONDITION, \"Firestore was not initialized using the Firebase SDK. 'app' is not available\");\n return this._app;\n }\n get _initialized() {\n return this._settingsFrozen;\n }\n get _terminated() {\n return void 0 !== this._terminateTask;\n }\n _setSettings(t) {\n if (this._settingsFrozen) throw new U(q.FAILED_PRECONDITION, \"Firestore has already been started and its settings can no longer be changed. You can only modify settings before calling any other methods on a Firestore object.\");\n this._settings = new ah(t), void 0 !== t.credentials && (this._authCredentials = function(t) {\n if (!t) return new Q;\n switch (t.type) {\n case \"firstParty\":\n return new H(t.sessionIndex || \"0\", t.iamToken || null, t.authTokenFactory || null);\n\n case \"provider\":\n return t.client;\n\n default:\n throw new U(q.INVALID_ARGUMENT, \"makeAuthCredentialsProvider failed due to invalid credential type\");\n }\n }(t.credentials));\n }\n _getSettings() {\n return this._settings;\n }\n _freezeSettings() {\n return this._settingsFrozen = !0, this._settings;\n }\n _delete() {\n return this._terminateTask || (this._terminateTask = this._terminate()), this._terminateTask;\n }\n /** Returns a JSON-serializable representation of this `Firestore` instance. */ toJSON() {\n return {\n app: this._app,\n databaseId: this._databaseId,\n settings: this._settings\n };\n }\n /**\n * Terminates all components used by this client. Subclasses can override\n * this method to clean up their own dependencies, but must also call this\n * method.\n *\n * Only ever called once.\n */ _terminate() {\n /**\n * Removes all components associated with the provided instance. Must be called\n * when the `Firestore` instance is terminated.\n */\n return function(t) {\n const e = eh.get(t);\n e && (N(\"ComponentProvider\", \"Removing Datastore\"), eh.delete(t), e.terminate());\n }(this), Promise.resolve();\n }\n}\n\n/**\n * Modify this instance to communicate with the Cloud Firestore emulator.\n *\n * Note: This must be called before this instance has been used to do any\n * operations.\n *\n * @param firestore - The `Firestore` instance to configure to connect to the\n * emulator.\n * @param host - the emulator host (ex: localhost).\n * @param port - the emulator port (ex: 9000).\n * @param options.mockUserToken - the mock auth token to use for unit testing\n * Security Rules.\n */ function lh(t, e, n, s = {}) {\n var i;\n const r = (t = uh(t, hh))._getSettings(), o = `${e}:${n}`;\n if (\"firestore.googleapis.com\" !== r.host && r.host !== o && M(\"Host has been set in both settings() and connectFirestoreEmulator(), emulator host will be used.\"), \n t._setSettings(Object.assign(Object.assign({}, r), {\n host: o,\n ssl: !1\n })), s.mockUserToken) {\n let e, n;\n if (\"string\" == typeof s.mockUserToken) e = s.mockUserToken, n = V.MOCK_USER; else {\n // Let createMockUserToken validate first (catches common mistakes like\n // invalid field \"uid\" and missing field \"sub\" / \"user_id\".)\n e = createMockUserToken(s.mockUserToken, null === (i = t._app) || void 0 === i ? void 0 : i.options.projectId);\n const r = s.mockUserToken.sub || s.mockUserToken.user_id;\n if (!r) throw new U(q.INVALID_ARGUMENT, \"mockUserToken must contain 'sub' or 'user_id' field!\");\n n = new V(r);\n }\n t._authCredentials = new j(new G(e, n));\n }\n}\n\n/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * A `DocumentReference` refers to a document location in a Firestore database\n * and can be used to write, read, or listen to the location. The document at\n * the referenced location may or may not exist.\n */ class fh {\n /** @hideconstructor */\n constructor(t, \n /**\n * If provided, the `FirestoreDataConverter` associated with this instance.\n */\n e, n) {\n this.converter = e, this._key = n, \n /** The type of this Firestore reference. */\n this.type = \"document\", this.firestore = t;\n }\n get _path() {\n return this._key.path;\n }\n /**\n * The document's identifier within its collection.\n */ get id() {\n return this._key.path.lastSegment();\n }\n /**\n * A string representing the path of the referenced document (relative\n * to the root of the database).\n */ get path() {\n return this._key.path.canonicalString();\n }\n /**\n * The collection this `DocumentReference` belongs to.\n */ get parent() {\n return new wh(this.firestore, this.converter, this._key.path.popLast());\n }\n withConverter(t) {\n return new fh(this.firestore, t, this._key);\n }\n}\n\n/**\n * A `Query` refers to a query which you can read or listen to. You can also\n * construct refined `Query` objects by adding filters and ordering.\n */ class dh {\n // This is the lite version of the Query class in the main SDK.\n /** @hideconstructor protected */\n constructor(t, \n /**\n * If provided, the `FirestoreDataConverter` associated with this instance.\n */\n e, n) {\n this.converter = e, this._query = n, \n /** The type of this Firestore reference. */\n this.type = \"query\", this.firestore = t;\n }\n withConverter(t) {\n return new dh(this.firestore, t, this._query);\n }\n}\n\n/**\n * A `CollectionReference` object can be used for adding documents, getting\n * document references, and querying for documents (using {@link (query:1)}).\n */ class wh extends dh {\n /** @hideconstructor */\n constructor(t, e, n) {\n super(t, e, Gn(n)), this._path = n, \n /** The type of this Firestore reference. */\n this.type = \"collection\";\n }\n /** The collection's identifier. */ get id() {\n return this._query.path.lastSegment();\n }\n /**\n * A string representing the path of the referenced collection (relative\n * to the root of the database).\n */ get path() {\n return this._query.path.canonicalString();\n }\n /**\n * A reference to the containing `DocumentReference` if this is a\n * subcollection. If this isn't a subcollection, the reference is null.\n */ get parent() {\n const t = this._path.popLast();\n return t.isEmpty() ? null : new fh(this.firestore, \n /* converter= */ null, new ht(t));\n }\n withConverter(t) {\n return new wh(this.firestore, t, this._path);\n }\n}\n\nfunction _h(t, e, ...n) {\n if (t = getModularInstance(t), nh(\"collection\", \"path\", e), t instanceof hh) {\n const s = ut.fromString(e, ...n);\n return rh(s), new wh(t, /* converter= */ null, s);\n }\n {\n if (!(t instanceof fh || t instanceof wh)) throw new U(q.INVALID_ARGUMENT, \"Expected first argument to collection() to be a CollectionReference, a DocumentReference or FirebaseFirestore\");\n const s = t._path.child(ut.fromString(e, ...n));\n return rh(s), new wh(t.firestore, \n /* converter= */ null, s);\n }\n}\n\n// TODO(firestorelite): Consider using ErrorFactory -\n// https://github.com/firebase/firebase-js-sdk/blob/0131e1f/packages/util/src/errors.ts#L106\n/**\n * Creates and returns a new `Query` instance that includes all documents in the\n * database that are contained in a collection or subcollection with the\n * given `collectionId`.\n *\n * @param firestore - A reference to the root `Firestore` instance.\n * @param collectionId - Identifies the collections to query over. Every\n * collection or subcollection with this ID as the last segment of its path\n * will be included. Cannot contain a slash.\n * @returns The created `Query`.\n */ function mh(t, e) {\n if (t = uh(t, hh), nh(\"collectionGroup\", \"collection id\", e), e.indexOf(\"/\") >= 0) throw new U(q.INVALID_ARGUMENT, `Invalid collection ID '${e}' passed to function collectionGroup(). Collection IDs must not contain '/'.`);\n return new dh(t, \n /* converter= */ null, function(t) {\n return new Un(ut.emptyPath(), t);\n }(e));\n}\n\nfunction gh(t, e, ...n) {\n if (t = getModularInstance(t), \n // We allow omission of 'pathString' but explicitly prohibit passing in both\n // 'undefined' and 'null'.\n 1 === arguments.length && (e = tt.A()), nh(\"doc\", \"path\", e), t instanceof hh) {\n const s = ut.fromString(e, ...n);\n return ih(s), new fh(t, \n /* converter= */ null, new ht(s));\n }\n {\n if (!(t instanceof fh || t instanceof wh)) throw new U(q.INVALID_ARGUMENT, \"Expected first argument to collection() to be a CollectionReference, a DocumentReference or FirebaseFirestore\");\n const s = t._path.child(ut.fromString(e, ...n));\n return ih(s), new fh(t.firestore, t instanceof wh ? t.converter : null, new ht(s));\n }\n}\n\n/**\n * Returns true if the provided references are equal.\n *\n * @param left - A reference to compare.\n * @param right - A reference to compare.\n * @returns true if the references point to the same location in the same\n * Firestore database.\n */ function yh(t, e) {\n return t = getModularInstance(t), e = getModularInstance(e), (t instanceof fh || t instanceof wh) && (e instanceof fh || e instanceof wh) && (t.firestore === e.firestore && t.path === e.path && t.converter === e.converter);\n}\n\n/**\n * Returns true if the provided queries point to the same collection and apply\n * the same constraints.\n *\n * @param left - A `Query` to compare.\n * @param right - A `Query` to compare.\n * @returns true if the references point to the same location in the same\n * Firestore database.\n */ function ph(t, e) {\n return t = getModularInstance(t), e = getModularInstance(e), t instanceof dh && e instanceof dh && (t.firestore === e.firestore && Zn(t._query, e._query) && t.converter === e.converter);\n}\n\n/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */ class Ih {\n constructor() {\n // The last promise in the queue.\n this.Gc = Promise.resolve(), \n // A list of retryable operations. Retryable operations are run in order and\n // retried with backoff.\n this.Qc = [], \n // Is this AsyncQueue being shut down? Once it is set to true, it will not\n // be changed again.\n this.jc = !1, \n // Operations scheduled to be queued in the future. Operations are\n // automatically removed after they are run or canceled.\n this.zc = [], \n // visible for testing\n this.Wc = null, \n // Flag set while there's an outstanding AsyncQueue operation, used for\n // assertion sanity-checks.\n this.Hc = !1, \n // Enabled during shutdown on Safari to prevent future access to IndexedDB.\n this.Jc = !1, \n // List of TimerIds to fast-forward delays for.\n this.Yc = [], \n // Backoff timer used to schedule retries for retryable operations\n this.qo = new Bu(this, \"async_queue_retry\" /* TimerId.AsyncQueueRetry */), \n // Visibility handler that triggers an immediate retry of all retryable\n // operations. Meant to speed up recovery when we regain file system access\n // after page comes into foreground.\n this.Xc = () => {\n const t = Ou();\n t && N(\"AsyncQueue\", \"Visibility state changed to \" + t.visibilityState), this.qo.Mo();\n };\n const t = Ou();\n t && \"function\" == typeof t.addEventListener && t.addEventListener(\"visibilitychange\", this.Xc);\n }\n get isShuttingDown() {\n return this.jc;\n }\n /**\n * Adds a new operation to the queue without waiting for it to complete (i.e.\n * we ignore the Promise result).\n */ enqueueAndForget(t) {\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\n this.enqueue(t);\n }\n enqueueAndForgetEvenWhileRestricted(t) {\n this.Zc(), \n // eslint-disable-next-line @typescript-eslint/no-floating-promises\n this.ta(t);\n }\n enterRestrictedMode(t) {\n if (!this.jc) {\n this.jc = !0, this.Jc = t || !1;\n const e = Ou();\n e && \"function\" == typeof e.removeEventListener && e.removeEventListener(\"visibilitychange\", this.Xc);\n }\n }\n enqueue(t) {\n if (this.Zc(), this.jc) \n // Return a Promise which never resolves.\n return new Promise((() => {}));\n // Create a deferred Promise that we can return to the callee. This\n // allows us to return a \"hanging Promise\" only to the callee and still\n // advance the queue even when the operation is not run.\n const e = new K;\n return this.ta((() => this.jc && this.Jc ? Promise.resolve() : (t().then(e.resolve, e.reject), \n e.promise))).then((() => e.promise));\n }\n enqueueRetryable(t) {\n this.enqueueAndForget((() => (this.Qc.push(t), this.ea())));\n }\n /**\n * Runs the next operation from the retryable queue. If the operation fails,\n * reschedules with backoff.\n */ async ea() {\n if (0 !== this.Qc.length) {\n try {\n await this.Qc[0](), this.Qc.shift(), this.qo.reset();\n } catch (t) {\n if (!Dt(t)) throw t;\n // Failure will be handled by AsyncQueue\n N(\"AsyncQueue\", \"Operation failed with retryable error: \" + t);\n }\n this.Qc.length > 0 && \n // If there are additional operations, we re-schedule `retryNextOp()`.\n // This is necessary to run retryable operations that failed during\n // their initial attempt since we don't know whether they are already\n // enqueued. If, for example, `op1`, `op2`, `op3` are enqueued and `op1`\n // needs to be re-run, we will run `op1`, `op1`, `op2` using the\n // already enqueued calls to `retryNextOp()`. `op3()` will then run in the\n // call scheduled here.\n // Since `backoffAndRun()` cancels an existing backoff and schedules a\n // new backoff on every call, there is only ever a single additional\n // operation in the queue.\n this.qo.No((() => this.ea()));\n }\n }\n ta(t) {\n const e = this.Gc.then((() => (this.Hc = !0, t().catch((t => {\n this.Wc = t, this.Hc = !1;\n const e = \n /**\n * Chrome includes Error.message in Error.stack. Other browsers do not.\n * This returns expected output of message + stack when available.\n * @param error - Error or FirestoreError\n */\n function(t) {\n let e = t.message || \"\";\n t.stack && (e = t.stack.includes(t.message) ? t.stack : t.message + \"\\n\" + t.stack);\n return e;\n }\n /**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */ (t);\n // Re-throw the error so that this.tail becomes a rejected Promise and\n // all further attempts to chain (via .then) will just short-circuit\n // and return the rejected Promise.\n throw k(\"INTERNAL UNHANDLED ERROR: \", e), t;\n })).then((t => (this.Hc = !1, t))))));\n return this.Gc = e, e;\n }\n enqueueAfterDelay(t, e, n) {\n this.Zc(), \n // Fast-forward delays for timerIds that have been overriden.\n this.Yc.indexOf(t) > -1 && (e = 0);\n const s = Tc.createAndSchedule(this, t, e, n, (t => this.na(t)));\n return this.zc.push(s), s;\n }\n Zc() {\n this.Wc && O();\n }\n verifyOperationInProgress() {}\n /**\n * Waits until all currently queued tasks are finished executing. Delayed\n * operations are not run.\n */ async sa() {\n // Operations in the queue prior to draining may have enqueued additional\n // operations. Keep draining the queue until the tail is no longer advanced,\n // which indicates that no more new operations were enqueued and that all\n // operations were executed.\n let t;\n do {\n t = this.Gc, await t;\n } while (t !== this.Gc);\n }\n /**\n * For Tests: Determine if a delayed operation with a particular TimerId\n * exists.\n */ ia(t) {\n for (const e of this.zc) if (e.timerId === t) return !0;\n return !1;\n }\n /**\n * For Tests: Runs some or all delayed operations early.\n *\n * @param lastTimerId - Delayed operations up to and including this TimerId\n * will be drained. Pass TimerId.All to run all delayed operations.\n * @returns a Promise that resolves once all operations have been run.\n */ ra(t) {\n // Note that draining may generate more delayed ops, so we do that first.\n return this.sa().then((() => {\n // Run ops in the same order they'd run if they ran naturally.\n this.zc.sort(((t, e) => t.targetTimeMs - e.targetTimeMs));\n for (const e of this.zc) if (e.skipDelay(), \"all\" /* TimerId.All */ !== t && e.timerId === t) break;\n return this.sa();\n }));\n }\n /**\n * For Tests: Skip all subsequent delays for a timer id.\n */ oa(t) {\n this.Yc.push(t);\n }\n /** Called once a DelayedOperation is run or canceled. */ na(t) {\n // NOTE: indexOf / slice are O(n), but delayedOperations is expected to be small.\n const e = this.zc.indexOf(t);\n this.zc.splice(e, 1);\n }\n}\n\nfunction Th(t) {\n /**\n * Returns true if obj is an object and contains at least one of the specified\n * methods.\n */\n return function(t, e) {\n if (\"object\" != typeof t || null === t) return !1;\n const n = t;\n for (const t of e) if (t in n && \"function\" == typeof n[t]) return !0;\n return !1;\n }\n /**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n /**\n * Represents the task of loading a Firestore bundle. It provides progress of bundle\n * loading, as well as task completion and error events.\n *\n * The API is compatible with `Promise`.\n */ (t, [ \"next\", \"error\", \"complete\" ]);\n}\n\nclass Eh {\n constructor() {\n this._progressObserver = {}, this._taskCompletionResolver = new K, this._lastProgress = {\n taskState: \"Running\",\n totalBytes: 0,\n totalDocuments: 0,\n bytesLoaded: 0,\n documentsLoaded: 0\n };\n }\n /**\n * Registers functions to listen to bundle loading progress events.\n * @param next - Called when there is a progress update from bundle loading. Typically `next` calls occur\n * each time a Firestore document is loaded from the bundle.\n * @param error - Called when an error occurs during bundle loading. The task aborts after reporting the\n * error, and there should be no more updates after this.\n * @param complete - Called when the loading task is complete.\n */ onProgress(t, e, n) {\n this._progressObserver = {\n next: t,\n error: e,\n complete: n\n };\n }\n /**\n * Implements the `Promise.catch` interface.\n *\n * @param onRejected - Called when an error occurs during bundle loading.\n */ catch(t) {\n return this._taskCompletionResolver.promise.catch(t);\n }\n /**\n * Implements the `Promise.then` interface.\n *\n * @param onFulfilled - Called on the completion of the loading task with a final `LoadBundleTaskProgress` update.\n * The update will always have its `taskState` set to `\"Success\"`.\n * @param onRejected - Called when an error occurs during bundle loading.\n */ then(t, e) {\n return this._taskCompletionResolver.promise.then(t, e);\n }\n /**\n * Notifies all observers that bundle loading has completed, with a provided\n * `LoadBundleTaskProgress` object.\n *\n * @private\n */ _completeWith(t) {\n this._updateProgress(t), this._progressObserver.complete && this._progressObserver.complete(), \n this._taskCompletionResolver.resolve(t);\n }\n /**\n * Notifies all observers that bundle loading has failed, with a provided\n * `Error` as the reason.\n *\n * @private\n */ _failWith(t) {\n this._lastProgress.taskState = \"Error\", this._progressObserver.next && this._progressObserver.next(this._lastProgress), \n this._progressObserver.error && this._progressObserver.error(t), this._taskCompletionResolver.reject(t);\n }\n /**\n * Notifies a progress update of loading a bundle.\n * @param progress - The new progress.\n *\n * @private\n */ _updateProgress(t) {\n this._lastProgress = t, this._progressObserver.next && this._progressObserver.next(t);\n }\n}\n\n/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * Constant used to indicate the LRU garbage collection should be disabled.\n * Set this value as the `cacheSizeBytes` on the settings passed to the\n * {@link Firestore} instance.\n */ const Ah = -1;\n\n/**\n * The Cloud Firestore service interface.\n *\n * Do not call this constructor directly. Instead, use {@link (getFirestore:1)}.\n */ class vh extends hh {\n /** @hideconstructor */\n constructor(t, e, n, s) {\n super(t, e, n, s), \n /**\n * Whether it's a {@link Firestore} or Firestore Lite instance.\n */\n this.type = \"firestore\", this._queue = new Ih, this._persistenceKey = (null == s ? void 0 : s.name) || \"[DEFAULT]\";\n }\n _terminate() {\n return this._firestoreClient || \n // The client must be initialized to ensure that all subsequent API\n // usage throws an exception.\n Vh(this), this._firestoreClient.terminate();\n }\n}\n\n/**\n * Initializes a new instance of {@link Firestore} with the provided settings.\n * Can only be called before any other function, including\n * {@link (getFirestore:1)}. If the custom settings are empty, this function is\n * equivalent to calling {@link (getFirestore:1)}.\n *\n * @param app - The {@link @firebase/app#FirebaseApp} with which the {@link Firestore} instance will\n * be associated.\n * @param settings - A settings object to configure the {@link Firestore} instance.\n * @param databaseId - The name of the database.\n * @returns A newly initialized {@link Firestore} instance.\n */ function Rh(t, e, n) {\n n || (n = \"(default)\");\n const s = _getProvider(t, \"firestore\");\n if (s.isInitialized(n)) {\n const t = s.getImmediate({\n identifier: n\n }), i = s.getOptions(n);\n if (deepEqual(i, e)) return t;\n throw new U(q.FAILED_PRECONDITION, \"initializeFirestore() has already been called with different options. To avoid this error, call initializeFirestore() with the same options as when it was originally called, or call getFirestore() to return the already initialized instance.\");\n }\n if (void 0 !== e.cacheSizeBytes && void 0 !== e.localCache) throw new U(q.INVALID_ARGUMENT, \"cache and cacheSizeBytes cannot be specified at the same time as cacheSizeBytes willbe deprecated. Instead, specify the cache size in the cache object\");\n if (void 0 !== e.cacheSizeBytes && -1 !== e.cacheSizeBytes && e.cacheSizeBytes < 1048576) throw new U(q.INVALID_ARGUMENT, \"cacheSizeBytes must be at least 1048576\");\n return s.initialize({\n options: e,\n instanceIdentifier: n\n });\n}\n\nfunction Ph(e, n) {\n const s = \"object\" == typeof e ? e : getApp(), i = \"string\" == typeof e ? e : n || \"(default)\", r = _getProvider(s, \"firestore\").getImmediate({\n identifier: i\n });\n if (!r._initialized) {\n const t = getDefaultEmulatorHostnameAndPort(\"firestore\");\n t && lh(r, ...t);\n }\n return r;\n}\n\n/**\n * @internal\n */ function bh(t) {\n return t._firestoreClient || Vh(t), t._firestoreClient.verifyNotTerminated(), t._firestoreClient;\n}\n\nfunction Vh(t) {\n var e, n, s;\n const i = t._freezeSettings(), r = function(t, e, n, s) {\n return new $e(t, e, n, s.host, s.ssl, s.experimentalForceLongPolling, s.experimentalAutoDetectLongPolling, th(s.experimentalLongPollingOptions), s.useFetchStreams);\n }(t._databaseId, (null === (e = t._app) || void 0 === e ? void 0 : e.options.appId) || \"\", t._persistenceKey, i);\n t._firestoreClient = new xa(t._authCredentials, t._appCheckCredentials, t._queue, r), \n (null === (n = i.cache) || void 0 === n ? void 0 : n._offlineComponentProvider) && (null === (s = i.cache) || void 0 === s ? void 0 : s._onlineComponentProvider) && (t._firestoreClient._uninitializedComponentsProvider = {\n _offlineKind: i.cache.kind,\n _offline: i.cache._offlineComponentProvider,\n _online: i.cache._onlineComponentProvider\n });\n}\n\n/**\n * Attempts to enable persistent storage, if possible.\n *\n * Must be called before any other functions (other than\n * {@link initializeFirestore}, {@link (getFirestore:1)} or\n * {@link clearIndexedDbPersistence}.\n *\n * If this fails, `enableIndexedDbPersistence()` will reject the promise it\n * returns. Note that even after this failure, the {@link Firestore} instance will\n * remain usable, however offline persistence will be disabled.\n *\n * There are several reasons why this can fail, which can be identified by\n * the `code` on the error.\n *\n * * failed-precondition: The app is already open in another browser tab.\n * * unimplemented: The browser is incompatible with the offline\n * persistence implementation.\n *\n * Persistence cannot be used in a Node.js environment.\n *\n * @param firestore - The {@link Firestore} instance to enable persistence for.\n * @param persistenceSettings - Optional settings object to configure\n * persistence.\n * @returns A `Promise` that represents successfully enabling persistent storage.\n * @deprecated This function will be removed in a future major release. Instead, set\n * `FirestoreSettings.cache` to an instance of `IndexedDbLocalCache` to\n * turn on IndexedDb cache. Calling this function when `FirestoreSettings.cache`\n * is already specified will throw an exception.\n */ function Sh(t, e) {\n Bh(t = uh(t, vh));\n const n = bh(t);\n if (n._uninitializedComponentsProvider) throw new U(q.FAILED_PRECONDITION, \"SDK cache is already specified.\");\n M(\"enableIndexedDbPersistence() will be deprecated in the future, you can use `FirestoreSettings.cache` instead.\");\n const s = t._freezeSettings(), i = new Pa;\n return Ch(n, i, new va(i, s.cacheSizeBytes, null == e ? void 0 : e.forceOwnership));\n}\n\n/**\n * Attempts to enable multi-tab persistent storage, if possible. If enabled\n * across all tabs, all operations share access to local persistence, including\n * shared execution of queries and latency-compensated local document updates\n * across all connected instances.\n *\n * If this fails, `enableMultiTabIndexedDbPersistence()` will reject the promise\n * it returns. Note that even after this failure, the {@link Firestore} instance will\n * remain usable, however offline persistence will be disabled.\n *\n * There are several reasons why this can fail, which can be identified by\n * the `code` on the error.\n *\n * * failed-precondition: The app is already open in another browser tab and\n * multi-tab is not enabled.\n * * unimplemented: The browser is incompatible with the offline\n * persistence implementation.\n *\n * @param firestore - The {@link Firestore} instance to enable persistence for.\n * @returns A `Promise` that represents successfully enabling persistent\n * storage.\n * @deprecated This function will be removed in a future major release. Instead, set\n * `FirestoreSettings.cache` to an instance of `IndexedDbLocalCache` to\n * turn on indexeddb cache. Calling this function when `FirestoreSettings.cache`\n * is already specified will throw an exception.\n */ function Dh(t) {\n Bh(t = uh(t, vh));\n const e = bh(t);\n if (e._uninitializedComponentsProvider) throw new U(q.FAILED_PRECONDITION, \"SDK cache is already specified.\");\n M(\"enableMultiTabIndexedDbPersistence() will be deprecated in the future, you can use `FirestoreSettings.cache` instead.\");\n const n = t._freezeSettings(), s = new Pa;\n return Ch(e, s, new Ra(s, n.cacheSizeBytes));\n}\n\n/**\n * Registers both the `OfflineComponentProvider` and `OnlineComponentProvider`.\n * If the operation fails with a recoverable error (see\n * `canRecoverFromIndexedDbError()` below), the returned Promise is rejected\n * but the client remains usable.\n */ function Ch(t, e, n) {\n const s = new K;\n return t.asyncQueue.enqueue((async () => {\n try {\n await Na(t, n), await ka(t, e), s.resolve();\n } catch (t) {\n const e = t;\n if (!Ma(e)) throw e;\n M(\"Error enabling indexeddb cache. Falling back to memory cache: \" + e), s.reject(e);\n }\n })).then((() => s.promise));\n}\n\n/**\n * Clears the persistent storage. This includes pending writes and cached\n * documents.\n *\n * Must be called while the {@link Firestore} instance is not started (after the app is\n * terminated or when the app is first initialized). On startup, this function\n * must be called before other functions (other than {@link\n * initializeFirestore} or {@link (getFirestore:1)})). If the {@link Firestore}\n * instance is still running, the promise will be rejected with the error code\n * of `failed-precondition`.\n *\n * Note: `clearIndexedDbPersistence()` is primarily intended to help write\n * reliable tests that use Cloud Firestore. It uses an efficient mechanism for\n * dropping existing data but does not attempt to securely overwrite or\n * otherwise make cached data unrecoverable. For applications that are sensitive\n * to the disclosure of cached data in between user sessions, we strongly\n * recommend not enabling persistence at all.\n *\n * @param firestore - The {@link Firestore} instance to clear persistence for.\n * @returns A `Promise` that is resolved when the persistent storage is\n * cleared. Otherwise, the promise is rejected with an error.\n */ function xh(t) {\n if (t._initialized && !t._terminated) throw new U(q.FAILED_PRECONDITION, \"Persistence can only be cleared before a Firestore instance is initialized or after it is terminated.\");\n const e = new K;\n return t._queue.enqueueAndForgetEvenWhileRestricted((async () => {\n try {\n await async function(t) {\n if (!bt.D()) return Promise.resolve();\n const e = t + \"main\";\n await bt.delete(e);\n }(Zo(t._databaseId, t._persistenceKey)), e.resolve();\n } catch (t) {\n e.reject(t);\n }\n })), e.promise;\n}\n\n/**\n * Waits until all currently pending writes for the active user have been\n * acknowledged by the backend.\n *\n * The returned promise resolves immediately if there are no outstanding writes.\n * Otherwise, the promise waits for all previously issued writes (including\n * those written in a previous app session), but it does not wait for writes\n * that were added after the function is called. If you want to wait for\n * additional writes, call `waitForPendingWrites()` again.\n *\n * Any outstanding `waitForPendingWrites()` promises are rejected during user\n * changes.\n *\n * @returns A `Promise` which resolves when all currently pending writes have been\n * acknowledged by the backend.\n */ function Nh(t) {\n return function(t) {\n const e = new K;\n return t.asyncQueue.enqueueAndForget((async () => Zc(await qa(t), e))), e.promise;\n }(bh(t = uh(t, vh)));\n}\n\n/**\n * Re-enables use of the network for this {@link Firestore} instance after a prior\n * call to {@link disableNetwork}.\n *\n * @returns A `Promise` that is resolved once the network has been enabled.\n */ function kh(t) {\n return Ga(bh(t = uh(t, vh)));\n}\n\n/**\n * Disables network usage for this instance. It can be re-enabled via {@link\n * enableNetwork}. While the network is disabled, any snapshot listeners,\n * `getDoc()` or `getDocs()` calls will return results from cache, and any write\n * operations will be queued until the network is restored.\n *\n * @returns A `Promise` that is resolved once the network has been disabled.\n */ function Mh(t) {\n return Qa(bh(t = uh(t, vh)));\n}\n\n/**\n * Terminates the provided {@link Firestore} instance.\n *\n * After calling `terminate()` only the `clearIndexedDbPersistence()` function\n * may be used. Any other function will throw a `FirestoreError`.\n *\n * To restart after termination, create a new instance of FirebaseFirestore with\n * {@link (getFirestore:1)}.\n *\n * Termination does not cancel any pending writes, and any promises that are\n * awaiting a response from the server will not be resolved. If you have\n * persistence enabled, the next time you start this instance, it will resume\n * sending these writes to the server.\n *\n * Note: Under normal circumstances, calling `terminate()` is not required. This\n * function is useful only when you want to force this instance to release all\n * of its resources or in combination with `clearIndexedDbPersistence()` to\n * ensure that all local state is destroyed between test runs.\n *\n * @returns A `Promise` that is resolved when the instance has been successfully\n * terminated.\n */ function $h(t) {\n return _removeServiceInstance(t.app, \"firestore\", t._databaseId.database), t._delete();\n}\n\n/**\n * Loads a Firestore bundle into the local cache.\n *\n * @param firestore - The {@link Firestore} instance to load bundles for.\n * @param bundleData - An object representing the bundle to be loaded. Valid\n * objects are `ArrayBuffer`, `ReadableStream` or `string`.\n *\n * @returns A `LoadBundleTask` object, which notifies callers with progress\n * updates, and completion or error events. It can be used as a\n * `Promise`.\n */ function Oh(t, e) {\n const n = bh(t = uh(t, vh)), s = new Eh;\n return Ya(n, t._databaseId, e, s), s;\n}\n\n/**\n * Reads a Firestore {@link Query} from local cache, identified by the given\n * name.\n *\n * The named queries are packaged into bundles on the server side (along\n * with resulting documents), and loaded to local cache using `loadBundle`. Once\n * in local cache, use this method to extract a {@link Query} by name.\n *\n * @param firestore - The {@link Firestore} instance to read the query from.\n * @param name - The name of the query.\n * @returns A `Promise` that is resolved with the Query or `null`.\n */ function Fh(t, e) {\n return Xa(bh(t = uh(t, vh)), e).then((e => e ? new dh(t, null, e.query) : null));\n}\n\nfunction Bh(t) {\n if (t._initialized || t._terminated) throw new U(q.FAILED_PRECONDITION, \"Firestore has already been started and persistence can no longer be enabled. You can only enable persistence before calling any other methods on a Firestore object.\");\n}\n\n/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * @license\n * Copyright 2022 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * Represents an aggregation that can be performed by Firestore.\n */\n// eslint-disable-next-line @typescript-eslint/no-unused-vars\nclass Lh {\n /**\n * Create a new AggregateField\n * @param _aggregateType Specifies the type of aggregation operation to perform.\n * @param _internalFieldPath Optionally specifies the field that is aggregated.\n * @internal\n */\n constructor(\n // TODO (sum/avg) make aggregateType public when the feature is supported\n t = \"count\", e) {\n this._aggregateType = t, this._internalFieldPath = e, \n /** A type string to uniquely identify instances of this class. */\n this.type = \"AggregateField\";\n }\n}\n\n/**\n * The results of executing an aggregation query.\n */ class qh {\n /** @hideconstructor */\n constructor(t, e, n) {\n this._userDataWriter = e, this._data = n, \n /** A type string to uniquely identify instances of this class. */\n this.type = \"AggregateQuerySnapshot\", this.query = t;\n }\n /**\n * Returns the results of the aggregations performed over the underlying\n * query.\n *\n * The keys of the returned object will be the same as those of the\n * `AggregateSpec` object specified to the aggregation method, and the values\n * will be the corresponding aggregation result.\n *\n * @returns The results of the aggregations performed over the underlying\n * query.\n */ data() {\n return this._userDataWriter.convertObjectMap(this._data);\n }\n}\n\n/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * An immutable object representing an array of bytes.\n */ class Uh {\n /** @hideconstructor */\n constructor(t) {\n this._byteString = t;\n }\n /**\n * Creates a new `Bytes` object from the given Base64 string, converting it to\n * bytes.\n *\n * @param base64 - The Base64 string used to create the `Bytes` object.\n */ static fromBase64String(t) {\n try {\n return new Uh(Ve.fromBase64String(t));\n } catch (t) {\n throw new U(q.INVALID_ARGUMENT, \"Failed to construct data from Base64 string: \" + t);\n }\n }\n /**\n * Creates a new `Bytes` object from the given Uint8Array.\n *\n * @param array - The Uint8Array used to create the `Bytes` object.\n */ static fromUint8Array(t) {\n return new Uh(Ve.fromUint8Array(t));\n }\n /**\n * Returns the underlying bytes as a Base64-encoded string.\n *\n * @returns The Base64-encoded string created from the `Bytes` object.\n */ toBase64() {\n return this._byteString.toBase64();\n }\n /**\n * Returns the underlying bytes in a new `Uint8Array`.\n *\n * @returns The Uint8Array created from the `Bytes` object.\n */ toUint8Array() {\n return this._byteString.toUint8Array();\n }\n /**\n * Returns a string representation of the `Bytes` object.\n *\n * @returns A string representation of the `Bytes` object.\n */ toString() {\n return \"Bytes(base64: \" + this.toBase64() + \")\";\n }\n /**\n * Returns true if this `Bytes` object is equal to the provided one.\n *\n * @param other - The `Bytes` object to compare against.\n * @returns true if this `Bytes` object is equal to the provided one.\n */ isEqual(t) {\n return this._byteString.isEqual(t._byteString);\n }\n}\n\n/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * A `FieldPath` refers to a field in a document. The path may consist of a\n * single field name (referring to a top-level field in the document), or a\n * list of field names (referring to a nested field in the document).\n *\n * Create a `FieldPath` by providing field names. If more than one field\n * name is provided, the path will point to a nested field in a document.\n */ class Kh {\n /**\n * Creates a `FieldPath` from the provided field names. If more than one field\n * name is provided, the path will point to a nested field in a document.\n *\n * @param fieldNames - A list of field names.\n */\n constructor(...t) {\n for (let e = 0; e < t.length; ++e) if (0 === t[e].length) throw new U(q.INVALID_ARGUMENT, \"Invalid field name at argument $(i + 1). Field names must not be empty.\");\n this._internalPath = new at(t);\n }\n /**\n * Returns true if this `FieldPath` is equal to the provided one.\n *\n * @param other - The `FieldPath` to compare against.\n * @returns true if this `FieldPath` is equal to the provided one.\n */ isEqual(t) {\n return this._internalPath.isEqual(t._internalPath);\n }\n}\n\n/**\n * Returns a special sentinel `FieldPath` to refer to the ID of a document.\n * It can be used in queries to sort or filter by the document ID.\n */ function Gh() {\n return new Kh(\"__name__\");\n}\n\n/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * Sentinel values that can be used when writing document fields with `set()`\n * or `update()`.\n */ class Qh {\n /**\n * @param _methodName - The public API endpoint that returns this class.\n * @hideconstructor\n */\n constructor(t) {\n this._methodName = t;\n }\n}\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * An immutable object representing a geographic location in Firestore. The\n * location is represented as latitude/longitude pair.\n *\n * Latitude values are in the range of [-90, 90].\n * Longitude values are in the range of [-180, 180].\n */ class jh {\n /**\n * Creates a new immutable `GeoPoint` object with the provided latitude and\n * longitude values.\n * @param latitude - The latitude as number between -90 and 90.\n * @param longitude - The longitude as number between -180 and 180.\n */\n constructor(t, e) {\n if (!isFinite(t) || t < -90 || t > 90) throw new U(q.INVALID_ARGUMENT, \"Latitude must be a number between -90 and 90, but was: \" + t);\n if (!isFinite(e) || e < -180 || e > 180) throw new U(q.INVALID_ARGUMENT, \"Longitude must be a number between -180 and 180, but was: \" + e);\n this._lat = t, this._long = e;\n }\n /**\n * The latitude of this `GeoPoint` instance.\n */ get latitude() {\n return this._lat;\n }\n /**\n * The longitude of this `GeoPoint` instance.\n */ get longitude() {\n return this._long;\n }\n /**\n * Returns true if this `GeoPoint` is equal to the provided one.\n *\n * @param other - The `GeoPoint` to compare against.\n * @returns true if this `GeoPoint` is equal to the provided one.\n */ isEqual(t) {\n return this._lat === t._lat && this._long === t._long;\n }\n /** Returns a JSON-serializable representation of this GeoPoint. */ toJSON() {\n return {\n latitude: this._lat,\n longitude: this._long\n };\n }\n /**\n * Actually private to JS consumers of our API, so this function is prefixed\n * with an underscore.\n */ _compareTo(t) {\n return et(this._lat, t._lat) || et(this._long, t._long);\n }\n}\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */ const zh = /^__.*__$/;\n\n/** The result of parsing document data (e.g. for a setData call). */ class Wh {\n constructor(t, e, n) {\n this.data = t, this.fieldMask = e, this.fieldTransforms = n;\n }\n toMutation(t, e) {\n return null !== this.fieldMask ? new zs(t, this.data, this.fieldMask, e, this.fieldTransforms) : new js(t, this.data, e, this.fieldTransforms);\n }\n}\n\n/** The result of parsing \"update\" data (i.e. for an updateData call). */ class Hh {\n constructor(t, \n // The fieldMask does not include document transforms.\n e, n) {\n this.data = t, this.fieldMask = e, this.fieldTransforms = n;\n }\n toMutation(t, e) {\n return new zs(t, this.data, this.fieldMask, e, this.fieldTransforms);\n }\n}\n\nfunction Jh(t) {\n switch (t) {\n case 0 /* UserDataSource.Set */ :\n // fall through\n case 2 /* UserDataSource.MergeSet */ :\n // fall through\n case 1 /* UserDataSource.Update */ :\n return !0;\n\n case 3 /* UserDataSource.Argument */ :\n case 4 /* UserDataSource.ArrayArgument */ :\n return !1;\n\n default:\n throw O();\n }\n}\n\n/** A \"context\" object passed around while parsing user data. */ class Yh {\n /**\n * Initializes a ParseContext with the given source and path.\n *\n * @param settings - The settings for the parser.\n * @param databaseId - The database ID of the Firestore instance.\n * @param serializer - The serializer to use to generate the Value proto.\n * @param ignoreUndefinedProperties - Whether to ignore undefined properties\n * rather than throw.\n * @param fieldTransforms - A mutable list of field transforms encountered\n * while parsing the data.\n * @param fieldMask - A mutable list of field paths encountered while parsing\n * the data.\n *\n * TODO(b/34871131): We don't support array paths right now, so path can be\n * null to indicate the context represents any location within an array (in\n * which case certain features will not work and errors will be somewhat\n * compromised).\n */\n constructor(t, e, n, s, i, r) {\n this.settings = t, this.databaseId = e, this.serializer = n, this.ignoreUndefinedProperties = s, \n // Minor hack: If fieldTransforms is undefined, we assume this is an\n // external call and we need to validate the entire path.\n void 0 === i && this.ua(), this.fieldTransforms = i || [], this.fieldMask = r || [];\n }\n get path() {\n return this.settings.path;\n }\n get ca() {\n return this.settings.ca;\n }\n /** Returns a new context with the specified settings overwritten. */ aa(t) {\n return new Yh(Object.assign(Object.assign({}, this.settings), t), this.databaseId, this.serializer, this.ignoreUndefinedProperties, this.fieldTransforms, this.fieldMask);\n }\n ha(t) {\n var e;\n const n = null === (e = this.path) || void 0 === e ? void 0 : e.child(t), s = this.aa({\n path: n,\n la: !1\n });\n return s.fa(t), s;\n }\n da(t) {\n var e;\n const n = null === (e = this.path) || void 0 === e ? void 0 : e.child(t), s = this.aa({\n path: n,\n la: !1\n });\n return s.ua(), s;\n }\n wa(t) {\n // TODO(b/34871131): We don't support array paths right now; so make path\n // undefined.\n return this.aa({\n path: void 0,\n la: !0\n });\n }\n _a(t) {\n return gl(t, this.settings.methodName, this.settings.ma || !1, this.path, this.settings.ga);\n }\n /** Returns 'true' if 'fieldPath' was traversed when creating this context. */ contains(t) {\n return void 0 !== this.fieldMask.find((e => t.isPrefixOf(e))) || void 0 !== this.fieldTransforms.find((e => t.isPrefixOf(e.field)));\n }\n ua() {\n // TODO(b/34871131): Remove null check once we have proper paths for fields\n // within arrays.\n if (this.path) for (let t = 0; t < this.path.length; t++) this.fa(this.path.get(t));\n }\n fa(t) {\n if (0 === t.length) throw this._a(\"Document fields must not be empty\");\n if (Jh(this.ca) && zh.test(t)) throw this._a('Document fields cannot begin and end with \"__\"');\n }\n}\n\n/**\n * Helper for parsing raw user input (provided via the API) into internal model\n * classes.\n */ class Xh {\n constructor(t, e, n) {\n this.databaseId = t, this.ignoreUndefinedProperties = e, this.serializer = n || Fu(t);\n }\n /** Creates a new top-level parse context. */ ya(t, e, n, s = !1) {\n return new Yh({\n ca: t,\n methodName: e,\n ga: n,\n path: at.emptyPath(),\n la: !1,\n ma: s\n }, this.databaseId, this.serializer, this.ignoreUndefinedProperties);\n }\n}\n\nfunction Zh(t) {\n const e = t._freezeSettings(), n = Fu(t._databaseId);\n return new Xh(t._databaseId, !!e.ignoreUndefinedProperties, n);\n}\n\n/** Parse document data from a set() call. */ function tl(t, e, n, s, i, r = {}) {\n const o = t.ya(r.merge || r.mergeFields ? 2 /* UserDataSource.MergeSet */ : 0 /* UserDataSource.Set */ , e, n, i);\n dl(\"Data must be an object, but it was:\", o, s);\n const u = ll(s, o);\n let c, a;\n if (r.merge) c = new Re(o.fieldMask), a = o.fieldTransforms; else if (r.mergeFields) {\n const t = [];\n for (const s of r.mergeFields) {\n const i = wl(e, s, n);\n if (!o.contains(i)) throw new U(q.INVALID_ARGUMENT, `Field '${i}' is specified in your field mask but missing from your input data.`);\n yl(t, i) || t.push(i);\n }\n c = new Re(t), a = o.fieldTransforms.filter((t => c.covers(t.field)));\n } else c = null, a = o.fieldTransforms;\n return new Wh(new un(u), c, a);\n}\n\nclass el extends Qh {\n _toFieldTransform(t) {\n if (2 /* UserDataSource.MergeSet */ !== t.ca) throw 1 /* UserDataSource.Update */ === t.ca ? t._a(`${this._methodName}() can only appear at the top level of your update data`) : t._a(`${this._methodName}() cannot be used with set() unless you pass {merge:true}`);\n // No transform to add for a delete, but we need to add it to our\n // fieldMask so it gets deleted.\n return t.fieldMask.push(t.path), null;\n }\n isEqual(t) {\n return t instanceof el;\n }\n}\n\n/**\n * Creates a child context for parsing SerializableFieldValues.\n *\n * This is different than calling `ParseContext.contextWith` because it keeps\n * the fieldTransforms and fieldMask separate.\n *\n * The created context has its `dataSource` set to `UserDataSource.Argument`.\n * Although these values are used with writes, any elements in these FieldValues\n * are not considered writes since they cannot contain any FieldValue sentinels,\n * etc.\n *\n * @param fieldValue - The sentinel FieldValue for which to create a child\n * context.\n * @param context - The parent context.\n * @param arrayElement - Whether or not the FieldValue has an array.\n */ function nl(t, e, n) {\n return new Yh({\n ca: 3 /* UserDataSource.Argument */ ,\n ga: e.settings.ga,\n methodName: t._methodName,\n la: n\n }, e.databaseId, e.serializer, e.ignoreUndefinedProperties);\n}\n\nclass sl extends Qh {\n _toFieldTransform(t) {\n return new Ms(t.path, new bs);\n }\n isEqual(t) {\n return t instanceof sl;\n }\n}\n\nclass il extends Qh {\n constructor(t, e) {\n super(t), this.pa = e;\n }\n _toFieldTransform(t) {\n const e = nl(this, t, \n /*array=*/ !0), n = this.pa.map((t => hl(t, e))), s = new Vs(n);\n return new Ms(t.path, s);\n }\n isEqual(t) {\n // TODO(mrschmidt): Implement isEquals\n return this === t;\n }\n}\n\nclass rl extends Qh {\n constructor(t, e) {\n super(t), this.pa = e;\n }\n _toFieldTransform(t) {\n const e = nl(this, t, \n /*array=*/ !0), n = this.pa.map((t => hl(t, e))), s = new Ds(n);\n return new Ms(t.path, s);\n }\n isEqual(t) {\n // TODO(mrschmidt): Implement isEquals\n return this === t;\n }\n}\n\nclass ol extends Qh {\n constructor(t, e) {\n super(t), this.Ia = e;\n }\n _toFieldTransform(t) {\n const e = new xs(t.serializer, Es(t.serializer, this.Ia));\n return new Ms(t.path, e);\n }\n isEqual(t) {\n // TODO(mrschmidt): Implement isEquals\n return this === t;\n }\n}\n\n/** Parse update data from an update() call. */ function ul(t, e, n, s) {\n const i = t.ya(1 /* UserDataSource.Update */ , e, n);\n dl(\"Data must be an object, but it was:\", i, s);\n const r = [], o = un.empty();\n ge(s, ((t, s) => {\n const u = ml(e, t, n);\n // For Compat types, we have to \"extract\" the underlying types before\n // performing validation.\n s = getModularInstance(s);\n const c = i.da(u);\n if (s instanceof el) \n // Add it to the field mask, but don't add anything to updateData.\n r.push(u); else {\n const t = hl(s, c);\n null != t && (r.push(u), o.set(u, t));\n }\n }));\n const u = new Re(r);\n return new Hh(o, u, i.fieldTransforms);\n}\n\n/** Parse update data from a list of field/value arguments. */ function cl(t, e, n, s, i, r) {\n const o = t.ya(1 /* UserDataSource.Update */ , e, n), u = [ wl(e, s, n) ], c = [ i ];\n if (r.length % 2 != 0) throw new U(q.INVALID_ARGUMENT, `Function ${e}() needs to be called with an even number of arguments that alternate between field names and values.`);\n for (let t = 0; t < r.length; t += 2) u.push(wl(e, r[t])), c.push(r[t + 1]);\n const a = [], h = un.empty();\n // We iterate in reverse order to pick the last value for a field if the\n // user specified the field multiple times.\n for (let t = u.length - 1; t >= 0; --t) if (!yl(a, u[t])) {\n const e = u[t];\n let n = c[t];\n // For Compat types, we have to \"extract\" the underlying types before\n // performing validation.\n n = getModularInstance(n);\n const s = o.da(e);\n if (n instanceof el) \n // Add it to the field mask, but don't add anything to updateData.\n a.push(e); else {\n const t = hl(n, s);\n null != t && (a.push(e), h.set(e, t));\n }\n }\n const l = new Re(a);\n return new Hh(h, l, o.fieldTransforms);\n}\n\n/**\n * Parse a \"query value\" (e.g. value in a where filter or a value in a cursor\n * bound).\n *\n * @param allowArrays - Whether the query value is an array that may directly\n * contain additional arrays (e.g. the operand of an `in` query).\n */ function al(t, e, n, s = !1) {\n return hl(n, t.ya(s ? 4 /* UserDataSource.ArrayArgument */ : 3 /* UserDataSource.Argument */ , e));\n}\n\n/**\n * Parses user data to Protobuf Values.\n *\n * @param input - Data to be parsed.\n * @param context - A context object representing the current path being parsed,\n * the source of the data being parsed, etc.\n * @returns The parsed value, or null if the value was a FieldValue sentinel\n * that should not be included in the resulting parsed data.\n */ function hl(t, e) {\n if (fl(\n // Unwrap the API type from the Compat SDK. This will return the API type\n // from firestore-exp.\n t = getModularInstance(t))) return dl(\"Unsupported field value:\", e, t), ll(t, e);\n if (t instanceof Qh) \n // FieldValues usually parse into transforms (except deleteField())\n // in which case we do not want to include this field in our parsed data\n // (as doing so will overwrite the field directly prior to the transform\n // trying to transform it). So we don't add this location to\n // context.fieldMask and we return null as our parsing result.\n /**\n * \"Parses\" the provided FieldValueImpl, adding any necessary transforms to\n * context.fieldTransforms.\n */\n return function(t, e) {\n // Sentinels are only supported with writes, and not within arrays.\n if (!Jh(e.ca)) throw e._a(`${t._methodName}() can only be used with update() and set()`);\n if (!e.path) throw e._a(`${t._methodName}() is not currently supported inside arrays`);\n const n = t._toFieldTransform(e);\n n && e.fieldTransforms.push(n);\n }\n /**\n * Helper to parse a scalar value (i.e. not an Object, Array, or FieldValue)\n *\n * @returns The parsed value\n */ (t, e), null;\n if (void 0 === t && e.ignoreUndefinedProperties) \n // If the input is undefined it can never participate in the fieldMask, so\n // don't handle this below. If `ignoreUndefinedProperties` is false,\n // `parseScalarValue` will reject an undefined value.\n return null;\n if (\n // If context.path is null we are inside an array and we don't support\n // field mask paths more granular than the top-level array.\n e.path && e.fieldMask.push(e.path), t instanceof Array) {\n // TODO(b/34871131): Include the path containing the array in the error\n // message.\n // In the case of IN queries, the parsed data is an array (representing\n // the set of values to be included for the IN query) that may directly\n // contain additional arrays (each representing an individual field\n // value), so we disable this validation.\n if (e.settings.la && 4 /* UserDataSource.ArrayArgument */ !== e.ca) throw e._a(\"Nested arrays are not supported\");\n return function(t, e) {\n const n = [];\n let s = 0;\n for (const i of t) {\n let t = hl(i, e.wa(s));\n null == t && (\n // Just include nulls in the array for fields being replaced with a\n // sentinel.\n t = {\n nullValue: \"NULL_VALUE\"\n }), n.push(t), s++;\n }\n return {\n arrayValue: {\n values: n\n }\n };\n }(t, e);\n }\n return function(t, e) {\n if (null === (t = getModularInstance(t))) return {\n nullValue: \"NULL_VALUE\"\n };\n if (\"number\" == typeof t) return Es(e.serializer, t);\n if (\"boolean\" == typeof t) return {\n booleanValue: t\n };\n if (\"string\" == typeof t) return {\n stringValue: t\n };\n if (t instanceof Date) {\n const n = it.fromDate(t);\n return {\n timestampValue: Di(e.serializer, n)\n };\n }\n if (t instanceof it) {\n // Firestore backend truncates precision down to microseconds. To ensure\n // offline mode works the same with regards to truncation, perform the\n // truncation immediately without waiting for the backend to do that.\n const n = new it(t.seconds, 1e3 * Math.floor(t.nanoseconds / 1e3));\n return {\n timestampValue: Di(e.serializer, n)\n };\n }\n if (t instanceof jh) return {\n geoPointValue: {\n latitude: t.latitude,\n longitude: t.longitude\n }\n };\n if (t instanceof Uh) return {\n bytesValue: Ci(e.serializer, t._byteString)\n };\n if (t instanceof fh) {\n const n = e.databaseId, s = t.firestore._databaseId;\n if (!s.isEqual(n)) throw e._a(`Document reference is for database ${s.projectId}/${s.database} but should be for database ${n.projectId}/${n.database}`);\n return {\n referenceValue: ki(t.firestore._databaseId || e.databaseId, t._key.path)\n };\n }\n throw e._a(`Unsupported field value: ${oh(t)}`);\n }\n /**\n * Checks whether an object looks like a JSON object that should be converted\n * into a struct. Normal class/prototype instances are considered to look like\n * JSON objects since they should be converted to a struct value. Arrays, Dates,\n * GeoPoints, etc. are not considered to look like JSON objects since they map\n * to specific FieldValue types other than ObjectValue.\n */ (t, e);\n}\n\nfunction ll(t, e) {\n const n = {};\n return ye(t) ? \n // If we encounter an empty object, we explicitly add it to the update\n // mask to ensure that the server creates a map entry.\n e.path && e.path.length > 0 && e.fieldMask.push(e.path) : ge(t, ((t, s) => {\n const i = hl(s, e.ha(t));\n null != i && (n[t] = i);\n })), {\n mapValue: {\n fields: n\n }\n };\n}\n\nfunction fl(t) {\n return !(\"object\" != typeof t || null === t || t instanceof Array || t instanceof Date || t instanceof it || t instanceof jh || t instanceof Uh || t instanceof fh || t instanceof Qh);\n}\n\nfunction dl(t, e, n) {\n if (!fl(n) || !function(t) {\n return \"object\" == typeof t && null !== t && (Object.getPrototypeOf(t) === Object.prototype || null === Object.getPrototypeOf(t));\n }(n)) {\n const s = oh(n);\n throw \"an object\" === s ? e._a(t + \" a custom object\") : e._a(t + \" \" + s);\n }\n}\n\n/**\n * Helper that calls fromDotSeparatedString() but wraps any error thrown.\n */ function wl(t, e, n) {\n if ((\n // If required, replace the FieldPath Compat class with with the firestore-exp\n // FieldPath.\n e = getModularInstance(e)) instanceof Kh) return e._internalPath;\n if (\"string\" == typeof e) return ml(t, e);\n throw gl(\"Field path arguments must be of type string or \", t, \n /* hasConverter= */ !1, \n /* path= */ void 0, n);\n}\n\n/**\n * Matches any characters in a field path string that are reserved.\n */ const _l = new RegExp(\"[~\\\\*/\\\\[\\\\]]\");\n\n/**\n * Wraps fromDotSeparatedString with an error message about the method that\n * was thrown.\n * @param methodName - The publicly visible method name\n * @param path - The dot-separated string form of a field path which will be\n * split on dots.\n * @param targetDoc - The document against which the field path will be\n * evaluated.\n */ function ml(t, e, n) {\n if (e.search(_l) >= 0) throw gl(`Invalid field path (${e}). Paths must not contain '~', '*', '/', '[', or ']'`, t, \n /* hasConverter= */ !1, \n /* path= */ void 0, n);\n try {\n return new Kh(...e.split(\".\"))._internalPath;\n } catch (s) {\n throw gl(`Invalid field path (${e}). Paths must not be empty, begin with '.', end with '.', or contain '..'`, t, \n /* hasConverter= */ !1, \n /* path= */ void 0, n);\n }\n}\n\nfunction gl(t, e, n, s, i) {\n const r = s && !s.isEmpty(), o = void 0 !== i;\n let u = `Function ${e}() called with invalid data`;\n n && (u += \" (via `toFirestore()`)\"), u += \". \";\n let c = \"\";\n return (r || o) && (c += \" (found\", r && (c += ` in field ${s}`), o && (c += ` in document ${i}`), \n c += \")\"), new U(q.INVALID_ARGUMENT, u + t + c);\n}\n\n/** Checks `haystack` if FieldPath `needle` is present. Runs in O(n). */ function yl(t, e) {\n return t.some((t => t.isEqual(e)));\n}\n\n/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * A `DocumentSnapshot` contains data read from a document in your Firestore\n * database. The data can be extracted with `.data()` or `.get()` to\n * get a specific field.\n *\n * For a `DocumentSnapshot` that points to a non-existing document, any data\n * access will return 'undefined'. You can use the `exists()` method to\n * explicitly verify a document's existence.\n */ class pl {\n // Note: This class is stripped down version of the DocumentSnapshot in\n // the legacy SDK. The changes are:\n // - No support for SnapshotMetadata.\n // - No support for SnapshotOptions.\n /** @hideconstructor protected */\n constructor(t, e, n, s, i) {\n this._firestore = t, this._userDataWriter = e, this._key = n, this._document = s, \n this._converter = i;\n }\n /** Property of the `DocumentSnapshot` that provides the document's ID. */ get id() {\n return this._key.path.lastSegment();\n }\n /**\n * The `DocumentReference` for the document included in the `DocumentSnapshot`.\n */ get ref() {\n return new fh(this._firestore, this._converter, this._key);\n }\n /**\n * Signals whether or not the document at the snapshot's location exists.\n *\n * @returns true if the document exists.\n */ exists() {\n return null !== this._document;\n }\n /**\n * Retrieves all fields in the document as an `Object`. Returns `undefined` if\n * the document doesn't exist.\n *\n * @returns An `Object` containing all fields in the document or `undefined`\n * if the document doesn't exist.\n */ data() {\n if (this._document) {\n if (this._converter) {\n // We only want to use the converter and create a new DocumentSnapshot\n // if a converter has been provided.\n const t = new Il(this._firestore, this._userDataWriter, this._key, this._document, \n /* converter= */ null);\n return this._converter.fromFirestore(t);\n }\n return this._userDataWriter.convertValue(this._document.data.value);\n }\n }\n /**\n * Retrieves the field specified by `fieldPath`. Returns `undefined` if the\n * document or field doesn't exist.\n *\n * @param fieldPath - The path (for example 'foo' or 'foo.bar') to a specific\n * field.\n * @returns The data at the specified field location or undefined if no such\n * field exists in the document.\n */\n // We are using `any` here to avoid an explicit cast by our users.\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n get(t) {\n if (this._document) {\n const e = this._document.data.field(Tl(\"DocumentSnapshot.get\", t));\n if (null !== e) return this._userDataWriter.convertValue(e);\n }\n }\n}\n\n/**\n * A `QueryDocumentSnapshot` contains data read from a document in your\n * Firestore database as part of a query. The document is guaranteed to exist\n * and its data can be extracted with `.data()` or `.get()` to get a\n * specific field.\n *\n * A `QueryDocumentSnapshot` offers the same API surface as a\n * `DocumentSnapshot`. Since query results contain only existing documents, the\n * `exists` property will always be true and `data()` will never return\n * 'undefined'.\n */ class Il extends pl {\n /**\n * Retrieves all fields in the document as an `Object`.\n *\n * @override\n * @returns An `Object` containing all fields in the document.\n */\n data() {\n return super.data();\n }\n}\n\n/**\n * Helper that calls `fromDotSeparatedString()` but wraps any error thrown.\n */ function Tl(t, e) {\n return \"string\" == typeof e ? ml(t, e) : e instanceof Kh ? e._internalPath : e._delegate._internalPath;\n}\n\n/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */ function El(t) {\n if (\"L\" /* LimitType.Last */ === t.limitType && 0 === t.explicitOrderBy.length) throw new U(q.UNIMPLEMENTED, \"limitToLast() queries require specifying at least one orderBy() clause\");\n}\n\n/**\n * An `AppliableConstraint` is an abstraction of a constraint that can be applied\n * to a Firestore query.\n */ class Al {}\n\n/**\n * A `QueryConstraint` is used to narrow the set of documents returned by a\n * Firestore query. `QueryConstraint`s are created by invoking {@link where},\n * {@link orderBy}, {@link (startAt:1)}, {@link (startAfter:1)}, {@link\n * (endBefore:1)}, {@link (endAt:1)}, {@link limit}, {@link limitToLast} and\n * can then be passed to {@link (query:1)} to create a new query instance that\n * also contains this `QueryConstraint`.\n */ class vl extends Al {}\n\nfunction Rl(t, e, ...n) {\n let s = [];\n e instanceof Al && s.push(e), s = s.concat(n), function(t) {\n const e = t.filter((t => t instanceof Vl)).length, n = t.filter((t => t instanceof Pl)).length;\n if (e > 1 || e > 0 && n > 0) throw new U(q.INVALID_ARGUMENT, \"InvalidQuery. When using composite filters, you cannot use more than one filter at the top level. Consider nesting the multiple filters within an `and(...)` statement. For example: change `query(query, where(...), or(...))` to `query(query, and(where(...), or(...)))`.\");\n }\n /**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n /**\n * Converts Firestore's internal types to the JavaScript types that we expose\n * to the user.\n *\n * @internal\n */ (s);\n for (const e of s) t = e._apply(t);\n return t;\n}\n\n/**\n * A `QueryFieldFilterConstraint` is used to narrow the set of documents returned by\n * a Firestore query by filtering on one or more document fields.\n * `QueryFieldFilterConstraint`s are created by invoking {@link where} and can then\n * be passed to {@link (query:1)} to create a new query instance that also contains\n * this `QueryFieldFilterConstraint`.\n */ class Pl extends vl {\n /**\n * @internal\n */\n constructor(t, e, n) {\n super(), this._field = t, this._op = e, this._value = n, \n /** The type of this query constraint */\n this.type = \"where\";\n }\n static _create(t, e, n) {\n return new Pl(t, e, n);\n }\n _apply(t) {\n const e = this._parse(t);\n return Ql(t._query, e), new dh(t.firestore, t.converter, Yn(t._query, e));\n }\n _parse(t) {\n const e = Zh(t.firestore), n = function(t, e, n, s, i, r, o) {\n let u;\n if (i.isKeyField()) {\n if (\"array-contains\" /* Operator.ARRAY_CONTAINS */ === r || \"array-contains-any\" /* Operator.ARRAY_CONTAINS_ANY */ === r) throw new U(q.INVALID_ARGUMENT, `Invalid Query. You can't perform '${r}' queries on documentId().`);\n if (\"in\" /* Operator.IN */ === r || \"not-in\" /* Operator.NOT_IN */ === r) {\n Gl(o, r);\n const e = [];\n for (const n of o) e.push(Kl(s, t, n));\n u = {\n arrayValue: {\n values: e\n }\n };\n } else u = Kl(s, t, o);\n } else \"in\" /* Operator.IN */ !== r && \"not-in\" /* Operator.NOT_IN */ !== r && \"array-contains-any\" /* Operator.ARRAY_CONTAINS_ANY */ !== r || Gl(o, r), \n u = al(n, e, o, \n /* allowArrays= */ \"in\" /* Operator.IN */ === r || \"not-in\" /* Operator.NOT_IN */ === r);\n return mn.create(i, r, u);\n }(t._query, \"where\", e, t.firestore._databaseId, this._field, this._op, this._value);\n return n;\n }\n}\n\n/**\n * Creates a {@link QueryFieldFilterConstraint} that enforces that documents\n * must contain the specified field and that the value should satisfy the\n * relation constraint provided.\n *\n * @param fieldPath - The path to compare\n * @param opStr - The operation string (e.g \"<\", \"<=\", \"==\", \"<\",\n * \"<=\", \"!=\").\n * @param value - The value for comparison\n * @returns The created {@link QueryFieldFilterConstraint}.\n */ function bl(t, e, n) {\n const s = e, i = Tl(\"where\", t);\n return Pl._create(i, s, n);\n}\n\n/**\n * A `QueryCompositeFilterConstraint` is used to narrow the set of documents\n * returned by a Firestore query by performing the logical OR or AND of multiple\n * {@link QueryFieldFilterConstraint}s or {@link QueryCompositeFilterConstraint}s.\n * `QueryCompositeFilterConstraint`s are created by invoking {@link or} or\n * {@link and} and can then be passed to {@link (query:1)} to create a new query\n * instance that also contains the `QueryCompositeFilterConstraint`.\n */ class Vl extends Al {\n /**\n * @internal\n */\n constructor(\n /** The type of this query constraint */\n t, e) {\n super(), this.type = t, this._queryConstraints = e;\n }\n static _create(t, e) {\n return new Vl(t, e);\n }\n _parse(t) {\n const e = this._queryConstraints.map((e => e._parse(t))).filter((t => t.getFilters().length > 0));\n return 1 === e.length ? e[0] : gn.create(e, this._getOperator());\n }\n _apply(t) {\n const e = this._parse(t);\n return 0 === e.getFilters().length ? t : (function(t, e) {\n let n = t;\n const s = e.getFlattenedFilters();\n for (const t of s) Ql(n, t), n = Yn(n, t);\n }\n // Checks if any of the provided filter operators are included in the given list of filters and\n // returns the first one that is, or null if none are.\n (t._query, e), new dh(t.firestore, t.converter, Yn(t._query, e)));\n }\n _getQueryConstraints() {\n return this._queryConstraints;\n }\n _getOperator() {\n return \"and\" === this.type ? \"and\" /* CompositeOperator.AND */ : \"or\" /* CompositeOperator.OR */;\n }\n}\n\n/**\n * Creates a new {@link QueryCompositeFilterConstraint} that is a disjunction of\n * the given filter constraints. A disjunction filter includes a document if it\n * satisfies any of the given filters.\n *\n * @param queryConstraints - Optional. The list of\n * {@link QueryFilterConstraint}s to perform a disjunction for. These must be\n * created with calls to {@link where}, {@link or}, or {@link and}.\n * @returns The newly created {@link QueryCompositeFilterConstraint}.\n */ function Sl(...t) {\n // Only support QueryFilterConstraints\n return t.forEach((t => zl(\"or\", t))), Vl._create(\"or\" /* CompositeOperator.OR */ , t);\n}\n\n/**\n * Creates a new {@link QueryCompositeFilterConstraint} that is a conjunction of\n * the given filter constraints. A conjunction filter includes a document if it\n * satisfies all of the given filters.\n *\n * @param queryConstraints - Optional. The list of\n * {@link QueryFilterConstraint}s to perform a conjunction for. These must be\n * created with calls to {@link where}, {@link or}, or {@link and}.\n * @returns The newly created {@link QueryCompositeFilterConstraint}.\n */ function Dl(...t) {\n // Only support QueryFilterConstraints\n return t.forEach((t => zl(\"and\", t))), Vl._create(\"and\" /* CompositeOperator.AND */ , t);\n}\n\n/**\n * A `QueryOrderByConstraint` is used to sort the set of documents returned by a\n * Firestore query. `QueryOrderByConstraint`s are created by invoking\n * {@link orderBy} and can then be passed to {@link (query:1)} to create a new query\n * instance that also contains this `QueryOrderByConstraint`.\n *\n * Note: Documents that do not contain the orderBy field will not be present in\n * the query result.\n */ class Cl extends vl {\n /**\n * @internal\n */\n constructor(t, e) {\n super(), this._field = t, this._direction = e, \n /** The type of this query constraint */\n this.type = \"orderBy\";\n }\n static _create(t, e) {\n return new Cl(t, e);\n }\n _apply(t) {\n const e = function(t, e, n) {\n if (null !== t.startAt) throw new U(q.INVALID_ARGUMENT, \"Invalid query. You must not call startAt() or startAfter() before calling orderBy().\");\n if (null !== t.endAt) throw new U(q.INVALID_ARGUMENT, \"Invalid query. You must not call endAt() or endBefore() before calling orderBy().\");\n const s = new dn(e, n);\n return function(t, e) {\n if (null === jn(t)) {\n // This is the first order by. It must match any inequality.\n const n = zn(t);\n null !== n && jl(t, n, e.field);\n }\n }(t, s), s;\n }\n /**\n * Create a `Bound` from a query and a document.\n *\n * Note that the `Bound` will always include the key of the document\n * and so only the provided document will compare equal to the returned\n * position.\n *\n * Will throw if the document does not contain all fields of the order by\n * of the query or if any of the fields in the order by are an uncommitted\n * server timestamp.\n */ (t._query, this._field, this._direction);\n return new dh(t.firestore, t.converter, function(t, e) {\n // TODO(dimond): validate that orderBy does not list the same key twice.\n const n = t.explicitOrderBy.concat([ e ]);\n return new Un(t.path, t.collectionGroup, n, t.filters.slice(), t.limit, t.limitType, t.startAt, t.endAt);\n }(t._query, e));\n }\n}\n\n/**\n * Creates a {@link QueryOrderByConstraint} that sorts the query result by the\n * specified field, optionally in descending order instead of ascending.\n *\n * Note: Documents that do not contain the specified field will not be present\n * in the query result.\n *\n * @param fieldPath - The field to sort by.\n * @param directionStr - Optional direction to sort by ('asc' or 'desc'). If\n * not specified, order will be ascending.\n * @returns The created {@link QueryOrderByConstraint}.\n */ function xl(t, e = \"asc\") {\n const n = e, s = Tl(\"orderBy\", t);\n return Cl._create(s, n);\n}\n\n/**\n * A `QueryLimitConstraint` is used to limit the number of documents returned by\n * a Firestore query.\n * `QueryLimitConstraint`s are created by invoking {@link limit} or\n * {@link limitToLast} and can then be passed to {@link (query:1)} to create a new\n * query instance that also contains this `QueryLimitConstraint`.\n */ class Nl extends vl {\n /**\n * @internal\n */\n constructor(\n /** The type of this query constraint */\n t, e, n) {\n super(), this.type = t, this._limit = e, this._limitType = n;\n }\n static _create(t, e, n) {\n return new Nl(t, e, n);\n }\n _apply(t) {\n return new dh(t.firestore, t.converter, Xn(t._query, this._limit, this._limitType));\n }\n}\n\n/**\n * Creates a {@link QueryLimitConstraint} that only returns the first matching\n * documents.\n *\n * @param limit - The maximum number of items to return.\n * @returns The created {@link QueryLimitConstraint}.\n */ function kl(t) {\n return ch(\"limit\", t), Nl._create(\"limit\", t, \"F\" /* LimitType.First */);\n}\n\n/**\n * Creates a {@link QueryLimitConstraint} that only returns the last matching\n * documents.\n *\n * You must specify at least one `orderBy` clause for `limitToLast` queries,\n * otherwise an exception will be thrown during execution.\n *\n * @param limit - The maximum number of items to return.\n * @returns The created {@link QueryLimitConstraint}.\n */ function Ml(t) {\n return ch(\"limitToLast\", t), Nl._create(\"limitToLast\", t, \"L\" /* LimitType.Last */);\n}\n\n/**\n * A `QueryStartAtConstraint` is used to exclude documents from the start of a\n * result set returned by a Firestore query.\n * `QueryStartAtConstraint`s are created by invoking {@link (startAt:1)} or\n * {@link (startAfter:1)} and can then be passed to {@link (query:1)} to create a\n * new query instance that also contains this `QueryStartAtConstraint`.\n */ class $l extends vl {\n /**\n * @internal\n */\n constructor(\n /** The type of this query constraint */\n t, e, n) {\n super(), this.type = t, this._docOrFields = e, this._inclusive = n;\n }\n static _create(t, e, n) {\n return new $l(t, e, n);\n }\n _apply(t) {\n const e = Ul(t, this.type, this._docOrFields, this._inclusive);\n return new dh(t.firestore, t.converter, function(t, e) {\n return new Un(t.path, t.collectionGroup, t.explicitOrderBy.slice(), t.filters.slice(), t.limit, t.limitType, e, t.endAt);\n }(t._query, e));\n }\n}\n\nfunction Ol(...t) {\n return $l._create(\"startAt\", t, \n /*inclusive=*/ !0);\n}\n\nfunction Fl(...t) {\n return $l._create(\"startAfter\", t, \n /*inclusive=*/ !1);\n}\n\n/**\n * A `QueryEndAtConstraint` is used to exclude documents from the end of a\n * result set returned by a Firestore query.\n * `QueryEndAtConstraint`s are created by invoking {@link (endAt:1)} or\n * {@link (endBefore:1)} and can then be passed to {@link (query:1)} to create a new\n * query instance that also contains this `QueryEndAtConstraint`.\n */ class Bl extends vl {\n /**\n * @internal\n */\n constructor(\n /** The type of this query constraint */\n t, e, n) {\n super(), this.type = t, this._docOrFields = e, this._inclusive = n;\n }\n static _create(t, e, n) {\n return new Bl(t, e, n);\n }\n _apply(t) {\n const e = Ul(t, this.type, this._docOrFields, this._inclusive);\n return new dh(t.firestore, t.converter, function(t, e) {\n return new Un(t.path, t.collectionGroup, t.explicitOrderBy.slice(), t.filters.slice(), t.limit, t.limitType, t.startAt, e);\n }(t._query, e));\n }\n}\n\nfunction Ll(...t) {\n return Bl._create(\"endBefore\", t, \n /*inclusive=*/ !1);\n}\n\nfunction ql(...t) {\n return Bl._create(\"endAt\", t, \n /*inclusive=*/ !0);\n}\n\n/** Helper function to create a bound from a document or fields */ function Ul(t, e, n, s) {\n if (n[0] = getModularInstance(n[0]), n[0] instanceof pl) return function(t, e, n, s, i) {\n if (!s) throw new U(q.NOT_FOUND, `Can't use a DocumentSnapshot that doesn't exist for ${n}().`);\n const r = [];\n // Because people expect to continue/end a query at the exact document\n // provided, we need to use the implicit sort order rather than the explicit\n // sort order, because it's guaranteed to contain the document key. That way\n // the position becomes unambiguous and the query continues/ends exactly at\n // the provided document. Without the key (by using the explicit sort\n // orders), multiple documents could match the position, yielding duplicate\n // results.\n for (const n of Hn(t)) if (n.field.isKeyField()) r.push(We(e, s.key)); else {\n const t = s.data.field(n.field);\n if (Ne(t)) throw new U(q.INVALID_ARGUMENT, 'Invalid query. You are trying to start or end a query using a document for which the field \"' + n.field + '\" is an uncommitted server timestamp. (Since the value of this field is unknown, you cannot start/end a query with it.)');\n if (null === t) {\n const t = n.field.canonicalString();\n throw new U(q.INVALID_ARGUMENT, `Invalid query. You are trying to start or end a query using a document for which the field '${t}' (used as the orderBy) does not exist.`);\n }\n r.push(t);\n }\n return new hn(r, i);\n }\n /**\n * Converts a list of field values to a `Bound` for the given query.\n */ (t._query, t.firestore._databaseId, e, n[0]._document, s);\n {\n const i = Zh(t.firestore);\n return function(t, e, n, s, i, r) {\n // Use explicit order by's because it has to match the query the user made\n const o = t.explicitOrderBy;\n if (i.length > o.length) throw new U(q.INVALID_ARGUMENT, `Too many arguments provided to ${s}(). The number of arguments must be less than or equal to the number of orderBy() clauses`);\n const u = [];\n for (let r = 0; r < i.length; r++) {\n const c = i[r];\n if (o[r].field.isKeyField()) {\n if (\"string\" != typeof c) throw new U(q.INVALID_ARGUMENT, `Invalid query. Expected a string for document ID in ${s}(), but got a ${typeof c}`);\n if (!Wn(t) && -1 !== c.indexOf(\"/\")) throw new U(q.INVALID_ARGUMENT, `Invalid query. When querying a collection and ordering by documentId(), the value passed to ${s}() must be a plain document ID, but '${c}' contains a slash.`);\n const n = t.path.child(ut.fromString(c));\n if (!ht.isDocumentKey(n)) throw new U(q.INVALID_ARGUMENT, `Invalid query. When querying a collection group and ordering by documentId(), the value passed to ${s}() must result in a valid document path, but '${n}' is not because it contains an odd number of segments.`);\n const i = new ht(n);\n u.push(We(e, i));\n } else {\n const t = al(n, s, c);\n u.push(t);\n }\n }\n return new hn(u, r);\n }\n /**\n * Parses the given `documentIdValue` into a `ReferenceValue`, throwing\n * appropriate errors if the value is anything other than a `DocumentReference`\n * or `string`, or if the string is malformed.\n */ (t._query, t.firestore._databaseId, i, e, n, s);\n }\n}\n\nfunction Kl(t, e, n) {\n if (\"string\" == typeof (n = getModularInstance(n))) {\n if (\"\" === n) throw new U(q.INVALID_ARGUMENT, \"Invalid query. When querying with documentId(), you must provide a valid document ID, but it was an empty string.\");\n if (!Wn(e) && -1 !== n.indexOf(\"/\")) throw new U(q.INVALID_ARGUMENT, `Invalid query. When querying a collection by documentId(), you must provide a plain document ID, but '${n}' contains a '/' character.`);\n const s = e.path.child(ut.fromString(n));\n if (!ht.isDocumentKey(s)) throw new U(q.INVALID_ARGUMENT, `Invalid query. When querying a collection group by documentId(), the value provided must result in a valid document path, but '${s}' is not because it has an odd number of segments (${s.length}).`);\n return We(t, new ht(s));\n }\n if (n instanceof fh) return We(t, n._key);\n throw new U(q.INVALID_ARGUMENT, `Invalid query. When querying with documentId(), you must provide a valid string or a DocumentReference, but it was: ${oh(n)}.`);\n}\n\n/**\n * Validates that the value passed into a disjunctive filter satisfies all\n * array requirements.\n */ function Gl(t, e) {\n if (!Array.isArray(t) || 0 === t.length) throw new U(q.INVALID_ARGUMENT, `Invalid Query. A non-empty array is required for '${e.toString()}' filters.`);\n}\n\n/**\n * Given an operator, returns the set of operators that cannot be used with it.\n *\n * This is not a comprehensive check, and this function should be removed in the\n * long term. Validations should occur in the Firestore backend.\n *\n * Operators in a query must adhere to the following set of rules:\n * 1. Only one inequality per query.\n * 2. `NOT_IN` cannot be used with array, disjunctive, or `NOT_EQUAL` operators.\n */ function Ql(t, e) {\n if (e.isInequality()) {\n const n = zn(t), s = e.field;\n if (null !== n && !n.isEqual(s)) throw new U(q.INVALID_ARGUMENT, `Invalid query. All where filters with an inequality (<, <=, !=, not-in, >, or >=) must be on the same field. But you have inequality filters on '${n.toString()}' and '${s.toString()}'`);\n const i = jn(t);\n null !== i && jl(t, s, i);\n }\n const n = function(t, e) {\n for (const n of t) for (const t of n.getFlattenedFilters()) if (e.indexOf(t.op) >= 0) return t.op;\n return null;\n }(t.filters, function(t) {\n switch (t) {\n case \"!=\" /* Operator.NOT_EQUAL */ :\n return [ \"!=\" /* Operator.NOT_EQUAL */ , \"not-in\" /* Operator.NOT_IN */ ];\n\n case \"array-contains-any\" /* Operator.ARRAY_CONTAINS_ANY */ :\n case \"in\" /* Operator.IN */ :\n return [ \"not-in\" /* Operator.NOT_IN */ ];\n\n case \"not-in\" /* Operator.NOT_IN */ :\n return [ \"array-contains-any\" /* Operator.ARRAY_CONTAINS_ANY */ , \"in\" /* Operator.IN */ , \"not-in\" /* Operator.NOT_IN */ , \"!=\" /* Operator.NOT_EQUAL */ ];\n\n default:\n return [];\n }\n }(e.op));\n if (null !== n) \n // Special case when it's a duplicate op to give a slightly clearer error message.\n throw n === e.op ? new U(q.INVALID_ARGUMENT, `Invalid query. You cannot use more than one '${e.op.toString()}' filter.`) : new U(q.INVALID_ARGUMENT, `Invalid query. You cannot use '${e.op.toString()}' filters with '${n.toString()}' filters.`);\n}\n\nfunction jl(t, e, n) {\n if (!n.isEqual(e)) throw new U(q.INVALID_ARGUMENT, `Invalid query. You have a where filter with an inequality (<, <=, !=, not-in, >, or >=) on field '${e.toString()}' and so you must also use '${e.toString()}' as your first argument to orderBy(), but your first orderBy() is on field '${n.toString()}' instead.`);\n}\n\nfunction zl(t, e) {\n if (!(e instanceof Pl || e instanceof Vl)) throw new U(q.INVALID_ARGUMENT, `Function ${t}() requires AppliableConstraints created with a call to 'where(...)', 'or(...)', or 'and(...)'.`);\n}\n\nclass Wl {\n convertValue(t, e = \"none\") {\n switch (Le(t)) {\n case 0 /* TypeOrder.NullValue */ :\n return null;\n\n case 1 /* TypeOrder.BooleanValue */ :\n return t.booleanValue;\n\n case 2 /* TypeOrder.NumberValue */ :\n return Ce(t.integerValue || t.doubleValue);\n\n case 3 /* TypeOrder.TimestampValue */ :\n return this.convertTimestamp(t.timestampValue);\n\n case 4 /* TypeOrder.ServerTimestampValue */ :\n return this.convertServerTimestamp(t, e);\n\n case 5 /* TypeOrder.StringValue */ :\n return t.stringValue;\n\n case 6 /* TypeOrder.BlobValue */ :\n return this.convertBytes(xe(t.bytesValue));\n\n case 7 /* TypeOrder.RefValue */ :\n return this.convertReference(t.referenceValue);\n\n case 8 /* TypeOrder.GeoPointValue */ :\n return this.convertGeoPoint(t.geoPointValue);\n\n case 9 /* TypeOrder.ArrayValue */ :\n return this.convertArray(t.arrayValue, e);\n\n case 10 /* TypeOrder.ObjectValue */ :\n return this.convertObject(t.mapValue, e);\n\n default:\n throw O();\n }\n }\n convertObject(t, e) {\n return this.convertObjectMap(t.fields, e);\n }\n /**\n * @internal\n */ convertObjectMap(t, e = \"none\") {\n const n = {};\n return ge(t, ((t, s) => {\n n[t] = this.convertValue(s, e);\n })), n;\n }\n convertGeoPoint(t) {\n return new jh(Ce(t.latitude), Ce(t.longitude));\n }\n convertArray(t, e) {\n return (t.values || []).map((t => this.convertValue(t, e)));\n }\n convertServerTimestamp(t, e) {\n switch (e) {\n case \"previous\":\n const n = ke(t);\n return null == n ? null : this.convertValue(n, e);\n\n case \"estimate\":\n return this.convertTimestamp(Me(t));\n\n default:\n return null;\n }\n }\n convertTimestamp(t) {\n const e = De(t);\n return new it(e.seconds, e.nanos);\n }\n convertDocumentKey(t, e) {\n const n = ut.fromString(t);\n F(ur(n));\n const s = new Oe(n.get(1), n.get(3)), i = new ht(n.popFirst(5));\n return s.isEqual(e) || \n // TODO(b/64130202): Somehow support foreign references.\n k(`Document ${i} contains a document reference within a different database (${s.projectId}/${s.database}) which is not supported. It will be treated as a reference in the current database (${e.projectId}/${e.database}) instead.`), \n i;\n }\n}\n\n/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * Converts custom model object of type T into `DocumentData` by applying the\n * converter if it exists.\n *\n * This function is used when converting user objects to `DocumentData`\n * because we want to provide the user with a more specific error message if\n * their `set()` or fails due to invalid data originating from a `toFirestore()`\n * call.\n */ function Hl(t, e, n) {\n let s;\n // Cast to `any` in order to satisfy the union type constraint on\n // toFirestore().\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n return s = t ? n && (n.merge || n.mergeFields) ? t.toFirestore(e, n) : t.toFirestore(e) : e, \n s;\n}\n\nclass Jl extends Wl {\n constructor(t) {\n super(), this.firestore = t;\n }\n convertBytes(t) {\n return new Uh(t);\n }\n convertReference(t) {\n const e = this.convertDocumentKey(t, this.firestore._databaseId);\n return new fh(this.firestore, /* converter= */ null, e);\n }\n}\n\n/**\n * @license\n * Copyright 2022 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * Create an AggregateField object that can be used to compute the sum of\n * a specified field over a range of documents in the result set of a query.\n * @param field Specifies the field to sum across the result set.\n * @internal TODO (sum/avg) remove when public\n */ function Yl(t) {\n return new Lh(\"sum\", wl(\"sum\", t));\n}\n\n/**\n * Create an AggregateField object that can be used to compute the average of\n * a specified field over a range of documents in the result set of a query.\n * @param field Specifies the field to average across the result set.\n * @internal TODO (sum/avg) remove when public\n */ function Xl(t) {\n return new Lh(\"avg\", wl(\"average\", t));\n}\n\n/**\n * Create an AggregateField object that can be used to compute the count of\n * documents in the result set of a query.\n * @internal TODO (sum/avg) remove when public\n */ function Zl() {\n return new Lh(\"count\");\n}\n\n/**\n * Compares two 'AggregateField` instances for equality.\n *\n * @param left Compare this AggregateField to the `right`.\n * @param right Compare this AggregateField to the `left`.\n * @internal TODO (sum/avg) remove when public\n */ function tf(t, e) {\n var n, s;\n return t instanceof Lh && e instanceof Lh && t._aggregateType === e._aggregateType && (null === (n = t._internalFieldPath) || void 0 === n ? void 0 : n.canonicalString()) === (null === (s = e._internalFieldPath) || void 0 === s ? void 0 : s.canonicalString());\n}\n\n/**\n * Compares two `AggregateQuerySnapshot` instances for equality.\n *\n * Two `AggregateQuerySnapshot` instances are considered \"equal\" if they have\n * underlying queries that compare equal, and the same data.\n *\n * @param left - The first `AggregateQuerySnapshot` to compare.\n * @param right - The second `AggregateQuerySnapshot` to compare.\n *\n * @returns `true` if the objects are \"equal\", as defined above, or `false`\n * otherwise.\n */ function ef(t, e) {\n return ph(t.query, e.query) && deepEqual(t.data(), e.data());\n}\n\n/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * Metadata about a snapshot, describing the state of the snapshot.\n */ class nf {\n /** @hideconstructor */\n constructor(t, e) {\n this.hasPendingWrites = t, this.fromCache = e;\n }\n /**\n * Returns true if this `SnapshotMetadata` is equal to the provided one.\n *\n * @param other - The `SnapshotMetadata` to compare against.\n * @returns true if this `SnapshotMetadata` is equal to the provided one.\n */ isEqual(t) {\n return this.hasPendingWrites === t.hasPendingWrites && this.fromCache === t.fromCache;\n }\n}\n\n/**\n * A `DocumentSnapshot` contains data read from a document in your Firestore\n * database. The data can be extracted with `.data()` or `.get()` to\n * get a specific field.\n *\n * For a `DocumentSnapshot` that points to a non-existing document, any data\n * access will return 'undefined'. You can use the `exists()` method to\n * explicitly verify a document's existence.\n */ class sf extends pl {\n /** @hideconstructor protected */\n constructor(t, e, n, s, i, r) {\n super(t, e, n, s, r), this._firestore = t, this._firestoreImpl = t, this.metadata = i;\n }\n /**\n * Returns whether or not the data exists. True if the document exists.\n */ exists() {\n return super.exists();\n }\n /**\n * Retrieves all fields in the document as an `Object`. Returns `undefined` if\n * the document doesn't exist.\n *\n * By default, `serverTimestamp()` values that have not yet been\n * set to their final value will be returned as `null`. You can override\n * this by passing an options object.\n *\n * @param options - An options object to configure how data is retrieved from\n * the snapshot (for example the desired behavior for server timestamps that\n * have not yet been set to their final value).\n * @returns An `Object` containing all fields in the document or `undefined` if\n * the document doesn't exist.\n */ data(t = {}) {\n if (this._document) {\n if (this._converter) {\n // We only want to use the converter and create a new DocumentSnapshot\n // if a converter has been provided.\n const e = new rf(this._firestore, this._userDataWriter, this._key, this._document, this.metadata, \n /* converter= */ null);\n return this._converter.fromFirestore(e, t);\n }\n return this._userDataWriter.convertValue(this._document.data.value, t.serverTimestamps);\n }\n }\n /**\n * Retrieves the field specified by `fieldPath`. Returns `undefined` if the\n * document or field doesn't exist.\n *\n * By default, a `serverTimestamp()` that has not yet been set to\n * its final value will be returned as `null`. You can override this by\n * passing an options object.\n *\n * @param fieldPath - The path (for example 'foo' or 'foo.bar') to a specific\n * field.\n * @param options - An options object to configure how the field is retrieved\n * from the snapshot (for example the desired behavior for server timestamps\n * that have not yet been set to their final value).\n * @returns The data at the specified field location or undefined if no such\n * field exists in the document.\n */\n // We are using `any` here to avoid an explicit cast by our users.\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n get(t, e = {}) {\n if (this._document) {\n const n = this._document.data.field(Tl(\"DocumentSnapshot.get\", t));\n if (null !== n) return this._userDataWriter.convertValue(n, e.serverTimestamps);\n }\n }\n}\n\n/**\n * A `QueryDocumentSnapshot` contains data read from a document in your\n * Firestore database as part of a query. The document is guaranteed to exist\n * and its data can be extracted with `.data()` or `.get()` to get a\n * specific field.\n *\n * A `QueryDocumentSnapshot` offers the same API surface as a\n * `DocumentSnapshot`. Since query results contain only existing documents, the\n * `exists` property will always be true and `data()` will never return\n * 'undefined'.\n */ class rf extends sf {\n /**\n * Retrieves all fields in the document as an `Object`.\n *\n * By default, `serverTimestamp()` values that have not yet been\n * set to their final value will be returned as `null`. You can override\n * this by passing an options object.\n *\n * @override\n * @param options - An options object to configure how data is retrieved from\n * the snapshot (for example the desired behavior for server timestamps that\n * have not yet been set to their final value).\n * @returns An `Object` containing all fields in the document.\n */\n data(t = {}) {\n return super.data(t);\n }\n}\n\n/**\n * A `QuerySnapshot` contains zero or more `DocumentSnapshot` objects\n * representing the results of a query. The documents can be accessed as an\n * array via the `docs` property or enumerated using the `forEach` method. The\n * number of documents can be determined via the `empty` and `size`\n * properties.\n */ class of {\n /** @hideconstructor */\n constructor(t, e, n, s) {\n this._firestore = t, this._userDataWriter = e, this._snapshot = s, this.metadata = new nf(s.hasPendingWrites, s.fromCache), \n this.query = n;\n }\n /** An array of all the documents in the `QuerySnapshot`. */ get docs() {\n const t = [];\n return this.forEach((e => t.push(e))), t;\n }\n /** The number of documents in the `QuerySnapshot`. */ get size() {\n return this._snapshot.docs.size;\n }\n /** True if there are no documents in the `QuerySnapshot`. */ get empty() {\n return 0 === this.size;\n }\n /**\n * Enumerates all of the documents in the `QuerySnapshot`.\n *\n * @param callback - A callback to be called with a `QueryDocumentSnapshot` for\n * each document in the snapshot.\n * @param thisArg - The `this` binding for the callback.\n */ forEach(t, e) {\n this._snapshot.docs.forEach((n => {\n t.call(e, new rf(this._firestore, this._userDataWriter, n.key, n, new nf(this._snapshot.mutatedKeys.has(n.key), this._snapshot.fromCache), this.query.converter));\n }));\n }\n /**\n * Returns an array of the documents changes since the last snapshot. If this\n * is the first snapshot, all documents will be in the list as 'added'\n * changes.\n *\n * @param options - `SnapshotListenOptions` that control whether metadata-only\n * changes (i.e. only `DocumentSnapshot.metadata` changed) should trigger\n * snapshot events.\n */ docChanges(t = {}) {\n const e = !!t.includeMetadataChanges;\n if (e && this._snapshot.excludesMetadataChanges) throw new U(q.INVALID_ARGUMENT, \"To include metadata changes with your document changes, you must also pass { includeMetadataChanges:true } to onSnapshot().\");\n return this._cachedChanges && this._cachedChangesIncludeMetadataChanges === e || (this._cachedChanges = \n /** Calculates the array of `DocumentChange`s for a given `ViewSnapshot`. */\n function(t, e) {\n if (t._snapshot.oldDocs.isEmpty()) {\n let e = 0;\n return t._snapshot.docChanges.map((n => {\n const s = new rf(t._firestore, t._userDataWriter, n.doc.key, n.doc, new nf(t._snapshot.mutatedKeys.has(n.doc.key), t._snapshot.fromCache), t.query.converter);\n return n.doc, {\n type: \"added\",\n doc: s,\n oldIndex: -1,\n newIndex: e++\n };\n }));\n }\n {\n // A `DocumentSet` that is updated incrementally as changes are applied to use\n // to lookup the index of a document.\n let n = t._snapshot.oldDocs;\n return t._snapshot.docChanges.filter((t => e || 3 /* ChangeType.Metadata */ !== t.type)).map((e => {\n const s = new rf(t._firestore, t._userDataWriter, e.doc.key, e.doc, new nf(t._snapshot.mutatedKeys.has(e.doc.key), t._snapshot.fromCache), t.query.converter);\n let i = -1, r = -1;\n return 0 /* ChangeType.Added */ !== e.type && (i = n.indexOf(e.doc.key), n = n.delete(e.doc.key)), \n 1 /* ChangeType.Removed */ !== e.type && (n = n.add(e.doc), r = n.indexOf(e.doc.key)), \n {\n type: uf(e.type),\n doc: s,\n oldIndex: i,\n newIndex: r\n };\n }));\n }\n }(this, e), this._cachedChangesIncludeMetadataChanges = e), this._cachedChanges;\n }\n}\n\nfunction uf(t) {\n switch (t) {\n case 0 /* ChangeType.Added */ :\n return \"added\";\n\n case 2 /* ChangeType.Modified */ :\n case 3 /* ChangeType.Metadata */ :\n return \"modified\";\n\n case 1 /* ChangeType.Removed */ :\n return \"removed\";\n\n default:\n return O();\n }\n}\n\n// TODO(firestoreexp): Add tests for snapshotEqual with different snapshot\n// metadata\n/**\n * Returns true if the provided snapshots are equal.\n *\n * @param left - A snapshot to compare.\n * @param right - A snapshot to compare.\n * @returns true if the snapshots are equal.\n */ function cf(t, e) {\n return t instanceof sf && e instanceof sf ? t._firestore === e._firestore && t._key.isEqual(e._key) && (null === t._document ? null === e._document : t._document.isEqual(e._document)) && t._converter === e._converter : t instanceof of && e instanceof of && (t._firestore === e._firestore && ph(t.query, e.query) && t.metadata.isEqual(e.metadata) && t._snapshot.isEqual(e._snapshot));\n}\n\n/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * Reads the document referred to by this `DocumentReference`.\n *\n * Note: `getDoc()` attempts to provide up-to-date data when possible by waiting\n * for data from the server, but it may return cached data or fail if you are\n * offline and the server cannot be reached. To specify this behavior, invoke\n * {@link getDocFromCache} or {@link getDocFromServer}.\n *\n * @param reference - The reference of the document to fetch.\n * @returns A Promise resolved with a `DocumentSnapshot` containing the\n * current document contents.\n */ function af(t) {\n t = uh(t, fh);\n const e = uh(t.firestore, vh);\n return za(bh(e), t._key).then((n => Af(e, t, n)));\n}\n\nclass hf extends Wl {\n constructor(t) {\n super(), this.firestore = t;\n }\n convertBytes(t) {\n return new Uh(t);\n }\n convertReference(t) {\n const e = this.convertDocumentKey(t, this.firestore._databaseId);\n return new fh(this.firestore, /* converter= */ null, e);\n }\n}\n\n/**\n * Reads the document referred to by this `DocumentReference` from cache.\n * Returns an error if the document is not currently cached.\n *\n * @returns A `Promise` resolved with a `DocumentSnapshot` containing the\n * current document contents.\n */ function lf(t) {\n t = uh(t, fh);\n const e = uh(t.firestore, vh), n = bh(e), s = new hf(e);\n return ja(n, t._key).then((n => new sf(e, s, t._key, n, new nf(null !== n && n.hasLocalMutations, \n /* fromCache= */ !0), t.converter)));\n}\n\n/**\n * Reads the document referred to by this `DocumentReference` from the server.\n * Returns an error if the network is not available.\n *\n * @returns A `Promise` resolved with a `DocumentSnapshot` containing the\n * current document contents.\n */ function ff(t) {\n t = uh(t, fh);\n const e = uh(t.firestore, vh);\n return za(bh(e), t._key, {\n source: \"server\"\n }).then((n => Af(e, t, n)));\n}\n\n/**\n * Executes the query and returns the results as a `QuerySnapshot`.\n *\n * Note: `getDocs()` attempts to provide up-to-date data when possible by\n * waiting for data from the server, but it may return cached data or fail if\n * you are offline and the server cannot be reached. To specify this behavior,\n * invoke {@link getDocsFromCache} or {@link getDocsFromServer}.\n *\n * @returns A `Promise` that will be resolved with the results of the query.\n */ function df(t) {\n t = uh(t, dh);\n const e = uh(t.firestore, vh), n = bh(e), s = new hf(e);\n return El(t._query), Ha(n, t._query).then((n => new of(e, s, t, n)));\n}\n\n/**\n * Executes the query and returns the results as a `QuerySnapshot` from cache.\n * Returns an empty result set if no documents matching the query are currently\n * cached.\n *\n * @returns A `Promise` that will be resolved with the results of the query.\n */ function wf(t) {\n t = uh(t, dh);\n const e = uh(t.firestore, vh), n = bh(e), s = new hf(e);\n return Wa(n, t._query).then((n => new of(e, s, t, n)));\n}\n\n/**\n * Executes the query and returns the results as a `QuerySnapshot` from the\n * server. Returns an error if the network is not available.\n *\n * @returns A `Promise` that will be resolved with the results of the query.\n */ function _f(t) {\n t = uh(t, dh);\n const e = uh(t.firestore, vh), n = bh(e), s = new hf(e);\n return Ha(n, t._query, {\n source: \"server\"\n }).then((n => new of(e, s, t, n)));\n}\n\nfunction mf(t, e, n) {\n t = uh(t, fh);\n const s = uh(t.firestore, vh), i = Hl(t.converter, e, n);\n return Ef(s, [ tl(Zh(s), \"setDoc\", t._key, i, null !== t.converter, n).toMutation(t._key, Fs.none()) ]);\n}\n\nfunction gf(t, e, n, ...s) {\n t = uh(t, fh);\n const i = uh(t.firestore, vh), r = Zh(i);\n let o;\n o = \"string\" == typeof (\n // For Compat types, we have to \"extract\" the underlying types before\n // performing validation.\n e = getModularInstance(e)) || e instanceof Kh ? cl(r, \"updateDoc\", t._key, e, n, s) : ul(r, \"updateDoc\", t._key, e);\n return Ef(i, [ o.toMutation(t._key, Fs.exists(!0)) ]);\n}\n\n/**\n * Deletes the document referred to by the specified `DocumentReference`.\n *\n * @param reference - A reference to the document to delete.\n * @returns A Promise resolved once the document has been successfully\n * deleted from the backend (note that it won't resolve while you're offline).\n */ function yf(t) {\n return Ef(uh(t.firestore, vh), [ new Ys(t._key, Fs.none()) ]);\n}\n\n/**\n * Add a new document to specified `CollectionReference` with the given data,\n * assigning it a document ID automatically.\n *\n * @param reference - A reference to the collection to add this document to.\n * @param data - An Object containing the data for the new document.\n * @returns A `Promise` resolved with a `DocumentReference` pointing to the\n * newly created document after it has been written to the backend (Note that it\n * won't resolve while you're offline).\n */ function pf(t, e) {\n const n = uh(t.firestore, vh), s = gh(t), i = Hl(t.converter, e);\n return Ef(n, [ tl(Zh(t.firestore), \"addDoc\", s._key, i, null !== t.converter, {}).toMutation(s._key, Fs.exists(!1)) ]).then((() => s));\n}\n\nfunction If(t, ...e) {\n var n, s, i;\n t = getModularInstance(t);\n let r = {\n includeMetadataChanges: !1\n }, o = 0;\n \"object\" != typeof e[o] || Th(e[o]) || (r = e[o], o++);\n const u = {\n includeMetadataChanges: r.includeMetadataChanges\n };\n if (Th(e[o])) {\n const t = e[o];\n e[o] = null === (n = t.next) || void 0 === n ? void 0 : n.bind(t), e[o + 1] = null === (s = t.error) || void 0 === s ? void 0 : s.bind(t), \n e[o + 2] = null === (i = t.complete) || void 0 === i ? void 0 : i.bind(t);\n }\n let c, a, h;\n if (t instanceof fh) a = uh(t.firestore, vh), h = Gn(t._key.path), c = {\n next: n => {\n e[o] && e[o](Af(a, t, n));\n },\n error: e[o + 1],\n complete: e[o + 2]\n }; else {\n const n = uh(t, dh);\n a = uh(n.firestore, vh), h = n._query;\n const s = new hf(a);\n c = {\n next: t => {\n e[o] && e[o](new of(a, s, n, t));\n },\n error: e[o + 1],\n complete: e[o + 2]\n }, El(t._query);\n }\n return function(t, e, n, s) {\n const i = new Va(s), r = new Nc(e, i, n);\n return t.asyncQueue.enqueueAndForget((async () => Vc(await Ka(t), r))), () => {\n i.Dc(), t.asyncQueue.enqueueAndForget((async () => Sc(await Ka(t), r)));\n };\n }(bh(a), h, u, c);\n}\n\nfunction Tf(t, e) {\n return Ja(bh(t = uh(t, vh)), Th(e) ? e : {\n next: e\n });\n}\n\n/**\n * Locally writes `mutations` on the async queue.\n * @internal\n */ function Ef(t, e) {\n return function(t, e) {\n const n = new K;\n return t.asyncQueue.enqueueAndForget((async () => zc(await qa(t), e, n))), n.promise;\n }(bh(t), e);\n}\n\n/**\n * Converts a {@link ViewSnapshot} that contains the single document specified by `ref`\n * to a {@link DocumentSnapshot}.\n */ function Af(t, e, n) {\n const s = n.docs.get(e._key), i = new hf(t);\n return new sf(t, i, e._key, s, new nf(n.hasPendingWrites, n.fromCache), e.converter);\n}\n\n/**\n * @license\n * Copyright 2022 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * Calculates the number of documents in the result set of the given query,\n * without actually downloading the documents.\n *\n * Using this function to count the documents is efficient because only the\n * final count, not the documents' data, is downloaded. This function can even\n * count the documents if the result set would be prohibitively large to\n * download entirely (e.g. thousands of documents).\n *\n * The result received from the server is presented, unaltered, without\n * considering any local state. That is, documents in the local cache are not\n * taken into consideration, neither are local modifications not yet\n * synchronized with the server. Previously-downloaded results, if any, are not\n * used: every request using this source necessarily involves a round trip to\n * the server.\n *\n * @param query - The query whose result set size to calculate.\n * @returns A Promise that will be resolved with the count; the count can be\n * retrieved from `snapshot.data().count`, where `snapshot` is the\n * `AggregateQuerySnapshot` to which the returned Promise resolves.\n */ function vf(t) {\n return Rf(t, {\n count: Zl()\n });\n}\n\n/**\n * Calculates the specified aggregations over the documents in the result\n * set of the given query, without actually downloading the documents.\n *\n * Using this function to perform aggregations is efficient because only the\n * final aggregation values, not the documents' data, is downloaded. This\n * function can even perform aggregations of the documents if the result set\n * would be prohibitively large to download entirely (e.g. thousands of documents).\n *\n * The result received from the server is presented, unaltered, without\n * considering any local state. That is, documents in the local cache are not\n * taken into consideration, neither are local modifications not yet\n * synchronized with the server. Previously-downloaded results, if any, are not\n * used: every request using this source necessarily involves a round trip to\n * the server.\n *\n * @param query The query whose result set to aggregate over.\n * @param aggregateSpec An `AggregateSpec` object that specifies the aggregates\n * to perform over the result set. The AggregateSpec specifies aliases for each\n * aggregate, which can be used to retrieve the aggregate result.\n * @example\n * ```typescript\n * const aggregateSnapshot = await getAggregateFromServer(query, {\n * countOfDocs: count(),\n * totalHours: sum('hours'),\n * averageScore: average('score')\n * });\n *\n * const countOfDocs: number = aggregateSnapshot.data().countOfDocs;\n * const totalHours: number = aggregateSnapshot.data().totalHours;\n * const averageScore: number | null = aggregateSnapshot.data().averageScore;\n * ```\n * @internal TODO (sum/avg) remove when public\n */ function Rf(t, e) {\n const n = uh(t.firestore, vh), s = bh(n), i = function(t, e) {\n const n = [];\n for (const s in t) Object.prototype.hasOwnProperty.call(t, s) && n.push(e(t[s], s, t));\n return n;\n }(e, ((t, e) => new ni(e, t._aggregateType, t._internalFieldPath)));\n // Run the aggregation and convert the results\n return function(t, e, n) {\n const s = new K;\n return t.asyncQueue.enqueueAndForget((async () => {\n // TODO (sum/avg) should we update this to use the event manager?\n // Implement and call executeAggregateQueryViaSnapshotListener, similar\n // to the implementation in firestoreClientGetDocumentsViaSnapshotListener\n // above\n try {\n // TODO(b/277628384): check `canUseNetwork()` and handle multi-tab.\n const i = await Ua(t);\n s.resolve(Gu(i, e, n));\n } catch (t) {\n s.reject(t);\n }\n })), s.promise;\n }(s, t._query, i).then((e => \n /**\n * Converts the core aggregration result to an `AggregateQuerySnapshot`\n * that can be returned to the consumer.\n * @param query\n * @param aggregateResult Core aggregation result\n * @internal\n */\n function(t, e, n) {\n const s = new hf(t);\n return new qh(e, s, n);\n }\n /**\n * @license\n * Copyright 2023 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */ (n, t, e)));\n}\n\nclass Pf {\n constructor(t) {\n this.kind = \"memory\", this._onlineComponentProvider = new Pa, (null == t ? void 0 : t.garbageCollector) ? this._offlineComponentProvider = t.garbageCollector._offlineComponentProvider : this._offlineComponentProvider = new Ea;\n }\n toJSON() {\n return {\n kind: this.kind\n };\n }\n}\n\nclass bf {\n constructor(t) {\n let e;\n this.kind = \"persistent\", (null == t ? void 0 : t.tabManager) ? (t.tabManager._initialize(t), \n e = t.tabManager) : (e = $f(void 0), e._initialize(t)), this._onlineComponentProvider = e._onlineComponentProvider, \n this._offlineComponentProvider = e._offlineComponentProvider;\n }\n toJSON() {\n return {\n kind: this.kind\n };\n }\n}\n\nclass Vf {\n constructor() {\n this.kind = \"memoryEager\", this._offlineComponentProvider = new Ea;\n }\n toJSON() {\n return {\n kind: this.kind\n };\n }\n}\n\nclass Sf {\n constructor(t) {\n this.kind = \"memoryLru\", this._offlineComponentProvider = new Aa(t);\n }\n toJSON() {\n return {\n kind: this.kind\n };\n }\n}\n\n/**\n * Creates an instance of `MemoryEagerGarbageCollector`. This is also the\n * default garbage collector unless it is explicitly specified otherwise.\n */ function Df() {\n return new Vf;\n}\n\n/**\n * Creates an instance of `MemoryLruGarbageCollector`.\n *\n * A target size can be specified as part of the setting parameter. The\n * collector will start deleting documents once the cache size exceeds\n * the given size. The default cache size is 40MB (40 * 1024 * 1024 bytes).\n */ function Cf(t) {\n return new Sf(null == t ? void 0 : t.cacheSizeBytes);\n}\n\n/**\n * Creates an instance of `MemoryLocalCache`. The instance can be set to\n * `FirestoreSettings.cache` to tell the SDK which cache layer to use.\n */ function xf(t) {\n return new Pf(t);\n}\n\n/**\n * Creates an instance of `PersistentLocalCache`. The instance can be set to\n * `FirestoreSettings.cache` to tell the SDK which cache layer to use.\n *\n * Persistent cache cannot be used in a Node.js environment.\n */ function Nf(t) {\n return new bf(t);\n}\n\nclass kf {\n constructor(t) {\n this.forceOwnership = t, this.kind = \"persistentSingleTab\";\n }\n toJSON() {\n return {\n kind: this.kind\n };\n }\n /**\n * @internal\n */ _initialize(t) {\n this._onlineComponentProvider = new Pa, this._offlineComponentProvider = new va(this._onlineComponentProvider, null == t ? void 0 : t.cacheSizeBytes, this.forceOwnership);\n }\n}\n\nclass Mf {\n constructor() {\n this.kind = \"PersistentMultipleTab\";\n }\n toJSON() {\n return {\n kind: this.kind\n };\n }\n /**\n * @internal\n */ _initialize(t) {\n this._onlineComponentProvider = new Pa, this._offlineComponentProvider = new Ra(this._onlineComponentProvider, null == t ? void 0 : t.cacheSizeBytes);\n }\n}\n\n/**\n * Creates an instance of `PersistentSingleTabManager`.\n *\n * @param settings Configures the created tab manager.\n */ function $f(t) {\n return new kf(null == t ? void 0 : t.forceOwnership);\n}\n\n/**\n * Creates an instance of `PersistentMultipleTabManager`.\n */ function Of() {\n return new Mf;\n}\n\n/**\n * @license\n * Copyright 2022 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */ const Ff = {\n maxAttempts: 5\n};\n\n/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * A write batch, used to perform multiple writes as a single atomic unit.\n *\n * A `WriteBatch` object can be acquired by calling {@link writeBatch}. It\n * provides methods for adding writes to the write batch. None of the writes\n * will be committed (or visible locally) until {@link WriteBatch.commit} is\n * called.\n */\nclass Bf {\n /** @hideconstructor */\n constructor(t, e) {\n this._firestore = t, this._commitHandler = e, this._mutations = [], this._committed = !1, \n this._dataReader = Zh(t);\n }\n set(t, e, n) {\n this._verifyNotCommitted();\n const s = Lf(t, this._firestore), i = Hl(s.converter, e, n), r = tl(this._dataReader, \"WriteBatch.set\", s._key, i, null !== s.converter, n);\n return this._mutations.push(r.toMutation(s._key, Fs.none())), this;\n }\n update(t, e, n, ...s) {\n this._verifyNotCommitted();\n const i = Lf(t, this._firestore);\n // For Compat types, we have to \"extract\" the underlying types before\n // performing validation.\n let r;\n return r = \"string\" == typeof (e = getModularInstance(e)) || e instanceof Kh ? cl(this._dataReader, \"WriteBatch.update\", i._key, e, n, s) : ul(this._dataReader, \"WriteBatch.update\", i._key, e), \n this._mutations.push(r.toMutation(i._key, Fs.exists(!0))), this;\n }\n /**\n * Deletes the document referred to by the provided {@link DocumentReference}.\n *\n * @param documentRef - A reference to the document to be deleted.\n * @returns This `WriteBatch` instance. Used for chaining method calls.\n */ delete(t) {\n this._verifyNotCommitted();\n const e = Lf(t, this._firestore);\n return this._mutations = this._mutations.concat(new Ys(e._key, Fs.none())), this;\n }\n /**\n * Commits all of the writes in this write batch as a single atomic unit.\n *\n * The result of these writes will only be reflected in document reads that\n * occur after the returned promise resolves. If the client is offline, the\n * write fails. If you would like to see local modifications or buffer writes\n * until the client is online, use the full Firestore SDK.\n *\n * @returns A `Promise` resolved once all of the writes in the batch have been\n * successfully written to the backend as an atomic unit (note that it won't\n * resolve while you're offline).\n */ commit() {\n return this._verifyNotCommitted(), this._committed = !0, this._mutations.length > 0 ? this._commitHandler(this._mutations) : Promise.resolve();\n }\n _verifyNotCommitted() {\n if (this._committed) throw new U(q.FAILED_PRECONDITION, \"A write batch can no longer be used after commit() has been called.\");\n }\n}\n\nfunction Lf(t, e) {\n if ((t = getModularInstance(t)).firestore !== e) throw new U(q.INVALID_ARGUMENT, \"Provided document reference is from a different Firestore instance.\");\n return t;\n}\n\n/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n// TODO(mrschmidt) Consider using `BaseTransaction` as the base class in the\n// legacy SDK.\n/**\n * A reference to a transaction.\n *\n * The `Transaction` object passed to a transaction's `updateFunction` provides\n * the methods to read and write data within the transaction context. See\n * {@link runTransaction}.\n */\n/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * A reference to a transaction.\n *\n * The `Transaction` object passed to a transaction's `updateFunction` provides\n * the methods to read and write data within the transaction context. See\n * {@link runTransaction}.\n */\nclass qf extends class {\n /** @hideconstructor */\n constructor(t, e) {\n this._firestore = t, this._transaction = e, this._dataReader = Zh(t);\n }\n /**\n * Reads the document referenced by the provided {@link DocumentReference}.\n *\n * @param documentRef - A reference to the document to be read.\n * @returns A `DocumentSnapshot` with the read data.\n */ get(t) {\n const e = Lf(t, this._firestore), n = new Jl(this._firestore);\n return this._transaction.lookup([ e._key ]).then((t => {\n if (!t || 1 !== t.length) return O();\n const s = t[0];\n if (s.isFoundDocument()) return new pl(this._firestore, n, s.key, s, e.converter);\n if (s.isNoDocument()) return new pl(this._firestore, n, e._key, null, e.converter);\n throw O();\n }));\n }\n set(t, e, n) {\n const s = Lf(t, this._firestore), i = Hl(s.converter, e, n), r = tl(this._dataReader, \"Transaction.set\", s._key, i, null !== s.converter, n);\n return this._transaction.set(s._key, r), this;\n }\n update(t, e, n, ...s) {\n const i = Lf(t, this._firestore);\n // For Compat types, we have to \"extract\" the underlying types before\n // performing validation.\n let r;\n return r = \"string\" == typeof (e = getModularInstance(e)) || e instanceof Kh ? cl(this._dataReader, \"Transaction.update\", i._key, e, n, s) : ul(this._dataReader, \"Transaction.update\", i._key, e), \n this._transaction.update(i._key, r), this;\n }\n /**\n * Deletes the document referred to by the provided {@link DocumentReference}.\n *\n * @param documentRef - A reference to the document to be deleted.\n * @returns This `Transaction` instance. Used for chaining method calls.\n */ delete(t) {\n const e = Lf(t, this._firestore);\n return this._transaction.delete(e._key), this;\n }\n} {\n // This class implements the same logic as the Transaction API in the Lite SDK\n // but is subclassed in order to return its own DocumentSnapshot types.\n /** @hideconstructor */\n constructor(t, e) {\n super(t, e), this._firestore = t;\n }\n /**\n * Reads the document referenced by the provided {@link DocumentReference}.\n *\n * @param documentRef - A reference to the document to be read.\n * @returns A `DocumentSnapshot` with the read data.\n */ get(t) {\n const e = Lf(t, this._firestore), n = new hf(this._firestore);\n return super.get(t).then((t => new sf(this._firestore, n, e._key, t._document, new nf(\n /* hasPendingWrites= */ !1, \n /* fromCache= */ !1), e.converter)));\n }\n}\n\n/**\n * Executes the given `updateFunction` and then attempts to commit the changes\n * applied within the transaction. If any document read within the transaction\n * has changed, Cloud Firestore retries the `updateFunction`. If it fails to\n * commit after 5 attempts, the transaction fails.\n *\n * The maximum number of writes allowed in a single transaction is 500.\n *\n * @param firestore - A reference to the Firestore database to run this\n * transaction against.\n * @param updateFunction - The function to execute within the transaction\n * context.\n * @param options - An options object to configure maximum number of attempts to\n * commit.\n * @returns If the transaction completed successfully or was explicitly aborted\n * (the `updateFunction` returned a failed promise), the promise returned by the\n * `updateFunction `is returned here. Otherwise, if the transaction failed, a\n * rejected promise with the corresponding failure error is returned.\n */ function Uf(t, e, n) {\n t = uh(t, vh);\n const s = Object.assign(Object.assign({}, Ff), n);\n !function(t) {\n if (t.maxAttempts < 1) throw new U(q.INVALID_ARGUMENT, \"Max attempts must be at least 1\");\n }(s);\n return function(t, e, n) {\n const s = new K;\n return t.asyncQueue.enqueueAndForget((async () => {\n const i = await Ua(t);\n new Ca(t.asyncQueue, i, n, e, s).run();\n })), s.promise;\n }(bh(t), (n => e(new qf(t, n))), s);\n}\n\n/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * Returns a sentinel for use with {@link @firebase/firestore/lite#(updateDoc:1)} or\n * {@link @firebase/firestore/lite#(setDoc:1)} with `{merge: true}` to mark a field for deletion.\n */ function Kf() {\n return new el(\"deleteField\");\n}\n\n/**\n * Returns a sentinel used with {@link @firebase/firestore/lite#(setDoc:1)} or {@link @firebase/firestore/lite#(updateDoc:1)} to\n * include a server-generated timestamp in the written data.\n */ function Gf() {\n return new sl(\"serverTimestamp\");\n}\n\n/**\n * Returns a special value that can be used with {@link @firebase/firestore/lite#(setDoc:1)} or {@link\n * @firebase/firestore/lite#(updateDoc:1)} that tells the server to union the given elements with any array\n * value that already exists on the server. Each specified element that doesn't\n * already exist in the array will be added to the end. If the field being\n * modified is not already an array it will be overwritten with an array\n * containing exactly the specified elements.\n *\n * @param elements - The elements to union into the array.\n * @returns The `FieldValue` sentinel for use in a call to `setDoc()` or\n * `updateDoc()`.\n */ function Qf(...t) {\n // NOTE: We don't actually parse the data until it's used in set() or\n // update() since we'd need the Firestore instance to do this.\n return new il(\"arrayUnion\", t);\n}\n\n/**\n * Returns a special value that can be used with {@link (setDoc:1)} or {@link\n * updateDoc:1} that tells the server to remove the given elements from any\n * array value that already exists on the server. All instances of each element\n * specified will be removed from the array. If the field being modified is not\n * already an array it will be overwritten with an empty array.\n *\n * @param elements - The elements to remove from the array.\n * @returns The `FieldValue` sentinel for use in a call to `setDoc()` or\n * `updateDoc()`\n */ function jf(...t) {\n // NOTE: We don't actually parse the data until it's used in set() or\n // update() since we'd need the Firestore instance to do this.\n return new rl(\"arrayRemove\", t);\n}\n\n/**\n * Returns a special value that can be used with {@link @firebase/firestore/lite#(setDoc:1)} or {@link\n * @firebase/firestore/lite#(updateDoc:1)} that tells the server to increment the field's current value by\n * the given value.\n *\n * If either the operand or the current field value uses floating point\n * precision, all arithmetic follows IEEE 754 semantics. If both values are\n * integers, values outside of JavaScript's safe number range\n * (`Number.MIN_SAFE_INTEGER` to `Number.MAX_SAFE_INTEGER`) are also subject to\n * precision loss. Furthermore, once processed by the Firestore backend, all\n * integer operations are capped between -2^63 and 2^63-1.\n *\n * If the current field value is not of type `number`, or if the field does not\n * yet exist, the transformation sets the field to the given value.\n *\n * @param n - The value to increment by.\n * @returns The `FieldValue` sentinel for use in a call to `setDoc()` or\n * `updateDoc()`\n */ function zf(t) {\n return new ol(\"increment\", t);\n}\n\n/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * Creates a write batch, used for performing multiple writes as a single\n * atomic operation. The maximum number of writes allowed in a single {@link WriteBatch}\n * is 500.\n *\n * Unlike transactions, write batches are persisted offline and therefore are\n * preferable when you don't need to condition your writes on read data.\n *\n * @returns A {@link WriteBatch} that can be used to atomically execute multiple\n * writes.\n */ function Wf(t) {\n return bh(t = uh(t, vh)), new Bf(t, (e => Ef(t, e)));\n}\n\n/**\n * @license\n * Copyright 2021 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */ function Hf(t, e) {\n var n;\n const s = bh(t = uh(t, vh));\n if (!s._uninitializedComponentsProvider || \"memory\" === (null === (n = s._uninitializedComponentsProvider) || void 0 === n ? void 0 : n._offlineKind)) \n // PORTING NOTE: We don't return an error if the user has not enabled\n // persistence since `enableIndexeddbPersistence()` can fail on the Web.\n return M(\"Cannot enable indexes when persistence is disabled\"), Promise.resolve();\n const i = function(t) {\n const e = \"string\" == typeof t ? function(t) {\n try {\n return JSON.parse(t);\n } catch (t) {\n throw new U(q.INVALID_ARGUMENT, \"Failed to parse JSON: \" + (null == t ? void 0 : t.message));\n }\n }(t) : t, n = [];\n if (Array.isArray(e.indexes)) for (const t of e.indexes) {\n const e = Jf(t, \"collectionGroup\"), s = [];\n if (Array.isArray(t.fields)) for (const e of t.fields) {\n const t = ml(\"setIndexConfiguration\", Jf(e, \"fieldPath\"));\n \"CONTAINS\" === e.arrayConfig ? s.push(new _t(t, 2 /* IndexKind.CONTAINS */)) : \"ASCENDING\" === e.order ? s.push(new _t(t, 0 /* IndexKind.ASCENDING */)) : \"DESCENDING\" === e.order && s.push(new _t(t, 1 /* IndexKind.DESCENDING */));\n }\n n.push(new lt(lt.UNKNOWN_ID, e, s, gt.empty()));\n }\n return n;\n }(e);\n return Za(s, i);\n}\n\nfunction Jf(t, e) {\n if (\"string\" != typeof t[e]) throw new U(q.INVALID_ARGUMENT, \"Missing string value for: \" + e);\n return t[e];\n}\n\n/**\n * Cloud Firestore\n *\n * @packageDocumentation\n */ !function(t, e = !0) {\n !function(t) {\n S = t;\n }(SDK_VERSION), _registerComponent(new Component(\"firestore\", ((t, {instanceIdentifier: n, options: s}) => {\n const i = t.getProvider(\"app\").getImmediate(), r = new vh(new z(t.getProvider(\"auth-internal\")), new Y(t.getProvider(\"app-check-internal\")), function(t, e) {\n if (!Object.prototype.hasOwnProperty.apply(t.options, [ \"projectId\" ])) throw new U(q.INVALID_ARGUMENT, '\"projectId\" not provided in firebase.initializeApp.');\n return new Oe(t.options.projectId, e);\n }(i, n), i);\n return s = Object.assign({\n useFetchStreams: e\n }, s), r._setSettings(s), r;\n }), \"PUBLIC\").setMultipleInstances(!0)), registerVersion(b, \"3.13.0\", t), \n // BUILD_TARGET will be replaced by values like esm5, esm2017, cjs5, etc during the compilation\n registerVersion(b, \"3.13.0\", \"esm2017\");\n}();\n\nexport { Wl as AbstractUserDataWriter, Lh as AggregateField, qh as AggregateQuerySnapshot, Uh as Bytes, Ah as CACHE_SIZE_UNLIMITED, wh as CollectionReference, fh as DocumentReference, sf as DocumentSnapshot, Kh as FieldPath, Qh as FieldValue, vh as Firestore, U as FirestoreError, jh as GeoPoint, Eh as LoadBundleTask, dh as Query, Vl as QueryCompositeFilterConstraint, vl as QueryConstraint, rf as QueryDocumentSnapshot, Bl as QueryEndAtConstraint, Pl as QueryFieldFilterConstraint, Nl as QueryLimitConstraint, Cl as QueryOrderByConstraint, of as QuerySnapshot, $l as QueryStartAtConstraint, nf as SnapshotMetadata, it as Timestamp, qf as Transaction, Bf as WriteBatch, Oe as _DatabaseId, ht as _DocumentKey, X as _EmptyAppCheckTokenProvider, Q as _EmptyAuthCredentialsProvider, at as _FieldPath, ci as _TestingHooks, uh as _cast, B as _debugAssert, be as _isBase64Available, M as _logWarn, sh as _validateIsNotUsedTogether, pf as addDoc, tf as aggregateFieldEqual, ef as aggregateQuerySnapshotEqual, Dl as and, jf as arrayRemove, Qf as arrayUnion, Xl as average, xh as clearIndexedDbPersistence, _h as collection, mh as collectionGroup, lh as connectFirestoreEmulator, Zl as count, yf as deleteDoc, Kf as deleteField, Mh as disableNetwork, gh as doc, Gh as documentId, Sh as enableIndexedDbPersistence, Dh as enableMultiTabIndexedDbPersistence, kh as enableNetwork, ql as endAt, Ll as endBefore, bh as ensureFirestoreConfigured, Ef as executeWrite, Rf as getAggregateFromServer, vf as getCountFromServer, af as getDoc, lf as getDocFromCache, ff as getDocFromServer, df as getDocs, wf as getDocsFromCache, _f as getDocsFromServer, Ph as getFirestore, zf as increment, Rh as initializeFirestore, kl as limit, Ml as limitToLast, Oh as loadBundle, Df as memoryEagerGarbageCollector, xf as memoryLocalCache, Cf as memoryLruGarbageCollector, Fh as namedQuery, If as onSnapshot, Tf as onSnapshotsInSync, Sl as or, xl as orderBy, Nf as persistentLocalCache, Of as persistentMultipleTabManager, $f as persistentSingleTabManager, Rl as query, ph as queryEqual, yh as refEqual, Uf as runTransaction, Gf as serverTimestamp, mf as setDoc, Hf as setIndexConfiguration, x as setLogLevel, cf as snapshotEqual, Fl as startAfter, Ol as startAt, Yl as sum, $h as terminate, gf as updateDoc, Nh as waitForPendingWrites, bl as where, Wf as writeBatch };\n//# sourceMappingURL=index.esm2017.js.map\n","import { _getProvider, getApp, _registerComponent, registerVersion, SDK_VERSION } from '@firebase/app';\nimport { FirebaseError, isNode, createMockUserToken, getModularInstance, getDefaultEmulatorHostnameAndPort } from '@firebase/util';\nimport { Component } from '@firebase/component';\n\n/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * @fileoverview Constants used in the Firebase Storage library.\r\n */\r\n/**\r\n * Domain name for firebase storage.\r\n */\r\nconst DEFAULT_HOST = 'firebasestorage.googleapis.com';\r\n/**\r\n * The key in Firebase config json for the storage bucket.\r\n */\r\nconst CONFIG_STORAGE_BUCKET_KEY = 'storageBucket';\r\n/**\r\n * 2 minutes\r\n *\r\n * The timeout for all operations except upload.\r\n */\r\nconst DEFAULT_MAX_OPERATION_RETRY_TIME = 2 * 60 * 1000;\r\n/**\r\n * 10 minutes\r\n *\r\n * The timeout for upload.\r\n */\r\nconst DEFAULT_MAX_UPLOAD_RETRY_TIME = 10 * 60 * 1000;\r\n/**\r\n * 1 second\r\n */\r\nconst DEFAULT_MIN_SLEEP_TIME_MILLIS = 1000;\n\n/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * An error returned by the Firebase Storage SDK.\r\n * @public\r\n */\r\nclass StorageError extends FirebaseError {\r\n /**\r\n * @param code - A `StorageErrorCode` string to be prefixed with 'storage/' and\r\n * added to the end of the message.\r\n * @param message - Error message.\r\n * @param status_ - Corresponding HTTP Status Code\r\n */\r\n constructor(code, message, status_ = 0) {\r\n super(prependCode(code), `Firebase Storage: ${message} (${prependCode(code)})`);\r\n this.status_ = status_;\r\n /**\r\n * Stores custom error data unique to the `StorageError`.\r\n */\r\n this.customData = { serverResponse: null };\r\n this._baseMessage = this.message;\r\n // Without this, `instanceof StorageError`, in tests for example,\r\n // returns false.\r\n Object.setPrototypeOf(this, StorageError.prototype);\r\n }\r\n get status() {\r\n return this.status_;\r\n }\r\n set status(status) {\r\n this.status_ = status;\r\n }\r\n /**\r\n * Compares a `StorageErrorCode` against this error's code, filtering out the prefix.\r\n */\r\n _codeEquals(code) {\r\n return prependCode(code) === this.code;\r\n }\r\n /**\r\n * Optional response message that was added by the server.\r\n */\r\n get serverResponse() {\r\n return this.customData.serverResponse;\r\n }\r\n set serverResponse(serverResponse) {\r\n this.customData.serverResponse = serverResponse;\r\n if (this.customData.serverResponse) {\r\n this.message = `${this._baseMessage}\\n${this.customData.serverResponse}`;\r\n }\r\n else {\r\n this.message = this._baseMessage;\r\n }\r\n }\r\n}\r\n/**\r\n * @public\r\n * Error codes that can be attached to `StorageError` objects.\r\n */\r\nvar StorageErrorCode;\r\n(function (StorageErrorCode) {\r\n // Shared between all platforms\r\n StorageErrorCode[\"UNKNOWN\"] = \"unknown\";\r\n StorageErrorCode[\"OBJECT_NOT_FOUND\"] = \"object-not-found\";\r\n StorageErrorCode[\"BUCKET_NOT_FOUND\"] = \"bucket-not-found\";\r\n StorageErrorCode[\"PROJECT_NOT_FOUND\"] = \"project-not-found\";\r\n StorageErrorCode[\"QUOTA_EXCEEDED\"] = \"quota-exceeded\";\r\n StorageErrorCode[\"UNAUTHENTICATED\"] = \"unauthenticated\";\r\n StorageErrorCode[\"UNAUTHORIZED\"] = \"unauthorized\";\r\n StorageErrorCode[\"UNAUTHORIZED_APP\"] = \"unauthorized-app\";\r\n StorageErrorCode[\"RETRY_LIMIT_EXCEEDED\"] = \"retry-limit-exceeded\";\r\n StorageErrorCode[\"INVALID_CHECKSUM\"] = \"invalid-checksum\";\r\n StorageErrorCode[\"CANCELED\"] = \"canceled\";\r\n // JS specific\r\n StorageErrorCode[\"INVALID_EVENT_NAME\"] = \"invalid-event-name\";\r\n StorageErrorCode[\"INVALID_URL\"] = \"invalid-url\";\r\n StorageErrorCode[\"INVALID_DEFAULT_BUCKET\"] = \"invalid-default-bucket\";\r\n StorageErrorCode[\"NO_DEFAULT_BUCKET\"] = \"no-default-bucket\";\r\n StorageErrorCode[\"CANNOT_SLICE_BLOB\"] = \"cannot-slice-blob\";\r\n StorageErrorCode[\"SERVER_FILE_WRONG_SIZE\"] = \"server-file-wrong-size\";\r\n StorageErrorCode[\"NO_DOWNLOAD_URL\"] = \"no-download-url\";\r\n StorageErrorCode[\"INVALID_ARGUMENT\"] = \"invalid-argument\";\r\n StorageErrorCode[\"INVALID_ARGUMENT_COUNT\"] = \"invalid-argument-count\";\r\n StorageErrorCode[\"APP_DELETED\"] = \"app-deleted\";\r\n StorageErrorCode[\"INVALID_ROOT_OPERATION\"] = \"invalid-root-operation\";\r\n StorageErrorCode[\"INVALID_FORMAT\"] = \"invalid-format\";\r\n StorageErrorCode[\"INTERNAL_ERROR\"] = \"internal-error\";\r\n StorageErrorCode[\"UNSUPPORTED_ENVIRONMENT\"] = \"unsupported-environment\";\r\n})(StorageErrorCode || (StorageErrorCode = {}));\r\nfunction prependCode(code) {\r\n return 'storage/' + code;\r\n}\r\nfunction unknown() {\r\n const message = 'An unknown error occurred, please check the error payload for ' +\r\n 'server response.';\r\n return new StorageError(StorageErrorCode.UNKNOWN, message);\r\n}\r\nfunction objectNotFound(path) {\r\n return new StorageError(StorageErrorCode.OBJECT_NOT_FOUND, \"Object '\" + path + \"' does not exist.\");\r\n}\r\nfunction quotaExceeded(bucket) {\r\n return new StorageError(StorageErrorCode.QUOTA_EXCEEDED, \"Quota for bucket '\" +\r\n bucket +\r\n \"' exceeded, please view quota on \" +\r\n 'https://firebase.google.com/pricing/.');\r\n}\r\nfunction unauthenticated() {\r\n const message = 'User is not authenticated, please authenticate using Firebase ' +\r\n 'Authentication and try again.';\r\n return new StorageError(StorageErrorCode.UNAUTHENTICATED, message);\r\n}\r\nfunction unauthorizedApp() {\r\n return new StorageError(StorageErrorCode.UNAUTHORIZED_APP, 'This app does not have permission to access Firebase Storage on this project.');\r\n}\r\nfunction unauthorized(path) {\r\n return new StorageError(StorageErrorCode.UNAUTHORIZED, \"User does not have permission to access '\" + path + \"'.\");\r\n}\r\nfunction retryLimitExceeded() {\r\n return new StorageError(StorageErrorCode.RETRY_LIMIT_EXCEEDED, 'Max retry time for operation exceeded, please try again.');\r\n}\r\nfunction canceled() {\r\n return new StorageError(StorageErrorCode.CANCELED, 'User canceled the upload/download.');\r\n}\r\nfunction invalidUrl(url) {\r\n return new StorageError(StorageErrorCode.INVALID_URL, \"Invalid URL '\" + url + \"'.\");\r\n}\r\nfunction invalidDefaultBucket(bucket) {\r\n return new StorageError(StorageErrorCode.INVALID_DEFAULT_BUCKET, \"Invalid default bucket '\" + bucket + \"'.\");\r\n}\r\nfunction noDefaultBucket() {\r\n return new StorageError(StorageErrorCode.NO_DEFAULT_BUCKET, 'No default bucket ' +\r\n \"found. Did you set the '\" +\r\n CONFIG_STORAGE_BUCKET_KEY +\r\n \"' property when initializing the app?\");\r\n}\r\nfunction cannotSliceBlob() {\r\n return new StorageError(StorageErrorCode.CANNOT_SLICE_BLOB, 'Cannot slice blob for upload. Please retry the upload.');\r\n}\r\nfunction serverFileWrongSize() {\r\n return new StorageError(StorageErrorCode.SERVER_FILE_WRONG_SIZE, 'Server recorded incorrect upload file size, please retry the upload.');\r\n}\r\nfunction noDownloadURL() {\r\n return new StorageError(StorageErrorCode.NO_DOWNLOAD_URL, 'The given file does not have any download URLs.');\r\n}\r\nfunction missingPolyFill(polyFill) {\r\n return new StorageError(StorageErrorCode.UNSUPPORTED_ENVIRONMENT, `${polyFill} is missing. Make sure to install the required polyfills. See https://firebase.google.com/docs/web/environments-js-sdk#polyfills for more information.`);\r\n}\r\n/**\r\n * @internal\r\n */\r\nfunction invalidArgument(message) {\r\n return new StorageError(StorageErrorCode.INVALID_ARGUMENT, message);\r\n}\r\nfunction appDeleted() {\r\n return new StorageError(StorageErrorCode.APP_DELETED, 'The Firebase app was deleted.');\r\n}\r\n/**\r\n * @param name - The name of the operation that was invalid.\r\n *\r\n * @internal\r\n */\r\nfunction invalidRootOperation(name) {\r\n return new StorageError(StorageErrorCode.INVALID_ROOT_OPERATION, \"The operation '\" +\r\n name +\r\n \"' cannot be performed on a root reference, create a non-root \" +\r\n \"reference using child, such as .child('file.png').\");\r\n}\r\n/**\r\n * @param format - The format that was not valid.\r\n * @param message - A message describing the format violation.\r\n */\r\nfunction invalidFormat(format, message) {\r\n return new StorageError(StorageErrorCode.INVALID_FORMAT, \"String does not match format '\" + format + \"': \" + message);\r\n}\r\n/**\r\n * @param message - A message describing the internal error.\r\n */\r\nfunction internalError(message) {\r\n throw new StorageError(StorageErrorCode.INTERNAL_ERROR, 'Internal error: ' + message);\r\n}\n\n/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Firebase Storage location data.\r\n *\r\n * @internal\r\n */\r\nclass Location {\r\n constructor(bucket, path) {\r\n this.bucket = bucket;\r\n this.path_ = path;\r\n }\r\n get path() {\r\n return this.path_;\r\n }\r\n get isRoot() {\r\n return this.path.length === 0;\r\n }\r\n fullServerUrl() {\r\n const encode = encodeURIComponent;\r\n return '/b/' + encode(this.bucket) + '/o/' + encode(this.path);\r\n }\r\n bucketOnlyServerUrl() {\r\n const encode = encodeURIComponent;\r\n return '/b/' + encode(this.bucket) + '/o';\r\n }\r\n static makeFromBucketSpec(bucketString, host) {\r\n let bucketLocation;\r\n try {\r\n bucketLocation = Location.makeFromUrl(bucketString, host);\r\n }\r\n catch (e) {\r\n // Not valid URL, use as-is. This lets you put bare bucket names in\r\n // config.\r\n return new Location(bucketString, '');\r\n }\r\n if (bucketLocation.path === '') {\r\n return bucketLocation;\r\n }\r\n else {\r\n throw invalidDefaultBucket(bucketString);\r\n }\r\n }\r\n static makeFromUrl(url, host) {\r\n let location = null;\r\n const bucketDomain = '([A-Za-z0-9.\\\\-_]+)';\r\n function gsModify(loc) {\r\n if (loc.path.charAt(loc.path.length - 1) === '/') {\r\n loc.path_ = loc.path_.slice(0, -1);\r\n }\r\n }\r\n const gsPath = '(/(.*))?$';\r\n const gsRegex = new RegExp('^gs://' + bucketDomain + gsPath, 'i');\r\n const gsIndices = { bucket: 1, path: 3 };\r\n function httpModify(loc) {\r\n loc.path_ = decodeURIComponent(loc.path);\r\n }\r\n const version = 'v[A-Za-z0-9_]+';\r\n const firebaseStorageHost = host.replace(/[.]/g, '\\\\.');\r\n const firebaseStoragePath = '(/([^?#]*).*)?$';\r\n const firebaseStorageRegExp = new RegExp(`^https?://${firebaseStorageHost}/${version}/b/${bucketDomain}/o${firebaseStoragePath}`, 'i');\r\n const firebaseStorageIndices = { bucket: 1, path: 3 };\r\n const cloudStorageHost = host === DEFAULT_HOST\r\n ? '(?:storage.googleapis.com|storage.cloud.google.com)'\r\n : host;\r\n const cloudStoragePath = '([^?#]*)';\r\n const cloudStorageRegExp = new RegExp(`^https?://${cloudStorageHost}/${bucketDomain}/${cloudStoragePath}`, 'i');\r\n const cloudStorageIndices = { bucket: 1, path: 2 };\r\n const groups = [\r\n { regex: gsRegex, indices: gsIndices, postModify: gsModify },\r\n {\r\n regex: firebaseStorageRegExp,\r\n indices: firebaseStorageIndices,\r\n postModify: httpModify\r\n },\r\n {\r\n regex: cloudStorageRegExp,\r\n indices: cloudStorageIndices,\r\n postModify: httpModify\r\n }\r\n ];\r\n for (let i = 0; i < groups.length; i++) {\r\n const group = groups[i];\r\n const captures = group.regex.exec(url);\r\n if (captures) {\r\n const bucketValue = captures[group.indices.bucket];\r\n let pathValue = captures[group.indices.path];\r\n if (!pathValue) {\r\n pathValue = '';\r\n }\r\n location = new Location(bucketValue, pathValue);\r\n group.postModify(location);\r\n break;\r\n }\r\n }\r\n if (location == null) {\r\n throw invalidUrl(url);\r\n }\r\n return location;\r\n }\r\n}\n\n/**\r\n * A request whose promise always fails.\r\n */\r\nclass FailRequest {\r\n constructor(error) {\r\n this.promise_ = Promise.reject(error);\r\n }\r\n /** @inheritDoc */\r\n getPromise() {\r\n return this.promise_;\r\n }\r\n /** @inheritDoc */\r\n cancel(_appDelete = false) { }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Accepts a callback for an action to perform (`doRequest`),\r\n * and then a callback for when the backoff has completed (`backoffCompleteCb`).\r\n * The callback sent to start requires an argument to call (`onRequestComplete`).\r\n * When `start` calls `doRequest`, it passes a callback for when the request has\r\n * completed, `onRequestComplete`. Based on this, the backoff continues, with\r\n * another call to `doRequest` and the above loop continues until the timeout\r\n * is hit, or a successful response occurs.\r\n * @description\r\n * @param doRequest Callback to perform request\r\n * @param backoffCompleteCb Callback to call when backoff has been completed\r\n */\r\nfunction start(doRequest, \r\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\r\nbackoffCompleteCb, timeout) {\r\n // TODO(andysoto): make this code cleaner (probably refactor into an actual\r\n // type instead of a bunch of functions with state shared in the closure)\r\n let waitSeconds = 1;\r\n // Would type this as \"number\" but that doesn't work for Node so ¯\\_(ツ)_/¯\r\n // TODO: find a way to exclude Node type definition for storage because storage only works in browser\r\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\r\n let retryTimeoutId = null;\r\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\r\n let globalTimeoutId = null;\r\n let hitTimeout = false;\r\n let cancelState = 0;\r\n function canceled() {\r\n return cancelState === 2;\r\n }\r\n let triggeredCallback = false;\r\n function triggerCallback(...args) {\r\n if (!triggeredCallback) {\r\n triggeredCallback = true;\r\n backoffCompleteCb.apply(null, args);\r\n }\r\n }\r\n function callWithDelay(millis) {\r\n retryTimeoutId = setTimeout(() => {\r\n retryTimeoutId = null;\r\n doRequest(responseHandler, canceled());\r\n }, millis);\r\n }\r\n function clearGlobalTimeout() {\r\n if (globalTimeoutId) {\r\n clearTimeout(globalTimeoutId);\r\n }\r\n }\r\n function responseHandler(success, ...args) {\r\n if (triggeredCallback) {\r\n clearGlobalTimeout();\r\n return;\r\n }\r\n if (success) {\r\n clearGlobalTimeout();\r\n triggerCallback.call(null, success, ...args);\r\n return;\r\n }\r\n const mustStop = canceled() || hitTimeout;\r\n if (mustStop) {\r\n clearGlobalTimeout();\r\n triggerCallback.call(null, success, ...args);\r\n return;\r\n }\r\n if (waitSeconds < 64) {\r\n /* TODO(andysoto): don't back off so quickly if we know we're offline. */\r\n waitSeconds *= 2;\r\n }\r\n let waitMillis;\r\n if (cancelState === 1) {\r\n cancelState = 2;\r\n waitMillis = 0;\r\n }\r\n else {\r\n waitMillis = (waitSeconds + Math.random()) * 1000;\r\n }\r\n callWithDelay(waitMillis);\r\n }\r\n let stopped = false;\r\n function stop(wasTimeout) {\r\n if (stopped) {\r\n return;\r\n }\r\n stopped = true;\r\n clearGlobalTimeout();\r\n if (triggeredCallback) {\r\n return;\r\n }\r\n if (retryTimeoutId !== null) {\r\n if (!wasTimeout) {\r\n cancelState = 2;\r\n }\r\n clearTimeout(retryTimeoutId);\r\n callWithDelay(0);\r\n }\r\n else {\r\n if (!wasTimeout) {\r\n cancelState = 1;\r\n }\r\n }\r\n }\r\n callWithDelay(0);\r\n globalTimeoutId = setTimeout(() => {\r\n hitTimeout = true;\r\n stop(true);\r\n }, timeout);\r\n return stop;\r\n}\r\n/**\r\n * Stops the retry loop from repeating.\r\n * If the function is currently \"in between\" retries, it is invoked immediately\r\n * with the second parameter as \"true\". Otherwise, it will be invoked once more\r\n * after the current invocation finishes iff the current invocation would have\r\n * triggered another retry.\r\n */\r\nfunction stop(id) {\r\n id(false);\r\n}\n\n/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nfunction isJustDef(p) {\r\n return p !== void 0;\r\n}\r\n// eslint-disable-next-line @typescript-eslint/ban-types\r\nfunction isFunction(p) {\r\n return typeof p === 'function';\r\n}\r\nfunction isNonArrayObject(p) {\r\n return typeof p === 'object' && !Array.isArray(p);\r\n}\r\nfunction isString(p) {\r\n return typeof p === 'string' || p instanceof String;\r\n}\r\nfunction isNativeBlob(p) {\r\n return isNativeBlobDefined() && p instanceof Blob;\r\n}\r\nfunction isNativeBlobDefined() {\r\n // Note: The `isNode()` check can be removed when `node-fetch` adds native Blob support\r\n // PR: https://github.com/node-fetch/node-fetch/pull/1664\r\n return typeof Blob !== 'undefined' && !isNode();\r\n}\r\nfunction validateNumber(argument, minValue, maxValue, value) {\r\n if (value < minValue) {\r\n throw invalidArgument(`Invalid value for '${argument}'. Expected ${minValue} or greater.`);\r\n }\r\n if (value > maxValue) {\r\n throw invalidArgument(`Invalid value for '${argument}'. Expected ${maxValue} or less.`);\r\n }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nfunction makeUrl(urlPart, host, protocol) {\r\n let origin = host;\r\n if (protocol == null) {\r\n origin = `https://${host}`;\r\n }\r\n return `${protocol}://${origin}/v0${urlPart}`;\r\n}\r\nfunction makeQueryString(params) {\r\n const encode = encodeURIComponent;\r\n let queryPart = '?';\r\n for (const key in params) {\r\n if (params.hasOwnProperty(key)) {\r\n const nextPart = encode(key) + '=' + encode(params[key]);\r\n queryPart = queryPart + nextPart + '&';\r\n }\r\n }\r\n // Chop off the extra '&' or '?' on the end\r\n queryPart = queryPart.slice(0, -1);\r\n return queryPart;\r\n}\n\n/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Error codes for requests made by the the XhrIo wrapper.\r\n */\r\nvar ErrorCode;\r\n(function (ErrorCode) {\r\n ErrorCode[ErrorCode[\"NO_ERROR\"] = 0] = \"NO_ERROR\";\r\n ErrorCode[ErrorCode[\"NETWORK_ERROR\"] = 1] = \"NETWORK_ERROR\";\r\n ErrorCode[ErrorCode[\"ABORT\"] = 2] = \"ABORT\";\r\n})(ErrorCode || (ErrorCode = {}));\n\n/**\r\n * @license\r\n * Copyright 2022 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Checks the status code to see if the action should be retried.\r\n *\r\n * @param status Current HTTP status code returned by server.\r\n * @param additionalRetryCodes additional retry codes to check against\r\n */\r\nfunction isRetryStatusCode(status, additionalRetryCodes) {\r\n // The codes for which to retry came from this page:\r\n // https://cloud.google.com/storage/docs/exponential-backoff\r\n const isFiveHundredCode = status >= 500 && status < 600;\r\n const extraRetryCodes = [\r\n // Request Timeout: web server didn't receive full request in time.\r\n 408,\r\n // Too Many Requests: you're getting rate-limited, basically.\r\n 429\r\n ];\r\n const isExtraRetryCode = extraRetryCodes.indexOf(status) !== -1;\r\n const isAdditionalRetryCode = additionalRetryCodes.indexOf(status) !== -1;\r\n return isFiveHundredCode || isExtraRetryCode || isAdditionalRetryCode;\r\n}\n\n/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Handles network logic for all Storage Requests, including error reporting and\r\n * retries with backoff.\r\n *\r\n * @param I - the type of the backend's network response.\r\n * @param - O the output type used by the rest of the SDK. The conversion\r\n * happens in the specified `callback_`.\r\n */\r\nclass NetworkRequest {\r\n constructor(url_, method_, headers_, body_, successCodes_, additionalRetryCodes_, callback_, errorCallback_, timeout_, progressCallback_, connectionFactory_, retry = true) {\r\n this.url_ = url_;\r\n this.method_ = method_;\r\n this.headers_ = headers_;\r\n this.body_ = body_;\r\n this.successCodes_ = successCodes_;\r\n this.additionalRetryCodes_ = additionalRetryCodes_;\r\n this.callback_ = callback_;\r\n this.errorCallback_ = errorCallback_;\r\n this.timeout_ = timeout_;\r\n this.progressCallback_ = progressCallback_;\r\n this.connectionFactory_ = connectionFactory_;\r\n this.retry = retry;\r\n this.pendingConnection_ = null;\r\n this.backoffId_ = null;\r\n this.canceled_ = false;\r\n this.appDelete_ = false;\r\n this.promise_ = new Promise((resolve, reject) => {\r\n this.resolve_ = resolve;\r\n this.reject_ = reject;\r\n this.start_();\r\n });\r\n }\r\n /**\r\n * Actually starts the retry loop.\r\n */\r\n start_() {\r\n const doTheRequest = (backoffCallback, canceled) => {\r\n if (canceled) {\r\n backoffCallback(false, new RequestEndStatus(false, null, true));\r\n return;\r\n }\r\n const connection = this.connectionFactory_();\r\n this.pendingConnection_ = connection;\r\n const progressListener = progressEvent => {\r\n const loaded = progressEvent.loaded;\r\n const total = progressEvent.lengthComputable ? progressEvent.total : -1;\r\n if (this.progressCallback_ !== null) {\r\n this.progressCallback_(loaded, total);\r\n }\r\n };\r\n if (this.progressCallback_ !== null) {\r\n connection.addUploadProgressListener(progressListener);\r\n }\r\n // connection.send() never rejects, so we don't need to have a error handler or use catch on the returned promise.\r\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\r\n connection\r\n .send(this.url_, this.method_, this.body_, this.headers_)\r\n .then(() => {\r\n if (this.progressCallback_ !== null) {\r\n connection.removeUploadProgressListener(progressListener);\r\n }\r\n this.pendingConnection_ = null;\r\n const hitServer = connection.getErrorCode() === ErrorCode.NO_ERROR;\r\n const status = connection.getStatus();\r\n if (!hitServer ||\r\n (isRetryStatusCode(status, this.additionalRetryCodes_) &&\r\n this.retry)) {\r\n const wasCanceled = connection.getErrorCode() === ErrorCode.ABORT;\r\n backoffCallback(false, new RequestEndStatus(false, null, wasCanceled));\r\n return;\r\n }\r\n const successCode = this.successCodes_.indexOf(status) !== -1;\r\n backoffCallback(true, new RequestEndStatus(successCode, connection));\r\n });\r\n };\r\n /**\r\n * @param requestWentThrough - True if the request eventually went\r\n * through, false if it hit the retry limit or was canceled.\r\n */\r\n const backoffDone = (requestWentThrough, status) => {\r\n const resolve = this.resolve_;\r\n const reject = this.reject_;\r\n const connection = status.connection;\r\n if (status.wasSuccessCode) {\r\n try {\r\n const result = this.callback_(connection, connection.getResponse());\r\n if (isJustDef(result)) {\r\n resolve(result);\r\n }\r\n else {\r\n resolve();\r\n }\r\n }\r\n catch (e) {\r\n reject(e);\r\n }\r\n }\r\n else {\r\n if (connection !== null) {\r\n const err = unknown();\r\n err.serverResponse = connection.getErrorText();\r\n if (this.errorCallback_) {\r\n reject(this.errorCallback_(connection, err));\r\n }\r\n else {\r\n reject(err);\r\n }\r\n }\r\n else {\r\n if (status.canceled) {\r\n const err = this.appDelete_ ? appDeleted() : canceled();\r\n reject(err);\r\n }\r\n else {\r\n const err = retryLimitExceeded();\r\n reject(err);\r\n }\r\n }\r\n }\r\n };\r\n if (this.canceled_) {\r\n backoffDone(false, new RequestEndStatus(false, null, true));\r\n }\r\n else {\r\n this.backoffId_ = start(doTheRequest, backoffDone, this.timeout_);\r\n }\r\n }\r\n /** @inheritDoc */\r\n getPromise() {\r\n return this.promise_;\r\n }\r\n /** @inheritDoc */\r\n cancel(appDelete) {\r\n this.canceled_ = true;\r\n this.appDelete_ = appDelete || false;\r\n if (this.backoffId_ !== null) {\r\n stop(this.backoffId_);\r\n }\r\n if (this.pendingConnection_ !== null) {\r\n this.pendingConnection_.abort();\r\n }\r\n }\r\n}\r\n/**\r\n * A collection of information about the result of a network request.\r\n * @param opt_canceled - Defaults to false.\r\n */\r\nclass RequestEndStatus {\r\n constructor(wasSuccessCode, connection, canceled) {\r\n this.wasSuccessCode = wasSuccessCode;\r\n this.connection = connection;\r\n this.canceled = !!canceled;\r\n }\r\n}\r\nfunction addAuthHeader_(headers, authToken) {\r\n if (authToken !== null && authToken.length > 0) {\r\n headers['Authorization'] = 'Firebase ' + authToken;\r\n }\r\n}\r\nfunction addVersionHeader_(headers, firebaseVersion) {\r\n headers['X-Firebase-Storage-Version'] =\r\n 'webjs/' + (firebaseVersion !== null && firebaseVersion !== void 0 ? firebaseVersion : 'AppManager');\r\n}\r\nfunction addGmpidHeader_(headers, appId) {\r\n if (appId) {\r\n headers['X-Firebase-GMPID'] = appId;\r\n }\r\n}\r\nfunction addAppCheckHeader_(headers, appCheckToken) {\r\n if (appCheckToken !== null) {\r\n headers['X-Firebase-AppCheck'] = appCheckToken;\r\n }\r\n}\r\nfunction makeRequest(requestInfo, appId, authToken, appCheckToken, requestFactory, firebaseVersion, retry = true) {\r\n const queryPart = makeQueryString(requestInfo.urlParams);\r\n const url = requestInfo.url + queryPart;\r\n const headers = Object.assign({}, requestInfo.headers);\r\n addGmpidHeader_(headers, appId);\r\n addAuthHeader_(headers, authToken);\r\n addVersionHeader_(headers, firebaseVersion);\r\n addAppCheckHeader_(headers, appCheckToken);\r\n return new NetworkRequest(url, requestInfo.method, headers, requestInfo.body, requestInfo.successCodes, requestInfo.additionalRetryCodes, requestInfo.handler, requestInfo.errorHandler, requestInfo.timeout, requestInfo.progressCallback, requestFactory, retry);\r\n}\n\n/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nfunction getBlobBuilder() {\r\n if (typeof BlobBuilder !== 'undefined') {\r\n return BlobBuilder;\r\n }\r\n else if (typeof WebKitBlobBuilder !== 'undefined') {\r\n return WebKitBlobBuilder;\r\n }\r\n else {\r\n return undefined;\r\n }\r\n}\r\n/**\r\n * Concatenates one or more values together and converts them to a Blob.\r\n *\r\n * @param args The values that will make up the resulting blob.\r\n * @return The blob.\r\n */\r\nfunction getBlob$1(...args) {\r\n const BlobBuilder = getBlobBuilder();\r\n if (BlobBuilder !== undefined) {\r\n const bb = new BlobBuilder();\r\n for (let i = 0; i < args.length; i++) {\r\n bb.append(args[i]);\r\n }\r\n return bb.getBlob();\r\n }\r\n else {\r\n if (isNativeBlobDefined()) {\r\n return new Blob(args);\r\n }\r\n else {\r\n throw new StorageError(StorageErrorCode.UNSUPPORTED_ENVIRONMENT, \"This browser doesn't seem to support creating Blobs\");\r\n }\r\n }\r\n}\r\n/**\r\n * Slices the blob. The returned blob contains data from the start byte\r\n * (inclusive) till the end byte (exclusive). Negative indices cannot be used.\r\n *\r\n * @param blob The blob to be sliced.\r\n * @param start Index of the starting byte.\r\n * @param end Index of the ending byte.\r\n * @return The blob slice or null if not supported.\r\n */\r\nfunction sliceBlob(blob, start, end) {\r\n if (blob.webkitSlice) {\r\n return blob.webkitSlice(start, end);\r\n }\r\n else if (blob.mozSlice) {\r\n return blob.mozSlice(start, end);\r\n }\r\n else if (blob.slice) {\r\n return blob.slice(start, end);\r\n }\r\n return null;\r\n}\n\n/**\r\n * @license\r\n * Copyright 2021 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/** Converts a Base64 encoded string to a binary string. */\r\nfunction decodeBase64(encoded) {\r\n if (typeof atob === 'undefined') {\r\n throw missingPolyFill('base-64');\r\n }\r\n return atob(encoded);\r\n}\n\n/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * An enumeration of the possible string formats for upload.\r\n * @public\r\n */\r\nconst StringFormat = {\r\n /**\r\n * Indicates the string should be interpreted \"raw\", that is, as normal text.\r\n * The string will be interpreted as UTF-16, then uploaded as a UTF-8 byte\r\n * sequence.\r\n * Example: The string 'Hello! \\\\ud83d\\\\ude0a' becomes the byte sequence\r\n * 48 65 6c 6c 6f 21 20 f0 9f 98 8a\r\n */\r\n RAW: 'raw',\r\n /**\r\n * Indicates the string should be interpreted as base64-encoded data.\r\n * Padding characters (trailing '='s) are optional.\r\n * Example: The string 'rWmO++E6t7/rlw==' becomes the byte sequence\r\n * ad 69 8e fb e1 3a b7 bf eb 97\r\n */\r\n BASE64: 'base64',\r\n /**\r\n * Indicates the string should be interpreted as base64url-encoded data.\r\n * Padding characters (trailing '='s) are optional.\r\n * Example: The string 'rWmO--E6t7_rlw==' becomes the byte sequence\r\n * ad 69 8e fb e1 3a b7 bf eb 97\r\n */\r\n BASE64URL: 'base64url',\r\n /**\r\n * Indicates the string is a data URL, such as one obtained from\r\n * canvas.toDataURL().\r\n * Example: the string 'data:application/octet-stream;base64,aaaa'\r\n * becomes the byte sequence\r\n * 69 a6 9a\r\n * (the content-type \"application/octet-stream\" is also applied, but can\r\n * be overridden in the metadata object).\r\n */\r\n DATA_URL: 'data_url'\r\n};\r\nclass StringData {\r\n constructor(data, contentType) {\r\n this.data = data;\r\n this.contentType = contentType || null;\r\n }\r\n}\r\n/**\r\n * @internal\r\n */\r\nfunction dataFromString(format, stringData) {\r\n switch (format) {\r\n case StringFormat.RAW:\r\n return new StringData(utf8Bytes_(stringData));\r\n case StringFormat.BASE64:\r\n case StringFormat.BASE64URL:\r\n return new StringData(base64Bytes_(format, stringData));\r\n case StringFormat.DATA_URL:\r\n return new StringData(dataURLBytes_(stringData), dataURLContentType_(stringData));\r\n // do nothing\r\n }\r\n // assert(false);\r\n throw unknown();\r\n}\r\nfunction utf8Bytes_(value) {\r\n const b = [];\r\n for (let i = 0; i < value.length; i++) {\r\n let c = value.charCodeAt(i);\r\n if (c <= 127) {\r\n b.push(c);\r\n }\r\n else {\r\n if (c <= 2047) {\r\n b.push(192 | (c >> 6), 128 | (c & 63));\r\n }\r\n else {\r\n if ((c & 64512) === 55296) {\r\n // The start of a surrogate pair.\r\n const valid = i < value.length - 1 && (value.charCodeAt(i + 1) & 64512) === 56320;\r\n if (!valid) {\r\n // The second surrogate wasn't there.\r\n b.push(239, 191, 189);\r\n }\r\n else {\r\n const hi = c;\r\n const lo = value.charCodeAt(++i);\r\n c = 65536 | ((hi & 1023) << 10) | (lo & 1023);\r\n b.push(240 | (c >> 18), 128 | ((c >> 12) & 63), 128 | ((c >> 6) & 63), 128 | (c & 63));\r\n }\r\n }\r\n else {\r\n if ((c & 64512) === 56320) {\r\n // Invalid low surrogate.\r\n b.push(239, 191, 189);\r\n }\r\n else {\r\n b.push(224 | (c >> 12), 128 | ((c >> 6) & 63), 128 | (c & 63));\r\n }\r\n }\r\n }\r\n }\r\n }\r\n return new Uint8Array(b);\r\n}\r\nfunction percentEncodedBytes_(value) {\r\n let decoded;\r\n try {\r\n decoded = decodeURIComponent(value);\r\n }\r\n catch (e) {\r\n throw invalidFormat(StringFormat.DATA_URL, 'Malformed data URL.');\r\n }\r\n return utf8Bytes_(decoded);\r\n}\r\nfunction base64Bytes_(format, value) {\r\n switch (format) {\r\n case StringFormat.BASE64: {\r\n const hasMinus = value.indexOf('-') !== -1;\r\n const hasUnder = value.indexOf('_') !== -1;\r\n if (hasMinus || hasUnder) {\r\n const invalidChar = hasMinus ? '-' : '_';\r\n throw invalidFormat(format, \"Invalid character '\" +\r\n invalidChar +\r\n \"' found: is it base64url encoded?\");\r\n }\r\n break;\r\n }\r\n case StringFormat.BASE64URL: {\r\n const hasPlus = value.indexOf('+') !== -1;\r\n const hasSlash = value.indexOf('/') !== -1;\r\n if (hasPlus || hasSlash) {\r\n const invalidChar = hasPlus ? '+' : '/';\r\n throw invalidFormat(format, \"Invalid character '\" + invalidChar + \"' found: is it base64 encoded?\");\r\n }\r\n value = value.replace(/-/g, '+').replace(/_/g, '/');\r\n break;\r\n }\r\n // do nothing\r\n }\r\n let bytes;\r\n try {\r\n bytes = decodeBase64(value);\r\n }\r\n catch (e) {\r\n if (e.message.includes('polyfill')) {\r\n throw e;\r\n }\r\n throw invalidFormat(format, 'Invalid character found');\r\n }\r\n const array = new Uint8Array(bytes.length);\r\n for (let i = 0; i < bytes.length; i++) {\r\n array[i] = bytes.charCodeAt(i);\r\n }\r\n return array;\r\n}\r\nclass DataURLParts {\r\n constructor(dataURL) {\r\n this.base64 = false;\r\n this.contentType = null;\r\n const matches = dataURL.match(/^data:([^,]+)?,/);\r\n if (matches === null) {\r\n throw invalidFormat(StringFormat.DATA_URL, \"Must be formatted 'data:[][;base64],\");\r\n }\r\n const middle = matches[1] || null;\r\n if (middle != null) {\r\n this.base64 = endsWith(middle, ';base64');\r\n this.contentType = this.base64\r\n ? middle.substring(0, middle.length - ';base64'.length)\r\n : middle;\r\n }\r\n this.rest = dataURL.substring(dataURL.indexOf(',') + 1);\r\n }\r\n}\r\nfunction dataURLBytes_(dataUrl) {\r\n const parts = new DataURLParts(dataUrl);\r\n if (parts.base64) {\r\n return base64Bytes_(StringFormat.BASE64, parts.rest);\r\n }\r\n else {\r\n return percentEncodedBytes_(parts.rest);\r\n }\r\n}\r\nfunction dataURLContentType_(dataUrl) {\r\n const parts = new DataURLParts(dataUrl);\r\n return parts.contentType;\r\n}\r\nfunction endsWith(s, end) {\r\n const longEnough = s.length >= end.length;\r\n if (!longEnough) {\r\n return false;\r\n }\r\n return s.substring(s.length - end.length) === end;\r\n}\n\n/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * @param opt_elideCopy - If true, doesn't copy mutable input data\r\n * (e.g. Uint8Arrays). Pass true only if you know the objects will not be\r\n * modified after this blob's construction.\r\n *\r\n * @internal\r\n */\r\nclass FbsBlob {\r\n constructor(data, elideCopy) {\r\n let size = 0;\r\n let blobType = '';\r\n if (isNativeBlob(data)) {\r\n this.data_ = data;\r\n size = data.size;\r\n blobType = data.type;\r\n }\r\n else if (data instanceof ArrayBuffer) {\r\n if (elideCopy) {\r\n this.data_ = new Uint8Array(data);\r\n }\r\n else {\r\n this.data_ = new Uint8Array(data.byteLength);\r\n this.data_.set(new Uint8Array(data));\r\n }\r\n size = this.data_.length;\r\n }\r\n else if (data instanceof Uint8Array) {\r\n if (elideCopy) {\r\n this.data_ = data;\r\n }\r\n else {\r\n this.data_ = new Uint8Array(data.length);\r\n this.data_.set(data);\r\n }\r\n size = data.length;\r\n }\r\n this.size_ = size;\r\n this.type_ = blobType;\r\n }\r\n size() {\r\n return this.size_;\r\n }\r\n type() {\r\n return this.type_;\r\n }\r\n slice(startByte, endByte) {\r\n if (isNativeBlob(this.data_)) {\r\n const realBlob = this.data_;\r\n const sliced = sliceBlob(realBlob, startByte, endByte);\r\n if (sliced === null) {\r\n return null;\r\n }\r\n return new FbsBlob(sliced);\r\n }\r\n else {\r\n const slice = new Uint8Array(this.data_.buffer, startByte, endByte - startByte);\r\n return new FbsBlob(slice, true);\r\n }\r\n }\r\n static getBlob(...args) {\r\n if (isNativeBlobDefined()) {\r\n const blobby = args.map((val) => {\r\n if (val instanceof FbsBlob) {\r\n return val.data_;\r\n }\r\n else {\r\n return val;\r\n }\r\n });\r\n return new FbsBlob(getBlob$1.apply(null, blobby));\r\n }\r\n else {\r\n const uint8Arrays = args.map((val) => {\r\n if (isString(val)) {\r\n return dataFromString(StringFormat.RAW, val).data;\r\n }\r\n else {\r\n // Blobs don't exist, so this has to be a Uint8Array.\r\n return val.data_;\r\n }\r\n });\r\n let finalLength = 0;\r\n uint8Arrays.forEach((array) => {\r\n finalLength += array.byteLength;\r\n });\r\n const merged = new Uint8Array(finalLength);\r\n let index = 0;\r\n uint8Arrays.forEach((array) => {\r\n for (let i = 0; i < array.length; i++) {\r\n merged[index++] = array[i];\r\n }\r\n });\r\n return new FbsBlob(merged, true);\r\n }\r\n }\r\n uploadData() {\r\n return this.data_;\r\n }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Returns the Object resulting from parsing the given JSON, or null if the\r\n * given string does not represent a JSON object.\r\n */\r\nfunction jsonObjectOrNull(s) {\r\n let obj;\r\n try {\r\n obj = JSON.parse(s);\r\n }\r\n catch (e) {\r\n return null;\r\n }\r\n if (isNonArrayObject(obj)) {\r\n return obj;\r\n }\r\n else {\r\n return null;\r\n }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * @fileoverview Contains helper methods for manipulating paths.\r\n */\r\n/**\r\n * @return Null if the path is already at the root.\r\n */\r\nfunction parent(path) {\r\n if (path.length === 0) {\r\n return null;\r\n }\r\n const index = path.lastIndexOf('/');\r\n if (index === -1) {\r\n return '';\r\n }\r\n const newPath = path.slice(0, index);\r\n return newPath;\r\n}\r\nfunction child(path, childPath) {\r\n const canonicalChildPath = childPath\r\n .split('/')\r\n .filter(component => component.length > 0)\r\n .join('/');\r\n if (path.length === 0) {\r\n return canonicalChildPath;\r\n }\r\n else {\r\n return path + '/' + canonicalChildPath;\r\n }\r\n}\r\n/**\r\n * Returns the last component of a path.\r\n * '/foo/bar' -> 'bar'\r\n * '/foo/bar/baz/' -> 'baz/'\r\n * '/a' -> 'a'\r\n */\r\nfunction lastComponent(path) {\r\n const index = path.lastIndexOf('/', path.length - 2);\r\n if (index === -1) {\r\n return path;\r\n }\r\n else {\r\n return path.slice(index + 1);\r\n }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nfunction noXform_(metadata, value) {\r\n return value;\r\n}\r\nclass Mapping {\r\n constructor(server, local, writable, xform) {\r\n this.server = server;\r\n this.local = local || server;\r\n this.writable = !!writable;\r\n this.xform = xform || noXform_;\r\n }\r\n}\r\nlet mappings_ = null;\r\nfunction xformPath(fullPath) {\r\n if (!isString(fullPath) || fullPath.length < 2) {\r\n return fullPath;\r\n }\r\n else {\r\n return lastComponent(fullPath);\r\n }\r\n}\r\nfunction getMappings() {\r\n if (mappings_) {\r\n return mappings_;\r\n }\r\n const mappings = [];\r\n mappings.push(new Mapping('bucket'));\r\n mappings.push(new Mapping('generation'));\r\n mappings.push(new Mapping('metageneration'));\r\n mappings.push(new Mapping('name', 'fullPath', true));\r\n function mappingsXformPath(_metadata, fullPath) {\r\n return xformPath(fullPath);\r\n }\r\n const nameMapping = new Mapping('name');\r\n nameMapping.xform = mappingsXformPath;\r\n mappings.push(nameMapping);\r\n /**\r\n * Coerces the second param to a number, if it is defined.\r\n */\r\n function xformSize(_metadata, size) {\r\n if (size !== undefined) {\r\n return Number(size);\r\n }\r\n else {\r\n return size;\r\n }\r\n }\r\n const sizeMapping = new Mapping('size');\r\n sizeMapping.xform = xformSize;\r\n mappings.push(sizeMapping);\r\n mappings.push(new Mapping('timeCreated'));\r\n mappings.push(new Mapping('updated'));\r\n mappings.push(new Mapping('md5Hash', null, true));\r\n mappings.push(new Mapping('cacheControl', null, true));\r\n mappings.push(new Mapping('contentDisposition', null, true));\r\n mappings.push(new Mapping('contentEncoding', null, true));\r\n mappings.push(new Mapping('contentLanguage', null, true));\r\n mappings.push(new Mapping('contentType', null, true));\r\n mappings.push(new Mapping('metadata', 'customMetadata', true));\r\n mappings_ = mappings;\r\n return mappings_;\r\n}\r\nfunction addRef(metadata, service) {\r\n function generateRef() {\r\n const bucket = metadata['bucket'];\r\n const path = metadata['fullPath'];\r\n const loc = new Location(bucket, path);\r\n return service._makeStorageReference(loc);\r\n }\r\n Object.defineProperty(metadata, 'ref', { get: generateRef });\r\n}\r\nfunction fromResource(service, resource, mappings) {\r\n const metadata = {};\r\n metadata['type'] = 'file';\r\n const len = mappings.length;\r\n for (let i = 0; i < len; i++) {\r\n const mapping = mappings[i];\r\n metadata[mapping.local] = mapping.xform(metadata, resource[mapping.server]);\r\n }\r\n addRef(metadata, service);\r\n return metadata;\r\n}\r\nfunction fromResourceString(service, resourceString, mappings) {\r\n const obj = jsonObjectOrNull(resourceString);\r\n if (obj === null) {\r\n return null;\r\n }\r\n const resource = obj;\r\n return fromResource(service, resource, mappings);\r\n}\r\nfunction downloadUrlFromResourceString(metadata, resourceString, host, protocol) {\r\n const obj = jsonObjectOrNull(resourceString);\r\n if (obj === null) {\r\n return null;\r\n }\r\n if (!isString(obj['downloadTokens'])) {\r\n // This can happen if objects are uploaded through GCS and retrieved\r\n // through list, so we don't want to throw an Error.\r\n return null;\r\n }\r\n const tokens = obj['downloadTokens'];\r\n if (tokens.length === 0) {\r\n return null;\r\n }\r\n const encode = encodeURIComponent;\r\n const tokensList = tokens.split(',');\r\n const urls = tokensList.map((token) => {\r\n const bucket = metadata['bucket'];\r\n const path = metadata['fullPath'];\r\n const urlPart = '/b/' + encode(bucket) + '/o/' + encode(path);\r\n const base = makeUrl(urlPart, host, protocol);\r\n const queryString = makeQueryString({\r\n alt: 'media',\r\n token\r\n });\r\n return base + queryString;\r\n });\r\n return urls[0];\r\n}\r\nfunction toResourceString(metadata, mappings) {\r\n const resource = {};\r\n const len = mappings.length;\r\n for (let i = 0; i < len; i++) {\r\n const mapping = mappings[i];\r\n if (mapping.writable) {\r\n resource[mapping.server] = metadata[mapping.local];\r\n }\r\n }\r\n return JSON.stringify(resource);\r\n}\n\n/**\r\n * @license\r\n * Copyright 2019 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nconst PREFIXES_KEY = 'prefixes';\r\nconst ITEMS_KEY = 'items';\r\nfunction fromBackendResponse(service, bucket, resource) {\r\n const listResult = {\r\n prefixes: [],\r\n items: [],\r\n nextPageToken: resource['nextPageToken']\r\n };\r\n if (resource[PREFIXES_KEY]) {\r\n for (const path of resource[PREFIXES_KEY]) {\r\n const pathWithoutTrailingSlash = path.replace(/\\/$/, '');\r\n const reference = service._makeStorageReference(new Location(bucket, pathWithoutTrailingSlash));\r\n listResult.prefixes.push(reference);\r\n }\r\n }\r\n if (resource[ITEMS_KEY]) {\r\n for (const item of resource[ITEMS_KEY]) {\r\n const reference = service._makeStorageReference(new Location(bucket, item['name']));\r\n listResult.items.push(reference);\r\n }\r\n }\r\n return listResult;\r\n}\r\nfunction fromResponseString(service, bucket, resourceString) {\r\n const obj = jsonObjectOrNull(resourceString);\r\n if (obj === null) {\r\n return null;\r\n }\r\n const resource = obj;\r\n return fromBackendResponse(service, bucket, resource);\r\n}\n\n/**\r\n * Contains a fully specified request.\r\n *\r\n * @param I - the type of the backend's network response.\r\n * @param O - the output response type used by the rest of the SDK.\r\n */\r\nclass RequestInfo {\r\n constructor(url, method, \r\n /**\r\n * Returns the value with which to resolve the request's promise. Only called\r\n * if the request is successful. Throw from this function to reject the\r\n * returned Request's promise with the thrown error.\r\n * Note: The XhrIo passed to this function may be reused after this callback\r\n * returns. Do not keep a reference to it in any way.\r\n */\r\n handler, timeout) {\r\n this.url = url;\r\n this.method = method;\r\n this.handler = handler;\r\n this.timeout = timeout;\r\n this.urlParams = {};\r\n this.headers = {};\r\n this.body = null;\r\n this.errorHandler = null;\r\n /**\r\n * Called with the current number of bytes uploaded and total size (-1 if not\r\n * computable) of the request body (i.e. used to report upload progress).\r\n */\r\n this.progressCallback = null;\r\n this.successCodes = [200];\r\n this.additionalRetryCodes = [];\r\n }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Throws the UNKNOWN StorageError if cndn is false.\r\n */\r\nfunction handlerCheck(cndn) {\r\n if (!cndn) {\r\n throw unknown();\r\n }\r\n}\r\nfunction metadataHandler(service, mappings) {\r\n function handler(xhr, text) {\r\n const metadata = fromResourceString(service, text, mappings);\r\n handlerCheck(metadata !== null);\r\n return metadata;\r\n }\r\n return handler;\r\n}\r\nfunction listHandler(service, bucket) {\r\n function handler(xhr, text) {\r\n const listResult = fromResponseString(service, bucket, text);\r\n handlerCheck(listResult !== null);\r\n return listResult;\r\n }\r\n return handler;\r\n}\r\nfunction downloadUrlHandler(service, mappings) {\r\n function handler(xhr, text) {\r\n const metadata = fromResourceString(service, text, mappings);\r\n handlerCheck(metadata !== null);\r\n return downloadUrlFromResourceString(metadata, text, service.host, service._protocol);\r\n }\r\n return handler;\r\n}\r\nfunction sharedErrorHandler(location) {\r\n function errorHandler(xhr, err) {\r\n let newErr;\r\n if (xhr.getStatus() === 401) {\r\n if (\r\n // This exact message string is the only consistent part of the\r\n // server's error response that identifies it as an App Check error.\r\n xhr.getErrorText().includes('Firebase App Check token is invalid')) {\r\n newErr = unauthorizedApp();\r\n }\r\n else {\r\n newErr = unauthenticated();\r\n }\r\n }\r\n else {\r\n if (xhr.getStatus() === 402) {\r\n newErr = quotaExceeded(location.bucket);\r\n }\r\n else {\r\n if (xhr.getStatus() === 403) {\r\n newErr = unauthorized(location.path);\r\n }\r\n else {\r\n newErr = err;\r\n }\r\n }\r\n }\r\n newErr.status = xhr.getStatus();\r\n newErr.serverResponse = err.serverResponse;\r\n return newErr;\r\n }\r\n return errorHandler;\r\n}\r\nfunction objectErrorHandler(location) {\r\n const shared = sharedErrorHandler(location);\r\n function errorHandler(xhr, err) {\r\n let newErr = shared(xhr, err);\r\n if (xhr.getStatus() === 404) {\r\n newErr = objectNotFound(location.path);\r\n }\r\n newErr.serverResponse = err.serverResponse;\r\n return newErr;\r\n }\r\n return errorHandler;\r\n}\r\nfunction getMetadata$2(service, location, mappings) {\r\n const urlPart = location.fullServerUrl();\r\n const url = makeUrl(urlPart, service.host, service._protocol);\r\n const method = 'GET';\r\n const timeout = service.maxOperationRetryTime;\r\n const requestInfo = new RequestInfo(url, method, metadataHandler(service, mappings), timeout);\r\n requestInfo.errorHandler = objectErrorHandler(location);\r\n return requestInfo;\r\n}\r\nfunction list$2(service, location, delimiter, pageToken, maxResults) {\r\n const urlParams = {};\r\n if (location.isRoot) {\r\n urlParams['prefix'] = '';\r\n }\r\n else {\r\n urlParams['prefix'] = location.path + '/';\r\n }\r\n if (delimiter && delimiter.length > 0) {\r\n urlParams['delimiter'] = delimiter;\r\n }\r\n if (pageToken) {\r\n urlParams['pageToken'] = pageToken;\r\n }\r\n if (maxResults) {\r\n urlParams['maxResults'] = maxResults;\r\n }\r\n const urlPart = location.bucketOnlyServerUrl();\r\n const url = makeUrl(urlPart, service.host, service._protocol);\r\n const method = 'GET';\r\n const timeout = service.maxOperationRetryTime;\r\n const requestInfo = new RequestInfo(url, method, listHandler(service, location.bucket), timeout);\r\n requestInfo.urlParams = urlParams;\r\n requestInfo.errorHandler = sharedErrorHandler(location);\r\n return requestInfo;\r\n}\r\nfunction getBytes$1(service, location, maxDownloadSizeBytes) {\r\n const urlPart = location.fullServerUrl();\r\n const url = makeUrl(urlPart, service.host, service._protocol) + '?alt=media';\r\n const method = 'GET';\r\n const timeout = service.maxOperationRetryTime;\r\n const requestInfo = new RequestInfo(url, method, (_, data) => data, timeout);\r\n requestInfo.errorHandler = objectErrorHandler(location);\r\n if (maxDownloadSizeBytes !== undefined) {\r\n requestInfo.headers['Range'] = `bytes=0-${maxDownloadSizeBytes}`;\r\n requestInfo.successCodes = [200 /* OK */, 206 /* Partial Content */];\r\n }\r\n return requestInfo;\r\n}\r\nfunction getDownloadUrl(service, location, mappings) {\r\n const urlPart = location.fullServerUrl();\r\n const url = makeUrl(urlPart, service.host, service._protocol);\r\n const method = 'GET';\r\n const timeout = service.maxOperationRetryTime;\r\n const requestInfo = new RequestInfo(url, method, downloadUrlHandler(service, mappings), timeout);\r\n requestInfo.errorHandler = objectErrorHandler(location);\r\n return requestInfo;\r\n}\r\nfunction updateMetadata$2(service, location, metadata, mappings) {\r\n const urlPart = location.fullServerUrl();\r\n const url = makeUrl(urlPart, service.host, service._protocol);\r\n const method = 'PATCH';\r\n const body = toResourceString(metadata, mappings);\r\n const headers = { 'Content-Type': 'application/json; charset=utf-8' };\r\n const timeout = service.maxOperationRetryTime;\r\n const requestInfo = new RequestInfo(url, method, metadataHandler(service, mappings), timeout);\r\n requestInfo.headers = headers;\r\n requestInfo.body = body;\r\n requestInfo.errorHandler = objectErrorHandler(location);\r\n return requestInfo;\r\n}\r\nfunction deleteObject$2(service, location) {\r\n const urlPart = location.fullServerUrl();\r\n const url = makeUrl(urlPart, service.host, service._protocol);\r\n const method = 'DELETE';\r\n const timeout = service.maxOperationRetryTime;\r\n function handler(_xhr, _text) { }\r\n const requestInfo = new RequestInfo(url, method, handler, timeout);\r\n requestInfo.successCodes = [200, 204];\r\n requestInfo.errorHandler = objectErrorHandler(location);\r\n return requestInfo;\r\n}\r\nfunction determineContentType_(metadata, blob) {\r\n return ((metadata && metadata['contentType']) ||\r\n (blob && blob.type()) ||\r\n 'application/octet-stream');\r\n}\r\nfunction metadataForUpload_(location, blob, metadata) {\r\n const metadataClone = Object.assign({}, metadata);\r\n metadataClone['fullPath'] = location.path;\r\n metadataClone['size'] = blob.size();\r\n if (!metadataClone['contentType']) {\r\n metadataClone['contentType'] = determineContentType_(null, blob);\r\n }\r\n return metadataClone;\r\n}\r\n/**\r\n * Prepare RequestInfo for uploads as Content-Type: multipart.\r\n */\r\nfunction multipartUpload(service, location, mappings, blob, metadata) {\r\n const urlPart = location.bucketOnlyServerUrl();\r\n const headers = {\r\n 'X-Goog-Upload-Protocol': 'multipart'\r\n };\r\n function genBoundary() {\r\n let str = '';\r\n for (let i = 0; i < 2; i++) {\r\n str = str + Math.random().toString().slice(2);\r\n }\r\n return str;\r\n }\r\n const boundary = genBoundary();\r\n headers['Content-Type'] = 'multipart/related; boundary=' + boundary;\r\n const metadata_ = metadataForUpload_(location, blob, metadata);\r\n const metadataString = toResourceString(metadata_, mappings);\r\n const preBlobPart = '--' +\r\n boundary +\r\n '\\r\\n' +\r\n 'Content-Type: application/json; charset=utf-8\\r\\n\\r\\n' +\r\n metadataString +\r\n '\\r\\n--' +\r\n boundary +\r\n '\\r\\n' +\r\n 'Content-Type: ' +\r\n metadata_['contentType'] +\r\n '\\r\\n\\r\\n';\r\n const postBlobPart = '\\r\\n--' + boundary + '--';\r\n const body = FbsBlob.getBlob(preBlobPart, blob, postBlobPart);\r\n if (body === null) {\r\n throw cannotSliceBlob();\r\n }\r\n const urlParams = { name: metadata_['fullPath'] };\r\n const url = makeUrl(urlPart, service.host, service._protocol);\r\n const method = 'POST';\r\n const timeout = service.maxUploadRetryTime;\r\n const requestInfo = new RequestInfo(url, method, metadataHandler(service, mappings), timeout);\r\n requestInfo.urlParams = urlParams;\r\n requestInfo.headers = headers;\r\n requestInfo.body = body.uploadData();\r\n requestInfo.errorHandler = sharedErrorHandler(location);\r\n return requestInfo;\r\n}\r\n/**\r\n * @param current The number of bytes that have been uploaded so far.\r\n * @param total The total number of bytes in the upload.\r\n * @param opt_finalized True if the server has finished the upload.\r\n * @param opt_metadata The upload metadata, should\r\n * only be passed if opt_finalized is true.\r\n */\r\nclass ResumableUploadStatus {\r\n constructor(current, total, finalized, metadata) {\r\n this.current = current;\r\n this.total = total;\r\n this.finalized = !!finalized;\r\n this.metadata = metadata || null;\r\n }\r\n}\r\nfunction checkResumeHeader_(xhr, allowed) {\r\n let status = null;\r\n try {\r\n status = xhr.getResponseHeader('X-Goog-Upload-Status');\r\n }\r\n catch (e) {\r\n handlerCheck(false);\r\n }\r\n const allowedStatus = allowed || ['active'];\r\n handlerCheck(!!status && allowedStatus.indexOf(status) !== -1);\r\n return status;\r\n}\r\nfunction createResumableUpload(service, location, mappings, blob, metadata) {\r\n const urlPart = location.bucketOnlyServerUrl();\r\n const metadataForUpload = metadataForUpload_(location, blob, metadata);\r\n const urlParams = { name: metadataForUpload['fullPath'] };\r\n const url = makeUrl(urlPart, service.host, service._protocol);\r\n const method = 'POST';\r\n const headers = {\r\n 'X-Goog-Upload-Protocol': 'resumable',\r\n 'X-Goog-Upload-Command': 'start',\r\n 'X-Goog-Upload-Header-Content-Length': `${blob.size()}`,\r\n 'X-Goog-Upload-Header-Content-Type': metadataForUpload['contentType'],\r\n 'Content-Type': 'application/json; charset=utf-8'\r\n };\r\n const body = toResourceString(metadataForUpload, mappings);\r\n const timeout = service.maxUploadRetryTime;\r\n function handler(xhr) {\r\n checkResumeHeader_(xhr);\r\n let url;\r\n try {\r\n url = xhr.getResponseHeader('X-Goog-Upload-URL');\r\n }\r\n catch (e) {\r\n handlerCheck(false);\r\n }\r\n handlerCheck(isString(url));\r\n return url;\r\n }\r\n const requestInfo = new RequestInfo(url, method, handler, timeout);\r\n requestInfo.urlParams = urlParams;\r\n requestInfo.headers = headers;\r\n requestInfo.body = body;\r\n requestInfo.errorHandler = sharedErrorHandler(location);\r\n return requestInfo;\r\n}\r\n/**\r\n * @param url From a call to fbs.requests.createResumableUpload.\r\n */\r\nfunction getResumableUploadStatus(service, location, url, blob) {\r\n const headers = { 'X-Goog-Upload-Command': 'query' };\r\n function handler(xhr) {\r\n const status = checkResumeHeader_(xhr, ['active', 'final']);\r\n let sizeString = null;\r\n try {\r\n sizeString = xhr.getResponseHeader('X-Goog-Upload-Size-Received');\r\n }\r\n catch (e) {\r\n handlerCheck(false);\r\n }\r\n if (!sizeString) {\r\n // null or empty string\r\n handlerCheck(false);\r\n }\r\n const size = Number(sizeString);\r\n handlerCheck(!isNaN(size));\r\n return new ResumableUploadStatus(size, blob.size(), status === 'final');\r\n }\r\n const method = 'POST';\r\n const timeout = service.maxUploadRetryTime;\r\n const requestInfo = new RequestInfo(url, method, handler, timeout);\r\n requestInfo.headers = headers;\r\n requestInfo.errorHandler = sharedErrorHandler(location);\r\n return requestInfo;\r\n}\r\n/**\r\n * Any uploads via the resumable upload API must transfer a number of bytes\r\n * that is a multiple of this number.\r\n */\r\nconst RESUMABLE_UPLOAD_CHUNK_SIZE = 256 * 1024;\r\n/**\r\n * @param url From a call to fbs.requests.createResumableUpload.\r\n * @param chunkSize Number of bytes to upload.\r\n * @param status The previous status.\r\n * If not passed or null, we start from the beginning.\r\n * @throws fbs.Error If the upload is already complete, the passed in status\r\n * has a final size inconsistent with the blob, or the blob cannot be sliced\r\n * for upload.\r\n */\r\nfunction continueResumableUpload(location, service, url, blob, chunkSize, mappings, status, progressCallback) {\r\n // TODO(andysoto): standardize on internal asserts\r\n // assert(!(opt_status && opt_status.finalized));\r\n const status_ = new ResumableUploadStatus(0, 0);\r\n if (status) {\r\n status_.current = status.current;\r\n status_.total = status.total;\r\n }\r\n else {\r\n status_.current = 0;\r\n status_.total = blob.size();\r\n }\r\n if (blob.size() !== status_.total) {\r\n throw serverFileWrongSize();\r\n }\r\n const bytesLeft = status_.total - status_.current;\r\n let bytesToUpload = bytesLeft;\r\n if (chunkSize > 0) {\r\n bytesToUpload = Math.min(bytesToUpload, chunkSize);\r\n }\r\n const startByte = status_.current;\r\n const endByte = startByte + bytesToUpload;\r\n let uploadCommand = '';\r\n if (bytesToUpload === 0) {\r\n uploadCommand = 'finalize';\r\n }\r\n else if (bytesLeft === bytesToUpload) {\r\n uploadCommand = 'upload, finalize';\r\n }\r\n else {\r\n uploadCommand = 'upload';\r\n }\r\n const headers = {\r\n 'X-Goog-Upload-Command': uploadCommand,\r\n 'X-Goog-Upload-Offset': `${status_.current}`\r\n };\r\n const body = blob.slice(startByte, endByte);\r\n if (body === null) {\r\n throw cannotSliceBlob();\r\n }\r\n function handler(xhr, text) {\r\n // TODO(andysoto): Verify the MD5 of each uploaded range:\r\n // the 'x-range-md5' header comes back with status code 308 responses.\r\n // We'll only be able to bail out though, because you can't re-upload a\r\n // range that you previously uploaded.\r\n const uploadStatus = checkResumeHeader_(xhr, ['active', 'final']);\r\n const newCurrent = status_.current + bytesToUpload;\r\n const size = blob.size();\r\n let metadata;\r\n if (uploadStatus === 'final') {\r\n metadata = metadataHandler(service, mappings)(xhr, text);\r\n }\r\n else {\r\n metadata = null;\r\n }\r\n return new ResumableUploadStatus(newCurrent, size, uploadStatus === 'final', metadata);\r\n }\r\n const method = 'POST';\r\n const timeout = service.maxUploadRetryTime;\r\n const requestInfo = new RequestInfo(url, method, handler, timeout);\r\n requestInfo.headers = headers;\r\n requestInfo.body = body.uploadData();\r\n requestInfo.progressCallback = progressCallback || null;\r\n requestInfo.errorHandler = sharedErrorHandler(location);\r\n return requestInfo;\r\n}\n\n/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * An event that is triggered on a task.\r\n * @internal\r\n */\r\nconst TaskEvent = {\r\n /**\r\n * For this event,\r\n *

    \r\n *
  • The `next` function is triggered on progress updates and when the\r\n * task is paused/resumed with an `UploadTaskSnapshot` as the first\r\n * argument.
  • \r\n *
  • The `error` function is triggered if the upload is canceled or fails\r\n * for another reason.
  • \r\n *
  • The `complete` function is triggered if the upload completes\r\n * successfully.
  • \r\n *
\r\n */\r\n STATE_CHANGED: 'state_changed'\r\n};\r\n// type keys = keyof TaskState\r\n/**\r\n * Represents the current state of a running upload.\r\n * @internal\r\n */\r\nconst TaskState = {\r\n /** The task is currently transferring data. */\r\n RUNNING: 'running',\r\n /** The task was paused by the user. */\r\n PAUSED: 'paused',\r\n /** The task completed successfully. */\r\n SUCCESS: 'success',\r\n /** The task was canceled. */\r\n CANCELED: 'canceled',\r\n /** The task failed with an error. */\r\n ERROR: 'error'\r\n};\r\nfunction taskStateFromInternalTaskState(state) {\r\n switch (state) {\r\n case \"running\" /* InternalTaskState.RUNNING */:\r\n case \"pausing\" /* InternalTaskState.PAUSING */:\r\n case \"canceling\" /* InternalTaskState.CANCELING */:\r\n return TaskState.RUNNING;\r\n case \"paused\" /* InternalTaskState.PAUSED */:\r\n return TaskState.PAUSED;\r\n case \"success\" /* InternalTaskState.SUCCESS */:\r\n return TaskState.SUCCESS;\r\n case \"canceled\" /* InternalTaskState.CANCELED */:\r\n return TaskState.CANCELED;\r\n case \"error\" /* InternalTaskState.ERROR */:\r\n return TaskState.ERROR;\r\n default:\r\n // TODO(andysoto): assert(false);\r\n return TaskState.ERROR;\r\n }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nclass Observer {\r\n constructor(nextOrObserver, error, complete) {\r\n const asFunctions = isFunction(nextOrObserver) || error != null || complete != null;\r\n if (asFunctions) {\r\n this.next = nextOrObserver;\r\n this.error = error !== null && error !== void 0 ? error : undefined;\r\n this.complete = complete !== null && complete !== void 0 ? complete : undefined;\r\n }\r\n else {\r\n const observer = nextOrObserver;\r\n this.next = observer.next;\r\n this.error = observer.error;\r\n this.complete = observer.complete;\r\n }\r\n }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Returns a function that invokes f with its arguments asynchronously as a\r\n * microtask, i.e. as soon as possible after the current script returns back\r\n * into browser code.\r\n */\r\n// eslint-disable-next-line @typescript-eslint/ban-types\r\nfunction async(f) {\r\n return (...argsToForward) => {\r\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\r\n Promise.resolve().then(() => f(...argsToForward));\r\n };\r\n}\n\n/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/** An override for the text-based Connection. Used in tests. */\r\nlet textFactoryOverride = null;\r\n/**\r\n * Network layer for browsers. We use this instead of goog.net.XhrIo because\r\n * goog.net.XhrIo is hyuuuuge and doesn't work in React Native on Android.\r\n */\r\nclass XhrConnection {\r\n constructor() {\r\n this.sent_ = false;\r\n this.xhr_ = new XMLHttpRequest();\r\n this.initXhr();\r\n this.errorCode_ = ErrorCode.NO_ERROR;\r\n this.sendPromise_ = new Promise(resolve => {\r\n this.xhr_.addEventListener('abort', () => {\r\n this.errorCode_ = ErrorCode.ABORT;\r\n resolve();\r\n });\r\n this.xhr_.addEventListener('error', () => {\r\n this.errorCode_ = ErrorCode.NETWORK_ERROR;\r\n resolve();\r\n });\r\n this.xhr_.addEventListener('load', () => {\r\n resolve();\r\n });\r\n });\r\n }\r\n send(url, method, body, headers) {\r\n if (this.sent_) {\r\n throw internalError('cannot .send() more than once');\r\n }\r\n this.sent_ = true;\r\n this.xhr_.open(method, url, true);\r\n if (headers !== undefined) {\r\n for (const key in headers) {\r\n if (headers.hasOwnProperty(key)) {\r\n this.xhr_.setRequestHeader(key, headers[key].toString());\r\n }\r\n }\r\n }\r\n if (body !== undefined) {\r\n this.xhr_.send(body);\r\n }\r\n else {\r\n this.xhr_.send();\r\n }\r\n return this.sendPromise_;\r\n }\r\n getErrorCode() {\r\n if (!this.sent_) {\r\n throw internalError('cannot .getErrorCode() before sending');\r\n }\r\n return this.errorCode_;\r\n }\r\n getStatus() {\r\n if (!this.sent_) {\r\n throw internalError('cannot .getStatus() before sending');\r\n }\r\n try {\r\n return this.xhr_.status;\r\n }\r\n catch (e) {\r\n return -1;\r\n }\r\n }\r\n getResponse() {\r\n if (!this.sent_) {\r\n throw internalError('cannot .getResponse() before sending');\r\n }\r\n return this.xhr_.response;\r\n }\r\n getErrorText() {\r\n if (!this.sent_) {\r\n throw internalError('cannot .getErrorText() before sending');\r\n }\r\n return this.xhr_.statusText;\r\n }\r\n /** Aborts the request. */\r\n abort() {\r\n this.xhr_.abort();\r\n }\r\n getResponseHeader(header) {\r\n return this.xhr_.getResponseHeader(header);\r\n }\r\n addUploadProgressListener(listener) {\r\n if (this.xhr_.upload != null) {\r\n this.xhr_.upload.addEventListener('progress', listener);\r\n }\r\n }\r\n removeUploadProgressListener(listener) {\r\n if (this.xhr_.upload != null) {\r\n this.xhr_.upload.removeEventListener('progress', listener);\r\n }\r\n }\r\n}\r\nclass XhrTextConnection extends XhrConnection {\r\n initXhr() {\r\n this.xhr_.responseType = 'text';\r\n }\r\n}\r\nfunction newTextConnection() {\r\n return textFactoryOverride ? textFactoryOverride() : new XhrTextConnection();\r\n}\r\nclass XhrBytesConnection extends XhrConnection {\r\n initXhr() {\r\n this.xhr_.responseType = 'arraybuffer';\r\n }\r\n}\r\nfunction newBytesConnection() {\r\n return new XhrBytesConnection();\r\n}\r\nclass XhrBlobConnection extends XhrConnection {\r\n initXhr() {\r\n this.xhr_.responseType = 'blob';\r\n }\r\n}\r\nfunction newBlobConnection() {\r\n return new XhrBlobConnection();\r\n}\n\n/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Represents a blob being uploaded. Can be used to pause/resume/cancel the\r\n * upload and manage callbacks for various events.\r\n * @internal\r\n */\r\nclass UploadTask {\r\n /**\r\n * @param ref - The firebaseStorage.Reference object this task came\r\n * from, untyped to avoid cyclic dependencies.\r\n * @param blob - The blob to upload.\r\n */\r\n constructor(ref, blob, metadata = null) {\r\n /**\r\n * Number of bytes transferred so far.\r\n */\r\n this._transferred = 0;\r\n this._needToFetchStatus = false;\r\n this._needToFetchMetadata = false;\r\n this._observers = [];\r\n this._error = undefined;\r\n this._uploadUrl = undefined;\r\n this._request = undefined;\r\n this._chunkMultiplier = 1;\r\n this._resolve = undefined;\r\n this._reject = undefined;\r\n this._ref = ref;\r\n this._blob = blob;\r\n this._metadata = metadata;\r\n this._mappings = getMappings();\r\n this._resumable = this._shouldDoResumable(this._blob);\r\n this._state = \"running\" /* InternalTaskState.RUNNING */;\r\n this._errorHandler = error => {\r\n this._request = undefined;\r\n this._chunkMultiplier = 1;\r\n if (error._codeEquals(StorageErrorCode.CANCELED)) {\r\n this._needToFetchStatus = true;\r\n this.completeTransitions_();\r\n }\r\n else {\r\n const backoffExpired = this.isExponentialBackoffExpired();\r\n if (isRetryStatusCode(error.status, [])) {\r\n if (backoffExpired) {\r\n error = retryLimitExceeded();\r\n }\r\n else {\r\n this.sleepTime = Math.max(this.sleepTime * 2, DEFAULT_MIN_SLEEP_TIME_MILLIS);\r\n this._needToFetchStatus = true;\r\n this.completeTransitions_();\r\n return;\r\n }\r\n }\r\n this._error = error;\r\n this._transition(\"error\" /* InternalTaskState.ERROR */);\r\n }\r\n };\r\n this._metadataErrorHandler = error => {\r\n this._request = undefined;\r\n if (error._codeEquals(StorageErrorCode.CANCELED)) {\r\n this.completeTransitions_();\r\n }\r\n else {\r\n this._error = error;\r\n this._transition(\"error\" /* InternalTaskState.ERROR */);\r\n }\r\n };\r\n this.sleepTime = 0;\r\n this.maxSleepTime = this._ref.storage.maxUploadRetryTime;\r\n this._promise = new Promise((resolve, reject) => {\r\n this._resolve = resolve;\r\n this._reject = reject;\r\n this._start();\r\n });\r\n // Prevent uncaught rejections on the internal promise from bubbling out\r\n // to the top level with a dummy handler.\r\n this._promise.then(null, () => { });\r\n }\r\n isExponentialBackoffExpired() {\r\n return this.sleepTime > this.maxSleepTime;\r\n }\r\n _makeProgressCallback() {\r\n const sizeBefore = this._transferred;\r\n return loaded => this._updateProgress(sizeBefore + loaded);\r\n }\r\n _shouldDoResumable(blob) {\r\n return blob.size() > 256 * 1024;\r\n }\r\n _start() {\r\n if (this._state !== \"running\" /* InternalTaskState.RUNNING */) {\r\n // This can happen if someone pauses us in a resume callback, for example.\r\n return;\r\n }\r\n if (this._request !== undefined) {\r\n return;\r\n }\r\n if (this._resumable) {\r\n if (this._uploadUrl === undefined) {\r\n this._createResumable();\r\n }\r\n else {\r\n if (this._needToFetchStatus) {\r\n this._fetchStatus();\r\n }\r\n else {\r\n if (this._needToFetchMetadata) {\r\n // Happens if we miss the metadata on upload completion.\r\n this._fetchMetadata();\r\n }\r\n else {\r\n this.pendingTimeout = setTimeout(() => {\r\n this.pendingTimeout = undefined;\r\n this._continueUpload();\r\n }, this.sleepTime);\r\n }\r\n }\r\n }\r\n }\r\n else {\r\n this._oneShotUpload();\r\n }\r\n }\r\n _resolveToken(callback) {\r\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\r\n Promise.all([\r\n this._ref.storage._getAuthToken(),\r\n this._ref.storage._getAppCheckToken()\r\n ]).then(([authToken, appCheckToken]) => {\r\n switch (this._state) {\r\n case \"running\" /* InternalTaskState.RUNNING */:\r\n callback(authToken, appCheckToken);\r\n break;\r\n case \"canceling\" /* InternalTaskState.CANCELING */:\r\n this._transition(\"canceled\" /* InternalTaskState.CANCELED */);\r\n break;\r\n case \"pausing\" /* InternalTaskState.PAUSING */:\r\n this._transition(\"paused\" /* InternalTaskState.PAUSED */);\r\n break;\r\n }\r\n });\r\n }\r\n // TODO(andysoto): assert false\r\n _createResumable() {\r\n this._resolveToken((authToken, appCheckToken) => {\r\n const requestInfo = createResumableUpload(this._ref.storage, this._ref._location, this._mappings, this._blob, this._metadata);\r\n const createRequest = this._ref.storage._makeRequest(requestInfo, newTextConnection, authToken, appCheckToken);\r\n this._request = createRequest;\r\n createRequest.getPromise().then((url) => {\r\n this._request = undefined;\r\n this._uploadUrl = url;\r\n this._needToFetchStatus = false;\r\n this.completeTransitions_();\r\n }, this._errorHandler);\r\n });\r\n }\r\n _fetchStatus() {\r\n // TODO(andysoto): assert(this.uploadUrl_ !== null);\r\n const url = this._uploadUrl;\r\n this._resolveToken((authToken, appCheckToken) => {\r\n const requestInfo = getResumableUploadStatus(this._ref.storage, this._ref._location, url, this._blob);\r\n const statusRequest = this._ref.storage._makeRequest(requestInfo, newTextConnection, authToken, appCheckToken);\r\n this._request = statusRequest;\r\n statusRequest.getPromise().then(status => {\r\n status = status;\r\n this._request = undefined;\r\n this._updateProgress(status.current);\r\n this._needToFetchStatus = false;\r\n if (status.finalized) {\r\n this._needToFetchMetadata = true;\r\n }\r\n this.completeTransitions_();\r\n }, this._errorHandler);\r\n });\r\n }\r\n _continueUpload() {\r\n const chunkSize = RESUMABLE_UPLOAD_CHUNK_SIZE * this._chunkMultiplier;\r\n const status = new ResumableUploadStatus(this._transferred, this._blob.size());\r\n // TODO(andysoto): assert(this.uploadUrl_ !== null);\r\n const url = this._uploadUrl;\r\n this._resolveToken((authToken, appCheckToken) => {\r\n let requestInfo;\r\n try {\r\n requestInfo = continueResumableUpload(this._ref._location, this._ref.storage, url, this._blob, chunkSize, this._mappings, status, this._makeProgressCallback());\r\n }\r\n catch (e) {\r\n this._error = e;\r\n this._transition(\"error\" /* InternalTaskState.ERROR */);\r\n return;\r\n }\r\n const uploadRequest = this._ref.storage._makeRequest(requestInfo, newTextConnection, authToken, appCheckToken, \r\n /*retry=*/ false // Upload requests should not be retried as each retry should be preceded by another query request. Which is handled in this file.\r\n );\r\n this._request = uploadRequest;\r\n uploadRequest.getPromise().then((newStatus) => {\r\n this._increaseMultiplier();\r\n this._request = undefined;\r\n this._updateProgress(newStatus.current);\r\n if (newStatus.finalized) {\r\n this._metadata = newStatus.metadata;\r\n this._transition(\"success\" /* InternalTaskState.SUCCESS */);\r\n }\r\n else {\r\n this.completeTransitions_();\r\n }\r\n }, this._errorHandler);\r\n });\r\n }\r\n _increaseMultiplier() {\r\n const currentSize = RESUMABLE_UPLOAD_CHUNK_SIZE * this._chunkMultiplier;\r\n // Max chunk size is 32M.\r\n if (currentSize * 2 < 32 * 1024 * 1024) {\r\n this._chunkMultiplier *= 2;\r\n }\r\n }\r\n _fetchMetadata() {\r\n this._resolveToken((authToken, appCheckToken) => {\r\n const requestInfo = getMetadata$2(this._ref.storage, this._ref._location, this._mappings);\r\n const metadataRequest = this._ref.storage._makeRequest(requestInfo, newTextConnection, authToken, appCheckToken);\r\n this._request = metadataRequest;\r\n metadataRequest.getPromise().then(metadata => {\r\n this._request = undefined;\r\n this._metadata = metadata;\r\n this._transition(\"success\" /* InternalTaskState.SUCCESS */);\r\n }, this._metadataErrorHandler);\r\n });\r\n }\r\n _oneShotUpload() {\r\n this._resolveToken((authToken, appCheckToken) => {\r\n const requestInfo = multipartUpload(this._ref.storage, this._ref._location, this._mappings, this._blob, this._metadata);\r\n const multipartRequest = this._ref.storage._makeRequest(requestInfo, newTextConnection, authToken, appCheckToken);\r\n this._request = multipartRequest;\r\n multipartRequest.getPromise().then(metadata => {\r\n this._request = undefined;\r\n this._metadata = metadata;\r\n this._updateProgress(this._blob.size());\r\n this._transition(\"success\" /* InternalTaskState.SUCCESS */);\r\n }, this._errorHandler);\r\n });\r\n }\r\n _updateProgress(transferred) {\r\n const old = this._transferred;\r\n this._transferred = transferred;\r\n // A progress update can make the \"transferred\" value smaller (e.g. a\r\n // partial upload not completed by server, after which the \"transferred\"\r\n // value may reset to the value at the beginning of the request).\r\n if (this._transferred !== old) {\r\n this._notifyObservers();\r\n }\r\n }\r\n _transition(state) {\r\n if (this._state === state) {\r\n return;\r\n }\r\n switch (state) {\r\n case \"canceling\" /* InternalTaskState.CANCELING */:\r\n case \"pausing\" /* InternalTaskState.PAUSING */:\r\n // TODO(andysoto):\r\n // assert(this.state_ === InternalTaskState.RUNNING ||\r\n // this.state_ === InternalTaskState.PAUSING);\r\n this._state = state;\r\n if (this._request !== undefined) {\r\n this._request.cancel();\r\n }\r\n else if (this.pendingTimeout) {\r\n clearTimeout(this.pendingTimeout);\r\n this.pendingTimeout = undefined;\r\n this.completeTransitions_();\r\n }\r\n break;\r\n case \"running\" /* InternalTaskState.RUNNING */:\r\n // TODO(andysoto):\r\n // assert(this.state_ === InternalTaskState.PAUSED ||\r\n // this.state_ === InternalTaskState.PAUSING);\r\n const wasPaused = this._state === \"paused\" /* InternalTaskState.PAUSED */;\r\n this._state = state;\r\n if (wasPaused) {\r\n this._notifyObservers();\r\n this._start();\r\n }\r\n break;\r\n case \"paused\" /* InternalTaskState.PAUSED */:\r\n // TODO(andysoto):\r\n // assert(this.state_ === InternalTaskState.PAUSING);\r\n this._state = state;\r\n this._notifyObservers();\r\n break;\r\n case \"canceled\" /* InternalTaskState.CANCELED */:\r\n // TODO(andysoto):\r\n // assert(this.state_ === InternalTaskState.PAUSED ||\r\n // this.state_ === InternalTaskState.CANCELING);\r\n this._error = canceled();\r\n this._state = state;\r\n this._notifyObservers();\r\n break;\r\n case \"error\" /* InternalTaskState.ERROR */:\r\n // TODO(andysoto):\r\n // assert(this.state_ === InternalTaskState.RUNNING ||\r\n // this.state_ === InternalTaskState.PAUSING ||\r\n // this.state_ === InternalTaskState.CANCELING);\r\n this._state = state;\r\n this._notifyObservers();\r\n break;\r\n case \"success\" /* InternalTaskState.SUCCESS */:\r\n // TODO(andysoto):\r\n // assert(this.state_ === InternalTaskState.RUNNING ||\r\n // this.state_ === InternalTaskState.PAUSING ||\r\n // this.state_ === InternalTaskState.CANCELING);\r\n this._state = state;\r\n this._notifyObservers();\r\n break;\r\n }\r\n }\r\n completeTransitions_() {\r\n switch (this._state) {\r\n case \"pausing\" /* InternalTaskState.PAUSING */:\r\n this._transition(\"paused\" /* InternalTaskState.PAUSED */);\r\n break;\r\n case \"canceling\" /* InternalTaskState.CANCELING */:\r\n this._transition(\"canceled\" /* InternalTaskState.CANCELED */);\r\n break;\r\n case \"running\" /* InternalTaskState.RUNNING */:\r\n this._start();\r\n break;\r\n }\r\n }\r\n /**\r\n * A snapshot of the current task state.\r\n */\r\n get snapshot() {\r\n const externalState = taskStateFromInternalTaskState(this._state);\r\n return {\r\n bytesTransferred: this._transferred,\r\n totalBytes: this._blob.size(),\r\n state: externalState,\r\n metadata: this._metadata,\r\n task: this,\r\n ref: this._ref\r\n };\r\n }\r\n /**\r\n * Adds a callback for an event.\r\n * @param type - The type of event to listen for.\r\n * @param nextOrObserver -\r\n * The `next` function, which gets called for each item in\r\n * the event stream, or an observer object with some or all of these three\r\n * properties (`next`, `error`, `complete`).\r\n * @param error - A function that gets called with a `StorageError`\r\n * if the event stream ends due to an error.\r\n * @param completed - A function that gets called if the\r\n * event stream ends normally.\r\n * @returns\r\n * If only the event argument is passed, returns a function you can use to\r\n * add callbacks (see the examples above). If more than just the event\r\n * argument is passed, returns a function you can call to unregister the\r\n * callbacks.\r\n */\r\n on(type, nextOrObserver, error, completed) {\r\n // Note: `type` isn't being used. Its type is also incorrect. TaskEvent should not be a string.\r\n const observer = new Observer(nextOrObserver || undefined, error || undefined, completed || undefined);\r\n this._addObserver(observer);\r\n return () => {\r\n this._removeObserver(observer);\r\n };\r\n }\r\n /**\r\n * This object behaves like a Promise, and resolves with its snapshot data\r\n * when the upload completes.\r\n * @param onFulfilled - The fulfillment callback. Promise chaining works as normal.\r\n * @param onRejected - The rejection callback.\r\n */\r\n then(onFulfilled, onRejected) {\r\n // These casts are needed so that TypeScript can infer the types of the\r\n // resulting Promise.\r\n return this._promise.then(onFulfilled, onRejected);\r\n }\r\n /**\r\n * Equivalent to calling `then(null, onRejected)`.\r\n */\r\n catch(onRejected) {\r\n return this.then(null, onRejected);\r\n }\r\n /**\r\n * Adds the given observer.\r\n */\r\n _addObserver(observer) {\r\n this._observers.push(observer);\r\n this._notifyObserver(observer);\r\n }\r\n /**\r\n * Removes the given observer.\r\n */\r\n _removeObserver(observer) {\r\n const i = this._observers.indexOf(observer);\r\n if (i !== -1) {\r\n this._observers.splice(i, 1);\r\n }\r\n }\r\n _notifyObservers() {\r\n this._finishPromise();\r\n const observers = this._observers.slice();\r\n observers.forEach(observer => {\r\n this._notifyObserver(observer);\r\n });\r\n }\r\n _finishPromise() {\r\n if (this._resolve !== undefined) {\r\n let triggered = true;\r\n switch (taskStateFromInternalTaskState(this._state)) {\r\n case TaskState.SUCCESS:\r\n async(this._resolve.bind(null, this.snapshot))();\r\n break;\r\n case TaskState.CANCELED:\r\n case TaskState.ERROR:\r\n const toCall = this._reject;\r\n async(toCall.bind(null, this._error))();\r\n break;\r\n default:\r\n triggered = false;\r\n break;\r\n }\r\n if (triggered) {\r\n this._resolve = undefined;\r\n this._reject = undefined;\r\n }\r\n }\r\n }\r\n _notifyObserver(observer) {\r\n const externalState = taskStateFromInternalTaskState(this._state);\r\n switch (externalState) {\r\n case TaskState.RUNNING:\r\n case TaskState.PAUSED:\r\n if (observer.next) {\r\n async(observer.next.bind(observer, this.snapshot))();\r\n }\r\n break;\r\n case TaskState.SUCCESS:\r\n if (observer.complete) {\r\n async(observer.complete.bind(observer))();\r\n }\r\n break;\r\n case TaskState.CANCELED:\r\n case TaskState.ERROR:\r\n if (observer.error) {\r\n async(observer.error.bind(observer, this._error))();\r\n }\r\n break;\r\n default:\r\n // TODO(andysoto): assert(false);\r\n if (observer.error) {\r\n async(observer.error.bind(observer, this._error))();\r\n }\r\n }\r\n }\r\n /**\r\n * Resumes a paused task. Has no effect on a currently running or failed task.\r\n * @returns True if the operation took effect, false if ignored.\r\n */\r\n resume() {\r\n const valid = this._state === \"paused\" /* InternalTaskState.PAUSED */ ||\r\n this._state === \"pausing\" /* InternalTaskState.PAUSING */;\r\n if (valid) {\r\n this._transition(\"running\" /* InternalTaskState.RUNNING */);\r\n }\r\n return valid;\r\n }\r\n /**\r\n * Pauses a currently running task. Has no effect on a paused or failed task.\r\n * @returns True if the operation took effect, false if ignored.\r\n */\r\n pause() {\r\n const valid = this._state === \"running\" /* InternalTaskState.RUNNING */;\r\n if (valid) {\r\n this._transition(\"pausing\" /* InternalTaskState.PAUSING */);\r\n }\r\n return valid;\r\n }\r\n /**\r\n * Cancels a currently running or paused task. Has no effect on a complete or\r\n * failed task.\r\n * @returns True if the operation took effect, false if ignored.\r\n */\r\n cancel() {\r\n const valid = this._state === \"running\" /* InternalTaskState.RUNNING */ ||\r\n this._state === \"pausing\" /* InternalTaskState.PAUSING */;\r\n if (valid) {\r\n this._transition(\"canceling\" /* InternalTaskState.CANCELING */);\r\n }\r\n return valid;\r\n }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2019 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Provides methods to interact with a bucket in the Firebase Storage service.\r\n * @internal\r\n * @param _location - An fbs.location, or the URL at\r\n * which to base this object, in one of the following forms:\r\n * gs:///\r\n * http[s]://firebasestorage.googleapis.com/\r\n * /b//o/\r\n * Any query or fragment strings will be ignored in the http[s]\r\n * format. If no value is passed, the storage object will use a URL based on\r\n * the project ID of the base firebase.App instance.\r\n */\r\nclass Reference {\r\n constructor(_service, location) {\r\n this._service = _service;\r\n if (location instanceof Location) {\r\n this._location = location;\r\n }\r\n else {\r\n this._location = Location.makeFromUrl(location, _service.host);\r\n }\r\n }\r\n /**\r\n * Returns the URL for the bucket and path this object references,\r\n * in the form gs:///\r\n * @override\r\n */\r\n toString() {\r\n return 'gs://' + this._location.bucket + '/' + this._location.path;\r\n }\r\n _newRef(service, location) {\r\n return new Reference(service, location);\r\n }\r\n /**\r\n * A reference to the root of this object's bucket.\r\n */\r\n get root() {\r\n const location = new Location(this._location.bucket, '');\r\n return this._newRef(this._service, location);\r\n }\r\n /**\r\n * The name of the bucket containing this reference's object.\r\n */\r\n get bucket() {\r\n return this._location.bucket;\r\n }\r\n /**\r\n * The full path of this object.\r\n */\r\n get fullPath() {\r\n return this._location.path;\r\n }\r\n /**\r\n * The short name of this object, which is the last component of the full path.\r\n * For example, if fullPath is 'full/path/image.png', name is 'image.png'.\r\n */\r\n get name() {\r\n return lastComponent(this._location.path);\r\n }\r\n /**\r\n * The `StorageService` instance this `StorageReference` is associated with.\r\n */\r\n get storage() {\r\n return this._service;\r\n }\r\n /**\r\n * A `StorageReference` pointing to the parent location of this `StorageReference`, or null if\r\n * this reference is the root.\r\n */\r\n get parent() {\r\n const newPath = parent(this._location.path);\r\n if (newPath === null) {\r\n return null;\r\n }\r\n const location = new Location(this._location.bucket, newPath);\r\n return new Reference(this._service, location);\r\n }\r\n /**\r\n * Utility function to throw an error in methods that do not accept a root reference.\r\n */\r\n _throwIfRoot(name) {\r\n if (this._location.path === '') {\r\n throw invalidRootOperation(name);\r\n }\r\n }\r\n}\r\n/**\r\n * Download the bytes at the object's location.\r\n * @returns A Promise containing the downloaded bytes.\r\n */\r\nfunction getBytesInternal(ref, maxDownloadSizeBytes) {\r\n ref._throwIfRoot('getBytes');\r\n const requestInfo = getBytes$1(ref.storage, ref._location, maxDownloadSizeBytes);\r\n return ref.storage\r\n .makeRequestWithTokens(requestInfo, newBytesConnection)\r\n .then(bytes => maxDownloadSizeBytes !== undefined\r\n ? // GCS may not honor the Range header for small files\r\n bytes.slice(0, maxDownloadSizeBytes)\r\n : bytes);\r\n}\r\n/**\r\n * Download the bytes at the object's location.\r\n * @returns A Promise containing the downloaded blob.\r\n */\r\nfunction getBlobInternal(ref, maxDownloadSizeBytes) {\r\n ref._throwIfRoot('getBlob');\r\n const requestInfo = getBytes$1(ref.storage, ref._location, maxDownloadSizeBytes);\r\n return ref.storage\r\n .makeRequestWithTokens(requestInfo, newBlobConnection)\r\n .then(blob => maxDownloadSizeBytes !== undefined\r\n ? // GCS may not honor the Range header for small files\r\n blob.slice(0, maxDownloadSizeBytes)\r\n : blob);\r\n}\r\n/**\r\n * Uploads data to this object's location.\r\n * The upload is not resumable.\r\n *\r\n * @param ref - StorageReference where data should be uploaded.\r\n * @param data - The data to upload.\r\n * @param metadata - Metadata for the newly uploaded data.\r\n * @returns A Promise containing an UploadResult\r\n */\r\nfunction uploadBytes$1(ref, data, metadata) {\r\n ref._throwIfRoot('uploadBytes');\r\n const requestInfo = multipartUpload(ref.storage, ref._location, getMappings(), new FbsBlob(data, true), metadata);\r\n return ref.storage\r\n .makeRequestWithTokens(requestInfo, newTextConnection)\r\n .then(finalMetadata => {\r\n return {\r\n metadata: finalMetadata,\r\n ref\r\n };\r\n });\r\n}\r\n/**\r\n * Uploads data to this object's location.\r\n * The upload can be paused and resumed, and exposes progress updates.\r\n * @public\r\n * @param ref - StorageReference where data should be uploaded.\r\n * @param data - The data to upload.\r\n * @param metadata - Metadata for the newly uploaded data.\r\n * @returns An UploadTask\r\n */\r\nfunction uploadBytesResumable$1(ref, data, metadata) {\r\n ref._throwIfRoot('uploadBytesResumable');\r\n return new UploadTask(ref, new FbsBlob(data), metadata);\r\n}\r\n/**\r\n * Uploads a string to this object's location.\r\n * The upload is not resumable.\r\n * @public\r\n * @param ref - StorageReference where string should be uploaded.\r\n * @param value - The string to upload.\r\n * @param format - The format of the string to upload.\r\n * @param metadata - Metadata for the newly uploaded string.\r\n * @returns A Promise containing an UploadResult\r\n */\r\nfunction uploadString$1(ref, value, format = StringFormat.RAW, metadata) {\r\n ref._throwIfRoot('uploadString');\r\n const data = dataFromString(format, value);\r\n const metadataClone = Object.assign({}, metadata);\r\n if (metadataClone['contentType'] == null && data.contentType != null) {\r\n metadataClone['contentType'] = data.contentType;\r\n }\r\n return uploadBytes$1(ref, data.data, metadataClone);\r\n}\r\n/**\r\n * List all items (files) and prefixes (folders) under this storage reference.\r\n *\r\n * This is a helper method for calling list() repeatedly until there are\r\n * no more results. The default pagination size is 1000.\r\n *\r\n * Note: The results may not be consistent if objects are changed while this\r\n * operation is running.\r\n *\r\n * Warning: listAll may potentially consume too many resources if there are\r\n * too many results.\r\n * @public\r\n * @param ref - StorageReference to get list from.\r\n *\r\n * @returns A Promise that resolves with all the items and prefixes under\r\n * the current storage reference. `prefixes` contains references to\r\n * sub-directories and `items` contains references to objects in this\r\n * folder. `nextPageToken` is never returned.\r\n */\r\nfunction listAll$1(ref) {\r\n const accumulator = {\r\n prefixes: [],\r\n items: []\r\n };\r\n return listAllHelper(ref, accumulator).then(() => accumulator);\r\n}\r\n/**\r\n * Separated from listAll because async functions can't use \"arguments\".\r\n * @param ref\r\n * @param accumulator\r\n * @param pageToken\r\n */\r\nasync function listAllHelper(ref, accumulator, pageToken) {\r\n const opt = {\r\n // maxResults is 1000 by default.\r\n pageToken\r\n };\r\n const nextPage = await list$1(ref, opt);\r\n accumulator.prefixes.push(...nextPage.prefixes);\r\n accumulator.items.push(...nextPage.items);\r\n if (nextPage.nextPageToken != null) {\r\n await listAllHelper(ref, accumulator, nextPage.nextPageToken);\r\n }\r\n}\r\n/**\r\n * List items (files) and prefixes (folders) under this storage reference.\r\n *\r\n * List API is only available for Firebase Rules Version 2.\r\n *\r\n * GCS is a key-blob store. Firebase Storage imposes the semantic of '/'\r\n * delimited folder structure.\r\n * Refer to GCS's List API if you want to learn more.\r\n *\r\n * To adhere to Firebase Rules's Semantics, Firebase Storage does not\r\n * support objects whose paths end with \"/\" or contain two consecutive\r\n * \"/\"s. Firebase Storage List API will filter these unsupported objects.\r\n * list() may fail if there are too many unsupported objects in the bucket.\r\n * @public\r\n *\r\n * @param ref - StorageReference to get list from.\r\n * @param options - See ListOptions for details.\r\n * @returns A Promise that resolves with the items and prefixes.\r\n * `prefixes` contains references to sub-folders and `items`\r\n * contains references to objects in this folder. `nextPageToken`\r\n * can be used to get the rest of the results.\r\n */\r\nfunction list$1(ref, options) {\r\n if (options != null) {\r\n if (typeof options.maxResults === 'number') {\r\n validateNumber('options.maxResults', \r\n /* minValue= */ 1, \r\n /* maxValue= */ 1000, options.maxResults);\r\n }\r\n }\r\n const op = options || {};\r\n const requestInfo = list$2(ref.storage, ref._location, \r\n /*delimiter= */ '/', op.pageToken, op.maxResults);\r\n return ref.storage.makeRequestWithTokens(requestInfo, newTextConnection);\r\n}\r\n/**\r\n * A `Promise` that resolves with the metadata for this object. If this\r\n * object doesn't exist or metadata cannot be retreived, the promise is\r\n * rejected.\r\n * @public\r\n * @param ref - StorageReference to get metadata from.\r\n */\r\nfunction getMetadata$1(ref) {\r\n ref._throwIfRoot('getMetadata');\r\n const requestInfo = getMetadata$2(ref.storage, ref._location, getMappings());\r\n return ref.storage.makeRequestWithTokens(requestInfo, newTextConnection);\r\n}\r\n/**\r\n * Updates the metadata for this object.\r\n * @public\r\n * @param ref - StorageReference to update metadata for.\r\n * @param metadata - The new metadata for the object.\r\n * Only values that have been explicitly set will be changed. Explicitly\r\n * setting a value to null will remove the metadata.\r\n * @returns A `Promise` that resolves\r\n * with the new metadata for this object.\r\n * See `firebaseStorage.Reference.prototype.getMetadata`\r\n */\r\nfunction updateMetadata$1(ref, metadata) {\r\n ref._throwIfRoot('updateMetadata');\r\n const requestInfo = updateMetadata$2(ref.storage, ref._location, metadata, getMappings());\r\n return ref.storage.makeRequestWithTokens(requestInfo, newTextConnection);\r\n}\r\n/**\r\n * Returns the download URL for the given Reference.\r\n * @public\r\n * @returns A `Promise` that resolves with the download\r\n * URL for this object.\r\n */\r\nfunction getDownloadURL$1(ref) {\r\n ref._throwIfRoot('getDownloadURL');\r\n const requestInfo = getDownloadUrl(ref.storage, ref._location, getMappings());\r\n return ref.storage\r\n .makeRequestWithTokens(requestInfo, newTextConnection)\r\n .then(url => {\r\n if (url === null) {\r\n throw noDownloadURL();\r\n }\r\n return url;\r\n });\r\n}\r\n/**\r\n * Deletes the object at this location.\r\n * @public\r\n * @param ref - StorageReference for object to delete.\r\n * @returns A `Promise` that resolves if the deletion succeeds.\r\n */\r\nfunction deleteObject$1(ref) {\r\n ref._throwIfRoot('deleteObject');\r\n const requestInfo = deleteObject$2(ref.storage, ref._location);\r\n return ref.storage.makeRequestWithTokens(requestInfo, newTextConnection);\r\n}\r\n/**\r\n * Returns reference for object obtained by appending `childPath` to `ref`.\r\n *\r\n * @param ref - StorageReference to get child of.\r\n * @param childPath - Child path from provided ref.\r\n * @returns A reference to the object obtained by\r\n * appending childPath, removing any duplicate, beginning, or trailing\r\n * slashes.\r\n *\r\n */\r\nfunction _getChild$1(ref, childPath) {\r\n const newPath = child(ref._location.path, childPath);\r\n const location = new Location(ref._location.bucket, newPath);\r\n return new Reference(ref.storage, location);\r\n}\n\n/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nfunction isUrl(path) {\r\n return /^[A-Za-z]+:\\/\\//.test(path);\r\n}\r\n/**\r\n * Returns a firebaseStorage.Reference for the given url.\r\n */\r\nfunction refFromURL(service, url) {\r\n return new Reference(service, url);\r\n}\r\n/**\r\n * Returns a firebaseStorage.Reference for the given path in the default\r\n * bucket.\r\n */\r\nfunction refFromPath(ref, path) {\r\n if (ref instanceof FirebaseStorageImpl) {\r\n const service = ref;\r\n if (service._bucket == null) {\r\n throw noDefaultBucket();\r\n }\r\n const reference = new Reference(service, service._bucket);\r\n if (path != null) {\r\n return refFromPath(reference, path);\r\n }\r\n else {\r\n return reference;\r\n }\r\n }\r\n else {\r\n // ref is a Reference\r\n if (path !== undefined) {\r\n return _getChild$1(ref, path);\r\n }\r\n else {\r\n return ref;\r\n }\r\n }\r\n}\r\nfunction ref$1(serviceOrRef, pathOrUrl) {\r\n if (pathOrUrl && isUrl(pathOrUrl)) {\r\n if (serviceOrRef instanceof FirebaseStorageImpl) {\r\n return refFromURL(serviceOrRef, pathOrUrl);\r\n }\r\n else {\r\n throw invalidArgument('To use ref(service, url), the first argument must be a Storage instance.');\r\n }\r\n }\r\n else {\r\n return refFromPath(serviceOrRef, pathOrUrl);\r\n }\r\n}\r\nfunction extractBucket(host, config) {\r\n const bucketString = config === null || config === void 0 ? void 0 : config[CONFIG_STORAGE_BUCKET_KEY];\r\n if (bucketString == null) {\r\n return null;\r\n }\r\n return Location.makeFromBucketSpec(bucketString, host);\r\n}\r\nfunction connectStorageEmulator$1(storage, host, port, options = {}) {\r\n storage.host = `${host}:${port}`;\r\n storage._protocol = 'http';\r\n const { mockUserToken } = options;\r\n if (mockUserToken) {\r\n storage._overrideAuthToken =\r\n typeof mockUserToken === 'string'\r\n ? mockUserToken\r\n : createMockUserToken(mockUserToken, storage.app.options.projectId);\r\n }\r\n}\r\n/**\r\n * A service that provides Firebase Storage Reference instances.\r\n * @param opt_url - gs:// url to a custom Storage Bucket\r\n *\r\n * @internal\r\n */\r\nclass FirebaseStorageImpl {\r\n constructor(\r\n /**\r\n * FirebaseApp associated with this StorageService instance.\r\n */\r\n app, _authProvider, \r\n /**\r\n * @internal\r\n */\r\n _appCheckProvider, \r\n /**\r\n * @internal\r\n */\r\n _url, _firebaseVersion) {\r\n this.app = app;\r\n this._authProvider = _authProvider;\r\n this._appCheckProvider = _appCheckProvider;\r\n this._url = _url;\r\n this._firebaseVersion = _firebaseVersion;\r\n this._bucket = null;\r\n /**\r\n * This string can be in the formats:\r\n * - host\r\n * - host:port\r\n */\r\n this._host = DEFAULT_HOST;\r\n this._protocol = 'https';\r\n this._appId = null;\r\n this._deleted = false;\r\n this._maxOperationRetryTime = DEFAULT_MAX_OPERATION_RETRY_TIME;\r\n this._maxUploadRetryTime = DEFAULT_MAX_UPLOAD_RETRY_TIME;\r\n this._requests = new Set();\r\n if (_url != null) {\r\n this._bucket = Location.makeFromBucketSpec(_url, this._host);\r\n }\r\n else {\r\n this._bucket = extractBucket(this._host, this.app.options);\r\n }\r\n }\r\n /**\r\n * The host string for this service, in the form of `host` or\r\n * `host:port`.\r\n */\r\n get host() {\r\n return this._host;\r\n }\r\n set host(host) {\r\n this._host = host;\r\n if (this._url != null) {\r\n this._bucket = Location.makeFromBucketSpec(this._url, host);\r\n }\r\n else {\r\n this._bucket = extractBucket(host, this.app.options);\r\n }\r\n }\r\n /**\r\n * The maximum time to retry uploads in milliseconds.\r\n */\r\n get maxUploadRetryTime() {\r\n return this._maxUploadRetryTime;\r\n }\r\n set maxUploadRetryTime(time) {\r\n validateNumber('time', \r\n /* minValue=*/ 0, \r\n /* maxValue= */ Number.POSITIVE_INFINITY, time);\r\n this._maxUploadRetryTime = time;\r\n }\r\n /**\r\n * The maximum time to retry operations other than uploads or downloads in\r\n * milliseconds.\r\n */\r\n get maxOperationRetryTime() {\r\n return this._maxOperationRetryTime;\r\n }\r\n set maxOperationRetryTime(time) {\r\n validateNumber('time', \r\n /* minValue=*/ 0, \r\n /* maxValue= */ Number.POSITIVE_INFINITY, time);\r\n this._maxOperationRetryTime = time;\r\n }\r\n async _getAuthToken() {\r\n if (this._overrideAuthToken) {\r\n return this._overrideAuthToken;\r\n }\r\n const auth = this._authProvider.getImmediate({ optional: true });\r\n if (auth) {\r\n const tokenData = await auth.getToken();\r\n if (tokenData !== null) {\r\n return tokenData.accessToken;\r\n }\r\n }\r\n return null;\r\n }\r\n async _getAppCheckToken() {\r\n const appCheck = this._appCheckProvider.getImmediate({ optional: true });\r\n if (appCheck) {\r\n const result = await appCheck.getToken();\r\n // TODO: What do we want to do if there is an error getting the token?\r\n // Context: appCheck.getToken() will never throw even if an error happened. In the error case, a dummy token will be\r\n // returned along with an error field describing the error. In general, we shouldn't care about the error condition and just use\r\n // the token (actual or dummy) to send requests.\r\n return result.token;\r\n }\r\n return null;\r\n }\r\n /**\r\n * Stop running requests and prevent more from being created.\r\n */\r\n _delete() {\r\n if (!this._deleted) {\r\n this._deleted = true;\r\n this._requests.forEach(request => request.cancel());\r\n this._requests.clear();\r\n }\r\n return Promise.resolve();\r\n }\r\n /**\r\n * Returns a new firebaseStorage.Reference object referencing this StorageService\r\n * at the given Location.\r\n */\r\n _makeStorageReference(loc) {\r\n return new Reference(this, loc);\r\n }\r\n /**\r\n * @param requestInfo - HTTP RequestInfo object\r\n * @param authToken - Firebase auth token\r\n */\r\n _makeRequest(requestInfo, requestFactory, authToken, appCheckToken, retry = true) {\r\n if (!this._deleted) {\r\n const request = makeRequest(requestInfo, this._appId, authToken, appCheckToken, requestFactory, this._firebaseVersion, retry);\r\n this._requests.add(request);\r\n // Request removes itself from set when complete.\r\n request.getPromise().then(() => this._requests.delete(request), () => this._requests.delete(request));\r\n return request;\r\n }\r\n else {\r\n return new FailRequest(appDeleted());\r\n }\r\n }\r\n async makeRequestWithTokens(requestInfo, requestFactory) {\r\n const [authToken, appCheckToken] = await Promise.all([\r\n this._getAuthToken(),\r\n this._getAppCheckToken()\r\n ]);\r\n return this._makeRequest(requestInfo, requestFactory, authToken, appCheckToken).getPromise();\r\n }\r\n}\n\nconst name = \"@firebase/storage\";\nconst version = \"0.11.2\";\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Type constant for Firebase Storage.\r\n */\r\nconst STORAGE_TYPE = 'storage';\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Downloads the data at the object's location. Returns an error if the object\r\n * is not found.\r\n *\r\n * To use this functionality, you have to whitelist your app's origin in your\r\n * Cloud Storage bucket. See also\r\n * https://cloud.google.com/storage/docs/configuring-cors\r\n *\r\n * @public\r\n * @param ref - StorageReference where data should be downloaded.\r\n * @param maxDownloadSizeBytes - If set, the maximum allowed size in bytes to\r\n * retrieve.\r\n * @returns A Promise containing the object's bytes\r\n */\r\nfunction getBytes(ref, maxDownloadSizeBytes) {\r\n ref = getModularInstance(ref);\r\n return getBytesInternal(ref, maxDownloadSizeBytes);\r\n}\r\n/**\r\n * Uploads data to this object's location.\r\n * The upload is not resumable.\r\n * @public\r\n * @param ref - {@link StorageReference} where data should be uploaded.\r\n * @param data - The data to upload.\r\n * @param metadata - Metadata for the data to upload.\r\n * @returns A Promise containing an UploadResult\r\n */\r\nfunction uploadBytes(ref, data, metadata) {\r\n ref = getModularInstance(ref);\r\n return uploadBytes$1(ref, data, metadata);\r\n}\r\n/**\r\n * Uploads a string to this object's location.\r\n * The upload is not resumable.\r\n * @public\r\n * @param ref - {@link StorageReference} where string should be uploaded.\r\n * @param value - The string to upload.\r\n * @param format - The format of the string to upload.\r\n * @param metadata - Metadata for the string to upload.\r\n * @returns A Promise containing an UploadResult\r\n */\r\nfunction uploadString(ref, value, format, metadata) {\r\n ref = getModularInstance(ref);\r\n return uploadString$1(ref, value, format, metadata);\r\n}\r\n/**\r\n * Uploads data to this object's location.\r\n * The upload can be paused and resumed, and exposes progress updates.\r\n * @public\r\n * @param ref - {@link StorageReference} where data should be uploaded.\r\n * @param data - The data to upload.\r\n * @param metadata - Metadata for the data to upload.\r\n * @returns An UploadTask\r\n */\r\nfunction uploadBytesResumable(ref, data, metadata) {\r\n ref = getModularInstance(ref);\r\n return uploadBytesResumable$1(ref, data, metadata);\r\n}\r\n/**\r\n * A `Promise` that resolves with the metadata for this object. If this\r\n * object doesn't exist or metadata cannot be retreived, the promise is\r\n * rejected.\r\n * @public\r\n * @param ref - {@link StorageReference} to get metadata from.\r\n */\r\nfunction getMetadata(ref) {\r\n ref = getModularInstance(ref);\r\n return getMetadata$1(ref);\r\n}\r\n/**\r\n * Updates the metadata for this object.\r\n * @public\r\n * @param ref - {@link StorageReference} to update metadata for.\r\n * @param metadata - The new metadata for the object.\r\n * Only values that have been explicitly set will be changed. Explicitly\r\n * setting a value to null will remove the metadata.\r\n * @returns A `Promise` that resolves with the new metadata for this object.\r\n */\r\nfunction updateMetadata(ref, metadata) {\r\n ref = getModularInstance(ref);\r\n return updateMetadata$1(ref, metadata);\r\n}\r\n/**\r\n * List items (files) and prefixes (folders) under this storage reference.\r\n *\r\n * List API is only available for Firebase Rules Version 2.\r\n *\r\n * GCS is a key-blob store. Firebase Storage imposes the semantic of '/'\r\n * delimited folder structure.\r\n * Refer to GCS's List API if you want to learn more.\r\n *\r\n * To adhere to Firebase Rules's Semantics, Firebase Storage does not\r\n * support objects whose paths end with \"/\" or contain two consecutive\r\n * \"/\"s. Firebase Storage List API will filter these unsupported objects.\r\n * list() may fail if there are too many unsupported objects in the bucket.\r\n * @public\r\n *\r\n * @param ref - {@link StorageReference} to get list from.\r\n * @param options - See {@link ListOptions} for details.\r\n * @returns A `Promise` that resolves with the items and prefixes.\r\n * `prefixes` contains references to sub-folders and `items`\r\n * contains references to objects in this folder. `nextPageToken`\r\n * can be used to get the rest of the results.\r\n */\r\nfunction list(ref, options) {\r\n ref = getModularInstance(ref);\r\n return list$1(ref, options);\r\n}\r\n/**\r\n * List all items (files) and prefixes (folders) under this storage reference.\r\n *\r\n * This is a helper method for calling list() repeatedly until there are\r\n * no more results. The default pagination size is 1000.\r\n *\r\n * Note: The results may not be consistent if objects are changed while this\r\n * operation is running.\r\n *\r\n * Warning: `listAll` may potentially consume too many resources if there are\r\n * too many results.\r\n * @public\r\n * @param ref - {@link StorageReference} to get list from.\r\n *\r\n * @returns A `Promise` that resolves with all the items and prefixes under\r\n * the current storage reference. `prefixes` contains references to\r\n * sub-directories and `items` contains references to objects in this\r\n * folder. `nextPageToken` is never returned.\r\n */\r\nfunction listAll(ref) {\r\n ref = getModularInstance(ref);\r\n return listAll$1(ref);\r\n}\r\n/**\r\n * Returns the download URL for the given {@link StorageReference}.\r\n * @public\r\n * @param ref - {@link StorageReference} to get the download URL for.\r\n * @returns A `Promise` that resolves with the download\r\n * URL for this object.\r\n */\r\nfunction getDownloadURL(ref) {\r\n ref = getModularInstance(ref);\r\n return getDownloadURL$1(ref);\r\n}\r\n/**\r\n * Deletes the object at this location.\r\n * @public\r\n * @param ref - {@link StorageReference} for object to delete.\r\n * @returns A `Promise` that resolves if the deletion succeeds.\r\n */\r\nfunction deleteObject(ref) {\r\n ref = getModularInstance(ref);\r\n return deleteObject$1(ref);\r\n}\r\nfunction ref(serviceOrRef, pathOrUrl) {\r\n serviceOrRef = getModularInstance(serviceOrRef);\r\n return ref$1(serviceOrRef, pathOrUrl);\r\n}\r\n/**\r\n * @internal\r\n */\r\nfunction _getChild(ref, childPath) {\r\n return _getChild$1(ref, childPath);\r\n}\r\n/**\r\n * Gets a {@link FirebaseStorage} instance for the given Firebase app.\r\n * @public\r\n * @param app - Firebase app to get {@link FirebaseStorage} instance for.\r\n * @param bucketUrl - The gs:// url to your Firebase Storage Bucket.\r\n * If not passed, uses the app's default Storage Bucket.\r\n * @returns A {@link FirebaseStorage} instance.\r\n */\r\nfunction getStorage(app = getApp(), bucketUrl) {\r\n app = getModularInstance(app);\r\n const storageProvider = _getProvider(app, STORAGE_TYPE);\r\n const storageInstance = storageProvider.getImmediate({\r\n identifier: bucketUrl\r\n });\r\n const emulator = getDefaultEmulatorHostnameAndPort('storage');\r\n if (emulator) {\r\n connectStorageEmulator(storageInstance, ...emulator);\r\n }\r\n return storageInstance;\r\n}\r\n/**\r\n * Modify this {@link FirebaseStorage} instance to communicate with the Cloud Storage emulator.\r\n *\r\n * @param storage - The {@link FirebaseStorage} instance\r\n * @param host - The emulator host (ex: localhost)\r\n * @param port - The emulator port (ex: 5001)\r\n * @param options - Emulator options. `options.mockUserToken` is the mock auth\r\n * token to use for unit testing Security Rules.\r\n * @public\r\n */\r\nfunction connectStorageEmulator(storage, host, port, options = {}) {\r\n connectStorageEmulator$1(storage, host, port, options);\r\n}\n\n/**\r\n * @license\r\n * Copyright 2021 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Downloads the data at the object's location. Returns an error if the object\r\n * is not found.\r\n *\r\n * To use this functionality, you have to whitelist your app's origin in your\r\n * Cloud Storage bucket. See also\r\n * https://cloud.google.com/storage/docs/configuring-cors\r\n *\r\n * This API is not available in Node.\r\n *\r\n * @public\r\n * @param ref - StorageReference where data should be downloaded.\r\n * @param maxDownloadSizeBytes - If set, the maximum allowed size in bytes to\r\n * retrieve.\r\n * @returns A Promise that resolves with a Blob containing the object's bytes\r\n */\r\nfunction getBlob(ref, maxDownloadSizeBytes) {\r\n ref = getModularInstance(ref);\r\n return getBlobInternal(ref, maxDownloadSizeBytes);\r\n}\r\n/**\r\n * Downloads the data at the object's location. Raises an error event if the\r\n * object is not found.\r\n *\r\n * This API is only available in Node.\r\n *\r\n * @public\r\n * @param ref - StorageReference where data should be downloaded.\r\n * @param maxDownloadSizeBytes - If set, the maximum allowed size in bytes to\r\n * retrieve.\r\n * @returns A stream with the object's data as bytes\r\n */\r\nfunction getStream(ref, maxDownloadSizeBytes) {\r\n throw new Error('getStream() is only supported by NodeJS builds');\r\n}\n\n/**\r\n * Cloud Storage for Firebase\r\n *\r\n * @packageDocumentation\r\n */\r\nfunction factory(container, { instanceIdentifier: url }) {\r\n const app = container.getProvider('app').getImmediate();\r\n const authProvider = container.getProvider('auth-internal');\r\n const appCheckProvider = container.getProvider('app-check-internal');\r\n return new FirebaseStorageImpl(app, authProvider, appCheckProvider, url, SDK_VERSION);\r\n}\r\nfunction registerStorage() {\r\n _registerComponent(new Component(STORAGE_TYPE, factory, \"PUBLIC\" /* ComponentType.PUBLIC */).setMultipleInstances(true));\r\n //RUNTIME_ENV will be replaced during the compilation to \"node\" for nodejs and an empty string for browser\r\n registerVersion(name, version, '');\r\n // BUILD_TARGET will be replaced by values like esm5, esm2017, cjs5, etc during the compilation\r\n registerVersion(name, version, 'esm2017');\r\n}\r\nregisterStorage();\n\nexport { StorageError, StorageErrorCode, StringFormat, FbsBlob as _FbsBlob, Location as _Location, TaskEvent as _TaskEvent, TaskState as _TaskState, UploadTask as _UploadTask, dataFromString as _dataFromString, _getChild, invalidArgument as _invalidArgument, invalidRootOperation as _invalidRootOperation, connectStorageEmulator, deleteObject, getBlob, getBytes, getDownloadURL, getMetadata, getStorage, getStream, list, listAll, ref, updateMetadata, uploadBytes, uploadBytesResumable, uploadString };\n//# sourceMappingURL=index.esm2017.js.map\n","const instanceOfAny = (object, constructors) => constructors.some((c) => object instanceof c);\n\nlet idbProxyableTypes;\nlet cursorAdvanceMethods;\n// This is a function to prevent it throwing up in node environments.\nfunction getIdbProxyableTypes() {\n return (idbProxyableTypes ||\n (idbProxyableTypes = [\n IDBDatabase,\n IDBObjectStore,\n IDBIndex,\n IDBCursor,\n IDBTransaction,\n ]));\n}\n// This is a function to prevent it throwing up in node environments.\nfunction getCursorAdvanceMethods() {\n return (cursorAdvanceMethods ||\n (cursorAdvanceMethods = [\n IDBCursor.prototype.advance,\n IDBCursor.prototype.continue,\n IDBCursor.prototype.continuePrimaryKey,\n ]));\n}\nconst cursorRequestMap = new WeakMap();\nconst transactionDoneMap = new WeakMap();\nconst transactionStoreNamesMap = new WeakMap();\nconst transformCache = new WeakMap();\nconst reverseTransformCache = new WeakMap();\nfunction promisifyRequest(request) {\n const promise = new Promise((resolve, reject) => {\n const unlisten = () => {\n request.removeEventListener('success', success);\n request.removeEventListener('error', error);\n };\n const success = () => {\n resolve(wrap(request.result));\n unlisten();\n };\n const error = () => {\n reject(request.error);\n unlisten();\n };\n request.addEventListener('success', success);\n request.addEventListener('error', error);\n });\n promise\n .then((value) => {\n // Since cursoring reuses the IDBRequest (*sigh*), we cache it for later retrieval\n // (see wrapFunction).\n if (value instanceof IDBCursor) {\n cursorRequestMap.set(value, request);\n }\n // Catching to avoid \"Uncaught Promise exceptions\"\n })\n .catch(() => { });\n // This mapping exists in reverseTransformCache but doesn't doesn't exist in transformCache. This\n // is because we create many promises from a single IDBRequest.\n reverseTransformCache.set(promise, request);\n return promise;\n}\nfunction cacheDonePromiseForTransaction(tx) {\n // Early bail if we've already created a done promise for this transaction.\n if (transactionDoneMap.has(tx))\n return;\n const done = new Promise((resolve, reject) => {\n const unlisten = () => {\n tx.removeEventListener('complete', complete);\n tx.removeEventListener('error', error);\n tx.removeEventListener('abort', error);\n };\n const complete = () => {\n resolve();\n unlisten();\n };\n const error = () => {\n reject(tx.error || new DOMException('AbortError', 'AbortError'));\n unlisten();\n };\n tx.addEventListener('complete', complete);\n tx.addEventListener('error', error);\n tx.addEventListener('abort', error);\n });\n // Cache it for later retrieval.\n transactionDoneMap.set(tx, done);\n}\nlet idbProxyTraps = {\n get(target, prop, receiver) {\n if (target instanceof IDBTransaction) {\n // Special handling for transaction.done.\n if (prop === 'done')\n return transactionDoneMap.get(target);\n // Polyfill for objectStoreNames because of Edge.\n if (prop === 'objectStoreNames') {\n return target.objectStoreNames || transactionStoreNamesMap.get(target);\n }\n // Make tx.store return the only store in the transaction, or undefined if there are many.\n if (prop === 'store') {\n return receiver.objectStoreNames[1]\n ? undefined\n : receiver.objectStore(receiver.objectStoreNames[0]);\n }\n }\n // Else transform whatever we get back.\n return wrap(target[prop]);\n },\n set(target, prop, value) {\n target[prop] = value;\n return true;\n },\n has(target, prop) {\n if (target instanceof IDBTransaction &&\n (prop === 'done' || prop === 'store')) {\n return true;\n }\n return prop in target;\n },\n};\nfunction replaceTraps(callback) {\n idbProxyTraps = callback(idbProxyTraps);\n}\nfunction wrapFunction(func) {\n // Due to expected object equality (which is enforced by the caching in `wrap`), we\n // only create one new func per func.\n // Edge doesn't support objectStoreNames (booo), so we polyfill it here.\n if (func === IDBDatabase.prototype.transaction &&\n !('objectStoreNames' in IDBTransaction.prototype)) {\n return function (storeNames, ...args) {\n const tx = func.call(unwrap(this), storeNames, ...args);\n transactionStoreNamesMap.set(tx, storeNames.sort ? storeNames.sort() : [storeNames]);\n return wrap(tx);\n };\n }\n // Cursor methods are special, as the behaviour is a little more different to standard IDB. In\n // IDB, you advance the cursor and wait for a new 'success' on the IDBRequest that gave you the\n // cursor. It's kinda like a promise that can resolve with many values. That doesn't make sense\n // with real promises, so each advance methods returns a new promise for the cursor object, or\n // undefined if the end of the cursor has been reached.\n if (getCursorAdvanceMethods().includes(func)) {\n return function (...args) {\n // Calling the original function with the proxy as 'this' causes ILLEGAL INVOCATION, so we use\n // the original object.\n func.apply(unwrap(this), args);\n return wrap(cursorRequestMap.get(this));\n };\n }\n return function (...args) {\n // Calling the original function with the proxy as 'this' causes ILLEGAL INVOCATION, so we use\n // the original object.\n return wrap(func.apply(unwrap(this), args));\n };\n}\nfunction transformCachableValue(value) {\n if (typeof value === 'function')\n return wrapFunction(value);\n // This doesn't return, it just creates a 'done' promise for the transaction,\n // which is later returned for transaction.done (see idbObjectHandler).\n if (value instanceof IDBTransaction)\n cacheDonePromiseForTransaction(value);\n if (instanceOfAny(value, getIdbProxyableTypes()))\n return new Proxy(value, idbProxyTraps);\n // Return the same value back if we're not going to transform it.\n return value;\n}\nfunction wrap(value) {\n // We sometimes generate multiple promises from a single IDBRequest (eg when cursoring), because\n // IDB is weird and a single IDBRequest can yield many responses, so these can't be cached.\n if (value instanceof IDBRequest)\n return promisifyRequest(value);\n // If we've already transformed this value before, reuse the transformed value.\n // This is faster, but it also provides object equality.\n if (transformCache.has(value))\n return transformCache.get(value);\n const newValue = transformCachableValue(value);\n // Not all types are transformed.\n // These may be primitive types, so they can't be WeakMap keys.\n if (newValue !== value) {\n transformCache.set(value, newValue);\n reverseTransformCache.set(newValue, value);\n }\n return newValue;\n}\nconst unwrap = (value) => reverseTransformCache.get(value);\n\nexport { reverseTransformCache as a, instanceOfAny as i, replaceTraps as r, unwrap as u, wrap as w };\n","import { w as wrap, r as replaceTraps } from './wrap-idb-value.js';\nexport { u as unwrap, w as wrap } from './wrap-idb-value.js';\n\n/**\n * Open a database.\n *\n * @param name Name of the database.\n * @param version Schema version.\n * @param callbacks Additional callbacks.\n */\nfunction openDB(name, version, { blocked, upgrade, blocking, terminated } = {}) {\n const request = indexedDB.open(name, version);\n const openPromise = wrap(request);\n if (upgrade) {\n request.addEventListener('upgradeneeded', (event) => {\n upgrade(wrap(request.result), event.oldVersion, event.newVersion, wrap(request.transaction));\n });\n }\n if (blocked)\n request.addEventListener('blocked', () => blocked());\n openPromise\n .then((db) => {\n if (terminated)\n db.addEventListener('close', () => terminated());\n if (blocking)\n db.addEventListener('versionchange', () => blocking());\n })\n .catch(() => { });\n return openPromise;\n}\n/**\n * Delete a database.\n *\n * @param name Name of the database.\n */\nfunction deleteDB(name, { blocked } = {}) {\n const request = indexedDB.deleteDatabase(name);\n if (blocked)\n request.addEventListener('blocked', () => blocked());\n return wrap(request).then(() => undefined);\n}\n\nconst readMethods = ['get', 'getKey', 'getAll', 'getAllKeys', 'count'];\nconst writeMethods = ['put', 'add', 'delete', 'clear'];\nconst cachedMethods = new Map();\nfunction getMethod(target, prop) {\n if (!(target instanceof IDBDatabase &&\n !(prop in target) &&\n typeof prop === 'string')) {\n return;\n }\n if (cachedMethods.get(prop))\n return cachedMethods.get(prop);\n const targetFuncName = prop.replace(/FromIndex$/, '');\n const useIndex = prop !== targetFuncName;\n const isWrite = writeMethods.includes(targetFuncName);\n if (\n // Bail if the target doesn't exist on the target. Eg, getAll isn't in Edge.\n !(targetFuncName in (useIndex ? IDBIndex : IDBObjectStore).prototype) ||\n !(isWrite || readMethods.includes(targetFuncName))) {\n return;\n }\n const method = async function (storeName, ...args) {\n // isWrite ? 'readwrite' : undefined gzipps better, but fails in Edge :(\n const tx = this.transaction(storeName, isWrite ? 'readwrite' : 'readonly');\n let target = tx.store;\n if (useIndex)\n target = target.index(args.shift());\n // Must reject if op rejects.\n // If it's a write operation, must reject if tx.done rejects.\n // Must reject with op rejection first.\n // Must resolve with op value.\n // Must handle both promises (no unhandled rejections)\n return (await Promise.all([\n target[targetFuncName](...args),\n isWrite && tx.done,\n ]))[0];\n };\n cachedMethods.set(prop, method);\n return method;\n}\nreplaceTraps((oldTraps) => ({\n ...oldTraps,\n get: (target, prop, receiver) => getMethod(target, prop) || oldTraps.get(target, prop, receiver),\n has: (target, prop) => !!getMethod(target, prop) || oldTraps.has(target, prop),\n}));\n\nexport { deleteDB, openDB };\n","import { _getProvider, getApp, _registerComponent, registerVersion } from '@firebase/app';\nimport { Component } from '@firebase/component';\nimport { ErrorFactory, FirebaseError } from '@firebase/util';\nimport { openDB } from 'idb';\n\nconst name = \"@firebase/installations\";\nconst version = \"0.6.4\";\n\n/**\r\n * @license\r\n * Copyright 2019 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nconst PENDING_TIMEOUT_MS = 10000;\r\nconst PACKAGE_VERSION = `w:${version}`;\r\nconst INTERNAL_AUTH_VERSION = 'FIS_v2';\r\nconst INSTALLATIONS_API_URL = 'https://firebaseinstallations.googleapis.com/v1';\r\nconst TOKEN_EXPIRATION_BUFFER = 60 * 60 * 1000; // One hour\r\nconst SERVICE = 'installations';\r\nconst SERVICE_NAME = 'Installations';\n\n/**\r\n * @license\r\n * Copyright 2019 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nconst ERROR_DESCRIPTION_MAP = {\r\n [\"missing-app-config-values\" /* ErrorCode.MISSING_APP_CONFIG_VALUES */]: 'Missing App configuration value: \"{$valueName}\"',\r\n [\"not-registered\" /* ErrorCode.NOT_REGISTERED */]: 'Firebase Installation is not registered.',\r\n [\"installation-not-found\" /* ErrorCode.INSTALLATION_NOT_FOUND */]: 'Firebase Installation not found.',\r\n [\"request-failed\" /* ErrorCode.REQUEST_FAILED */]: '{$requestName} request failed with error \"{$serverCode} {$serverStatus}: {$serverMessage}\"',\r\n [\"app-offline\" /* ErrorCode.APP_OFFLINE */]: 'Could not process request. Application offline.',\r\n [\"delete-pending-registration\" /* ErrorCode.DELETE_PENDING_REGISTRATION */]: \"Can't delete installation while there is a pending registration request.\"\r\n};\r\nconst ERROR_FACTORY = new ErrorFactory(SERVICE, SERVICE_NAME, ERROR_DESCRIPTION_MAP);\r\n/** Returns true if error is a FirebaseError that is based on an error from the server. */\r\nfunction isServerError(error) {\r\n return (error instanceof FirebaseError &&\r\n error.code.includes(\"request-failed\" /* ErrorCode.REQUEST_FAILED */));\r\n}\n\n/**\r\n * @license\r\n * Copyright 2019 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nfunction getInstallationsEndpoint({ projectId }) {\r\n return `${INSTALLATIONS_API_URL}/projects/${projectId}/installations`;\r\n}\r\nfunction extractAuthTokenInfoFromResponse(response) {\r\n return {\r\n token: response.token,\r\n requestStatus: 2 /* RequestStatus.COMPLETED */,\r\n expiresIn: getExpiresInFromResponseExpiresIn(response.expiresIn),\r\n creationTime: Date.now()\r\n };\r\n}\r\nasync function getErrorFromResponse(requestName, response) {\r\n const responseJson = await response.json();\r\n const errorData = responseJson.error;\r\n return ERROR_FACTORY.create(\"request-failed\" /* ErrorCode.REQUEST_FAILED */, {\r\n requestName,\r\n serverCode: errorData.code,\r\n serverMessage: errorData.message,\r\n serverStatus: errorData.status\r\n });\r\n}\r\nfunction getHeaders({ apiKey }) {\r\n return new Headers({\r\n 'Content-Type': 'application/json',\r\n Accept: 'application/json',\r\n 'x-goog-api-key': apiKey\r\n });\r\n}\r\nfunction getHeadersWithAuth(appConfig, { refreshToken }) {\r\n const headers = getHeaders(appConfig);\r\n headers.append('Authorization', getAuthorizationHeader(refreshToken));\r\n return headers;\r\n}\r\n/**\r\n * Calls the passed in fetch wrapper and returns the response.\r\n * If the returned response has a status of 5xx, re-runs the function once and\r\n * returns the response.\r\n */\r\nasync function retryIfServerError(fn) {\r\n const result = await fn();\r\n if (result.status >= 500 && result.status < 600) {\r\n // Internal Server Error. Retry request.\r\n return fn();\r\n }\r\n return result;\r\n}\r\nfunction getExpiresInFromResponseExpiresIn(responseExpiresIn) {\r\n // This works because the server will never respond with fractions of a second.\r\n return Number(responseExpiresIn.replace('s', '000'));\r\n}\r\nfunction getAuthorizationHeader(refreshToken) {\r\n return `${INTERNAL_AUTH_VERSION} ${refreshToken}`;\r\n}\n\n/**\r\n * @license\r\n * Copyright 2019 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nasync function createInstallationRequest({ appConfig, heartbeatServiceProvider }, { fid }) {\r\n const endpoint = getInstallationsEndpoint(appConfig);\r\n const headers = getHeaders(appConfig);\r\n // If heartbeat service exists, add the heartbeat string to the header.\r\n const heartbeatService = heartbeatServiceProvider.getImmediate({\r\n optional: true\r\n });\r\n if (heartbeatService) {\r\n const heartbeatsHeader = await heartbeatService.getHeartbeatsHeader();\r\n if (heartbeatsHeader) {\r\n headers.append('x-firebase-client', heartbeatsHeader);\r\n }\r\n }\r\n const body = {\r\n fid,\r\n authVersion: INTERNAL_AUTH_VERSION,\r\n appId: appConfig.appId,\r\n sdkVersion: PACKAGE_VERSION\r\n };\r\n const request = {\r\n method: 'POST',\r\n headers,\r\n body: JSON.stringify(body)\r\n };\r\n const response = await retryIfServerError(() => fetch(endpoint, request));\r\n if (response.ok) {\r\n const responseValue = await response.json();\r\n const registeredInstallationEntry = {\r\n fid: responseValue.fid || fid,\r\n registrationStatus: 2 /* RequestStatus.COMPLETED */,\r\n refreshToken: responseValue.refreshToken,\r\n authToken: extractAuthTokenInfoFromResponse(responseValue.authToken)\r\n };\r\n return registeredInstallationEntry;\r\n }\r\n else {\r\n throw await getErrorFromResponse('Create Installation', response);\r\n }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2019 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/** Returns a promise that resolves after given time passes. */\r\nfunction sleep(ms) {\r\n return new Promise(resolve => {\r\n setTimeout(resolve, ms);\r\n });\r\n}\n\n/**\r\n * @license\r\n * Copyright 2019 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nfunction bufferToBase64UrlSafe(array) {\r\n const b64 = btoa(String.fromCharCode(...array));\r\n return b64.replace(/\\+/g, '-').replace(/\\//g, '_');\r\n}\n\n/**\r\n * @license\r\n * Copyright 2019 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nconst VALID_FID_PATTERN = /^[cdef][\\w-]{21}$/;\r\nconst INVALID_FID = '';\r\n/**\r\n * Generates a new FID using random values from Web Crypto API.\r\n * Returns an empty string if FID generation fails for any reason.\r\n */\r\nfunction generateFid() {\r\n try {\r\n // A valid FID has exactly 22 base64 characters, which is 132 bits, or 16.5\r\n // bytes. our implementation generates a 17 byte array instead.\r\n const fidByteArray = new Uint8Array(17);\r\n const crypto = self.crypto || self.msCrypto;\r\n crypto.getRandomValues(fidByteArray);\r\n // Replace the first 4 random bits with the constant FID header of 0b0111.\r\n fidByteArray[0] = 0b01110000 + (fidByteArray[0] % 0b00010000);\r\n const fid = encode(fidByteArray);\r\n return VALID_FID_PATTERN.test(fid) ? fid : INVALID_FID;\r\n }\r\n catch (_a) {\r\n // FID generation errored\r\n return INVALID_FID;\r\n }\r\n}\r\n/** Converts a FID Uint8Array to a base64 string representation. */\r\nfunction encode(fidByteArray) {\r\n const b64String = bufferToBase64UrlSafe(fidByteArray);\r\n // Remove the 23rd character that was added because of the extra 4 bits at the\r\n // end of our 17 byte array, and the '=' padding.\r\n return b64String.substr(0, 22);\r\n}\n\n/**\r\n * @license\r\n * Copyright 2019 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/** Returns a string key that can be used to identify the app. */\r\nfunction getKey(appConfig) {\r\n return `${appConfig.appName}!${appConfig.appId}`;\r\n}\n\n/**\r\n * @license\r\n * Copyright 2019 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nconst fidChangeCallbacks = new Map();\r\n/**\r\n * Calls the onIdChange callbacks with the new FID value, and broadcasts the\r\n * change to other tabs.\r\n */\r\nfunction fidChanged(appConfig, fid) {\r\n const key = getKey(appConfig);\r\n callFidChangeCallbacks(key, fid);\r\n broadcastFidChange(key, fid);\r\n}\r\nfunction addCallback(appConfig, callback) {\r\n // Open the broadcast channel if it's not already open,\r\n // to be able to listen to change events from other tabs.\r\n getBroadcastChannel();\r\n const key = getKey(appConfig);\r\n let callbackSet = fidChangeCallbacks.get(key);\r\n if (!callbackSet) {\r\n callbackSet = new Set();\r\n fidChangeCallbacks.set(key, callbackSet);\r\n }\r\n callbackSet.add(callback);\r\n}\r\nfunction removeCallback(appConfig, callback) {\r\n const key = getKey(appConfig);\r\n const callbackSet = fidChangeCallbacks.get(key);\r\n if (!callbackSet) {\r\n return;\r\n }\r\n callbackSet.delete(callback);\r\n if (callbackSet.size === 0) {\r\n fidChangeCallbacks.delete(key);\r\n }\r\n // Close broadcast channel if there are no more callbacks.\r\n closeBroadcastChannel();\r\n}\r\nfunction callFidChangeCallbacks(key, fid) {\r\n const callbacks = fidChangeCallbacks.get(key);\r\n if (!callbacks) {\r\n return;\r\n }\r\n for (const callback of callbacks) {\r\n callback(fid);\r\n }\r\n}\r\nfunction broadcastFidChange(key, fid) {\r\n const channel = getBroadcastChannel();\r\n if (channel) {\r\n channel.postMessage({ key, fid });\r\n }\r\n closeBroadcastChannel();\r\n}\r\nlet broadcastChannel = null;\r\n/** Opens and returns a BroadcastChannel if it is supported by the browser. */\r\nfunction getBroadcastChannel() {\r\n if (!broadcastChannel && 'BroadcastChannel' in self) {\r\n broadcastChannel = new BroadcastChannel('[Firebase] FID Change');\r\n broadcastChannel.onmessage = e => {\r\n callFidChangeCallbacks(e.data.key, e.data.fid);\r\n };\r\n }\r\n return broadcastChannel;\r\n}\r\nfunction closeBroadcastChannel() {\r\n if (fidChangeCallbacks.size === 0 && broadcastChannel) {\r\n broadcastChannel.close();\r\n broadcastChannel = null;\r\n }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2019 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nconst DATABASE_NAME = 'firebase-installations-database';\r\nconst DATABASE_VERSION = 1;\r\nconst OBJECT_STORE_NAME = 'firebase-installations-store';\r\nlet dbPromise = null;\r\nfunction getDbPromise() {\r\n if (!dbPromise) {\r\n dbPromise = openDB(DATABASE_NAME, DATABASE_VERSION, {\r\n upgrade: (db, oldVersion) => {\r\n // We don't use 'break' in this switch statement, the fall-through\r\n // behavior is what we want, because if there are multiple versions between\r\n // the old version and the current version, we want ALL the migrations\r\n // that correspond to those versions to run, not only the last one.\r\n // eslint-disable-next-line default-case\r\n switch (oldVersion) {\r\n case 0:\r\n db.createObjectStore(OBJECT_STORE_NAME);\r\n }\r\n }\r\n });\r\n }\r\n return dbPromise;\r\n}\r\n/** Assigns or overwrites the record for the given key with the given value. */\r\nasync function set(appConfig, value) {\r\n const key = getKey(appConfig);\r\n const db = await getDbPromise();\r\n const tx = db.transaction(OBJECT_STORE_NAME, 'readwrite');\r\n const objectStore = tx.objectStore(OBJECT_STORE_NAME);\r\n const oldValue = (await objectStore.get(key));\r\n await objectStore.put(value, key);\r\n await tx.done;\r\n if (!oldValue || oldValue.fid !== value.fid) {\r\n fidChanged(appConfig, value.fid);\r\n }\r\n return value;\r\n}\r\n/** Removes record(s) from the objectStore that match the given key. */\r\nasync function remove(appConfig) {\r\n const key = getKey(appConfig);\r\n const db = await getDbPromise();\r\n const tx = db.transaction(OBJECT_STORE_NAME, 'readwrite');\r\n await tx.objectStore(OBJECT_STORE_NAME).delete(key);\r\n await tx.done;\r\n}\r\n/**\r\n * Atomically updates a record with the result of updateFn, which gets\r\n * called with the current value. If newValue is undefined, the record is\r\n * deleted instead.\r\n * @return Updated value\r\n */\r\nasync function update(appConfig, updateFn) {\r\n const key = getKey(appConfig);\r\n const db = await getDbPromise();\r\n const tx = db.transaction(OBJECT_STORE_NAME, 'readwrite');\r\n const store = tx.objectStore(OBJECT_STORE_NAME);\r\n const oldValue = (await store.get(key));\r\n const newValue = updateFn(oldValue);\r\n if (newValue === undefined) {\r\n await store.delete(key);\r\n }\r\n else {\r\n await store.put(newValue, key);\r\n }\r\n await tx.done;\r\n if (newValue && (!oldValue || oldValue.fid !== newValue.fid)) {\r\n fidChanged(appConfig, newValue.fid);\r\n }\r\n return newValue;\r\n}\n\n/**\r\n * @license\r\n * Copyright 2019 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Updates and returns the InstallationEntry from the database.\r\n * Also triggers a registration request if it is necessary and possible.\r\n */\r\nasync function getInstallationEntry(installations) {\r\n let registrationPromise;\r\n const installationEntry = await update(installations.appConfig, oldEntry => {\r\n const installationEntry = updateOrCreateInstallationEntry(oldEntry);\r\n const entryWithPromise = triggerRegistrationIfNecessary(installations, installationEntry);\r\n registrationPromise = entryWithPromise.registrationPromise;\r\n return entryWithPromise.installationEntry;\r\n });\r\n if (installationEntry.fid === INVALID_FID) {\r\n // FID generation failed. Waiting for the FID from the server.\r\n return { installationEntry: await registrationPromise };\r\n }\r\n return {\r\n installationEntry,\r\n registrationPromise\r\n };\r\n}\r\n/**\r\n * Creates a new Installation Entry if one does not exist.\r\n * Also clears timed out pending requests.\r\n */\r\nfunction updateOrCreateInstallationEntry(oldEntry) {\r\n const entry = oldEntry || {\r\n fid: generateFid(),\r\n registrationStatus: 0 /* RequestStatus.NOT_STARTED */\r\n };\r\n return clearTimedOutRequest(entry);\r\n}\r\n/**\r\n * If the Firebase Installation is not registered yet, this will trigger the\r\n * registration and return an InProgressInstallationEntry.\r\n *\r\n * If registrationPromise does not exist, the installationEntry is guaranteed\r\n * to be registered.\r\n */\r\nfunction triggerRegistrationIfNecessary(installations, installationEntry) {\r\n if (installationEntry.registrationStatus === 0 /* RequestStatus.NOT_STARTED */) {\r\n if (!navigator.onLine) {\r\n // Registration required but app is offline.\r\n const registrationPromiseWithError = Promise.reject(ERROR_FACTORY.create(\"app-offline\" /* ErrorCode.APP_OFFLINE */));\r\n return {\r\n installationEntry,\r\n registrationPromise: registrationPromiseWithError\r\n };\r\n }\r\n // Try registering. Change status to IN_PROGRESS.\r\n const inProgressEntry = {\r\n fid: installationEntry.fid,\r\n registrationStatus: 1 /* RequestStatus.IN_PROGRESS */,\r\n registrationTime: Date.now()\r\n };\r\n const registrationPromise = registerInstallation(installations, inProgressEntry);\r\n return { installationEntry: inProgressEntry, registrationPromise };\r\n }\r\n else if (installationEntry.registrationStatus === 1 /* RequestStatus.IN_PROGRESS */) {\r\n return {\r\n installationEntry,\r\n registrationPromise: waitUntilFidRegistration(installations)\r\n };\r\n }\r\n else {\r\n return { installationEntry };\r\n }\r\n}\r\n/** This will be executed only once for each new Firebase Installation. */\r\nasync function registerInstallation(installations, installationEntry) {\r\n try {\r\n const registeredInstallationEntry = await createInstallationRequest(installations, installationEntry);\r\n return set(installations.appConfig, registeredInstallationEntry);\r\n }\r\n catch (e) {\r\n if (isServerError(e) && e.customData.serverCode === 409) {\r\n // Server returned a \"FID can not be used\" error.\r\n // Generate a new ID next time.\r\n await remove(installations.appConfig);\r\n }\r\n else {\r\n // Registration failed. Set FID as not registered.\r\n await set(installations.appConfig, {\r\n fid: installationEntry.fid,\r\n registrationStatus: 0 /* RequestStatus.NOT_STARTED */\r\n });\r\n }\r\n throw e;\r\n }\r\n}\r\n/** Call if FID registration is pending in another request. */\r\nasync function waitUntilFidRegistration(installations) {\r\n // Unfortunately, there is no way of reliably observing when a value in\r\n // IndexedDB changes (yet, see https://github.com/WICG/indexed-db-observers),\r\n // so we need to poll.\r\n let entry = await updateInstallationRequest(installations.appConfig);\r\n while (entry.registrationStatus === 1 /* RequestStatus.IN_PROGRESS */) {\r\n // createInstallation request still in progress.\r\n await sleep(100);\r\n entry = await updateInstallationRequest(installations.appConfig);\r\n }\r\n if (entry.registrationStatus === 0 /* RequestStatus.NOT_STARTED */) {\r\n // The request timed out or failed in a different call. Try again.\r\n const { installationEntry, registrationPromise } = await getInstallationEntry(installations);\r\n if (registrationPromise) {\r\n return registrationPromise;\r\n }\r\n else {\r\n // if there is no registrationPromise, entry is registered.\r\n return installationEntry;\r\n }\r\n }\r\n return entry;\r\n}\r\n/**\r\n * Called only if there is a CreateInstallation request in progress.\r\n *\r\n * Updates the InstallationEntry in the DB based on the status of the\r\n * CreateInstallation request.\r\n *\r\n * Returns the updated InstallationEntry.\r\n */\r\nfunction updateInstallationRequest(appConfig) {\r\n return update(appConfig, oldEntry => {\r\n if (!oldEntry) {\r\n throw ERROR_FACTORY.create(\"installation-not-found\" /* ErrorCode.INSTALLATION_NOT_FOUND */);\r\n }\r\n return clearTimedOutRequest(oldEntry);\r\n });\r\n}\r\nfunction clearTimedOutRequest(entry) {\r\n if (hasInstallationRequestTimedOut(entry)) {\r\n return {\r\n fid: entry.fid,\r\n registrationStatus: 0 /* RequestStatus.NOT_STARTED */\r\n };\r\n }\r\n return entry;\r\n}\r\nfunction hasInstallationRequestTimedOut(installationEntry) {\r\n return (installationEntry.registrationStatus === 1 /* RequestStatus.IN_PROGRESS */ &&\r\n installationEntry.registrationTime + PENDING_TIMEOUT_MS < Date.now());\r\n}\n\n/**\r\n * @license\r\n * Copyright 2019 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nasync function generateAuthTokenRequest({ appConfig, heartbeatServiceProvider }, installationEntry) {\r\n const endpoint = getGenerateAuthTokenEndpoint(appConfig, installationEntry);\r\n const headers = getHeadersWithAuth(appConfig, installationEntry);\r\n // If heartbeat service exists, add the heartbeat string to the header.\r\n const heartbeatService = heartbeatServiceProvider.getImmediate({\r\n optional: true\r\n });\r\n if (heartbeatService) {\r\n const heartbeatsHeader = await heartbeatService.getHeartbeatsHeader();\r\n if (heartbeatsHeader) {\r\n headers.append('x-firebase-client', heartbeatsHeader);\r\n }\r\n }\r\n const body = {\r\n installation: {\r\n sdkVersion: PACKAGE_VERSION,\r\n appId: appConfig.appId\r\n }\r\n };\r\n const request = {\r\n method: 'POST',\r\n headers,\r\n body: JSON.stringify(body)\r\n };\r\n const response = await retryIfServerError(() => fetch(endpoint, request));\r\n if (response.ok) {\r\n const responseValue = await response.json();\r\n const completedAuthToken = extractAuthTokenInfoFromResponse(responseValue);\r\n return completedAuthToken;\r\n }\r\n else {\r\n throw await getErrorFromResponse('Generate Auth Token', response);\r\n }\r\n}\r\nfunction getGenerateAuthTokenEndpoint(appConfig, { fid }) {\r\n return `${getInstallationsEndpoint(appConfig)}/${fid}/authTokens:generate`;\r\n}\n\n/**\r\n * @license\r\n * Copyright 2019 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Returns a valid authentication token for the installation. Generates a new\r\n * token if one doesn't exist, is expired or about to expire.\r\n *\r\n * Should only be called if the Firebase Installation is registered.\r\n */\r\nasync function refreshAuthToken(installations, forceRefresh = false) {\r\n let tokenPromise;\r\n const entry = await update(installations.appConfig, oldEntry => {\r\n if (!isEntryRegistered(oldEntry)) {\r\n throw ERROR_FACTORY.create(\"not-registered\" /* ErrorCode.NOT_REGISTERED */);\r\n }\r\n const oldAuthToken = oldEntry.authToken;\r\n if (!forceRefresh && isAuthTokenValid(oldAuthToken)) {\r\n // There is a valid token in the DB.\r\n return oldEntry;\r\n }\r\n else if (oldAuthToken.requestStatus === 1 /* RequestStatus.IN_PROGRESS */) {\r\n // There already is a token request in progress.\r\n tokenPromise = waitUntilAuthTokenRequest(installations, forceRefresh);\r\n return oldEntry;\r\n }\r\n else {\r\n // No token or token expired.\r\n if (!navigator.onLine) {\r\n throw ERROR_FACTORY.create(\"app-offline\" /* ErrorCode.APP_OFFLINE */);\r\n }\r\n const inProgressEntry = makeAuthTokenRequestInProgressEntry(oldEntry);\r\n tokenPromise = fetchAuthTokenFromServer(installations, inProgressEntry);\r\n return inProgressEntry;\r\n }\r\n });\r\n const authToken = tokenPromise\r\n ? await tokenPromise\r\n : entry.authToken;\r\n return authToken;\r\n}\r\n/**\r\n * Call only if FID is registered and Auth Token request is in progress.\r\n *\r\n * Waits until the current pending request finishes. If the request times out,\r\n * tries once in this thread as well.\r\n */\r\nasync function waitUntilAuthTokenRequest(installations, forceRefresh) {\r\n // Unfortunately, there is no way of reliably observing when a value in\r\n // IndexedDB changes (yet, see https://github.com/WICG/indexed-db-observers),\r\n // so we need to poll.\r\n let entry = await updateAuthTokenRequest(installations.appConfig);\r\n while (entry.authToken.requestStatus === 1 /* RequestStatus.IN_PROGRESS */) {\r\n // generateAuthToken still in progress.\r\n await sleep(100);\r\n entry = await updateAuthTokenRequest(installations.appConfig);\r\n }\r\n const authToken = entry.authToken;\r\n if (authToken.requestStatus === 0 /* RequestStatus.NOT_STARTED */) {\r\n // The request timed out or failed in a different call. Try again.\r\n return refreshAuthToken(installations, forceRefresh);\r\n }\r\n else {\r\n return authToken;\r\n }\r\n}\r\n/**\r\n * Called only if there is a GenerateAuthToken request in progress.\r\n *\r\n * Updates the InstallationEntry in the DB based on the status of the\r\n * GenerateAuthToken request.\r\n *\r\n * Returns the updated InstallationEntry.\r\n */\r\nfunction updateAuthTokenRequest(appConfig) {\r\n return update(appConfig, oldEntry => {\r\n if (!isEntryRegistered(oldEntry)) {\r\n throw ERROR_FACTORY.create(\"not-registered\" /* ErrorCode.NOT_REGISTERED */);\r\n }\r\n const oldAuthToken = oldEntry.authToken;\r\n if (hasAuthTokenRequestTimedOut(oldAuthToken)) {\r\n return Object.assign(Object.assign({}, oldEntry), { authToken: { requestStatus: 0 /* RequestStatus.NOT_STARTED */ } });\r\n }\r\n return oldEntry;\r\n });\r\n}\r\nasync function fetchAuthTokenFromServer(installations, installationEntry) {\r\n try {\r\n const authToken = await generateAuthTokenRequest(installations, installationEntry);\r\n const updatedInstallationEntry = Object.assign(Object.assign({}, installationEntry), { authToken });\r\n await set(installations.appConfig, updatedInstallationEntry);\r\n return authToken;\r\n }\r\n catch (e) {\r\n if (isServerError(e) &&\r\n (e.customData.serverCode === 401 || e.customData.serverCode === 404)) {\r\n // Server returned a \"FID not found\" or a \"Invalid authentication\" error.\r\n // Generate a new ID next time.\r\n await remove(installations.appConfig);\r\n }\r\n else {\r\n const updatedInstallationEntry = Object.assign(Object.assign({}, installationEntry), { authToken: { requestStatus: 0 /* RequestStatus.NOT_STARTED */ } });\r\n await set(installations.appConfig, updatedInstallationEntry);\r\n }\r\n throw e;\r\n }\r\n}\r\nfunction isEntryRegistered(installationEntry) {\r\n return (installationEntry !== undefined &&\r\n installationEntry.registrationStatus === 2 /* RequestStatus.COMPLETED */);\r\n}\r\nfunction isAuthTokenValid(authToken) {\r\n return (authToken.requestStatus === 2 /* RequestStatus.COMPLETED */ &&\r\n !isAuthTokenExpired(authToken));\r\n}\r\nfunction isAuthTokenExpired(authToken) {\r\n const now = Date.now();\r\n return (now < authToken.creationTime ||\r\n authToken.creationTime + authToken.expiresIn < now + TOKEN_EXPIRATION_BUFFER);\r\n}\r\n/** Returns an updated InstallationEntry with an InProgressAuthToken. */\r\nfunction makeAuthTokenRequestInProgressEntry(oldEntry) {\r\n const inProgressAuthToken = {\r\n requestStatus: 1 /* RequestStatus.IN_PROGRESS */,\r\n requestTime: Date.now()\r\n };\r\n return Object.assign(Object.assign({}, oldEntry), { authToken: inProgressAuthToken });\r\n}\r\nfunction hasAuthTokenRequestTimedOut(authToken) {\r\n return (authToken.requestStatus === 1 /* RequestStatus.IN_PROGRESS */ &&\r\n authToken.requestTime + PENDING_TIMEOUT_MS < Date.now());\r\n}\n\n/**\r\n * @license\r\n * Copyright 2019 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Creates a Firebase Installation if there isn't one for the app and\r\n * returns the Installation ID.\r\n * @param installations - The `Installations` instance.\r\n *\r\n * @public\r\n */\r\nasync function getId(installations) {\r\n const installationsImpl = installations;\r\n const { installationEntry, registrationPromise } = await getInstallationEntry(installationsImpl);\r\n if (registrationPromise) {\r\n registrationPromise.catch(console.error);\r\n }\r\n else {\r\n // If the installation is already registered, update the authentication\r\n // token if needed.\r\n refreshAuthToken(installationsImpl).catch(console.error);\r\n }\r\n return installationEntry.fid;\r\n}\n\n/**\r\n * @license\r\n * Copyright 2019 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Returns a Firebase Installations auth token, identifying the current\r\n * Firebase Installation.\r\n * @param installations - The `Installations` instance.\r\n * @param forceRefresh - Force refresh regardless of token expiration.\r\n *\r\n * @public\r\n */\r\nasync function getToken(installations, forceRefresh = false) {\r\n const installationsImpl = installations;\r\n await completeInstallationRegistration(installationsImpl);\r\n // At this point we either have a Registered Installation in the DB, or we've\r\n // already thrown an error.\r\n const authToken = await refreshAuthToken(installationsImpl, forceRefresh);\r\n return authToken.token;\r\n}\r\nasync function completeInstallationRegistration(installations) {\r\n const { registrationPromise } = await getInstallationEntry(installations);\r\n if (registrationPromise) {\r\n // A createInstallation request is in progress. Wait until it finishes.\r\n await registrationPromise;\r\n }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2019 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nasync function deleteInstallationRequest(appConfig, installationEntry) {\r\n const endpoint = getDeleteEndpoint(appConfig, installationEntry);\r\n const headers = getHeadersWithAuth(appConfig, installationEntry);\r\n const request = {\r\n method: 'DELETE',\r\n headers\r\n };\r\n const response = await retryIfServerError(() => fetch(endpoint, request));\r\n if (!response.ok) {\r\n throw await getErrorFromResponse('Delete Installation', response);\r\n }\r\n}\r\nfunction getDeleteEndpoint(appConfig, { fid }) {\r\n return `${getInstallationsEndpoint(appConfig)}/${fid}`;\r\n}\n\n/**\r\n * @license\r\n * Copyright 2019 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Deletes the Firebase Installation and all associated data.\r\n * @param installations - The `Installations` instance.\r\n *\r\n * @public\r\n */\r\nasync function deleteInstallations(installations) {\r\n const { appConfig } = installations;\r\n const entry = await update(appConfig, oldEntry => {\r\n if (oldEntry && oldEntry.registrationStatus === 0 /* RequestStatus.NOT_STARTED */) {\r\n // Delete the unregistered entry without sending a deleteInstallation request.\r\n return undefined;\r\n }\r\n return oldEntry;\r\n });\r\n if (entry) {\r\n if (entry.registrationStatus === 1 /* RequestStatus.IN_PROGRESS */) {\r\n // Can't delete while trying to register.\r\n throw ERROR_FACTORY.create(\"delete-pending-registration\" /* ErrorCode.DELETE_PENDING_REGISTRATION */);\r\n }\r\n else if (entry.registrationStatus === 2 /* RequestStatus.COMPLETED */) {\r\n if (!navigator.onLine) {\r\n throw ERROR_FACTORY.create(\"app-offline\" /* ErrorCode.APP_OFFLINE */);\r\n }\r\n else {\r\n await deleteInstallationRequest(appConfig, entry);\r\n await remove(appConfig);\r\n }\r\n }\r\n }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2019 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Sets a new callback that will get called when Installation ID changes.\r\n * Returns an unsubscribe function that will remove the callback when called.\r\n * @param installations - The `Installations` instance.\r\n * @param callback - The callback function that is invoked when FID changes.\r\n * @returns A function that can be called to unsubscribe.\r\n *\r\n * @public\r\n */\r\nfunction onIdChange(installations, callback) {\r\n const { appConfig } = installations;\r\n addCallback(appConfig, callback);\r\n return () => {\r\n removeCallback(appConfig, callback);\r\n };\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Returns an instance of {@link Installations} associated with the given\r\n * {@link @firebase/app#FirebaseApp} instance.\r\n * @param app - The {@link @firebase/app#FirebaseApp} instance.\r\n *\r\n * @public\r\n */\r\nfunction getInstallations(app = getApp()) {\r\n const installationsImpl = _getProvider(app, 'installations').getImmediate();\r\n return installationsImpl;\r\n}\n\n/**\r\n * @license\r\n * Copyright 2019 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nfunction extractAppConfig(app) {\r\n if (!app || !app.options) {\r\n throw getMissingValueError('App Configuration');\r\n }\r\n if (!app.name) {\r\n throw getMissingValueError('App Name');\r\n }\r\n // Required app config keys\r\n const configKeys = [\r\n 'projectId',\r\n 'apiKey',\r\n 'appId'\r\n ];\r\n for (const keyName of configKeys) {\r\n if (!app.options[keyName]) {\r\n throw getMissingValueError(keyName);\r\n }\r\n }\r\n return {\r\n appName: app.name,\r\n projectId: app.options.projectId,\r\n apiKey: app.options.apiKey,\r\n appId: app.options.appId\r\n };\r\n}\r\nfunction getMissingValueError(valueName) {\r\n return ERROR_FACTORY.create(\"missing-app-config-values\" /* ErrorCode.MISSING_APP_CONFIG_VALUES */, {\r\n valueName\r\n });\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nconst INSTALLATIONS_NAME = 'installations';\r\nconst INSTALLATIONS_NAME_INTERNAL = 'installations-internal';\r\nconst publicFactory = (container) => {\r\n const app = container.getProvider('app').getImmediate();\r\n // Throws if app isn't configured properly.\r\n const appConfig = extractAppConfig(app);\r\n const heartbeatServiceProvider = _getProvider(app, 'heartbeat');\r\n const installationsImpl = {\r\n app,\r\n appConfig,\r\n heartbeatServiceProvider,\r\n _delete: () => Promise.resolve()\r\n };\r\n return installationsImpl;\r\n};\r\nconst internalFactory = (container) => {\r\n const app = container.getProvider('app').getImmediate();\r\n // Internal FIS instance relies on public FIS instance.\r\n const installations = _getProvider(app, INSTALLATIONS_NAME).getImmediate();\r\n const installationsInternal = {\r\n getId: () => getId(installations),\r\n getToken: (forceRefresh) => getToken(installations, forceRefresh)\r\n };\r\n return installationsInternal;\r\n};\r\nfunction registerInstallations() {\r\n _registerComponent(new Component(INSTALLATIONS_NAME, publicFactory, \"PUBLIC\" /* ComponentType.PUBLIC */));\r\n _registerComponent(new Component(INSTALLATIONS_NAME_INTERNAL, internalFactory, \"PRIVATE\" /* ComponentType.PRIVATE */));\r\n}\n\n/**\r\n * Firebase Installations\r\n *\r\n * @packageDocumentation\r\n */\r\nregisterInstallations();\r\nregisterVersion(name, version);\r\n// BUILD_TARGET will be replaced by values like esm5, esm2017, cjs5, etc during the compilation\r\nregisterVersion(name, version, 'esm2017');\n\nexport { deleteInstallations, getId, getInstallations, getToken, onIdChange };\n//# sourceMappingURL=index.esm2017.js.map\n","const instanceOfAny = (object, constructors) => constructors.some((c) => object instanceof c);\n\nlet idbProxyableTypes;\nlet cursorAdvanceMethods;\n// This is a function to prevent it throwing up in node environments.\nfunction getIdbProxyableTypes() {\n return (idbProxyableTypes ||\n (idbProxyableTypes = [\n IDBDatabase,\n IDBObjectStore,\n IDBIndex,\n IDBCursor,\n IDBTransaction,\n ]));\n}\n// This is a function to prevent it throwing up in node environments.\nfunction getCursorAdvanceMethods() {\n return (cursorAdvanceMethods ||\n (cursorAdvanceMethods = [\n IDBCursor.prototype.advance,\n IDBCursor.prototype.continue,\n IDBCursor.prototype.continuePrimaryKey,\n ]));\n}\nconst cursorRequestMap = new WeakMap();\nconst transactionDoneMap = new WeakMap();\nconst transactionStoreNamesMap = new WeakMap();\nconst transformCache = new WeakMap();\nconst reverseTransformCache = new WeakMap();\nfunction promisifyRequest(request) {\n const promise = new Promise((resolve, reject) => {\n const unlisten = () => {\n request.removeEventListener('success', success);\n request.removeEventListener('error', error);\n };\n const success = () => {\n resolve(wrap(request.result));\n unlisten();\n };\n const error = () => {\n reject(request.error);\n unlisten();\n };\n request.addEventListener('success', success);\n request.addEventListener('error', error);\n });\n promise\n .then((value) => {\n // Since cursoring reuses the IDBRequest (*sigh*), we cache it for later retrieval\n // (see wrapFunction).\n if (value instanceof IDBCursor) {\n cursorRequestMap.set(value, request);\n }\n // Catching to avoid \"Uncaught Promise exceptions\"\n })\n .catch(() => { });\n // This mapping exists in reverseTransformCache but doesn't doesn't exist in transformCache. This\n // is because we create many promises from a single IDBRequest.\n reverseTransformCache.set(promise, request);\n return promise;\n}\nfunction cacheDonePromiseForTransaction(tx) {\n // Early bail if we've already created a done promise for this transaction.\n if (transactionDoneMap.has(tx))\n return;\n const done = new Promise((resolve, reject) => {\n const unlisten = () => {\n tx.removeEventListener('complete', complete);\n tx.removeEventListener('error', error);\n tx.removeEventListener('abort', error);\n };\n const complete = () => {\n resolve();\n unlisten();\n };\n const error = () => {\n reject(tx.error || new DOMException('AbortError', 'AbortError'));\n unlisten();\n };\n tx.addEventListener('complete', complete);\n tx.addEventListener('error', error);\n tx.addEventListener('abort', error);\n });\n // Cache it for later retrieval.\n transactionDoneMap.set(tx, done);\n}\nlet idbProxyTraps = {\n get(target, prop, receiver) {\n if (target instanceof IDBTransaction) {\n // Special handling for transaction.done.\n if (prop === 'done')\n return transactionDoneMap.get(target);\n // Polyfill for objectStoreNames because of Edge.\n if (prop === 'objectStoreNames') {\n return target.objectStoreNames || transactionStoreNamesMap.get(target);\n }\n // Make tx.store return the only store in the transaction, or undefined if there are many.\n if (prop === 'store') {\n return receiver.objectStoreNames[1]\n ? undefined\n : receiver.objectStore(receiver.objectStoreNames[0]);\n }\n }\n // Else transform whatever we get back.\n return wrap(target[prop]);\n },\n set(target, prop, value) {\n target[prop] = value;\n return true;\n },\n has(target, prop) {\n if (target instanceof IDBTransaction &&\n (prop === 'done' || prop === 'store')) {\n return true;\n }\n return prop in target;\n },\n};\nfunction replaceTraps(callback) {\n idbProxyTraps = callback(idbProxyTraps);\n}\nfunction wrapFunction(func) {\n // Due to expected object equality (which is enforced by the caching in `wrap`), we\n // only create one new func per func.\n // Edge doesn't support objectStoreNames (booo), so we polyfill it here.\n if (func === IDBDatabase.prototype.transaction &&\n !('objectStoreNames' in IDBTransaction.prototype)) {\n return function (storeNames, ...args) {\n const tx = func.call(unwrap(this), storeNames, ...args);\n transactionStoreNamesMap.set(tx, storeNames.sort ? storeNames.sort() : [storeNames]);\n return wrap(tx);\n };\n }\n // Cursor methods are special, as the behaviour is a little more different to standard IDB. In\n // IDB, you advance the cursor and wait for a new 'success' on the IDBRequest that gave you the\n // cursor. It's kinda like a promise that can resolve with many values. That doesn't make sense\n // with real promises, so each advance methods returns a new promise for the cursor object, or\n // undefined if the end of the cursor has been reached.\n if (getCursorAdvanceMethods().includes(func)) {\n return function (...args) {\n // Calling the original function with the proxy as 'this' causes ILLEGAL INVOCATION, so we use\n // the original object.\n func.apply(unwrap(this), args);\n return wrap(cursorRequestMap.get(this));\n };\n }\n return function (...args) {\n // Calling the original function with the proxy as 'this' causes ILLEGAL INVOCATION, so we use\n // the original object.\n return wrap(func.apply(unwrap(this), args));\n };\n}\nfunction transformCachableValue(value) {\n if (typeof value === 'function')\n return wrapFunction(value);\n // This doesn't return, it just creates a 'done' promise for the transaction,\n // which is later returned for transaction.done (see idbObjectHandler).\n if (value instanceof IDBTransaction)\n cacheDonePromiseForTransaction(value);\n if (instanceOfAny(value, getIdbProxyableTypes()))\n return new Proxy(value, idbProxyTraps);\n // Return the same value back if we're not going to transform it.\n return value;\n}\nfunction wrap(value) {\n // We sometimes generate multiple promises from a single IDBRequest (eg when cursoring), because\n // IDB is weird and a single IDBRequest can yield many responses, so these can't be cached.\n if (value instanceof IDBRequest)\n return promisifyRequest(value);\n // If we've already transformed this value before, reuse the transformed value.\n // This is faster, but it also provides object equality.\n if (transformCache.has(value))\n return transformCache.get(value);\n const newValue = transformCachableValue(value);\n // Not all types are transformed.\n // These may be primitive types, so they can't be WeakMap keys.\n if (newValue !== value) {\n transformCache.set(value, newValue);\n reverseTransformCache.set(newValue, value);\n }\n return newValue;\n}\nconst unwrap = (value) => reverseTransformCache.get(value);\n\nexport { reverseTransformCache as a, instanceOfAny as i, replaceTraps as r, unwrap as u, wrap as w };\n","import { w as wrap, r as replaceTraps } from './wrap-idb-value.js';\nexport { u as unwrap, w as wrap } from './wrap-idb-value.js';\n\n/**\n * Open a database.\n *\n * @param name Name of the database.\n * @param version Schema version.\n * @param callbacks Additional callbacks.\n */\nfunction openDB(name, version, { blocked, upgrade, blocking, terminated } = {}) {\n const request = indexedDB.open(name, version);\n const openPromise = wrap(request);\n if (upgrade) {\n request.addEventListener('upgradeneeded', (event) => {\n upgrade(wrap(request.result), event.oldVersion, event.newVersion, wrap(request.transaction));\n });\n }\n if (blocked)\n request.addEventListener('blocked', () => blocked());\n openPromise\n .then((db) => {\n if (terminated)\n db.addEventListener('close', () => terminated());\n if (blocking)\n db.addEventListener('versionchange', () => blocking());\n })\n .catch(() => { });\n return openPromise;\n}\n/**\n * Delete a database.\n *\n * @param name Name of the database.\n */\nfunction deleteDB(name, { blocked } = {}) {\n const request = indexedDB.deleteDatabase(name);\n if (blocked)\n request.addEventListener('blocked', () => blocked());\n return wrap(request).then(() => undefined);\n}\n\nconst readMethods = ['get', 'getKey', 'getAll', 'getAllKeys', 'count'];\nconst writeMethods = ['put', 'add', 'delete', 'clear'];\nconst cachedMethods = new Map();\nfunction getMethod(target, prop) {\n if (!(target instanceof IDBDatabase &&\n !(prop in target) &&\n typeof prop === 'string')) {\n return;\n }\n if (cachedMethods.get(prop))\n return cachedMethods.get(prop);\n const targetFuncName = prop.replace(/FromIndex$/, '');\n const useIndex = prop !== targetFuncName;\n const isWrite = writeMethods.includes(targetFuncName);\n if (\n // Bail if the target doesn't exist on the target. Eg, getAll isn't in Edge.\n !(targetFuncName in (useIndex ? IDBIndex : IDBObjectStore).prototype) ||\n !(isWrite || readMethods.includes(targetFuncName))) {\n return;\n }\n const method = async function (storeName, ...args) {\n // isWrite ? 'readwrite' : undefined gzipps better, but fails in Edge :(\n const tx = this.transaction(storeName, isWrite ? 'readwrite' : 'readonly');\n let target = tx.store;\n if (useIndex)\n target = target.index(args.shift());\n // Must reject if op rejects.\n // If it's a write operation, must reject if tx.done rejects.\n // Must reject with op rejection first.\n // Must resolve with op value.\n // Must handle both promises (no unhandled rejections)\n return (await Promise.all([\n target[targetFuncName](...args),\n isWrite && tx.done,\n ]))[0];\n };\n cachedMethods.set(prop, method);\n return method;\n}\nreplaceTraps((oldTraps) => ({\n ...oldTraps,\n get: (target, prop, receiver) => getMethod(target, prop) || oldTraps.get(target, prop, receiver),\n has: (target, prop) => !!getMethod(target, prop) || oldTraps.has(target, prop),\n}));\n\nexport { deleteDB, openDB };\n","import '@firebase/installations';\nimport { Component } from '@firebase/component';\nimport { openDB, deleteDB } from 'idb';\nimport { ErrorFactory, validateIndexedDBOpenable, isIndexedDBAvailable, areCookiesEnabled, getModularInstance } from '@firebase/util';\nimport { _registerComponent, registerVersion, _getProvider, getApp } from '@firebase/app';\n\n/**\r\n * @license\r\n * Copyright 2019 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nconst DEFAULT_SW_PATH = '/firebase-messaging-sw.js';\r\nconst DEFAULT_SW_SCOPE = '/firebase-cloud-messaging-push-scope';\r\nconst DEFAULT_VAPID_KEY = 'BDOU99-h67HcA6JeFXHbSNMu7e2yNNu3RzoMj8TM4W88jITfq7ZmPvIM1Iv-4_l2LxQcYwhqby2xGpWwzjfAnG4';\r\nconst ENDPOINT = 'https://fcmregistrations.googleapis.com/v1';\r\nconst CONSOLE_CAMPAIGN_ID = 'google.c.a.c_id';\r\nconst CONSOLE_CAMPAIGN_NAME = 'google.c.a.c_l';\r\nconst CONSOLE_CAMPAIGN_TIME = 'google.c.a.ts';\r\n/** Set to '1' if Analytics is enabled for the campaign */\r\nconst CONSOLE_CAMPAIGN_ANALYTICS_ENABLED = 'google.c.a.e';\r\nvar MessageType$1;\r\n(function (MessageType) {\r\n MessageType[MessageType[\"DATA_MESSAGE\"] = 1] = \"DATA_MESSAGE\";\r\n MessageType[MessageType[\"DISPLAY_NOTIFICATION\"] = 3] = \"DISPLAY_NOTIFICATION\";\r\n})(MessageType$1 || (MessageType$1 = {}));\n\n/**\r\n * @license\r\n * Copyright 2018 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\"); you may not use this file except\r\n * in compliance with the License. You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software distributed under the License\r\n * is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express\r\n * or implied. See the License for the specific language governing permissions and limitations under\r\n * the License.\r\n */\r\nvar MessageType;\r\n(function (MessageType) {\r\n MessageType[\"PUSH_RECEIVED\"] = \"push-received\";\r\n MessageType[\"NOTIFICATION_CLICKED\"] = \"notification-clicked\";\r\n})(MessageType || (MessageType = {}));\n\n/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nfunction arrayToBase64(array) {\r\n const uint8Array = new Uint8Array(array);\r\n const base64String = btoa(String.fromCharCode(...uint8Array));\r\n return base64String.replace(/=/g, '').replace(/\\+/g, '-').replace(/\\//g, '_');\r\n}\r\nfunction base64ToArray(base64String) {\r\n const padding = '='.repeat((4 - (base64String.length % 4)) % 4);\r\n const base64 = (base64String + padding)\r\n .replace(/\\-/g, '+')\r\n .replace(/_/g, '/');\r\n const rawData = atob(base64);\r\n const outputArray = new Uint8Array(rawData.length);\r\n for (let i = 0; i < rawData.length; ++i) {\r\n outputArray[i] = rawData.charCodeAt(i);\r\n }\r\n return outputArray;\r\n}\n\n/**\r\n * @license\r\n * Copyright 2019 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nconst OLD_DB_NAME = 'fcm_token_details_db';\r\n/**\r\n * The last DB version of 'fcm_token_details_db' was 4. This is one higher, so that the upgrade\r\n * callback is called for all versions of the old DB.\r\n */\r\nconst OLD_DB_VERSION = 5;\r\nconst OLD_OBJECT_STORE_NAME = 'fcm_token_object_Store';\r\nasync function migrateOldDatabase(senderId) {\r\n if ('databases' in indexedDB) {\r\n // indexedDb.databases() is an IndexedDB v3 API and does not exist in all browsers. TODO: Remove\r\n // typecast when it lands in TS types.\r\n const databases = await indexedDB.databases();\r\n const dbNames = databases.map(db => db.name);\r\n if (!dbNames.includes(OLD_DB_NAME)) {\r\n // old DB didn't exist, no need to open.\r\n return null;\r\n }\r\n }\r\n let tokenDetails = null;\r\n const db = await openDB(OLD_DB_NAME, OLD_DB_VERSION, {\r\n upgrade: async (db, oldVersion, newVersion, upgradeTransaction) => {\r\n var _a;\r\n if (oldVersion < 2) {\r\n // Database too old, skip migration.\r\n return;\r\n }\r\n if (!db.objectStoreNames.contains(OLD_OBJECT_STORE_NAME)) {\r\n // Database did not exist. Nothing to do.\r\n return;\r\n }\r\n const objectStore = upgradeTransaction.objectStore(OLD_OBJECT_STORE_NAME);\r\n const value = await objectStore.index('fcmSenderId').get(senderId);\r\n await objectStore.clear();\r\n if (!value) {\r\n // No entry in the database, nothing to migrate.\r\n return;\r\n }\r\n if (oldVersion === 2) {\r\n const oldDetails = value;\r\n if (!oldDetails.auth || !oldDetails.p256dh || !oldDetails.endpoint) {\r\n return;\r\n }\r\n tokenDetails = {\r\n token: oldDetails.fcmToken,\r\n createTime: (_a = oldDetails.createTime) !== null && _a !== void 0 ? _a : Date.now(),\r\n subscriptionOptions: {\r\n auth: oldDetails.auth,\r\n p256dh: oldDetails.p256dh,\r\n endpoint: oldDetails.endpoint,\r\n swScope: oldDetails.swScope,\r\n vapidKey: typeof oldDetails.vapidKey === 'string'\r\n ? oldDetails.vapidKey\r\n : arrayToBase64(oldDetails.vapidKey)\r\n }\r\n };\r\n }\r\n else if (oldVersion === 3) {\r\n const oldDetails = value;\r\n tokenDetails = {\r\n token: oldDetails.fcmToken,\r\n createTime: oldDetails.createTime,\r\n subscriptionOptions: {\r\n auth: arrayToBase64(oldDetails.auth),\r\n p256dh: arrayToBase64(oldDetails.p256dh),\r\n endpoint: oldDetails.endpoint,\r\n swScope: oldDetails.swScope,\r\n vapidKey: arrayToBase64(oldDetails.vapidKey)\r\n }\r\n };\r\n }\r\n else if (oldVersion === 4) {\r\n const oldDetails = value;\r\n tokenDetails = {\r\n token: oldDetails.fcmToken,\r\n createTime: oldDetails.createTime,\r\n subscriptionOptions: {\r\n auth: arrayToBase64(oldDetails.auth),\r\n p256dh: arrayToBase64(oldDetails.p256dh),\r\n endpoint: oldDetails.endpoint,\r\n swScope: oldDetails.swScope,\r\n vapidKey: arrayToBase64(oldDetails.vapidKey)\r\n }\r\n };\r\n }\r\n }\r\n });\r\n db.close();\r\n // Delete all old databases.\r\n await deleteDB(OLD_DB_NAME);\r\n await deleteDB('fcm_vapid_details_db');\r\n await deleteDB('undefined');\r\n return checkTokenDetails(tokenDetails) ? tokenDetails : null;\r\n}\r\nfunction checkTokenDetails(tokenDetails) {\r\n if (!tokenDetails || !tokenDetails.subscriptionOptions) {\r\n return false;\r\n }\r\n const { subscriptionOptions } = tokenDetails;\r\n return (typeof tokenDetails.createTime === 'number' &&\r\n tokenDetails.createTime > 0 &&\r\n typeof tokenDetails.token === 'string' &&\r\n tokenDetails.token.length > 0 &&\r\n typeof subscriptionOptions.auth === 'string' &&\r\n subscriptionOptions.auth.length > 0 &&\r\n typeof subscriptionOptions.p256dh === 'string' &&\r\n subscriptionOptions.p256dh.length > 0 &&\r\n typeof subscriptionOptions.endpoint === 'string' &&\r\n subscriptionOptions.endpoint.length > 0 &&\r\n typeof subscriptionOptions.swScope === 'string' &&\r\n subscriptionOptions.swScope.length > 0 &&\r\n typeof subscriptionOptions.vapidKey === 'string' &&\r\n subscriptionOptions.vapidKey.length > 0);\r\n}\n\n/**\r\n * @license\r\n * Copyright 2019 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n// Exported for tests.\r\nconst DATABASE_NAME = 'firebase-messaging-database';\r\nconst DATABASE_VERSION = 1;\r\nconst OBJECT_STORE_NAME = 'firebase-messaging-store';\r\nlet dbPromise = null;\r\nfunction getDbPromise() {\r\n if (!dbPromise) {\r\n dbPromise = openDB(DATABASE_NAME, DATABASE_VERSION, {\r\n upgrade: (upgradeDb, oldVersion) => {\r\n // We don't use 'break' in this switch statement, the fall-through behavior is what we want,\r\n // because if there are multiple versions between the old version and the current version, we\r\n // want ALL the migrations that correspond to those versions to run, not only the last one.\r\n // eslint-disable-next-line default-case\r\n switch (oldVersion) {\r\n case 0:\r\n upgradeDb.createObjectStore(OBJECT_STORE_NAME);\r\n }\r\n }\r\n });\r\n }\r\n return dbPromise;\r\n}\r\n/** Gets record(s) from the objectStore that match the given key. */\r\nasync function dbGet(firebaseDependencies) {\r\n const key = getKey(firebaseDependencies);\r\n const db = await getDbPromise();\r\n const tokenDetails = (await db\r\n .transaction(OBJECT_STORE_NAME)\r\n .objectStore(OBJECT_STORE_NAME)\r\n .get(key));\r\n if (tokenDetails) {\r\n return tokenDetails;\r\n }\r\n else {\r\n // Check if there is a tokenDetails object in the old DB.\r\n const oldTokenDetails = await migrateOldDatabase(firebaseDependencies.appConfig.senderId);\r\n if (oldTokenDetails) {\r\n await dbSet(firebaseDependencies, oldTokenDetails);\r\n return oldTokenDetails;\r\n }\r\n }\r\n}\r\n/** Assigns or overwrites the record for the given key with the given value. */\r\nasync function dbSet(firebaseDependencies, tokenDetails) {\r\n const key = getKey(firebaseDependencies);\r\n const db = await getDbPromise();\r\n const tx = db.transaction(OBJECT_STORE_NAME, 'readwrite');\r\n await tx.objectStore(OBJECT_STORE_NAME).put(tokenDetails, key);\r\n await tx.done;\r\n return tokenDetails;\r\n}\r\n/** Removes record(s) from the objectStore that match the given key. */\r\nasync function dbRemove(firebaseDependencies) {\r\n const key = getKey(firebaseDependencies);\r\n const db = await getDbPromise();\r\n const tx = db.transaction(OBJECT_STORE_NAME, 'readwrite');\r\n await tx.objectStore(OBJECT_STORE_NAME).delete(key);\r\n await tx.done;\r\n}\r\nfunction getKey({ appConfig }) {\r\n return appConfig.appId;\r\n}\n\n/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nconst ERROR_MAP = {\r\n [\"missing-app-config-values\" /* ErrorCode.MISSING_APP_CONFIG_VALUES */]: 'Missing App configuration value: \"{$valueName}\"',\r\n [\"only-available-in-window\" /* ErrorCode.AVAILABLE_IN_WINDOW */]: 'This method is available in a Window context.',\r\n [\"only-available-in-sw\" /* ErrorCode.AVAILABLE_IN_SW */]: 'This method is available in a service worker context.',\r\n [\"permission-default\" /* ErrorCode.PERMISSION_DEFAULT */]: 'The notification permission was not granted and dismissed instead.',\r\n [\"permission-blocked\" /* ErrorCode.PERMISSION_BLOCKED */]: 'The notification permission was not granted and blocked instead.',\r\n [\"unsupported-browser\" /* ErrorCode.UNSUPPORTED_BROWSER */]: \"This browser doesn't support the API's required to use the Firebase SDK.\",\r\n [\"indexed-db-unsupported\" /* ErrorCode.INDEXED_DB_UNSUPPORTED */]: \"This browser doesn't support indexedDb.open() (ex. Safari iFrame, Firefox Private Browsing, etc)\",\r\n [\"failed-service-worker-registration\" /* ErrorCode.FAILED_DEFAULT_REGISTRATION */]: 'We are unable to register the default service worker. {$browserErrorMessage}',\r\n [\"token-subscribe-failed\" /* ErrorCode.TOKEN_SUBSCRIBE_FAILED */]: 'A problem occurred while subscribing the user to FCM: {$errorInfo}',\r\n [\"token-subscribe-no-token\" /* ErrorCode.TOKEN_SUBSCRIBE_NO_TOKEN */]: 'FCM returned no token when subscribing the user to push.',\r\n [\"token-unsubscribe-failed\" /* ErrorCode.TOKEN_UNSUBSCRIBE_FAILED */]: 'A problem occurred while unsubscribing the ' +\r\n 'user from FCM: {$errorInfo}',\r\n [\"token-update-failed\" /* ErrorCode.TOKEN_UPDATE_FAILED */]: 'A problem occurred while updating the user from FCM: {$errorInfo}',\r\n [\"token-update-no-token\" /* ErrorCode.TOKEN_UPDATE_NO_TOKEN */]: 'FCM returned no token when updating the user to push.',\r\n [\"use-sw-after-get-token\" /* ErrorCode.USE_SW_AFTER_GET_TOKEN */]: 'The useServiceWorker() method may only be called once and must be ' +\r\n 'called before calling getToken() to ensure your service worker is used.',\r\n [\"invalid-sw-registration\" /* ErrorCode.INVALID_SW_REGISTRATION */]: 'The input to useServiceWorker() must be a ServiceWorkerRegistration.',\r\n [\"invalid-bg-handler\" /* ErrorCode.INVALID_BG_HANDLER */]: 'The input to setBackgroundMessageHandler() must be a function.',\r\n [\"invalid-vapid-key\" /* ErrorCode.INVALID_VAPID_KEY */]: 'The public VAPID key must be a string.',\r\n [\"use-vapid-key-after-get-token\" /* ErrorCode.USE_VAPID_KEY_AFTER_GET_TOKEN */]: 'The usePublicVapidKey() method may only be called once and must be ' +\r\n 'called before calling getToken() to ensure your VAPID key is used.'\r\n};\r\nconst ERROR_FACTORY = new ErrorFactory('messaging', 'Messaging', ERROR_MAP);\n\n/**\r\n * @license\r\n * Copyright 2019 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nasync function requestGetToken(firebaseDependencies, subscriptionOptions) {\r\n const headers = await getHeaders(firebaseDependencies);\r\n const body = getBody(subscriptionOptions);\r\n const subscribeOptions = {\r\n method: 'POST',\r\n headers,\r\n body: JSON.stringify(body)\r\n };\r\n let responseData;\r\n try {\r\n const response = await fetch(getEndpoint(firebaseDependencies.appConfig), subscribeOptions);\r\n responseData = await response.json();\r\n }\r\n catch (err) {\r\n throw ERROR_FACTORY.create(\"token-subscribe-failed\" /* ErrorCode.TOKEN_SUBSCRIBE_FAILED */, {\r\n errorInfo: err === null || err === void 0 ? void 0 : err.toString()\r\n });\r\n }\r\n if (responseData.error) {\r\n const message = responseData.error.message;\r\n throw ERROR_FACTORY.create(\"token-subscribe-failed\" /* ErrorCode.TOKEN_SUBSCRIBE_FAILED */, {\r\n errorInfo: message\r\n });\r\n }\r\n if (!responseData.token) {\r\n throw ERROR_FACTORY.create(\"token-subscribe-no-token\" /* ErrorCode.TOKEN_SUBSCRIBE_NO_TOKEN */);\r\n }\r\n return responseData.token;\r\n}\r\nasync function requestUpdateToken(firebaseDependencies, tokenDetails) {\r\n const headers = await getHeaders(firebaseDependencies);\r\n const body = getBody(tokenDetails.subscriptionOptions);\r\n const updateOptions = {\r\n method: 'PATCH',\r\n headers,\r\n body: JSON.stringify(body)\r\n };\r\n let responseData;\r\n try {\r\n const response = await fetch(`${getEndpoint(firebaseDependencies.appConfig)}/${tokenDetails.token}`, updateOptions);\r\n responseData = await response.json();\r\n }\r\n catch (err) {\r\n throw ERROR_FACTORY.create(\"token-update-failed\" /* ErrorCode.TOKEN_UPDATE_FAILED */, {\r\n errorInfo: err === null || err === void 0 ? void 0 : err.toString()\r\n });\r\n }\r\n if (responseData.error) {\r\n const message = responseData.error.message;\r\n throw ERROR_FACTORY.create(\"token-update-failed\" /* ErrorCode.TOKEN_UPDATE_FAILED */, {\r\n errorInfo: message\r\n });\r\n }\r\n if (!responseData.token) {\r\n throw ERROR_FACTORY.create(\"token-update-no-token\" /* ErrorCode.TOKEN_UPDATE_NO_TOKEN */);\r\n }\r\n return responseData.token;\r\n}\r\nasync function requestDeleteToken(firebaseDependencies, token) {\r\n const headers = await getHeaders(firebaseDependencies);\r\n const unsubscribeOptions = {\r\n method: 'DELETE',\r\n headers\r\n };\r\n try {\r\n const response = await fetch(`${getEndpoint(firebaseDependencies.appConfig)}/${token}`, unsubscribeOptions);\r\n const responseData = await response.json();\r\n if (responseData.error) {\r\n const message = responseData.error.message;\r\n throw ERROR_FACTORY.create(\"token-unsubscribe-failed\" /* ErrorCode.TOKEN_UNSUBSCRIBE_FAILED */, {\r\n errorInfo: message\r\n });\r\n }\r\n }\r\n catch (err) {\r\n throw ERROR_FACTORY.create(\"token-unsubscribe-failed\" /* ErrorCode.TOKEN_UNSUBSCRIBE_FAILED */, {\r\n errorInfo: err === null || err === void 0 ? void 0 : err.toString()\r\n });\r\n }\r\n}\r\nfunction getEndpoint({ projectId }) {\r\n return `${ENDPOINT}/projects/${projectId}/registrations`;\r\n}\r\nasync function getHeaders({ appConfig, installations }) {\r\n const authToken = await installations.getToken();\r\n return new Headers({\r\n 'Content-Type': 'application/json',\r\n Accept: 'application/json',\r\n 'x-goog-api-key': appConfig.apiKey,\r\n 'x-goog-firebase-installations-auth': `FIS ${authToken}`\r\n });\r\n}\r\nfunction getBody({ p256dh, auth, endpoint, vapidKey }) {\r\n const body = {\r\n web: {\r\n endpoint,\r\n auth,\r\n p256dh\r\n }\r\n };\r\n if (vapidKey !== DEFAULT_VAPID_KEY) {\r\n body.web.applicationPubKey = vapidKey;\r\n }\r\n return body;\r\n}\n\n/**\r\n * @license\r\n * Copyright 2019 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n// UpdateRegistration will be called once every week.\r\nconst TOKEN_EXPIRATION_MS = 7 * 24 * 60 * 60 * 1000; // 7 days\r\nasync function getTokenInternal(messaging) {\r\n const pushSubscription = await getPushSubscription(messaging.swRegistration, messaging.vapidKey);\r\n const subscriptionOptions = {\r\n vapidKey: messaging.vapidKey,\r\n swScope: messaging.swRegistration.scope,\r\n endpoint: pushSubscription.endpoint,\r\n auth: arrayToBase64(pushSubscription.getKey('auth')),\r\n p256dh: arrayToBase64(pushSubscription.getKey('p256dh'))\r\n };\r\n const tokenDetails = await dbGet(messaging.firebaseDependencies);\r\n if (!tokenDetails) {\r\n // No token, get a new one.\r\n return getNewToken(messaging.firebaseDependencies, subscriptionOptions);\r\n }\r\n else if (!isTokenValid(tokenDetails.subscriptionOptions, subscriptionOptions)) {\r\n // Invalid token, get a new one.\r\n try {\r\n await requestDeleteToken(messaging.firebaseDependencies, tokenDetails.token);\r\n }\r\n catch (e) {\r\n // Suppress errors because of #2364\r\n console.warn(e);\r\n }\r\n return getNewToken(messaging.firebaseDependencies, subscriptionOptions);\r\n }\r\n else if (Date.now() >= tokenDetails.createTime + TOKEN_EXPIRATION_MS) {\r\n // Weekly token refresh\r\n return updateToken(messaging, {\r\n token: tokenDetails.token,\r\n createTime: Date.now(),\r\n subscriptionOptions\r\n });\r\n }\r\n else {\r\n // Valid token, nothing to do.\r\n return tokenDetails.token;\r\n }\r\n}\r\n/**\r\n * This method deletes the token from the database, unsubscribes the token from FCM, and unregisters\r\n * the push subscription if it exists.\r\n */\r\nasync function deleteTokenInternal(messaging) {\r\n const tokenDetails = await dbGet(messaging.firebaseDependencies);\r\n if (tokenDetails) {\r\n await requestDeleteToken(messaging.firebaseDependencies, tokenDetails.token);\r\n await dbRemove(messaging.firebaseDependencies);\r\n }\r\n // Unsubscribe from the push subscription.\r\n const pushSubscription = await messaging.swRegistration.pushManager.getSubscription();\r\n if (pushSubscription) {\r\n return pushSubscription.unsubscribe();\r\n }\r\n // If there's no SW, consider it a success.\r\n return true;\r\n}\r\nasync function updateToken(messaging, tokenDetails) {\r\n try {\r\n const updatedToken = await requestUpdateToken(messaging.firebaseDependencies, tokenDetails);\r\n const updatedTokenDetails = Object.assign(Object.assign({}, tokenDetails), { token: updatedToken, createTime: Date.now() });\r\n await dbSet(messaging.firebaseDependencies, updatedTokenDetails);\r\n return updatedToken;\r\n }\r\n catch (e) {\r\n await deleteTokenInternal(messaging);\r\n throw e;\r\n }\r\n}\r\nasync function getNewToken(firebaseDependencies, subscriptionOptions) {\r\n const token = await requestGetToken(firebaseDependencies, subscriptionOptions);\r\n const tokenDetails = {\r\n token,\r\n createTime: Date.now(),\r\n subscriptionOptions\r\n };\r\n await dbSet(firebaseDependencies, tokenDetails);\r\n return tokenDetails.token;\r\n}\r\n/**\r\n * Gets a PushSubscription for the current user.\r\n */\r\nasync function getPushSubscription(swRegistration, vapidKey) {\r\n const subscription = await swRegistration.pushManager.getSubscription();\r\n if (subscription) {\r\n return subscription;\r\n }\r\n return swRegistration.pushManager.subscribe({\r\n userVisibleOnly: true,\r\n // Chrome <= 75 doesn't support base64-encoded VAPID key. For backward compatibility, VAPID key\r\n // submitted to pushManager#subscribe must be of type Uint8Array.\r\n applicationServerKey: base64ToArray(vapidKey)\r\n });\r\n}\r\n/**\r\n * Checks if the saved tokenDetails object matches the configuration provided.\r\n */\r\nfunction isTokenValid(dbOptions, currentOptions) {\r\n const isVapidKeyEqual = currentOptions.vapidKey === dbOptions.vapidKey;\r\n const isEndpointEqual = currentOptions.endpoint === dbOptions.endpoint;\r\n const isAuthEqual = currentOptions.auth === dbOptions.auth;\r\n const isP256dhEqual = currentOptions.p256dh === dbOptions.p256dh;\r\n return isVapidKeyEqual && isEndpointEqual && isAuthEqual && isP256dhEqual;\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nfunction externalizePayload(internalPayload) {\r\n const payload = {\r\n from: internalPayload.from,\r\n // eslint-disable-next-line camelcase\r\n collapseKey: internalPayload.collapse_key,\r\n // eslint-disable-next-line camelcase\r\n messageId: internalPayload.fcmMessageId\r\n };\r\n propagateNotificationPayload(payload, internalPayload);\r\n propagateDataPayload(payload, internalPayload);\r\n propagateFcmOptions(payload, internalPayload);\r\n return payload;\r\n}\r\nfunction propagateNotificationPayload(payload, messagePayloadInternal) {\r\n if (!messagePayloadInternal.notification) {\r\n return;\r\n }\r\n payload.notification = {};\r\n const title = messagePayloadInternal.notification.title;\r\n if (!!title) {\r\n payload.notification.title = title;\r\n }\r\n const body = messagePayloadInternal.notification.body;\r\n if (!!body) {\r\n payload.notification.body = body;\r\n }\r\n const image = messagePayloadInternal.notification.image;\r\n if (!!image) {\r\n payload.notification.image = image;\r\n }\r\n const icon = messagePayloadInternal.notification.icon;\r\n if (!!icon) {\r\n payload.notification.icon = icon;\r\n }\r\n}\r\nfunction propagateDataPayload(payload, messagePayloadInternal) {\r\n if (!messagePayloadInternal.data) {\r\n return;\r\n }\r\n payload.data = messagePayloadInternal.data;\r\n}\r\nfunction propagateFcmOptions(payload, messagePayloadInternal) {\r\n var _a, _b, _c, _d, _e;\r\n // fcmOptions.link value is written into notification.click_action. see more in b/232072111\r\n if (!messagePayloadInternal.fcmOptions &&\r\n !((_a = messagePayloadInternal.notification) === null || _a === void 0 ? void 0 : _a.click_action)) {\r\n return;\r\n }\r\n payload.fcmOptions = {};\r\n const link = (_c = (_b = messagePayloadInternal.fcmOptions) === null || _b === void 0 ? void 0 : _b.link) !== null && _c !== void 0 ? _c : (_d = messagePayloadInternal.notification) === null || _d === void 0 ? void 0 : _d.click_action;\r\n if (!!link) {\r\n payload.fcmOptions.link = link;\r\n }\r\n // eslint-disable-next-line camelcase\r\n const analyticsLabel = (_e = messagePayloadInternal.fcmOptions) === null || _e === void 0 ? void 0 : _e.analytics_label;\r\n if (!!analyticsLabel) {\r\n payload.fcmOptions.analyticsLabel = analyticsLabel;\r\n }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2019 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nfunction isConsoleMessage(data) {\r\n // This message has a campaign ID, meaning it was sent using the Firebase Console.\r\n return typeof data === 'object' && !!data && CONSOLE_CAMPAIGN_ID in data;\r\n}\n\n/**\r\n * @license\r\n * Copyright 2019 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n_mergeStrings('hts/frbslgigp.ogepscmv/ieo/eaylg', 'tp:/ieaeogn-agolai.o/1frlglgc/o');\r\n_mergeStrings('AzSCbw63g1R0nCw85jG8', 'Iaya3yLKwmgvh7cF0q4');\r\nfunction _mergeStrings(s1, s2) {\r\n const resultArray = [];\r\n for (let i = 0; i < s1.length; i++) {\r\n resultArray.push(s1.charAt(i));\r\n if (i < s2.length) {\r\n resultArray.push(s2.charAt(i));\r\n }\r\n }\r\n return resultArray.join('');\r\n}\n\n/**\r\n * @license\r\n * Copyright 2019 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nfunction extractAppConfig(app) {\r\n if (!app || !app.options) {\r\n throw getMissingValueError('App Configuration Object');\r\n }\r\n if (!app.name) {\r\n throw getMissingValueError('App Name');\r\n }\r\n // Required app config keys\r\n const configKeys = [\r\n 'projectId',\r\n 'apiKey',\r\n 'appId',\r\n 'messagingSenderId'\r\n ];\r\n const { options } = app;\r\n for (const keyName of configKeys) {\r\n if (!options[keyName]) {\r\n throw getMissingValueError(keyName);\r\n }\r\n }\r\n return {\r\n appName: app.name,\r\n projectId: options.projectId,\r\n apiKey: options.apiKey,\r\n appId: options.appId,\r\n senderId: options.messagingSenderId\r\n };\r\n}\r\nfunction getMissingValueError(valueName) {\r\n return ERROR_FACTORY.create(\"missing-app-config-values\" /* ErrorCode.MISSING_APP_CONFIG_VALUES */, {\r\n valueName\r\n });\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nclass MessagingService {\r\n constructor(app, installations, analyticsProvider) {\r\n // logging is only done with end user consent. Default to false.\r\n this.deliveryMetricsExportedToBigQueryEnabled = false;\r\n this.onBackgroundMessageHandler = null;\r\n this.onMessageHandler = null;\r\n this.logEvents = [];\r\n this.isLogServiceStarted = false;\r\n const appConfig = extractAppConfig(app);\r\n this.firebaseDependencies = {\r\n app,\r\n appConfig,\r\n installations,\r\n analyticsProvider\r\n };\r\n }\r\n _delete() {\r\n return Promise.resolve();\r\n }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nasync function registerDefaultSw(messaging) {\r\n try {\r\n messaging.swRegistration = await navigator.serviceWorker.register(DEFAULT_SW_PATH, {\r\n scope: DEFAULT_SW_SCOPE\r\n });\r\n // The timing when browser updates sw when sw has an update is unreliable from experiment. It\r\n // leads to version conflict when the SDK upgrades to a newer version in the main page, but sw\r\n // is stuck with the old version. For example,\r\n // https://github.com/firebase/firebase-js-sdk/issues/2590 The following line reliably updates\r\n // sw if there was an update.\r\n messaging.swRegistration.update().catch(() => {\r\n /* it is non blocking and we don't care if it failed */\r\n });\r\n }\r\n catch (e) {\r\n throw ERROR_FACTORY.create(\"failed-service-worker-registration\" /* ErrorCode.FAILED_DEFAULT_REGISTRATION */, {\r\n browserErrorMessage: e === null || e === void 0 ? void 0 : e.message\r\n });\r\n }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nasync function updateSwReg(messaging, swRegistration) {\r\n if (!swRegistration && !messaging.swRegistration) {\r\n await registerDefaultSw(messaging);\r\n }\r\n if (!swRegistration && !!messaging.swRegistration) {\r\n return;\r\n }\r\n if (!(swRegistration instanceof ServiceWorkerRegistration)) {\r\n throw ERROR_FACTORY.create(\"invalid-sw-registration\" /* ErrorCode.INVALID_SW_REGISTRATION */);\r\n }\r\n messaging.swRegistration = swRegistration;\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nasync function updateVapidKey(messaging, vapidKey) {\r\n if (!!vapidKey) {\r\n messaging.vapidKey = vapidKey;\r\n }\r\n else if (!messaging.vapidKey) {\r\n messaging.vapidKey = DEFAULT_VAPID_KEY;\r\n }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nasync function getToken$1(messaging, options) {\r\n if (!navigator) {\r\n throw ERROR_FACTORY.create(\"only-available-in-window\" /* ErrorCode.AVAILABLE_IN_WINDOW */);\r\n }\r\n if (Notification.permission === 'default') {\r\n await Notification.requestPermission();\r\n }\r\n if (Notification.permission !== 'granted') {\r\n throw ERROR_FACTORY.create(\"permission-blocked\" /* ErrorCode.PERMISSION_BLOCKED */);\r\n }\r\n await updateVapidKey(messaging, options === null || options === void 0 ? void 0 : options.vapidKey);\r\n await updateSwReg(messaging, options === null || options === void 0 ? void 0 : options.serviceWorkerRegistration);\r\n return getTokenInternal(messaging);\r\n}\n\n/**\r\n * @license\r\n * Copyright 2019 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nasync function logToScion(messaging, messageType, data) {\r\n const eventType = getEventType(messageType);\r\n const analytics = await messaging.firebaseDependencies.analyticsProvider.get();\r\n analytics.logEvent(eventType, {\r\n /* eslint-disable camelcase */\r\n message_id: data[CONSOLE_CAMPAIGN_ID],\r\n message_name: data[CONSOLE_CAMPAIGN_NAME],\r\n message_time: data[CONSOLE_CAMPAIGN_TIME],\r\n message_device_time: Math.floor(Date.now() / 1000)\r\n /* eslint-enable camelcase */\r\n });\r\n}\r\nfunction getEventType(messageType) {\r\n switch (messageType) {\r\n case MessageType.NOTIFICATION_CLICKED:\r\n return 'notification_open';\r\n case MessageType.PUSH_RECEIVED:\r\n return 'notification_foreground';\r\n default:\r\n throw new Error();\r\n }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nasync function messageEventListener(messaging, event) {\r\n const internalPayload = event.data;\r\n if (!internalPayload.isFirebaseMessaging) {\r\n return;\r\n }\r\n if (messaging.onMessageHandler &&\r\n internalPayload.messageType === MessageType.PUSH_RECEIVED) {\r\n if (typeof messaging.onMessageHandler === 'function') {\r\n messaging.onMessageHandler(externalizePayload(internalPayload));\r\n }\r\n else {\r\n messaging.onMessageHandler.next(externalizePayload(internalPayload));\r\n }\r\n }\r\n // Log to Scion if applicable\r\n const dataPayload = internalPayload.data;\r\n if (isConsoleMessage(dataPayload) &&\r\n dataPayload[CONSOLE_CAMPAIGN_ANALYTICS_ENABLED] === '1') {\r\n await logToScion(messaging, internalPayload.messageType, dataPayload);\r\n }\r\n}\n\nconst name = \"@firebase/messaging\";\nconst version = \"0.12.4\";\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nconst WindowMessagingFactory = (container) => {\r\n const messaging = new MessagingService(container.getProvider('app').getImmediate(), container.getProvider('installations-internal').getImmediate(), container.getProvider('analytics-internal'));\r\n navigator.serviceWorker.addEventListener('message', e => messageEventListener(messaging, e));\r\n return messaging;\r\n};\r\nconst WindowMessagingInternalFactory = (container) => {\r\n const messaging = container\r\n .getProvider('messaging')\r\n .getImmediate();\r\n const messagingInternal = {\r\n getToken: (options) => getToken$1(messaging, options)\r\n };\r\n return messagingInternal;\r\n};\r\nfunction registerMessagingInWindow() {\r\n _registerComponent(new Component('messaging', WindowMessagingFactory, \"PUBLIC\" /* ComponentType.PUBLIC */));\r\n _registerComponent(new Component('messaging-internal', WindowMessagingInternalFactory, \"PRIVATE\" /* ComponentType.PRIVATE */));\r\n registerVersion(name, version);\r\n // BUILD_TARGET will be replaced by values like esm5, esm2017, cjs5, etc during the compilation\r\n registerVersion(name, version, 'esm2017');\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Checks if all required APIs exist in the browser.\r\n * @returns a Promise that resolves to a boolean.\r\n *\r\n * @public\r\n */\r\nasync function isWindowSupported() {\r\n try {\r\n // This throws if open() is unsupported, so adding it to the conditional\r\n // statement below can cause an uncaught error.\r\n await validateIndexedDBOpenable();\r\n }\r\n catch (e) {\r\n return false;\r\n }\r\n // firebase-js-sdk/issues/2393 reveals that idb#open in Safari iframe and Firefox private browsing\r\n // might be prohibited to run. In these contexts, an error would be thrown during the messaging\r\n // instantiating phase, informing the developers to import/call isSupported for special handling.\r\n return (typeof window !== 'undefined' &&\r\n isIndexedDBAvailable() &&\r\n areCookiesEnabled() &&\r\n 'serviceWorker' in navigator &&\r\n 'PushManager' in window &&\r\n 'Notification' in window &&\r\n 'fetch' in window &&\r\n ServiceWorkerRegistration.prototype.hasOwnProperty('showNotification') &&\r\n PushSubscription.prototype.hasOwnProperty('getKey'));\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nasync function deleteToken$1(messaging) {\r\n if (!navigator) {\r\n throw ERROR_FACTORY.create(\"only-available-in-window\" /* ErrorCode.AVAILABLE_IN_WINDOW */);\r\n }\r\n if (!messaging.swRegistration) {\r\n await registerDefaultSw(messaging);\r\n }\r\n return deleteTokenInternal(messaging);\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nfunction onMessage$1(messaging, nextOrObserver) {\r\n if (!navigator) {\r\n throw ERROR_FACTORY.create(\"only-available-in-window\" /* ErrorCode.AVAILABLE_IN_WINDOW */);\r\n }\r\n messaging.onMessageHandler = nextOrObserver;\r\n return () => {\r\n messaging.onMessageHandler = null;\r\n };\r\n}\n\n/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Retrieves a Firebase Cloud Messaging instance.\r\n *\r\n * @returns The Firebase Cloud Messaging instance associated with the provided firebase app.\r\n *\r\n * @public\r\n */\r\nfunction getMessagingInWindow(app = getApp()) {\r\n // Conscious decision to make this async check non-blocking during the messaging instance\r\n // initialization phase for performance consideration. An error would be thrown latter for\r\n // developer's information. Developers can then choose to import and call `isSupported` for\r\n // special handling.\r\n isWindowSupported().then(isSupported => {\r\n // If `isWindowSupported()` resolved, but returned false.\r\n if (!isSupported) {\r\n throw ERROR_FACTORY.create(\"unsupported-browser\" /* ErrorCode.UNSUPPORTED_BROWSER */);\r\n }\r\n }, _ => {\r\n // If `isWindowSupported()` rejected.\r\n throw ERROR_FACTORY.create(\"indexed-db-unsupported\" /* ErrorCode.INDEXED_DB_UNSUPPORTED */);\r\n });\r\n return _getProvider(getModularInstance(app), 'messaging').getImmediate();\r\n}\r\n/**\r\n * Subscribes the {@link Messaging} instance to push notifications. Returns an Firebase Cloud\r\n * Messaging registration token that can be used to send push messages to that {@link Messaging}\r\n * instance.\r\n *\r\n * If a notification permission isn't already granted, this method asks the user for permission. The\r\n * returned promise rejects if the user does not allow the app to show notifications.\r\n *\r\n * @param messaging - The {@link Messaging} instance.\r\n * @param options - Provides an optional vapid key and an optinoal service worker registration\r\n *\r\n * @returns The promise resolves with an FCM registration token.\r\n *\r\n * @public\r\n */\r\nasync function getToken(messaging, options) {\r\n messaging = getModularInstance(messaging);\r\n return getToken$1(messaging, options);\r\n}\r\n/**\r\n * Deletes the registration token associated with this {@link Messaging} instance and unsubscribes\r\n * the {@link Messaging} instance from the push subscription.\r\n *\r\n * @param messaging - The {@link Messaging} instance.\r\n *\r\n * @returns The promise resolves when the token has been successfully deleted.\r\n *\r\n * @public\r\n */\r\nfunction deleteToken(messaging) {\r\n messaging = getModularInstance(messaging);\r\n return deleteToken$1(messaging);\r\n}\r\n/**\r\n * When a push message is received and the user is currently on a page for your origin, the\r\n * message is passed to the page and an `onMessage()` event is dispatched with the payload of\r\n * the push message.\r\n *\r\n *\r\n * @param messaging - The {@link Messaging} instance.\r\n * @param nextOrObserver - This function, or observer object with `next` defined,\r\n * is called when a message is received and the user is currently viewing your page.\r\n * @returns To stop listening for messages execute this returned function.\r\n *\r\n * @public\r\n */\r\nfunction onMessage(messaging, nextOrObserver) {\r\n messaging = getModularInstance(messaging);\r\n return onMessage$1(messaging, nextOrObserver);\r\n}\n\n/**\r\n * Firebase Cloud Messaging\r\n *\r\n * @packageDocumentation\r\n */\r\nregisterMessagingInWindow();\n\nexport { deleteToken, getMessagingInWindow as getMessaging, getToken, isWindowSupported as isSupported, onMessage };\n//# sourceMappingURL=index.esm2017.js.map\n","import { ErrorFactory, areCookiesEnabled, isIndexedDBAvailable, validateIndexedDBOpenable, getModularInstance, deepEqual } from '@firebase/util';\nimport { Logger, LogLevel } from '@firebase/logger';\nimport { _getProvider, getApp, _registerComponent, registerVersion } from '@firebase/app';\nimport { Component } from '@firebase/component';\nimport '@firebase/installations';\n\nconst name = \"@firebase/performance\";\nconst version = \"0.6.4\";\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nconst SDK_VERSION = version;\r\n/** The prefix for start User Timing marks used for creating Traces. */\r\nconst TRACE_START_MARK_PREFIX = 'FB-PERF-TRACE-START';\r\n/** The prefix for stop User Timing marks used for creating Traces. */\r\nconst TRACE_STOP_MARK_PREFIX = 'FB-PERF-TRACE-STOP';\r\n/** The prefix for User Timing measure used for creating Traces. */\r\nconst TRACE_MEASURE_PREFIX = 'FB-PERF-TRACE-MEASURE';\r\n/** The prefix for out of the box page load Trace name. */\r\nconst OOB_TRACE_PAGE_LOAD_PREFIX = '_wt_';\r\nconst FIRST_PAINT_COUNTER_NAME = '_fp';\r\nconst FIRST_CONTENTFUL_PAINT_COUNTER_NAME = '_fcp';\r\nconst FIRST_INPUT_DELAY_COUNTER_NAME = '_fid';\r\nconst CONFIG_LOCAL_STORAGE_KEY = '@firebase/performance/config';\r\nconst CONFIG_EXPIRY_LOCAL_STORAGE_KEY = '@firebase/performance/configexpire';\r\nconst SERVICE = 'performance';\r\nconst SERVICE_NAME = 'Performance';\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nconst ERROR_DESCRIPTION_MAP = {\r\n [\"trace started\" /* ErrorCode.TRACE_STARTED_BEFORE */]: 'Trace {$traceName} was started before.',\r\n [\"trace stopped\" /* ErrorCode.TRACE_STOPPED_BEFORE */]: 'Trace {$traceName} is not running.',\r\n [\"nonpositive trace startTime\" /* ErrorCode.NONPOSITIVE_TRACE_START_TIME */]: 'Trace {$traceName} startTime should be positive.',\r\n [\"nonpositive trace duration\" /* ErrorCode.NONPOSITIVE_TRACE_DURATION */]: 'Trace {$traceName} duration should be positive.',\r\n [\"no window\" /* ErrorCode.NO_WINDOW */]: 'Window is not available.',\r\n [\"no app id\" /* ErrorCode.NO_APP_ID */]: 'App id is not available.',\r\n [\"no project id\" /* ErrorCode.NO_PROJECT_ID */]: 'Project id is not available.',\r\n [\"no api key\" /* ErrorCode.NO_API_KEY */]: 'Api key is not available.',\r\n [\"invalid cc log\" /* ErrorCode.INVALID_CC_LOG */]: 'Attempted to queue invalid cc event',\r\n [\"FB not default\" /* ErrorCode.FB_NOT_DEFAULT */]: 'Performance can only start when Firebase app instance is the default one.',\r\n [\"RC response not ok\" /* ErrorCode.RC_NOT_OK */]: 'RC response is not ok',\r\n [\"invalid attribute name\" /* ErrorCode.INVALID_ATTRIBUTE_NAME */]: 'Attribute name {$attributeName} is invalid.',\r\n [\"invalid attribute value\" /* ErrorCode.INVALID_ATTRIBUTE_VALUE */]: 'Attribute value {$attributeValue} is invalid.',\r\n [\"invalid custom metric name\" /* ErrorCode.INVALID_CUSTOM_METRIC_NAME */]: 'Custom metric name {$customMetricName} is invalid',\r\n [\"invalid String merger input\" /* ErrorCode.INVALID_STRING_MERGER_PARAMETER */]: 'Input for String merger is invalid, contact support team to resolve.',\r\n [\"already initialized\" /* ErrorCode.ALREADY_INITIALIZED */]: 'initializePerformance() has already been called with ' +\r\n 'different options. To avoid this error, call initializePerformance() with the ' +\r\n 'same options as when it was originally called, or call getPerformance() to return the' +\r\n ' already initialized instance.'\r\n};\r\nconst ERROR_FACTORY = new ErrorFactory(SERVICE, SERVICE_NAME, ERROR_DESCRIPTION_MAP);\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nconst consoleLogger = new Logger(SERVICE_NAME);\r\nconsoleLogger.logLevel = LogLevel.INFO;\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nlet apiInstance;\r\nlet windowInstance;\r\n/**\r\n * This class holds a reference to various browser related objects injected by\r\n * set methods.\r\n */\r\nclass Api {\r\n constructor(window) {\r\n this.window = window;\r\n if (!window) {\r\n throw ERROR_FACTORY.create(\"no window\" /* ErrorCode.NO_WINDOW */);\r\n }\r\n this.performance = window.performance;\r\n this.PerformanceObserver = window.PerformanceObserver;\r\n this.windowLocation = window.location;\r\n this.navigator = window.navigator;\r\n this.document = window.document;\r\n if (this.navigator && this.navigator.cookieEnabled) {\r\n // If user blocks cookies on the browser, accessing localStorage will\r\n // throw an exception.\r\n this.localStorage = window.localStorage;\r\n }\r\n if (window.perfMetrics && window.perfMetrics.onFirstInputDelay) {\r\n this.onFirstInputDelay = window.perfMetrics.onFirstInputDelay;\r\n }\r\n }\r\n getUrl() {\r\n // Do not capture the string query part of url.\r\n return this.windowLocation.href.split('?')[0];\r\n }\r\n mark(name) {\r\n if (!this.performance || !this.performance.mark) {\r\n return;\r\n }\r\n this.performance.mark(name);\r\n }\r\n measure(measureName, mark1, mark2) {\r\n if (!this.performance || !this.performance.measure) {\r\n return;\r\n }\r\n this.performance.measure(measureName, mark1, mark2);\r\n }\r\n getEntriesByType(type) {\r\n if (!this.performance || !this.performance.getEntriesByType) {\r\n return [];\r\n }\r\n return this.performance.getEntriesByType(type);\r\n }\r\n getEntriesByName(name) {\r\n if (!this.performance || !this.performance.getEntriesByName) {\r\n return [];\r\n }\r\n return this.performance.getEntriesByName(name);\r\n }\r\n getTimeOrigin() {\r\n // Polyfill the time origin with performance.timing.navigationStart.\r\n return (this.performance &&\r\n (this.performance.timeOrigin || this.performance.timing.navigationStart));\r\n }\r\n requiredApisAvailable() {\r\n if (!fetch || !Promise || !areCookiesEnabled()) {\r\n consoleLogger.info('Firebase Performance cannot start if browser does not support fetch and Promise or cookie is disabled.');\r\n return false;\r\n }\r\n if (!isIndexedDBAvailable()) {\r\n consoleLogger.info('IndexedDB is not supported by current browswer');\r\n return false;\r\n }\r\n return true;\r\n }\r\n setupObserver(entryType, callback) {\r\n if (!this.PerformanceObserver) {\r\n return;\r\n }\r\n const observer = new this.PerformanceObserver(list => {\r\n for (const entry of list.getEntries()) {\r\n // `entry` is a PerformanceEntry instance.\r\n callback(entry);\r\n }\r\n });\r\n // Start observing the entry types you care about.\r\n observer.observe({ entryTypes: [entryType] });\r\n }\r\n static getInstance() {\r\n if (apiInstance === undefined) {\r\n apiInstance = new Api(windowInstance);\r\n }\r\n return apiInstance;\r\n }\r\n}\r\nfunction setupApi(window) {\r\n windowInstance = window;\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nlet iid;\r\nfunction getIidPromise(installationsService) {\r\n const iidPromise = installationsService.getId();\r\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\r\n iidPromise.then((iidVal) => {\r\n iid = iidVal;\r\n });\r\n return iidPromise;\r\n}\r\n// This method should be used after the iid is retrieved by getIidPromise method.\r\nfunction getIid() {\r\n return iid;\r\n}\r\nfunction getAuthTokenPromise(installationsService) {\r\n const authTokenPromise = installationsService.getToken();\r\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\r\n authTokenPromise.then((authTokenVal) => {\r\n });\r\n return authTokenPromise;\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nfunction mergeStrings(part1, part2) {\r\n const sizeDiff = part1.length - part2.length;\r\n if (sizeDiff < 0 || sizeDiff > 1) {\r\n throw ERROR_FACTORY.create(\"invalid String merger input\" /* ErrorCode.INVALID_STRING_MERGER_PARAMETER */);\r\n }\r\n const resultArray = [];\r\n for (let i = 0; i < part1.length; i++) {\r\n resultArray.push(part1.charAt(i));\r\n if (part2.length > i) {\r\n resultArray.push(part2.charAt(i));\r\n }\r\n }\r\n return resultArray.join('');\r\n}\n\n/**\r\n * @license\r\n * Copyright 2019 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nlet settingsServiceInstance;\r\nclass SettingsService {\r\n constructor() {\r\n // The variable which controls logging of automatic traces and HTTP/S network monitoring.\r\n this.instrumentationEnabled = true;\r\n // The variable which controls logging of custom traces.\r\n this.dataCollectionEnabled = true;\r\n // Configuration flags set through remote config.\r\n this.loggingEnabled = false;\r\n // Sampling rate between 0 and 1.\r\n this.tracesSamplingRate = 1;\r\n this.networkRequestsSamplingRate = 1;\r\n // Address of logging service.\r\n this.logEndPointUrl = 'https://firebaselogging.googleapis.com/v0cc/log?format=json_proto';\r\n // Performance event transport endpoint URL which should be compatible with proto3.\r\n // New Address for transport service, not configurable via Remote Config.\r\n this.flTransportEndpointUrl = mergeStrings('hts/frbslgigp.ogepscmv/ieo/eaylg', 'tp:/ieaeogn-agolai.o/1frlglgc/o');\r\n this.transportKey = mergeStrings('AzSC8r6ReiGqFMyfvgow', 'Iayx0u-XT3vksVM-pIV');\r\n // Source type for performance event logs.\r\n this.logSource = 462;\r\n // Flags which control per session logging of traces and network requests.\r\n this.logTraceAfterSampling = false;\r\n this.logNetworkAfterSampling = false;\r\n // TTL of config retrieved from remote config in hours.\r\n this.configTimeToLive = 12;\r\n }\r\n getFlTransportFullUrl() {\r\n return this.flTransportEndpointUrl.concat('?key=', this.transportKey);\r\n }\r\n static getInstance() {\r\n if (settingsServiceInstance === undefined) {\r\n settingsServiceInstance = new SettingsService();\r\n }\r\n return settingsServiceInstance;\r\n }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nvar VisibilityState;\r\n(function (VisibilityState) {\r\n VisibilityState[VisibilityState[\"UNKNOWN\"] = 0] = \"UNKNOWN\";\r\n VisibilityState[VisibilityState[\"VISIBLE\"] = 1] = \"VISIBLE\";\r\n VisibilityState[VisibilityState[\"HIDDEN\"] = 2] = \"HIDDEN\";\r\n})(VisibilityState || (VisibilityState = {}));\r\nconst RESERVED_ATTRIBUTE_PREFIXES = ['firebase_', 'google_', 'ga_'];\r\nconst ATTRIBUTE_FORMAT_REGEX = new RegExp('^[a-zA-Z]\\\\w*$');\r\nconst MAX_ATTRIBUTE_NAME_LENGTH = 40;\r\nconst MAX_ATTRIBUTE_VALUE_LENGTH = 100;\r\nfunction getServiceWorkerStatus() {\r\n const navigator = Api.getInstance().navigator;\r\n if (navigator === null || navigator === void 0 ? void 0 : navigator.serviceWorker) {\r\n if (navigator.serviceWorker.controller) {\r\n return 2 /* ServiceWorkerStatus.CONTROLLED */;\r\n }\r\n else {\r\n return 3 /* ServiceWorkerStatus.UNCONTROLLED */;\r\n }\r\n }\r\n else {\r\n return 1 /* ServiceWorkerStatus.UNSUPPORTED */;\r\n }\r\n}\r\nfunction getVisibilityState() {\r\n const document = Api.getInstance().document;\r\n const visibilityState = document.visibilityState;\r\n switch (visibilityState) {\r\n case 'visible':\r\n return VisibilityState.VISIBLE;\r\n case 'hidden':\r\n return VisibilityState.HIDDEN;\r\n default:\r\n return VisibilityState.UNKNOWN;\r\n }\r\n}\r\nfunction getEffectiveConnectionType() {\r\n const navigator = Api.getInstance().navigator;\r\n const navigatorConnection = navigator.connection;\r\n const effectiveType = navigatorConnection && navigatorConnection.effectiveType;\r\n switch (effectiveType) {\r\n case 'slow-2g':\r\n return 1 /* EffectiveConnectionType.CONNECTION_SLOW_2G */;\r\n case '2g':\r\n return 2 /* EffectiveConnectionType.CONNECTION_2G */;\r\n case '3g':\r\n return 3 /* EffectiveConnectionType.CONNECTION_3G */;\r\n case '4g':\r\n return 4 /* EffectiveConnectionType.CONNECTION_4G */;\r\n default:\r\n return 0 /* EffectiveConnectionType.UNKNOWN */;\r\n }\r\n}\r\nfunction isValidCustomAttributeName(name) {\r\n if (name.length === 0 || name.length > MAX_ATTRIBUTE_NAME_LENGTH) {\r\n return false;\r\n }\r\n const matchesReservedPrefix = RESERVED_ATTRIBUTE_PREFIXES.some(prefix => name.startsWith(prefix));\r\n return !matchesReservedPrefix && !!name.match(ATTRIBUTE_FORMAT_REGEX);\r\n}\r\nfunction isValidCustomAttributeValue(value) {\r\n return value.length !== 0 && value.length <= MAX_ATTRIBUTE_VALUE_LENGTH;\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nfunction getAppId(firebaseApp) {\r\n var _a;\r\n const appId = (_a = firebaseApp.options) === null || _a === void 0 ? void 0 : _a.appId;\r\n if (!appId) {\r\n throw ERROR_FACTORY.create(\"no app id\" /* ErrorCode.NO_APP_ID */);\r\n }\r\n return appId;\r\n}\r\nfunction getProjectId(firebaseApp) {\r\n var _a;\r\n const projectId = (_a = firebaseApp.options) === null || _a === void 0 ? void 0 : _a.projectId;\r\n if (!projectId) {\r\n throw ERROR_FACTORY.create(\"no project id\" /* ErrorCode.NO_PROJECT_ID */);\r\n }\r\n return projectId;\r\n}\r\nfunction getApiKey(firebaseApp) {\r\n var _a;\r\n const apiKey = (_a = firebaseApp.options) === null || _a === void 0 ? void 0 : _a.apiKey;\r\n if (!apiKey) {\r\n throw ERROR_FACTORY.create(\"no api key\" /* ErrorCode.NO_API_KEY */);\r\n }\r\n return apiKey;\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nconst REMOTE_CONFIG_SDK_VERSION = '0.0.1';\r\n// These values will be used if the remote config object is successfully\r\n// retrieved, but the template does not have these fields.\r\nconst DEFAULT_CONFIGS = {\r\n loggingEnabled: true\r\n};\r\nconst FIS_AUTH_PREFIX = 'FIREBASE_INSTALLATIONS_AUTH';\r\nfunction getConfig(performanceController, iid) {\r\n const config = getStoredConfig();\r\n if (config) {\r\n processConfig(config);\r\n return Promise.resolve();\r\n }\r\n return getRemoteConfig(performanceController, iid)\r\n .then(processConfig)\r\n .then(config => storeConfig(config), \r\n /** Do nothing for error, use defaults set in settings service. */\r\n () => { });\r\n}\r\nfunction getStoredConfig() {\r\n const localStorage = Api.getInstance().localStorage;\r\n if (!localStorage) {\r\n return;\r\n }\r\n const expiryString = localStorage.getItem(CONFIG_EXPIRY_LOCAL_STORAGE_KEY);\r\n if (!expiryString || !configValid(expiryString)) {\r\n return;\r\n }\r\n const configStringified = localStorage.getItem(CONFIG_LOCAL_STORAGE_KEY);\r\n if (!configStringified) {\r\n return;\r\n }\r\n try {\r\n const configResponse = JSON.parse(configStringified);\r\n return configResponse;\r\n }\r\n catch (_a) {\r\n return;\r\n }\r\n}\r\nfunction storeConfig(config) {\r\n const localStorage = Api.getInstance().localStorage;\r\n if (!config || !localStorage) {\r\n return;\r\n }\r\n localStorage.setItem(CONFIG_LOCAL_STORAGE_KEY, JSON.stringify(config));\r\n localStorage.setItem(CONFIG_EXPIRY_LOCAL_STORAGE_KEY, String(Date.now() +\r\n SettingsService.getInstance().configTimeToLive * 60 * 60 * 1000));\r\n}\r\nconst COULD_NOT_GET_CONFIG_MSG = 'Could not fetch config, will use default configs';\r\nfunction getRemoteConfig(performanceController, iid) {\r\n // Perf needs auth token only to retrieve remote config.\r\n return getAuthTokenPromise(performanceController.installations)\r\n .then(authToken => {\r\n const projectId = getProjectId(performanceController.app);\r\n const apiKey = getApiKey(performanceController.app);\r\n const configEndPoint = `https://firebaseremoteconfig.googleapis.com/v1/projects/${projectId}/namespaces/fireperf:fetch?key=${apiKey}`;\r\n const request = new Request(configEndPoint, {\r\n method: 'POST',\r\n headers: { Authorization: `${FIS_AUTH_PREFIX} ${authToken}` },\r\n /* eslint-disable camelcase */\r\n body: JSON.stringify({\r\n app_instance_id: iid,\r\n app_instance_id_token: authToken,\r\n app_id: getAppId(performanceController.app),\r\n app_version: SDK_VERSION,\r\n sdk_version: REMOTE_CONFIG_SDK_VERSION\r\n })\r\n /* eslint-enable camelcase */\r\n });\r\n return fetch(request).then(response => {\r\n if (response.ok) {\r\n return response.json();\r\n }\r\n // In case response is not ok. This will be caught by catch.\r\n throw ERROR_FACTORY.create(\"RC response not ok\" /* ErrorCode.RC_NOT_OK */);\r\n });\r\n })\r\n .catch(() => {\r\n consoleLogger.info(COULD_NOT_GET_CONFIG_MSG);\r\n return undefined;\r\n });\r\n}\r\n/**\r\n * Processes config coming either from calling RC or from local storage.\r\n * This method only runs if call is successful or config in storage\r\n * is valid.\r\n */\r\nfunction processConfig(config) {\r\n if (!config) {\r\n return config;\r\n }\r\n const settingsServiceInstance = SettingsService.getInstance();\r\n const entries = config.entries || {};\r\n if (entries.fpr_enabled !== undefined) {\r\n // TODO: Change the assignment of loggingEnabled once the received type is\r\n // known.\r\n settingsServiceInstance.loggingEnabled =\r\n String(entries.fpr_enabled) === 'true';\r\n }\r\n else {\r\n // Config retrieved successfully, but there is no fpr_enabled in template.\r\n // Use secondary configs value.\r\n settingsServiceInstance.loggingEnabled = DEFAULT_CONFIGS.loggingEnabled;\r\n }\r\n if (entries.fpr_log_source) {\r\n settingsServiceInstance.logSource = Number(entries.fpr_log_source);\r\n }\r\n else if (DEFAULT_CONFIGS.logSource) {\r\n settingsServiceInstance.logSource = DEFAULT_CONFIGS.logSource;\r\n }\r\n if (entries.fpr_log_endpoint_url) {\r\n settingsServiceInstance.logEndPointUrl = entries.fpr_log_endpoint_url;\r\n }\r\n else if (DEFAULT_CONFIGS.logEndPointUrl) {\r\n settingsServiceInstance.logEndPointUrl = DEFAULT_CONFIGS.logEndPointUrl;\r\n }\r\n // Key from Remote Config has to be non-empty string, otherwsie use local value.\r\n if (entries.fpr_log_transport_key) {\r\n settingsServiceInstance.transportKey = entries.fpr_log_transport_key;\r\n }\r\n else if (DEFAULT_CONFIGS.transportKey) {\r\n settingsServiceInstance.transportKey = DEFAULT_CONFIGS.transportKey;\r\n }\r\n if (entries.fpr_vc_network_request_sampling_rate !== undefined) {\r\n settingsServiceInstance.networkRequestsSamplingRate = Number(entries.fpr_vc_network_request_sampling_rate);\r\n }\r\n else if (DEFAULT_CONFIGS.networkRequestsSamplingRate !== undefined) {\r\n settingsServiceInstance.networkRequestsSamplingRate =\r\n DEFAULT_CONFIGS.networkRequestsSamplingRate;\r\n }\r\n if (entries.fpr_vc_trace_sampling_rate !== undefined) {\r\n settingsServiceInstance.tracesSamplingRate = Number(entries.fpr_vc_trace_sampling_rate);\r\n }\r\n else if (DEFAULT_CONFIGS.tracesSamplingRate !== undefined) {\r\n settingsServiceInstance.tracesSamplingRate =\r\n DEFAULT_CONFIGS.tracesSamplingRate;\r\n }\r\n // Set the per session trace and network logging flags.\r\n settingsServiceInstance.logTraceAfterSampling = shouldLogAfterSampling(settingsServiceInstance.tracesSamplingRate);\r\n settingsServiceInstance.logNetworkAfterSampling = shouldLogAfterSampling(settingsServiceInstance.networkRequestsSamplingRate);\r\n return config;\r\n}\r\nfunction configValid(expiry) {\r\n return Number(expiry) > Date.now();\r\n}\r\nfunction shouldLogAfterSampling(samplingRate) {\r\n return Math.random() <= samplingRate;\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nlet initializationStatus = 1 /* InitializationStatus.notInitialized */;\r\nlet initializationPromise;\r\nfunction getInitializationPromise(performanceController) {\r\n initializationStatus = 2 /* InitializationStatus.initializationPending */;\r\n initializationPromise =\r\n initializationPromise || initializePerf(performanceController);\r\n return initializationPromise;\r\n}\r\nfunction isPerfInitialized() {\r\n return initializationStatus === 3 /* InitializationStatus.initialized */;\r\n}\r\nfunction initializePerf(performanceController) {\r\n return getDocumentReadyComplete()\r\n .then(() => getIidPromise(performanceController.installations))\r\n .then(iid => getConfig(performanceController, iid))\r\n .then(() => changeInitializationStatus(), () => changeInitializationStatus());\r\n}\r\n/**\r\n * Returns a promise which resolves whenever the document readystate is complete or\r\n * immediately if it is called after page load complete.\r\n */\r\nfunction getDocumentReadyComplete() {\r\n const document = Api.getInstance().document;\r\n return new Promise(resolve => {\r\n if (document && document.readyState !== 'complete') {\r\n const handler = () => {\r\n if (document.readyState === 'complete') {\r\n document.removeEventListener('readystatechange', handler);\r\n resolve();\r\n }\r\n };\r\n document.addEventListener('readystatechange', handler);\r\n }\r\n else {\r\n resolve();\r\n }\r\n });\r\n}\r\nfunction changeInitializationStatus() {\r\n initializationStatus = 3 /* InitializationStatus.initialized */;\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nconst DEFAULT_SEND_INTERVAL_MS = 10 * 1000;\r\nconst INITIAL_SEND_TIME_DELAY_MS = 5.5 * 1000;\r\n// If end point does not work, the call will be tried for these many times.\r\nconst DEFAULT_REMAINING_TRIES = 3;\r\nconst MAX_EVENT_COUNT_PER_REQUEST = 1000;\r\nlet remainingTries = DEFAULT_REMAINING_TRIES;\r\n/* eslint-enable camelcase */\r\nlet queue = [];\r\nlet isTransportSetup = false;\r\nfunction setupTransportService() {\r\n if (!isTransportSetup) {\r\n processQueue(INITIAL_SEND_TIME_DELAY_MS);\r\n isTransportSetup = true;\r\n }\r\n}\r\nfunction processQueue(timeOffset) {\r\n setTimeout(() => {\r\n // If there is no remainingTries left, stop retrying.\r\n if (remainingTries === 0) {\r\n return;\r\n }\r\n // If there are no events to process, wait for DEFAULT_SEND_INTERVAL_MS and try again.\r\n if (!queue.length) {\r\n return processQueue(DEFAULT_SEND_INTERVAL_MS);\r\n }\r\n dispatchQueueEvents();\r\n }, timeOffset);\r\n}\r\nfunction dispatchQueueEvents() {\r\n // Extract events up to the maximum cap of single logRequest from top of \"official queue\".\r\n // The staged events will be used for current logRequest attempt, remaining events will be kept\r\n // for next attempt.\r\n const staged = queue.splice(0, MAX_EVENT_COUNT_PER_REQUEST);\r\n /* eslint-disable camelcase */\r\n // We will pass the JSON serialized event to the backend.\r\n const log_event = staged.map(evt => ({\r\n source_extension_json_proto3: evt.message,\r\n event_time_ms: String(evt.eventTime)\r\n }));\r\n const data = {\r\n request_time_ms: String(Date.now()),\r\n client_info: {\r\n client_type: 1,\r\n js_client_info: {}\r\n },\r\n log_source: SettingsService.getInstance().logSource,\r\n log_event\r\n };\r\n /* eslint-enable camelcase */\r\n sendEventsToFl(data, staged).catch(() => {\r\n // If the request fails for some reason, add the events that were attempted\r\n // back to the primary queue to retry later.\r\n queue = [...staged, ...queue];\r\n remainingTries--;\r\n consoleLogger.info(`Tries left: ${remainingTries}.`);\r\n processQueue(DEFAULT_SEND_INTERVAL_MS);\r\n });\r\n}\r\nfunction sendEventsToFl(data, staged) {\r\n return postToFlEndpoint(data)\r\n .then(res => {\r\n if (!res.ok) {\r\n consoleLogger.info('Call to Firebase backend failed.');\r\n }\r\n return res.json();\r\n })\r\n .then(res => {\r\n // Find the next call wait time from the response.\r\n const transportWait = Number(res.nextRequestWaitMillis);\r\n let requestOffset = DEFAULT_SEND_INTERVAL_MS;\r\n if (!isNaN(transportWait)) {\r\n requestOffset = Math.max(transportWait, requestOffset);\r\n }\r\n // Delete request if response include RESPONSE_ACTION_UNKNOWN or DELETE_REQUEST action.\r\n // Otherwise, retry request using normal scheduling if response include RETRY_REQUEST_LATER.\r\n const logResponseDetails = res.logResponseDetails;\r\n if (Array.isArray(logResponseDetails) &&\r\n logResponseDetails.length > 0 &&\r\n logResponseDetails[0].responseAction === 'RETRY_REQUEST_LATER') {\r\n queue = [...staged, ...queue];\r\n consoleLogger.info(`Retry transport request later.`);\r\n }\r\n remainingTries = DEFAULT_REMAINING_TRIES;\r\n // Schedule the next process.\r\n processQueue(requestOffset);\r\n });\r\n}\r\nfunction postToFlEndpoint(data) {\r\n const flTransportFullUrl = SettingsService.getInstance().getFlTransportFullUrl();\r\n return fetch(flTransportFullUrl, {\r\n method: 'POST',\r\n body: JSON.stringify(data)\r\n });\r\n}\r\nfunction addToQueue(evt) {\r\n if (!evt.eventTime || !evt.message) {\r\n throw ERROR_FACTORY.create(\"invalid cc log\" /* ErrorCode.INVALID_CC_LOG */);\r\n }\r\n // Add the new event to the queue.\r\n queue = [...queue, evt];\r\n}\r\n/** Log handler for cc service to send the performance logs to the server. */\r\nfunction transportHandler(\r\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\r\nserializer) {\r\n return (...args) => {\r\n const message = serializer(...args);\r\n addToQueue({\r\n message,\r\n eventTime: Date.now()\r\n });\r\n };\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/* eslint-enble camelcase */\r\nlet logger;\r\n// This method is not called before initialization.\r\nfunction sendLog(resource, resourceType) {\r\n if (!logger) {\r\n logger = transportHandler(serializer);\r\n }\r\n logger(resource, resourceType);\r\n}\r\nfunction logTrace(trace) {\r\n const settingsService = SettingsService.getInstance();\r\n // Do not log if trace is auto generated and instrumentation is disabled.\r\n if (!settingsService.instrumentationEnabled && trace.isAuto) {\r\n return;\r\n }\r\n // Do not log if trace is custom and data collection is disabled.\r\n if (!settingsService.dataCollectionEnabled && !trace.isAuto) {\r\n return;\r\n }\r\n // Do not log if required apis are not available.\r\n if (!Api.getInstance().requiredApisAvailable()) {\r\n return;\r\n }\r\n // Only log the page load auto traces if page is visible.\r\n if (trace.isAuto && getVisibilityState() !== VisibilityState.VISIBLE) {\r\n return;\r\n }\r\n if (isPerfInitialized()) {\r\n sendTraceLog(trace);\r\n }\r\n else {\r\n // Custom traces can be used before the initialization but logging\r\n // should wait until after.\r\n getInitializationPromise(trace.performanceController).then(() => sendTraceLog(trace), () => sendTraceLog(trace));\r\n }\r\n}\r\nfunction sendTraceLog(trace) {\r\n if (!getIid()) {\r\n return;\r\n }\r\n const settingsService = SettingsService.getInstance();\r\n if (!settingsService.loggingEnabled ||\r\n !settingsService.logTraceAfterSampling) {\r\n return;\r\n }\r\n setTimeout(() => sendLog(trace, 1 /* ResourceType.Trace */), 0);\r\n}\r\nfunction logNetworkRequest(networkRequest) {\r\n const settingsService = SettingsService.getInstance();\r\n // Do not log network requests if instrumentation is disabled.\r\n if (!settingsService.instrumentationEnabled) {\r\n return;\r\n }\r\n // Do not log the js sdk's call to transport service domain to avoid unnecessary cycle.\r\n // Need to blacklist both old and new endpoints to avoid migration gap.\r\n const networkRequestUrl = networkRequest.url;\r\n // Blacklist old log endpoint and new transport endpoint.\r\n // Because Performance SDK doesn't instrument requests sent from SDK itself.\r\n const logEndpointUrl = settingsService.logEndPointUrl.split('?')[0];\r\n const flEndpointUrl = settingsService.flTransportEndpointUrl.split('?')[0];\r\n if (networkRequestUrl === logEndpointUrl ||\r\n networkRequestUrl === flEndpointUrl) {\r\n return;\r\n }\r\n if (!settingsService.loggingEnabled ||\r\n !settingsService.logNetworkAfterSampling) {\r\n return;\r\n }\r\n setTimeout(() => sendLog(networkRequest, 0 /* ResourceType.NetworkRequest */), 0);\r\n}\r\nfunction serializer(resource, resourceType) {\r\n if (resourceType === 0 /* ResourceType.NetworkRequest */) {\r\n return serializeNetworkRequest(resource);\r\n }\r\n return serializeTrace(resource);\r\n}\r\nfunction serializeNetworkRequest(networkRequest) {\r\n const networkRequestMetric = {\r\n url: networkRequest.url,\r\n http_method: networkRequest.httpMethod || 0,\r\n http_response_code: 200,\r\n response_payload_bytes: networkRequest.responsePayloadBytes,\r\n client_start_time_us: networkRequest.startTimeUs,\r\n time_to_response_initiated_us: networkRequest.timeToResponseInitiatedUs,\r\n time_to_response_completed_us: networkRequest.timeToResponseCompletedUs\r\n };\r\n const perfMetric = {\r\n application_info: getApplicationInfo(networkRequest.performanceController.app),\r\n network_request_metric: networkRequestMetric\r\n };\r\n return JSON.stringify(perfMetric);\r\n}\r\nfunction serializeTrace(trace) {\r\n const traceMetric = {\r\n name: trace.name,\r\n is_auto: trace.isAuto,\r\n client_start_time_us: trace.startTimeUs,\r\n duration_us: trace.durationUs\r\n };\r\n if (Object.keys(trace.counters).length !== 0) {\r\n traceMetric.counters = trace.counters;\r\n }\r\n const customAttributes = trace.getAttributes();\r\n if (Object.keys(customAttributes).length !== 0) {\r\n traceMetric.custom_attributes = customAttributes;\r\n }\r\n const perfMetric = {\r\n application_info: getApplicationInfo(trace.performanceController.app),\r\n trace_metric: traceMetric\r\n };\r\n return JSON.stringify(perfMetric);\r\n}\r\nfunction getApplicationInfo(firebaseApp) {\r\n return {\r\n google_app_id: getAppId(firebaseApp),\r\n app_instance_id: getIid(),\r\n web_app_info: {\r\n sdk_version: SDK_VERSION,\r\n page_url: Api.getInstance().getUrl(),\r\n service_worker_status: getServiceWorkerStatus(),\r\n visibility_state: getVisibilityState(),\r\n effective_connection_type: getEffectiveConnectionType()\r\n },\r\n application_process_state: 0\r\n };\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nconst MAX_METRIC_NAME_LENGTH = 100;\r\nconst RESERVED_AUTO_PREFIX = '_';\r\nconst oobMetrics = [\r\n FIRST_PAINT_COUNTER_NAME,\r\n FIRST_CONTENTFUL_PAINT_COUNTER_NAME,\r\n FIRST_INPUT_DELAY_COUNTER_NAME\r\n];\r\n/**\r\n * Returns true if the metric is custom and does not start with reserved prefix, or if\r\n * the metric is one of out of the box page load trace metrics.\r\n */\r\nfunction isValidMetricName(name, traceName) {\r\n if (name.length === 0 || name.length > MAX_METRIC_NAME_LENGTH) {\r\n return false;\r\n }\r\n return ((traceName &&\r\n traceName.startsWith(OOB_TRACE_PAGE_LOAD_PREFIX) &&\r\n oobMetrics.indexOf(name) > -1) ||\r\n !name.startsWith(RESERVED_AUTO_PREFIX));\r\n}\r\n/**\r\n * Converts the provided value to an integer value to be used in case of a metric.\r\n * @param providedValue Provided number value of the metric that needs to be converted to an integer.\r\n *\r\n * @returns Converted integer number to be set for the metric.\r\n */\r\nfunction convertMetricValueToInteger(providedValue) {\r\n const valueAsInteger = Math.floor(providedValue);\r\n if (valueAsInteger < providedValue) {\r\n consoleLogger.info(`Metric value should be an Integer, setting the value as : ${valueAsInteger}.`);\r\n }\r\n return valueAsInteger;\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nclass Trace {\r\n /**\r\n * @param performanceController The performance controller running.\r\n * @param name The name of the trace.\r\n * @param isAuto If the trace is auto-instrumented.\r\n * @param traceMeasureName The name of the measure marker in user timing specification. This field\r\n * is only set when the trace is built for logging when the user directly uses the user timing\r\n * api (performance.mark and performance.measure).\r\n */\r\n constructor(performanceController, name, isAuto = false, traceMeasureName) {\r\n this.performanceController = performanceController;\r\n this.name = name;\r\n this.isAuto = isAuto;\r\n this.state = 1 /* TraceState.UNINITIALIZED */;\r\n this.customAttributes = {};\r\n this.counters = {};\r\n this.api = Api.getInstance();\r\n this.randomId = Math.floor(Math.random() * 1000000);\r\n if (!this.isAuto) {\r\n this.traceStartMark = `${TRACE_START_MARK_PREFIX}-${this.randomId}-${this.name}`;\r\n this.traceStopMark = `${TRACE_STOP_MARK_PREFIX}-${this.randomId}-${this.name}`;\r\n this.traceMeasure =\r\n traceMeasureName ||\r\n `${TRACE_MEASURE_PREFIX}-${this.randomId}-${this.name}`;\r\n if (traceMeasureName) {\r\n // For the case of direct user timing traces, no start stop will happen. The measure object\r\n // is already available.\r\n this.calculateTraceMetrics();\r\n }\r\n }\r\n }\r\n /**\r\n * Starts a trace. The measurement of the duration starts at this point.\r\n */\r\n start() {\r\n if (this.state !== 1 /* TraceState.UNINITIALIZED */) {\r\n throw ERROR_FACTORY.create(\"trace started\" /* ErrorCode.TRACE_STARTED_BEFORE */, {\r\n traceName: this.name\r\n });\r\n }\r\n this.api.mark(this.traceStartMark);\r\n this.state = 2 /* TraceState.RUNNING */;\r\n }\r\n /**\r\n * Stops the trace. The measurement of the duration of the trace stops at this point and trace\r\n * is logged.\r\n */\r\n stop() {\r\n if (this.state !== 2 /* TraceState.RUNNING */) {\r\n throw ERROR_FACTORY.create(\"trace stopped\" /* ErrorCode.TRACE_STOPPED_BEFORE */, {\r\n traceName: this.name\r\n });\r\n }\r\n this.state = 3 /* TraceState.TERMINATED */;\r\n this.api.mark(this.traceStopMark);\r\n this.api.measure(this.traceMeasure, this.traceStartMark, this.traceStopMark);\r\n this.calculateTraceMetrics();\r\n logTrace(this);\r\n }\r\n /**\r\n * Records a trace with predetermined values. If this method is used a trace is created and logged\r\n * directly. No need to use start and stop methods.\r\n * @param startTime Trace start time since epoch in millisec\r\n * @param duration The duraction of the trace in millisec\r\n * @param options An object which can optionally hold maps of custom metrics and custom attributes\r\n */\r\n record(startTime, duration, options) {\r\n if (startTime <= 0) {\r\n throw ERROR_FACTORY.create(\"nonpositive trace startTime\" /* ErrorCode.NONPOSITIVE_TRACE_START_TIME */, {\r\n traceName: this.name\r\n });\r\n }\r\n if (duration <= 0) {\r\n throw ERROR_FACTORY.create(\"nonpositive trace duration\" /* ErrorCode.NONPOSITIVE_TRACE_DURATION */, {\r\n traceName: this.name\r\n });\r\n }\r\n this.durationUs = Math.floor(duration * 1000);\r\n this.startTimeUs = Math.floor(startTime * 1000);\r\n if (options && options.attributes) {\r\n this.customAttributes = Object.assign({}, options.attributes);\r\n }\r\n if (options && options.metrics) {\r\n for (const metricName of Object.keys(options.metrics)) {\r\n if (!isNaN(Number(options.metrics[metricName]))) {\r\n this.counters[metricName] = Math.floor(Number(options.metrics[metricName]));\r\n }\r\n }\r\n }\r\n logTrace(this);\r\n }\r\n /**\r\n * Increments a custom metric by a certain number or 1 if number not specified. Will create a new\r\n * custom metric if one with the given name does not exist. The value will be floored down to an\r\n * integer.\r\n * @param counter Name of the custom metric\r\n * @param numAsInteger Increment by value\r\n */\r\n incrementMetric(counter, numAsInteger = 1) {\r\n if (this.counters[counter] === undefined) {\r\n this.putMetric(counter, numAsInteger);\r\n }\r\n else {\r\n this.putMetric(counter, this.counters[counter] + numAsInteger);\r\n }\r\n }\r\n /**\r\n * Sets a custom metric to a specified value. Will create a new custom metric if one with the\r\n * given name does not exist. The value will be floored down to an integer.\r\n * @param counter Name of the custom metric\r\n * @param numAsInteger Set custom metric to this value\r\n */\r\n putMetric(counter, numAsInteger) {\r\n if (isValidMetricName(counter, this.name)) {\r\n this.counters[counter] = convertMetricValueToInteger(numAsInteger !== null && numAsInteger !== void 0 ? numAsInteger : 0);\r\n }\r\n else {\r\n throw ERROR_FACTORY.create(\"invalid custom metric name\" /* ErrorCode.INVALID_CUSTOM_METRIC_NAME */, {\r\n customMetricName: counter\r\n });\r\n }\r\n }\r\n /**\r\n * Returns the value of the custom metric by that name. If a custom metric with that name does\r\n * not exist will return zero.\r\n * @param counter\r\n */\r\n getMetric(counter) {\r\n return this.counters[counter] || 0;\r\n }\r\n /**\r\n * Sets a custom attribute of a trace to a certain value.\r\n * @param attr\r\n * @param value\r\n */\r\n putAttribute(attr, value) {\r\n const isValidName = isValidCustomAttributeName(attr);\r\n const isValidValue = isValidCustomAttributeValue(value);\r\n if (isValidName && isValidValue) {\r\n this.customAttributes[attr] = value;\r\n return;\r\n }\r\n // Throw appropriate error when the attribute name or value is invalid.\r\n if (!isValidName) {\r\n throw ERROR_FACTORY.create(\"invalid attribute name\" /* ErrorCode.INVALID_ATTRIBUTE_NAME */, {\r\n attributeName: attr\r\n });\r\n }\r\n if (!isValidValue) {\r\n throw ERROR_FACTORY.create(\"invalid attribute value\" /* ErrorCode.INVALID_ATTRIBUTE_VALUE */, {\r\n attributeValue: value\r\n });\r\n }\r\n }\r\n /**\r\n * Retrieves the value a custom attribute of a trace is set to.\r\n * @param attr\r\n */\r\n getAttribute(attr) {\r\n return this.customAttributes[attr];\r\n }\r\n removeAttribute(attr) {\r\n if (this.customAttributes[attr] === undefined) {\r\n return;\r\n }\r\n delete this.customAttributes[attr];\r\n }\r\n getAttributes() {\r\n return Object.assign({}, this.customAttributes);\r\n }\r\n setStartTime(startTime) {\r\n this.startTimeUs = startTime;\r\n }\r\n setDuration(duration) {\r\n this.durationUs = duration;\r\n }\r\n /**\r\n * Calculates and assigns the duration and start time of the trace using the measure performance\r\n * entry.\r\n */\r\n calculateTraceMetrics() {\r\n const perfMeasureEntries = this.api.getEntriesByName(this.traceMeasure);\r\n const perfMeasureEntry = perfMeasureEntries && perfMeasureEntries[0];\r\n if (perfMeasureEntry) {\r\n this.durationUs = Math.floor(perfMeasureEntry.duration * 1000);\r\n this.startTimeUs = Math.floor((perfMeasureEntry.startTime + this.api.getTimeOrigin()) * 1000);\r\n }\r\n }\r\n /**\r\n * @param navigationTimings A single element array which contains the navigationTIming object of\r\n * the page load\r\n * @param paintTimings A array which contains paintTiming object of the page load\r\n * @param firstInputDelay First input delay in millisec\r\n */\r\n static createOobTrace(performanceController, navigationTimings, paintTimings, firstInputDelay) {\r\n const route = Api.getInstance().getUrl();\r\n if (!route) {\r\n return;\r\n }\r\n const trace = new Trace(performanceController, OOB_TRACE_PAGE_LOAD_PREFIX + route, true);\r\n const timeOriginUs = Math.floor(Api.getInstance().getTimeOrigin() * 1000);\r\n trace.setStartTime(timeOriginUs);\r\n // navigationTimings includes only one element.\r\n if (navigationTimings && navigationTimings[0]) {\r\n trace.setDuration(Math.floor(navigationTimings[0].duration * 1000));\r\n trace.putMetric('domInteractive', Math.floor(navigationTimings[0].domInteractive * 1000));\r\n trace.putMetric('domContentLoadedEventEnd', Math.floor(navigationTimings[0].domContentLoadedEventEnd * 1000));\r\n trace.putMetric('loadEventEnd', Math.floor(navigationTimings[0].loadEventEnd * 1000));\r\n }\r\n const FIRST_PAINT = 'first-paint';\r\n const FIRST_CONTENTFUL_PAINT = 'first-contentful-paint';\r\n if (paintTimings) {\r\n const firstPaint = paintTimings.find(paintObject => paintObject.name === FIRST_PAINT);\r\n if (firstPaint && firstPaint.startTime) {\r\n trace.putMetric(FIRST_PAINT_COUNTER_NAME, Math.floor(firstPaint.startTime * 1000));\r\n }\r\n const firstContentfulPaint = paintTimings.find(paintObject => paintObject.name === FIRST_CONTENTFUL_PAINT);\r\n if (firstContentfulPaint && firstContentfulPaint.startTime) {\r\n trace.putMetric(FIRST_CONTENTFUL_PAINT_COUNTER_NAME, Math.floor(firstContentfulPaint.startTime * 1000));\r\n }\r\n if (firstInputDelay) {\r\n trace.putMetric(FIRST_INPUT_DELAY_COUNTER_NAME, Math.floor(firstInputDelay * 1000));\r\n }\r\n }\r\n logTrace(trace);\r\n }\r\n static createUserTimingTrace(performanceController, measureName) {\r\n const trace = new Trace(performanceController, measureName, false, measureName);\r\n logTrace(trace);\r\n }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nfunction createNetworkRequestEntry(performanceController, entry) {\r\n const performanceEntry = entry;\r\n if (!performanceEntry || performanceEntry.responseStart === undefined) {\r\n return;\r\n }\r\n const timeOrigin = Api.getInstance().getTimeOrigin();\r\n const startTimeUs = Math.floor((performanceEntry.startTime + timeOrigin) * 1000);\r\n const timeToResponseInitiatedUs = performanceEntry.responseStart\r\n ? Math.floor((performanceEntry.responseStart - performanceEntry.startTime) * 1000)\r\n : undefined;\r\n const timeToResponseCompletedUs = Math.floor((performanceEntry.responseEnd - performanceEntry.startTime) * 1000);\r\n // Remove the query params from logged network request url.\r\n const url = performanceEntry.name && performanceEntry.name.split('?')[0];\r\n const networkRequest = {\r\n performanceController,\r\n url,\r\n responsePayloadBytes: performanceEntry.transferSize,\r\n startTimeUs,\r\n timeToResponseInitiatedUs,\r\n timeToResponseCompletedUs\r\n };\r\n logNetworkRequest(networkRequest);\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nconst FID_WAIT_TIME_MS = 5000;\r\nfunction setupOobResources(performanceController) {\r\n // Do not initialize unless iid is available.\r\n if (!getIid()) {\r\n return;\r\n }\r\n // The load event might not have fired yet, and that means performance navigation timing\r\n // object has a duration of 0. The setup should run after all current tasks in js queue.\r\n setTimeout(() => setupOobTraces(performanceController), 0);\r\n setTimeout(() => setupNetworkRequests(performanceController), 0);\r\n setTimeout(() => setupUserTimingTraces(performanceController), 0);\r\n}\r\nfunction setupNetworkRequests(performanceController) {\r\n const api = Api.getInstance();\r\n const resources = api.getEntriesByType('resource');\r\n for (const resource of resources) {\r\n createNetworkRequestEntry(performanceController, resource);\r\n }\r\n api.setupObserver('resource', entry => createNetworkRequestEntry(performanceController, entry));\r\n}\r\nfunction setupOobTraces(performanceController) {\r\n const api = Api.getInstance();\r\n const navigationTimings = api.getEntriesByType('navigation');\r\n const paintTimings = api.getEntriesByType('paint');\r\n // If First Input Desly polyfill is added to the page, report the fid value.\r\n // https://github.com/GoogleChromeLabs/first-input-delay\r\n if (api.onFirstInputDelay) {\r\n // If the fid call back is not called for certain time, continue without it.\r\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\r\n let timeoutId = setTimeout(() => {\r\n Trace.createOobTrace(performanceController, navigationTimings, paintTimings);\r\n timeoutId = undefined;\r\n }, FID_WAIT_TIME_MS);\r\n api.onFirstInputDelay((fid) => {\r\n if (timeoutId) {\r\n clearTimeout(timeoutId);\r\n Trace.createOobTrace(performanceController, navigationTimings, paintTimings, fid);\r\n }\r\n });\r\n }\r\n else {\r\n Trace.createOobTrace(performanceController, navigationTimings, paintTimings);\r\n }\r\n}\r\nfunction setupUserTimingTraces(performanceController) {\r\n const api = Api.getInstance();\r\n // Run through the measure performance entries collected up to this point.\r\n const measures = api.getEntriesByType('measure');\r\n for (const measure of measures) {\r\n createUserTimingTrace(performanceController, measure);\r\n }\r\n // Setup an observer to capture the measures from this point on.\r\n api.setupObserver('measure', entry => createUserTimingTrace(performanceController, entry));\r\n}\r\nfunction createUserTimingTrace(performanceController, measure) {\r\n const measureName = measure.name;\r\n // Do not create a trace, if the user timing marks and measures are created by the sdk itself.\r\n if (measureName.substring(0, TRACE_MEASURE_PREFIX.length) ===\r\n TRACE_MEASURE_PREFIX) {\r\n return;\r\n }\r\n Trace.createUserTimingTrace(performanceController, measureName);\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nclass PerformanceController {\r\n constructor(app, installations) {\r\n this.app = app;\r\n this.installations = installations;\r\n this.initialized = false;\r\n }\r\n /**\r\n * This method *must* be called internally as part of creating a\r\n * PerformanceController instance.\r\n *\r\n * Currently it's not possible to pass the settings object through the\r\n * constructor using Components, so this method exists to be called with the\r\n * desired settings, to ensure nothing is collected without the user's\r\n * consent.\r\n */\r\n _init(settings) {\r\n if (this.initialized) {\r\n return;\r\n }\r\n if ((settings === null || settings === void 0 ? void 0 : settings.dataCollectionEnabled) !== undefined) {\r\n this.dataCollectionEnabled = settings.dataCollectionEnabled;\r\n }\r\n if ((settings === null || settings === void 0 ? void 0 : settings.instrumentationEnabled) !== undefined) {\r\n this.instrumentationEnabled = settings.instrumentationEnabled;\r\n }\r\n if (Api.getInstance().requiredApisAvailable()) {\r\n validateIndexedDBOpenable()\r\n .then(isAvailable => {\r\n if (isAvailable) {\r\n setupTransportService();\r\n getInitializationPromise(this).then(() => setupOobResources(this), () => setupOobResources(this));\r\n this.initialized = true;\r\n }\r\n })\r\n .catch(error => {\r\n consoleLogger.info(`Environment doesn't support IndexedDB: ${error}`);\r\n });\r\n }\r\n else {\r\n consoleLogger.info('Firebase Performance cannot start if the browser does not support ' +\r\n '\"Fetch\" and \"Promise\", or cookies are disabled.');\r\n }\r\n }\r\n set instrumentationEnabled(val) {\r\n SettingsService.getInstance().instrumentationEnabled = val;\r\n }\r\n get instrumentationEnabled() {\r\n return SettingsService.getInstance().instrumentationEnabled;\r\n }\r\n set dataCollectionEnabled(val) {\r\n SettingsService.getInstance().dataCollectionEnabled = val;\r\n }\r\n get dataCollectionEnabled() {\r\n return SettingsService.getInstance().dataCollectionEnabled;\r\n }\r\n}\n\n/**\r\n * Firebase Performance Monitoring\r\n *\r\n * @packageDocumentation\r\n */\r\nconst DEFAULT_ENTRY_NAME = '[DEFAULT]';\r\n/**\r\n * Returns a {@link FirebasePerformance} instance for the given app.\r\n * @param app - The {@link @firebase/app#FirebaseApp} to use.\r\n * @public\r\n */\r\nfunction getPerformance(app = getApp()) {\r\n app = getModularInstance(app);\r\n const provider = _getProvider(app, 'performance');\r\n const perfInstance = provider.getImmediate();\r\n return perfInstance;\r\n}\r\n/**\r\n * Returns a {@link FirebasePerformance} instance for the given app. Can only be called once.\r\n * @param app - The {@link @firebase/app#FirebaseApp} to use.\r\n * @param settings - Optional settings for the {@link FirebasePerformance} instance.\r\n * @public\r\n */\r\nfunction initializePerformance(app, settings) {\r\n app = getModularInstance(app);\r\n const provider = _getProvider(app, 'performance');\r\n // throw if an instance was already created.\r\n // It could happen if initializePerformance() is called more than once, or getPerformance() is called first.\r\n if (provider.isInitialized()) {\r\n const existingInstance = provider.getImmediate();\r\n const initialSettings = provider.getOptions();\r\n if (deepEqual(initialSettings, settings !== null && settings !== void 0 ? settings : {})) {\r\n return existingInstance;\r\n }\r\n else {\r\n throw ERROR_FACTORY.create(\"already initialized\" /* ErrorCode.ALREADY_INITIALIZED */);\r\n }\r\n }\r\n const perfInstance = provider.initialize({\r\n options: settings\r\n });\r\n return perfInstance;\r\n}\r\n/**\r\n * Returns a new `PerformanceTrace` instance.\r\n * @param performance - The {@link FirebasePerformance} instance to use.\r\n * @param name - The name of the trace.\r\n * @public\r\n */\r\nfunction trace(performance, name) {\r\n performance = getModularInstance(performance);\r\n return new Trace(performance, name);\r\n}\r\nconst factory = (container, { options: settings }) => {\r\n // Dependencies\r\n const app = container.getProvider('app').getImmediate();\r\n const installations = container\r\n .getProvider('installations-internal')\r\n .getImmediate();\r\n if (app.name !== DEFAULT_ENTRY_NAME) {\r\n throw ERROR_FACTORY.create(\"FB not default\" /* ErrorCode.FB_NOT_DEFAULT */);\r\n }\r\n if (typeof window === 'undefined') {\r\n throw ERROR_FACTORY.create(\"no window\" /* ErrorCode.NO_WINDOW */);\r\n }\r\n setupApi(window);\r\n const perfInstance = new PerformanceController(app, installations);\r\n perfInstance._init(settings);\r\n return perfInstance;\r\n};\r\nfunction registerPerformance() {\r\n _registerComponent(new Component('performance', factory, \"PUBLIC\" /* ComponentType.PUBLIC */));\r\n registerVersion(name, version);\r\n // BUILD_TARGET will be replaced by values like esm5, esm2017, cjs5, etc during the compilation\r\n registerVersion(name, version, 'esm2017');\r\n}\r\nregisterPerformance();\n\nexport { getPerformance, initializePerformance, trace };\n//# sourceMappingURL=index.esm2017.js.map\n","/**\r\n * To find your Firebase config object:\r\n * \r\n * 1. Go to your [Project settings in the Firebase console](https://console.firebase.google.com/project/_/settings/general/)\r\n * 2. In the \"Your apps\" card, select the nickname of the app for which you need a config object.\r\n * 3. Select Config from the Firebase SDK snippet pane.\r\n * 4. Copy the config object snippet, then add it here.\r\n */\r\n//const config = {\r\n// apiKey: \"AIzaSyAfbRToAYeUc-yB6NuWpPND70N4QdpZsz8\",\r\n// authDomain: \"friendlychat-f9242.firebaseapp.com\",\r\n// databaseURL: \"https://friendlychat-f9242-default-rtdb.firebaseio.com\",\r\n// projectId: \"friendlychat-f9242\",\r\n// storageBucket: \"friendlychat-f9242.appspot.com\",\r\n// messagingSenderId: \"165780709589\",\r\n// appId: \"1:165780709589:web:15806a795ef8ec9af6025c\"\r\n//};\r\n\r\nconst config = {\r\n apiKey: \"AIzaSyCgYLUomIjhs4uA2imn5GZpF3YgyJp8hS8\",\r\n authDomain: \"gostay-1ae07.firebaseapp.com\",\r\n projectId: \"gostay-1ae07\",\r\n storageBucket: \"gostay-1ae07.appspot.com\",\r\n messagingSenderId: \"565579751675\",\r\n appId: \"1:565579751675:web:08ff3773f89159a438905e\",\r\n measurementId: \"G-NK9LLCYW8H\"\r\n};\r\n\r\nexport function getFirebaseConfig() {\r\n if (!config || !config.apiKey) {\r\n throw new Error('No Firebase configuration object provided.' + '\\n' +\r\n 'Add your web app\\'s configuration object to firebase-config.js');\r\n } else {\r\n return config;\r\n }\r\n}\r\n\r\n","/**\r\n * Copyright 2015 Google Inc. All Rights Reserved.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n'use strict';\r\n\r\n// This code is for v4 of the openai package: npmjs.com/package/openai\r\nimport OpenAI from \"openai\";\r\n\r\nconst openai = new OpenAI({\r\n apiKey: '',//process.env.OPENAI_API_KEY,\r\n dangerouslyAllowBrowser:true,\r\n});\r\n\r\n//const response = await openai.chat.completions.create({\r\n// model: \"text-davinci-003\",\r\n// messages: [],\r\n// temperature: 0,\r\n// max_tokens: 2048,\r\n//});\r\n\r\nimport { initializeApp } from 'firebase/app';\r\nimport {\r\n getAuth,\r\n onAuthStateChanged,\r\n GoogleAuthProvider,\r\n signInWithPopup,\r\n signOut,\r\n} from 'firebase/auth';\r\nimport {\r\n getFirestore,\r\n collection,\r\n addDoc,\r\n query,\r\n orderBy,\r\n limit,\r\n onSnapshot,\r\n setDoc,\r\n updateDoc,\r\n doc,\r\n serverTimestamp,\r\n} from 'firebase/firestore';\r\nimport {\r\n getStorage,\r\n ref,\r\n uploadBytesResumable,\r\n getDownloadURL,\r\n} from 'firebase/storage';\r\nimport { getMessaging, getToken, onMessage } from 'firebase/messaging';\r\n\r\n\r\n\r\nimport { getPerformance } from 'firebase/performance';\r\n\r\nimport { getFirebaseConfig } from './firebase-config.js';\r\n\r\n//const messaging = getMessaging();\r\n//onMessage(messaging, (payload) => {\r\n// console.log('Message received. ', payload);\r\n// // ...\r\n//});\r\n\r\n// Signs-in Friendly Chat.\r\nasync function signIn() {\r\n var provider = new GoogleAuthProvider();\r\n await signInWithPopup(getAuth(), provider);\r\n}\r\n\r\n// Signs-out of Friendly Chat.\r\nfunction signOutUser() {\r\n signOut(getAuth());\r\n}\r\n\r\n// Initiate firebase auth\r\nfunction initFirebaseAuth() {\r\n onAuthStateChanged(getAuth(), authStateObserver);\r\n}\r\n\r\n// Returns the signed-in user's profile Pic URL.\r\nfunction getProfilePicUrl() {\r\n return getAuth().currentUser.photoURL || '/images/profile_placeholder.png';\r\n}\r\n\r\n// Returns the signed-in user's display name.\r\nfunction getUserName() {\r\n return getAuth().currentUser.displayName;\r\n}\r\nfunction getChucVu() {\r\n return document.getElementById(\"idchucvu\").textContent;\r\n}\r\nfunction getidtopic() {\r\n return document.getElementById(\"idtopic\").textContent;\r\n}\r\nfunction settopic(idtopic) {\r\n document.getElementById(\"idtopic\").value = idtopic;\r\n}\r\n// Returns true if a user is signed-in.\r\nfunction isUserSignedIn() {\r\n return !!getAuth().currentUser;\r\n}\r\n\r\n\r\nasync function MakeAssistantAI(assistant_id, _content, _ChatPath) {\r\n\r\n // alert(assistant_id);\r\n\r\n console.log('MakeAssistantAI: ' + _content);\r\n\r\n displayMessage('open-ai', \"Trợ lý ảo\", 'message-loading-chat', null, \"Sgoland AI\", '', 'https://sgoland.vn/assets/img/logo2.jpg', '')\r\n\r\n const thread = await openai.beta.threads.create();\r\n\r\n await openai.beta.threads.messages.create(\r\n thread.id,\r\n {\r\n role: \"user\",\r\n content: _content\r\n },\r\n {\r\n headers: {\r\n \"OpenAI-Beta\": \"assistants=v2\", // Thêm header tại đây\r\n },\r\n }\r\n );\r\n const run = await openai.beta.threads.runs.create(\r\n thread.id,\r\n {\r\n assistant_id: assistant_id,\r\n },\r\n {\r\n headers: {\r\n \"OpenAI-Beta\": \"assistants=v2\", // Thêm header tại đây\r\n },\r\n }\r\n )\r\n var div = document.getElementById('message-loading-chat');\r\n var messageElement = div.querySelector('.message');\r\n loadingAI.style.display = \"block\";\r\n var content = '';\r\n while (run.status != \"completed\") {\r\n const run_response = await openai.beta.threads.runs.retrieve(\r\n thread.id,\r\n run.id\r\n );\r\n\r\n const messages = await openai.beta.threads.messages.list(\r\n thread.id\r\n );\r\n\r\n if (run_response.status == 'completed') {\r\n\r\n content = messages.body.data[0].content[0].text.value;\r\n\r\n await addDoc(collection(getFirestore(), _ChatPath), {\r\n userid: 'open-ai',\r\n name: \"Sgoland AI\",\r\n chucvu: 'Trợ lý ảo',\r\n text: content,//completion.choices[0].message.content,\r\n incoming: 0,\r\n profilePicUrl: 'https://sgoland.vn/assets/img/logo2.jpg',\r\n timestamp: serverTimestamp()\r\n });\r\n\r\n break;\r\n }\r\n }\r\n\r\n loadingAI.style.display = \"none\";\r\n document.getElementById(\"message-loading-chat\").remove();\r\n}\r\n\r\n\r\nasync function MakeChatAI(_content, _ChatPath) {\r\n\r\n try {\r\n\r\n console.log('make2: ' + _content);\r\n\r\n displayMessage('open-ai', \"Trợ lý ảo\", 'message-loading-chat', null, \"Sgoland AI\", '', 'https://sgoland.vn/assets/img/logo2.jpg','')\r\n\r\n var div = document.getElementById('message-loading-chat');\r\n\r\n \r\n var messageElement = div.querySelector('.message');\r\n\r\n\r\n loadingAI.style.display = \"block\";\r\n const completion = await openai.chat.completions.create({\r\n messages: [{ role: \"user\", content: _content }],\r\n model:\"ft:gpt-3.5-turbo-0613:personal::8IxFrhnT\",\r\n stream: true,\r\n });\r\n\r\n var content = '';\r\n\r\n for await (const chunk of completion) {\r\n if (chunk.choices[0].delta.content) {\r\n content += chunk.choices[0].delta.content;\r\n messageElement.innerHTML = content\r\n console.log(content);\r\n }\r\n }\r\n //console.log('tra loi: ' + completion.choices[0].message.content);\r\n\r\n await addDoc(collection(getFirestore(), _ChatPath), {\r\n userid: 'open-ai',\r\n name: \"Sgoland AI\",\r\n chucvu: 'Trợ lý ảo',\r\n text: content,//completion.choices[0].message.content,\r\n incoming: 0,\r\n profilePicUrl: 'https://sgoland.vn/assets/img/logo2.jpg',\r\n timestamp: serverTimestamp()\r\n });\r\n\r\n loadingAI.style.display = \"none\";\r\n document.getElementById(\"message-loading-chat\").remove();\r\n \r\n } catch (error) {\r\n\r\n if (error.response) {\r\n console.error(error.response.status, error.response.data);\r\n } else {\r\n console.error(`Error with OpenAI API request: ${error.message}`);\r\n }\r\n\r\n\r\n loadingAI.style.display = \"none\";\r\n }\r\n \r\n \r\n}\r\n\r\n//console.log(main(\"làm một bài thơ về bất động sản nhé\"));\r\n\r\n// Saves a new message on the Cloud Firestore.\r\n\r\n//async function saveMessage(messageText) {\r\n// try {\r\n// await addDoc(collection(getFirestore(), 'messages'), {\r\n// userid: getAuth().currentUser.uid,\r\n// name: getUserName(),\r\n// chucvu: getChucVu(),\r\n// text: messageText,\r\n// profilePicUrl: getProfilePicUrl(),\r\n// timestamp: serverTimestamp()\r\n// });\r\n// }\r\n// catch (error) {\r\n// console.error('Error writing new message to Firebase Database', error);\r\n// }\r\n//}\r\n\r\n\r\nasync function saveMessagetoPic(idTopic, messageText, mainChat) {\r\n console.log(idTopic);\r\n try {\r\n\r\n const _ChatPath = `${mainChat}/${idTopic}/messages`;\r\n await addDoc(collection(getFirestore(), _ChatPath), {\r\n userid: getAuth().currentUser.uid,\r\n name: getUserName(),\r\n chucvu: getChucVu(),\r\n asstId: _assistant_id,//\"asst_RcuNIfuNDlp7E6kb98fnneIU\",\r\n text: messageText,\r\n incoming: 1,\r\n profilePicUrl: getProfilePicUrl(),\r\n timestamp: serverTimestamp()\r\n });\r\n\r\n if (mainChat == 'chatassistants') {\r\n if (_assistant_id) {\r\n MakeAssistantAI(_assistant_id, messageText, _ChatPath);\r\n }\r\n else {\r\n MakeChatAI(messageText, _ChatPath);\r\n }\r\n }\r\n \r\n }\r\n catch (error) {\r\n console.error('Error writing new message to Firebase Database', error);\r\n }\r\n}\r\n\r\n// Loads chat messages history and listens for upcoming ones.\r\nfunction loadMessages(idTopic, mainChat) {\r\n if (idTopic) {\r\n const _ChatPath = `${mainChat}/${idTopic}/messages`;\r\n const recentMessagesQuery = query(collection(getFirestore(), _ChatPath), orderBy('timestamp', 'desc'), limit(12));\r\n\r\n // Start listening to the query.\r\n onSnapshot(recentMessagesQuery, function (snapshot) {\r\n snapshot.docChanges().forEach(function (change) {\r\n if (change.type === 'removed') {\r\n deleteMessage(change.doc.id);\r\n } else {\r\n var message = change.doc.data();\r\n displayMessage(message.userid, message.chucvu, change.doc.id, message.timestamp, message.name,\r\n message.text, message.profilePicUrl, message.imageUrl);\r\n }\r\n });\r\n });\r\n\r\n const _ChatPathUser = `${mainChat}/${idTopic}/userlist/${getAuth().currentUser.uid}`;\r\n\r\n var docRef = doc(getFirestore(), _ChatPathUser);\r\n\r\n setDoc(docRef, { on: 1 });\r\n\r\n\r\n loadingAI.style.display = \"none\";\r\n }\r\n // Create the query to load the last 12 messages and listen for new ones.\r\n \r\n}\r\n\r\n// Saves a new message containing an image in Firebase.\r\n// This first saves the image in Firebase storage.\r\nasync function saveImageMessage(file, idTopic, mainChat) {\r\n try {\r\n // 1 - We add a message with a loading icon that will get updated with the shared image.\r\n const _ChatPath = `${mainChat}/${idTopic}/messages`;\r\n const messageRef = await addDoc(collection(getFirestore(), _ChatPath), {\r\n userid: getAuth().currentUser.uid,\r\n name: getUserName(),\r\n chucvu: getChucVu(),\r\n imageUrl: LOADING_IMAGE_URL,\r\n profilePicUrl: getProfilePicUrl(),\r\n timestamp: serverTimestamp()\r\n });\r\n\r\n // 2 - Upload the image to Cloud Storage.\r\n const filePath = `${getAuth().currentUser.uid}/${messageRef.id}/${file.name}`;\r\n const newImageRef = ref(getStorage(), filePath);\r\n const fileSnapshot = await uploadBytesResumable(newImageRef, file);\r\n\r\n // 3 - Generate a public URL for the file.\r\n const publicImageUrl = await getDownloadURL(newImageRef);\r\n\r\n // 4 - Update the chat message placeholder with the image’s URL.\r\n await updateDoc(messageRef, {\r\n imageUrl: publicImageUrl,\r\n storageUri: fileSnapshot.metadata.fullPath\r\n });\r\n } catch (error) {\r\n console.error('There was an error uploading a file to Cloud Storage:', error);\r\n }\r\n}\r\n\r\n// Saves the messaging device token to Cloud Firestore.\r\nasync function saveMessagingDeviceToken() {\r\n try {\r\n const currentToken = await getToken(getMessaging());\r\n if (currentToken) {\r\n console.log('Got FCM device token:', currentToken);\r\n\r\n onMessage(getMessaging(), (message) => {\r\n console.log(\r\n 'New foreground notification from Firebase Messaging!',\r\n message.notification\r\n );\r\n });\r\n\r\n const tokenRef = doc(getFirestore(), 'fcmTokens', getAuth().currentUser.uid);\r\n\r\n localStorage.setItem(\"currentToken\", currentToken);\r\n\r\n await setDoc(tokenRef, { token: currentToken });\r\n\r\n } else {\r\n // Need to request permissions to show notifications.\r\n requestNotificationsPermissions();\r\n }\r\n } catch (error) {\r\n console.error('Unable to get messaging token.', error);\r\n };\r\n}\r\n\r\n// Requests permissions to show notifications.\r\nasync function requestNotificationsPermissions() {\r\n console.log('Requesting notifications permission...');\r\n const permission = await Notification.requestPermission();\r\n\r\n if (permission === 'granted') {\r\n console.log('Notification permission granted.');\r\n // Notification permission granted.\r\n await saveMessagingDeviceToken();\r\n } else {\r\n console.log('Unable to get permission to notify.');\r\n }\r\n}\r\n\r\n// Triggered when a file is selected via the media picker.\r\nfunction onMediaFileSelected(event) {\r\n event.preventDefault();\r\n var file = event.target.files[0];\r\n\r\n // Clear the selection in the file picker input.\r\n imageFormElement.reset();\r\n\r\n // Check if the file is an image.\r\n if (!file.type.match('image.*')) {\r\n var data = {\r\n message: 'You can only share images',\r\n timeout: 2000,\r\n };\r\n //signInSnackbarElement.MaterialSnackbar.showSnackbar(data);\r\n return;\r\n }\r\n // Check if the user is signed-in\r\n if (checkSignedInWithMessage()) {\r\n saveImageMessage(file, idtopic, mainChat);\r\n }\r\n}\r\n\r\n// Triggered when the send new message form is submitted.\r\nfunction onMessageFormSubmit(e) {\r\n e.preventDefault();\r\n // Check that the user entered a message and is signed in.\r\n if (messageInputElement.value && checkSignedInWithMessage()) {\r\n saveMessagetoPic(idtopic, messageInputElement.value, mainChat).then(function () {\r\n // Clear message text field and re-enable the SEND button.\r\n resetMaterialTextfield(messageInputElement);\r\n toggleButton();\r\n });\r\n }\r\n}\r\n\r\n// Triggers when the auth state change for instance when the user signs-in or signs-out.\r\nfunction authStateObserver(user) {\r\n if (user) {\r\n // User is signed in!\r\n // Get the signed-in user's profile pic and name.\r\n var profilePicUrl = getProfilePicUrl();\r\n var userName = getUserName();\r\n\r\n\r\n // Set the user's profile pic and name.\r\n userPicElement.style.backgroundImage =\r\n 'url(' + addSizeToGoogleProfilePic(profilePicUrl) + ')';\r\n userNameElement.textContent = userName;\r\n\r\n // Show user's profile and sign-out button.\r\n userNameElement.removeAttribute('hidden');\r\n userPicElement.removeAttribute('hidden');\r\n signOutButtonElement.removeAttribute('hidden');\r\n\r\n // Hide sign-in button.\r\n signInButtonElement.setAttribute('hidden', 'true');\r\n\r\n // We save the Firebase Messaging Device token and enable notifications.\r\n\r\n saveMessagingDeviceToken();\r\n\r\n \r\n \r\n\r\n } else {\r\n // User is signed out!\r\n // Hide user's profile and sign-out button.\r\n userNameElement.setAttribute('hidden', 'true');\r\n userPicElement.setAttribute('hidden', 'true');\r\n signOutButtonElement.setAttribute('hidden', 'true');\r\n // Show sign-in button.\r\n signInButtonElement.removeAttribute('hidden');\r\n }\r\n}\r\n\r\n// Returns true if user is signed-in. Otherwise false and displays a message.\r\nfunction checkSignedInWithMessage() {\r\n // Return true if the user is signed in Firebase\r\n if (isUserSignedIn()) {\r\n return true;\r\n }\r\n\r\n // Display a message to the user using a Toast.\r\n var data = {\r\n message: 'You must sign-in first',\r\n timeout: 2000,\r\n };\r\n // signInSnackbarElement.MaterialSnackbar.showSnackbar(data);\r\n return false;\r\n}\r\n\r\n// Resets the given MaterialTextField.\r\nfunction resetMaterialTextfield(element) {\r\n element.value = '';\r\n // element.parentNode.MaterialTextfield.boundUpdateClassesHandler();\r\n}\r\n\r\n// Template for messages.\r\nvar MESSAGE_TEMPLATE =\r\n '
'+\r\n '
'+\r\n '
' +\r\n '
' +\r\n '
' +\r\n '
' +\r\n '
' +\r\n '
' +\r\n '' +\r\n '' +\r\n '
' +\r\n '
' +\r\n '
' +\r\n '
' +\r\n '
' +\r\n '
' +\r\n '
' +\r\n '
' +\r\n '
' +\r\n '
';\r\n\r\nvar MY_MESSAGE_TEMPLATE =\r\n '
' +\r\n '
' +\r\n '
' +\r\n '
' +\r\n '
' +\r\n '
' +\r\n '
' +\r\n '
' +\r\n '' +\r\n '' +\r\n '
' +\r\n '
' +\r\n '
' +\r\n '
' +\r\n '
' +\r\n '
' +\r\n '
' +\r\n '
' +\r\n '
' +\r\n '
';\r\n\r\n// Adds a size to Google Profile pics URLs.\r\nfunction addSizeToGoogleProfilePic(url) {\r\n if (url.indexOf('googleusercontent.com') !== -1 && url.indexOf('?') === -1) {\r\n return url + '?sz=150';\r\n }\r\n return url;\r\n}\r\n\r\n// A loading image URL.\r\nvar LOADING_IMAGE_URL = 'https://www.google.com/images/spin-32.gif?a';\r\n\r\n// Delete a Message from the UI.\r\nfunction deleteMessage(id) {\r\n var div = document.getElementById(id);\r\n // If an element for that message exists we delete it.\r\n if (div) {\r\n div.parentNode.removeChild(div);\r\n }\r\n}\r\n\r\nfunction createAndInsertMessage(userid, id, timestamp) {\r\n const container = document.createElement('div');\r\n if (userid == getAuth().currentUser.uid) {\r\n container.innerHTML = MY_MESSAGE_TEMPLATE;\r\n }\r\n else {\r\n container.innerHTML = MESSAGE_TEMPLATE;\r\n }\r\n \r\n const div = container.firstChild;\r\n div.setAttribute('id', id);\r\n\r\n // If timestamp is null, assume we've gotten a brand new message.\r\n // https://stackoverflow.com/a/47781432/4816918\r\n timestamp = timestamp ? timestamp.toMillis() : Date.now();\r\n div.setAttribute('timestamp', timestamp);\r\n\r\n // figure out where to insert new message\r\n const existingMessages = messageListElement.children;\r\n if (existingMessages.length === 0) {\r\n messageListElement.appendChild(div);\r\n } else {\r\n let messageListNode = existingMessages[0];\r\n\r\n while (messageListNode) {\r\n const messageListNodeTime = messageListNode.getAttribute('timestamp');\r\n\r\n if (!messageListNodeTime) {\r\n throw new Error(\r\n `Child ${messageListNode.id} has no 'timestamp' attribute`\r\n );\r\n }\r\n\r\n if (messageListNodeTime > timestamp) {\r\n break;\r\n }\r\n\r\n messageListNode = messageListNode.nextSibling;\r\n }\r\n\r\n messageListElement.insertBefore(div, messageListNode);\r\n }\r\n\r\n return div;\r\n}\r\n\r\n// Displays a Message in the UI.\r\nfunction displayMessage(userid,chucvu, id, timestamp, name, text, picUrl, imageUrl) {\r\n var div = document.getElementById(id) || createAndInsertMessage(userid, id, timestamp);\r\n\r\n // profile picture\r\n if (picUrl) {\r\n div.querySelector('.pic').style.backgroundImage =\r\n 'url(' + addSizeToGoogleProfilePic(picUrl) + ')';\r\n }\r\n\r\n div.querySelector('.name').textContent = name;\r\n div.querySelector('.chucvu').textContent = chucvu;\r\n var messageElement = div.querySelector('.message');\r\n\r\n if (text) {\r\n // If the message is text.\r\n messageElement.textContent = text;\r\n // Replace all line breaks by
.\r\n messageElement.innerHTML = urlify(messageElement.innerHTML.replace(/\\n/g, '
'));\r\n } else if (imageUrl) {\r\n // If the message is an image.\r\n var image = document.createElement('img');\r\n image.addEventListener('load', function () {\r\n messageListElement.scrollTop = messageListElement.scrollHeight;\r\n });\r\n image.src = imageUrl + '&' + new Date().getTime();\r\n messageElement.innerHTML = '';\r\n messageElement.appendChild(image);\r\n }\r\n // Show the card fading-in and scroll to view the new message.\r\n setTimeout(function () {\r\n div.classList.add('visible');\r\n }, 1);\r\n messageListElement.scrollTop = messageListElement.scrollHeight;\r\n messageInputElement.focus();\r\n}\r\n\r\n// Enables or disables the submit button depending on the values of the input\r\n// fields.\r\nfunction toggleButton() {\r\n if (messageInputElement.value) {\r\n submitButtonElement.removeAttribute('disabled');\r\n } else {\r\n submitButtonElement.setAttribute('disabled', 'true');\r\n }\r\n}\r\nfunction urlify(text) {\r\n var urlRegex = /(https?:\\/\\/[^\\s()]+(?:\\([^\\s()]*\\)[^\\s()]*)*)/g;\r\n return text.replace(urlRegex, function (url) {\r\n return '' + url + '';\r\n })\r\n // or alternatively\r\n // return text.replace(urlRegex, '$1')\r\n}\r\nvar mainChat = \"chatda\";\r\n\r\nvar _assistant_id = \"asst_RcuNIfuNDlp7E6kb98fnneIU\";\r\n\r\nvar binchat = function () {\r\n if (isUserSignedIn()) {\r\n\r\n idtopic = this.getAttribute(\"data-topicid\") || getAuth().currentUser.uid;\r\n document.getElementById(\"IDtopicthumbnai\").src = this.getAttribute(\"data-topicthumbnai\");\r\n document.getElementById(\"IDtopicname\").textContent = this.getAttribute(\"data-topicname\");\r\n document.getElementById('idtopic').value = idtopic;\r\n document.getElementById(\"messages\").innerHTML = \"\";\r\n\r\n if (this.getAttribute(\"data-assistantid\")) {\r\n _assistant_id = this.getAttribute(\"data-assistantid\");\r\n }\r\n\r\n if (this.getAttribute(\"data-mainchat\")) {\r\n mainChat = this.getAttribute(\"data-mainchat\");\r\n subnamechat.innerText = \"Trợ lý ảo\";\r\n }\r\n else {\r\n subnamechat.innerText = \"Trợ lý ảo\";\r\n mainChat = \"chatda\";\r\n }\r\n loadMessages(idtopic, mainChat);\r\n\r\n const toastLiveExample = document.getElementById('toast-chat-wellcome');\r\n const toast = new bootstrap.Offcanvas(toastLiveExample);\r\n\r\n toastLiveExample.addEventListener('hidden.bs.offcanvas', function () {\r\n\r\n const path = `${mainChat}/${idtopic}/userlist/${getAuth().currentUser.uid}`;\r\n var docRef = doc(getFirestore(), path);\r\n\r\n updateDoc(docRef, {\r\n on:0\r\n });\r\n\r\n console.log('hidden offcanvas' + path);\r\n })\r\n\r\n var currentToken = localStorage.getItem(\"currentToken\");\r\n\r\n if (currentToken) {\r\n\r\n const registrationTokens = [];\r\n registrationTokens.push(currentToken);\r\n }\r\n\r\n toast.show();\r\n }\r\n else {\r\n let text = \"Xác thực tài khoản email là chính tài khoản bạn đã đăng nhập.\";\r\n if (confirm(text) == true) {\r\n signIn();\r\n } else {\r\n }\r\n \r\n }\r\n \r\n};\r\n\r\nvar classnameChat = document.getElementsByClassName(\"binchat\");\r\n\r\nfor (var i = 0; i < classnameChat.length; i++) {\r\n (function (index) {\r\n classnameChat[index].addEventListener(\"click\", binchat);\r\n })(i);\r\n}\r\n\r\nvar signInButtonElement = document.getElementById('sign-in');\r\nsignInButtonElement.addEventListener('click', signIn);\r\nvar messageListElement = document.getElementById('messages');\r\nvar messageFormElement = document.getElementById('message-form');\r\nvar messageInputElement = document.getElementById('message');\r\n\r\nvar submitButtonElement = document.getElementById('submit');\r\nvar subnamechat = document.getElementById('subnamechat');\r\n\r\nvar imageButtonElement = document.getElementById('submitImage');\r\nvar imageFormElement = document.getElementById('image-form');\r\nvar mediaCaptureElement = document.getElementById('mediaCapture');\r\n\r\nvar userPicElement = document.getElementById('user-pic');\r\nvar userNameElement = document.getElementById('user-name');\r\nvar loadingAI = document.getElementById('ailoading');\r\n\r\nvar signOutButtonElement = document.getElementById('sign-out');\r\nsignOutButtonElement.addEventListener('click', signOutUser);\r\n//var signInSnackbarElement = document.getElementById('must-signin-snackbar');\r\n\r\n\r\ninitializeApp(getFirebaseConfig());\r\ngetPerformance();\r\ninitFirebaseAuth();\r\n\r\n\r\n// Saves message on form submit.\r\nvar idtopic = document.getElementById('idtopic').value;\r\nmessageFormElement.addEventListener('submit', onMessageFormSubmit);\r\n\r\n\r\n\r\n\r\n\r\n// Toggle for the button.\r\nmessageInputElement.addEventListener('keyup', toggleButton);\r\nmessageInputElement.addEventListener('change', toggleButton);\r\n\r\n// Events for image upload.\r\nimageButtonElement.addEventListener('click', function (e) {\r\n e.preventDefault();\r\n mediaCaptureElement.click();\r\n});\r\nmediaCaptureElement.addEventListener('change', onMediaFileSelected);\r\n\r\n\r\n\r\n// const firebaseAppConfig = getFirebaseConfig();\r\n\r\n\r\n// TODO 12: Initialize Firebase Performance Monitoring\r\n\r\n//loadMessages(idtopic, mainChat);"],"names":["__webpack_require__","g","globalThis","this","Function","e","window","default_format","formatters","RFC1738","v","String","replace","RFC3986","is_array","Object","prototype","hasOwnProperty","Array","isArray","hex_table","array","i","push","toString","toUpperCase","limit","maybe_map","val","fn","mapped","length","array_prefix_generators","brackets","prefix","comma","indices","key","repeat","push_to_array","arr","value_or_array","apply","to_ISO","Date","toISOString","defaults","addQueryPrefix","allowDots","allowEmptyArrays","arrayFormat","charset","charsetSentinel","delimiter","encode","encodeDotInKeys","encoder","str","_defaultEncoder","_kind","format","string","Symbol","call","escape","$0","parseInt","slice","out","j","segment","c","charCodeAt","charAt","join","encodeValuesOnly","formatter","serializeDate","date","skipNulls","strictNullHandling","sentinel","inner_stringify","object","generateArrayPrefix","commaRoundTrip","filter","sort","sideChannel","obj","tmp_sc","step","find_flag","get","pos","RangeError","value","is_non_nullish_primitive","constructor","isBuffer","is_buffer","key_value","values","obj_keys","keys","encoded_prefix","adjusted_prefix","encoded_key","key_prefix","set","valueSideChannel","WeakMap","VERSION","kind","getDefaultAgent","fileFromPath","isFsReadStream","auto","MultipartBody","body","toStringTag","shims","options","Error","fetch","Request","Response","Headers","FormData","Blob","File","ReadableStream","getMultipartRequestOptions","manuallyImported","recommendation","_fetch","_Request","_Response","_Headers","error","message","async","form","opts","url","APIError","status","headers","super","makeMessage","request_id","data","code","param","type","msg","JSON","stringify","generate","errorResponse","APIConnectionError","cause","castToError","BadRequestError","AuthenticationError","PermissionDeniedError","NotFoundError","ConflictError","UnprocessableEntityError","RateLimitError","InternalServerError","APIUserAbortError","undefined","APIConnectionTimeoutError","LengthFinishReasonError","ContentFilterFinishReasonError","_LineDecoder_carriageReturnIndex","__classPrivateFieldSet","receiver","state","f","TypeError","has","__classPrivateFieldGet","buffer","Uint8Array","decode","chunk","binaryChunk","ArrayBuffer","TextEncoder","newData","lines","patternIndex","findNewlineIndex","carriage","index","decodeText","endIndex","preceding","line","bytes","Buffer","from","name","TextDecoder","textDecoder","flush","startIndex","ReadableStreamToAsyncIterable","stream","asyncIterator","reader","getReader","next","result","read","done","releaseLock","cancelPromise","cancel","NEWLINE_CHARS","Set","NEWLINE_REGEXP","Stream","iterator","controller","fromSSEResponse","response","consumed","sse","abort","sseDecoder","SSEDecoder","lineDecoder","iter","sseChunk","findDoubleNewlineIndex","iterSSEChunks","_iterSSEMessages","startsWith","event","parse","console","raw","fromReadableStream","readableStream","iterLines","tee","left","right","teeIterator","queue","shift","toReadableStream","self","start","pull","ctrl","close","enqueue","err","return","chunks","endsWith","substring","fieldname","_","indexOf","partition","isResponseLike","blob","isFileLike","lastModified","isBlobLike","size","text","arrayBuffer","toFile","URL","pathname","split","pop","bits","parts","isView","isAsyncIterableIterator","getOwnPropertyNames","map","p","propsForError","getBytes","getStringFromMaybeBuffer","filename","path","getName","x","isMultipartBody","multipartFormRequestOptions","createForm","Promise","all","entries","addFormValue","append","isUploadable","file","entry","prop","_AbstractPage_client","defaultParseResponse","props","debug","__streamClass","__binaryResponse","contentType","includes","json","_addRequestID","defineProperty","enumerable","APIPromise","responsePromise","parseResponse","resolve","_thenUnwrap","transform","asResponse","then","withResponse","parsedPromise","onfulfilled","onrejected","catch","onfinally","finally","APIClient","baseURL","maxRetries","timeout","httpAgent","overriddenFetch","validatePositiveInteger","authHeaders","defaultHeaders","Accept","getUserAgent","getPlatformHeaders","validateHeaders","customHeaders","defaultIdempotencyKey","uuid4","methodRequest","post","patch","put","method","request","DataView","getAPIList","Page","requestAPIList","calculateContentLength","byteLength","buildRequest","retryCount","query","__binaryRequest","contentLength","buildURL","minAgentTimeout","idempotencyHeader","idempotencyKey","req","buildHeaders","agent","signal","reqHeaders","applyHeadersMut","getHeader","prepareOptions","prepareRequest","parseHeaders","fromEntries","header","makeStatusError","remainingRetries","makeRequest","optionsInput","retriesRemaining","aborted","AbortController","fetchWithTimeout","retryRequest","responseHeaders","createResponseHeaders","ok","shouldRetry","errText","errJSON","safeJSON","errMessage","PagePromise","isAbsoluteURL","defaultQuery","isEmptyObj","search","stringifyQuery","encodeURIComponent","init","ms","addEventListener","setTimeout","fetchOptions","clearTimeout","shouldRetryHeader","timeoutMillis","retryAfterMillisHeader","timeoutMs","parseFloat","Number","isNaN","retryAfterHeader","timeoutSeconds","now","calculateDefaultRetryTimeoutMillis","sleep","numRetries","Math","min","pow","random","AbstractPage","client","hasNextPage","getPaginatedItems","nextPageInfo","getNextPage","nextInfo","nextOptions","params","searchParams","iterPages","page","item","Proxy","target","toLowerCase","requestOptionsKeys","__metadata","isRequestOptions","every","k","hasOwn","normalizeArch","arch","normalizePlatform","platform","_platformHeaders","Deno","build","os","version","deno","EdgeRuntime","process","browserInfo","navigator","browserPatterns","pattern","match","exec","userAgent","browser","getBrowserInfo","getPlatformProperties","startsWithSchemeRegexp","test","n","isInteger","readEnv","env","trim","_k","targetHeaders","newHeaders","lowerKey","SENSITIVE_HEADERS","action","args","modifiedArgs","arg","modifiedArg","log","r","lowerCasedHeader","isHeadersProtocol","intercapsHeader","_m","g1","g2","warn","isObj","APIResource","_client","Completions","create","Messages","list","completionId","ChatCompletionStoreMessagesPage","nextPageParams","CursorPage","has_more","info","id","after","arguments","messages","retrieve","update","ChatCompletionsPage","del","delete","Chat","completions","Embeddings","Files","fileId","FileObjectsPage","content","retrieveContent","waitForProcessing","pollInterval","maxWait","TERMINAL_STATES","Images","createVariation","edit","Speech","Transcriptions","model","Translations","Audio","transcriptions","translations","speech","Moderations","Models","ModelsPage","Checkpoints","fineTuningJobId","FineTuningJobCheckpointsPage","Jobs","checkpoints","FineTuningJobsPage","listEvents","FineTuningJobEventsPage","FineTuning","jobs","Assistants","assistantId","AssistantsPage","isRunnableFunctionWithParse","isAssistantMessage","role","isFunctionMessage","isToolMessage","_EventStream_instances","_EventStream_connectedPromise","_EventStream_resolveConnectedPromise","_EventStream_rejectConnectedPromise","_EventStream_endPromise","_EventStream_resolveEndPromise","_EventStream_rejectEndPromise","_EventStream_listeners","_EventStream_ended","_EventStream_errored","_EventStream_aborted","_EventStream_catchingPromiseCreated","_EventStream_handleError","EventStream","add","reject","_run","executor","_emitFinal","_emit","bind","_connected","ended","errored","on","listener","off","listeners","findIndex","l","splice","once","emitted","forEach","isAutoParsableResponseFormat","response_format","isAutoParsableTool","tool","parseChatCompletion","completion","choices","choice","finish_reason","tool_calls","toolCall","inputTool","tools","find","function","parsed_arguments","$parseRaw","strict","parseToolCall","parsed","refusal","parseResponseFormat","shouldParseToolCall","hasAutoParseableInput","some","t","WeakSet","openAIError","_AbstractChatCompletionRunner_instances","_AbstractChatCompletionRunner_getFinalContent","_AbstractChatCompletionRunner_getFinalMessage","_AbstractChatCompletionRunner_getFinalFunctionCall","_AbstractChatCompletionRunner_getFinalFunctionCallResult","_AbstractChatCompletionRunner_calculateTotalUsage","_AbstractChatCompletionRunner_validateParams","_AbstractChatCompletionRunner_stringifyFunctionCallResult","DEFAULT_MAX_CHAT_COMPLETIONS","AbstractChatCompletionRunner","_chatCompletions","_addChatCompletion","chatCompletion","_addMessage","emit","function_call","tool_call","finalChatCompletion","finalContent","finalMessage","finalFunctionCall","finalFunctionCallResult","totalUsage","allChatCompletions","usage","_createChatCompletion","chat","_runChatCompletion","_runFunctions","restParams","singleFunctionToCall","maxChatCompletions","functionsByName","functions","parameters","description","rawContent","_runTools","tool_choice","inputTools","$callback","tool_call_id","rest","ret","at","y","total","completion_tokens","prompt_tokens","total_tokens","ChatCompletionRunner","runFunctions","runner","runTools","PartialJSON","MalformedJSON","partialParse","input","jsonString","allowPartial","ATOM","allow","markPartialJSON","throwMalformedError","parseAny","skipBlank","parseStr","parseObj","parseArr","Infinity","NaN","parseNum","lastIndexOf","writable","configurable","_parseJSON","parseJSON","Allow","_ChatCompletionStream_instances","_ChatCompletionStream_params","_ChatCompletionStream_choiceEventStates","_ChatCompletionStream_currentChatCompletionSnapshot","_ChatCompletionStream_beginRequest","_ChatCompletionStream_getChoiceEventState","_ChatCompletionStream_addChunk","_ChatCompletionStream_emitToolCallDoneEvent","_ChatCompletionStream_emitContentDoneEvents","_ChatCompletionStream_endRequest","_ChatCompletionStream_getAutoParseableResponseFormat","_ChatCompletionStream_accumulateChatCompletion","ChatCompletionStream","currentChatCompletionSnapshot","_fromReadableStream","createChatCompletion","chatId","content_done","refusal_done","logprobs_content_done","logprobs_refusal_done","done_tool_calls","current_tool_call_index","choiceSnapshot","delta","snapshot","logprobs","toolCallDelta","toolCallSnapshot","arguments_delta","toolCallIndex","responseFormat","created","system_fingerprint","choiceRest","messageRest","toolRest","fnRest","maybeParseChatCompletion","finalizeChatCompletion","_a","_b","_c","_d","assign","other","pushQueue","readQueue","ChatCompletionStreamingRunner","validateInputTools","Sessions","Realtime","sessions","_AssistantStream_instances","_AssistantStream_events","_AssistantStream_runStepSnapshots","_AssistantStream_messageSnapshots","_AssistantStream_messageSnapshot","_AssistantStream_finalRun","_AssistantStream_currentContentIndex","_AssistantStream_currentContent","_AssistantStream_currentToolCallIndex","_AssistantStream_currentToolCall","_AssistantStream_currentEvent","_AssistantStream_currentRunSnapshot","_AssistantStream_currentRunStepSnapshot","_AssistantStream_addEvent","_AssistantStream_endRequest","_AssistantStream_handleMessage","_AssistantStream_handleRunStep","_AssistantStream_handleEvent","_AssistantStream_accumulateRunStep","_AssistantStream_accumulateMessage","_AssistantStream_accumulateContent","_AssistantStream_handleRun","AssistantStream","_addRun","createToolAssistantStream","threadId","runId","runs","_runToolAssistantStream","_createToolAssistantStream","run","submitToolOutputs","createThreadAssistantStream","thread","_threadAssistantStream","createAssistantStream","_runAssistantStream","currentEvent","currentRun","currentMessageSnapshot","currentRunStepSnapshot","finalRunSteps","finalMessages","finalRun","_createThreadAssistantStream","createAndRun","_createAssistantStream","accumulateDelta","acc","deltaValue","accValue","deltaEntry","accEntry","accumulatedMessage","newContent","snapshotContent","textDelta","image_file","currentContent","accumulatedRunStep","step_details","accumulated","contentElement","messageId","MessagesPage","Steps","stepId","RunStepsPage","Runs","steps","include","RunsPage","createAndPoll","poll","createAndStream","beta","threads","pollIntervalMs","sleepInterval","headerInterval","headerIntervalMs","submitToolOutputsAndPoll","submitToolOutputsStream","Threads","createAndRunPoll","thread_id","createAndRunStream","vectorStoreId","VectorStoreFilesPage","fileResponse","upload","fileInfo","files","purpose","file_id","uploadAndPoll","FileBatches","batchId","batch","listFiles","fileIds","configuredConcurrency","maxConcurrency","concurrencyLimit","fileIterator","allFileIds","workers","fill","fileObj","promises","results","allSettled","rejected","reason","allSettledWithThrow","file_ids","VectorStores","fileBatches","VectorStoresPage","Beta","realtime","vectorStores","assistants","Batches","BatchesPage","Parts","uploadId","Uploads","complete","OpenAI","apiKey","organization","project","dangerouslyAllowBrowser","document","embeddings","images","audio","moderations","models","fineTuning","batches","uploads","_options","Authorization","normalize_stringify_options","joined","DEFAULT_TIMEOUT","OpenAIError","stringToByteArray$1","base64","byteToCharMap_","charToByteMap_","byteToCharMapWebSafe_","charToByteMapWebSafe_","ENCODED_VALS_BASE","ENCODED_VALS","ENCODED_VALS_WEBSAFE","HAS_NATIVE_SUPPORT","atob","encodeByteArray","webSafe","init_","byteToCharMap","output","byte1","haveByte2","byte2","haveByte3","byte3","outByte1","outByte2","outByte3","outByte4","encodeString","btoa","decodeString","c1","fromCharCode","c2","u","c3","byteArrayToString","decodeStringToByteArray","charToByteMap","byte4","DecodeBase64StringError","base64urlEncodeWithoutPadding","utf8Bytes","base64Encode","base64Decode","getDefaults","getGlobal","__FIREBASE_DEFAULTS__","defaultsJsonString","getDefaultsFromEnvVariable","cookie","decoded","getDefaultsFromCookie","getDefaultEmulatorHost","productName","emulatorHosts","getDefaultEmulatorHostnameAndPort","host","separatorIndex","port","getDefaultAppConfig","config","getExperimentalSetting","Deferred","promise","wrapCallback","callback","createMockUserToken","token","projectId","uid","iat","sub","user_id","payload","iss","aud","exp","auth_time","firebase","sign_in_provider","identities","alg","indexedDB","validateIndexedDBOpenable","preExist","DB_CHECK_NAME","open","onsuccess","deleteDatabase","onupgradeneeded","onerror","areCookiesEnabled","cookieEnabled","FirebaseError","customData","setPrototypeOf","captureStackTrace","ErrorFactory","service","serviceName","errors","fullCode","template","PATTERN","replaceTemplate","fullMessage","a","b","aKeys","bKeys","aProp","bProp","isObject","thing","querystringParams","arrayVal","querystringDecode","querystring","decodeURIComponent","extractQuerystring","queryStart","fragmentStart","ObserverProxy","onNoObservers","observers","unsubscribes","observerCount","task","finalized","forEachObserver","observer","subscribe","nextOrObserver","methods","implementsAnyMethods","noop","unsub","unsubscribeOne","finalError","sendOne","_delegate","Component","instanceFactory","multipleInstances","serviceProps","instantiationMode","onInstanceCreated","setInstantiationMode","mode","setMultipleInstances","setServiceProps","setInstanceCreatedCallback","DEFAULT_ENTRY_NAME","Provider","container","component","instances","Map","instancesDeferred","instancesOptions","onInitCallbacks","identifier","normalizedIdentifier","normalizeInstanceIdentifier","deferred","isInitialized","shouldAutoInitialize","instance","getOrInitializeService","instanceIdentifier","getImmediate","optional","getComponent","setComponent","isComponentEager","instanceDeferred","clearInstance","services","INTERNAL","_delete","isComponentSet","getOptions","initialize","onInit","existingCallbacks","existingInstance","invokeOnInitCallbacks","callbacks","ComponentContainer","providers","addComponent","provider","getProvider","addOrOverwriteComponent","getProviders","LogLevel","levelStringToEnum","DEBUG","VERBOSE","INFO","WARN","ERROR","SILENT","defaultLogLevel","ConsoleMethod","defaultLogHandler","logType","logLevel","Logger","_logLevel","_logHandler","_userLogHandler","setLogLevel","logHandler","userLogHandler","instanceOfAny","constructors","idbProxyableTypes","cursorAdvanceMethods","cursorRequestMap","transactionDoneMap","transactionStoreNamesMap","transformCache","reverseTransformCache","idbProxyTraps","IDBTransaction","objectStoreNames","objectStore","transformCachableValue","func","IDBDatabase","transaction","IDBCursor","advance","continue","continuePrimaryKey","unwrap","storeNames","tx","unlisten","removeEventListener","DOMException","cacheDonePromiseForTransaction","IDBObjectStore","IDBIndex","IDBRequest","success","promisifyRequest","newValue","readMethods","writeMethods","cachedMethods","getMethod","targetFuncName","useIndex","isWrite","storeName","store","oldTraps","PlatformLoggerServiceImpl","getPlatformInfoString","isVersionServiceProvider","library","logString","name$o","version$1","logger","PLATFORM_LOG_STRING","_apps","_components","_addComponent","app","_registerComponent","componentName","heartbeatController","triggerHeartbeat","ERROR_FACTORY","FirebaseAppImpl","_isDeleted","_config","_name","_automaticDataCollectionEnabled","automaticDataCollectionEnabled","_container","checkDestroyed","isDeleted","appName","SDK_VERSION","initializeApp","rawConfig","existingApp","newApp","registerVersion","libraryKeyOrName","variant","libraryMismatch","versionMismatch","warning","DB_NAME","DB_VERSION","STORE_NAME","dbPromise","getDbPromise","blocked","upgrade","blocking","terminated","openPromise","oldVersion","newVersion","db","openDB","createObjectStore","originalErrorMessage","writeHeartbeatsToIndexedDB","heartbeatObject","computeKey","idbGetError","appId","HeartbeatServiceImpl","_heartbeatsCache","_storage","HeartbeatStorageImpl","_heartbeatsCachePromise","getUTCDateString","lastSentHeartbeatDate","heartbeats","singleDateHeartbeat","hbTimestamp","valueOf","overwrite","getHeartbeatsHeader","heartbeatsToSend","unsentEntries","heartbeatsCache","maxSize","heartbeatEntry","hb","dates","countBytes","extractHeartbeatsForHeader","headerString","_canUseIndexedDBPromise","runIndexedDBEnvironmentCheck","idbHeartbeatObject","readHeartbeatsFromIndexedDB","heartbeatsObject","existingHeartbeatsObject","__rest","s","getOwnPropertySymbols","propertyIsEnumerable","SuppressedError","prodErrorMap","_DEFAULT_AUTH_ERROR_FACTORY","logClient","_logError","_fail","authOrCode","createErrorInternal","_createError","_errorWithCustomMessage","auth","errorMap","fullParams","_errorFactory","_assert","assertion","debugFail","failure","debugAssert","_getCurrentUrl","location","href","_getCurrentScheme","protocol","_isOnline","onLine","runtime","chrome","isBrowserExtension","Delay","shortDelay","longDelay","isMobile","_emulatorUrl","emulator","FetchProvider","fetchImpl","headersImpl","responseImpl","SERVER_ERROR_MAP","DEFAULT_API_TIMEOUT_MS","_addTidIfNecessary","tenantId","_performApiRequest","customErrorMap","_performFetchWithErrorHandling","_getAdditionalHeaders","languageCode","_getFinalTarget","apiHost","referrerPolicy","fetchFn","_canInitEmulator","networkTimeout","NetworkTimeout","race","clearNetworkTimeout","_makeTaggedError","errorMessage","serverErrorCode","serverErrorMessage","authError","_performSignInRequest","serverResponse","_serverResponse","base","apiScheme","timer","errorParams","email","phoneNumber","_tokenResponse","utcTimestampToDateString","utcTimestamp","getTime","toUTCString","secondsStringToMilliseconds","seconds","_parseToken","algorithm","signature","_logoutIfInvalidated","user","bypassAuthState","isUserInvalidated","currentUser","signOut","ProactiveRefresh","isRunning","timerId","errorBackoff","_start","schedule","_stop","getInterval","wasError","interval","stsTokenManager","expirationTime","max","iteration","getIdToken","UserMetadata","createdAt","lastLoginAt","_initializeTime","lastSignInTime","creationTime","_copy","metadata","toJSON","_reloadWithoutSaving","idToken","getAccountInfo","users","coreAccount","_notifyReloadListener","newProviderData","providerUserInfo","providerId","rawId","displayName","photoURL","photoUrl","providerData","original","o","oldIsAnonymous","isAnonymous","newIsAnonymous","passwordHash","updates","localId","emailVerified","StsTokenManager","refreshToken","accessToken","isExpired","updateFromServerResponse","expiresIn","parsedToken","_tokenExpiresIn","updateTokensAndExpiration","getToken","forceRefresh","refresh","clearRefreshToken","oldToken","tokenApiHost","access_token","expires_in","refresh_token","requestStsToken","expiresInSec","fromJSON","manager","_assign","_clone","_performRefresh","assertStringOrUndefined","UserImpl","opt","proactiveRefresh","reloadUserInfo","reloadListener","_persistUserIfCurrent","_notifyListenersIfCurrent","getIdTokenResult","userInternal","claims","signInProvider","authTime","issuedAtTime","signInSecondFactor","reload","userInfo","newUser","_onReload","_startProactiveRefresh","_stopProactiveRefresh","_updateTokensIfNecessary","tokensRefreshed","deleteAccount","_redirectEventId","_fromJSON","_e","_f","_g","_h","plainObjectTokenManager","_fromIdTokenResponse","idTokenResponse","instanceCache","_getInstance","cls","InMemoryPersistence","storage","_isAvailable","_set","_get","_remove","_addListener","_key","_listener","_removeListener","inMemoryPersistence","_persistenceKeyName","PersistenceUserManager","persistence","userKey","fullUserKey","fullPersistenceKey","boundEventHandler","_onStorageEvent","setCurrentUser","getCurrentUser","removeCurrentUser","savePersistenceForRedirect","setPersistence","newPersistence","persistenceHierarchy","availablePersistences","selectedPersistence","userToMigrate","migrationHierarchy","_shouldAllowMigration","_getBrowserName","ua","_isIEMobile","_isFirefox","_isBlackBerry","_isWebOS","_isSafari","_isChromeIOS","_isAndroid","re","matches","_isIOS","_isMobileBrowser","_getClientVersion","clientPlatform","frameworks","reportedPlatform","reportedFrameworks","getRecaptchaConfig","isEnterprise","grecaptcha","enterprise","RecaptchaConfig","siteKey","emailPasswordEnabled","recaptchaKey","recaptchaEnforcementState","enforcementState","_loadJS","el","createElement","setAttribute","onload","getElementsByTagName","getScriptParentElement","appendChild","_generateCallbackName","floor","RecaptchaEnterpriseVerifier","authExtern","_castAuth","verify","retrieveRecaptchaToken","ready","execute","_agentRecaptchaConfig","_tenantRecaptchaConfigs","clientType","retrieveSiteKey","injectRecaptchaFields","captchaResp","verifier","captchaResponse","newRequest","AuthMiddlewareQueue","pushCallback","onAbort","wrappedCallback","runMiddleware","nextUser","onAbortStack","beforeStateCallback","reverse","originalMessage","AuthImpl","heartbeatServiceProvider","appCheckServiceProvider","emulatorConfig","operations","authStateSubscription","Subscription","idTokenSubscription","beforeStateQueue","redirectUser","isProactiveRefreshEnabled","_isInitialized","_deleted","_initializationPromise","_popupRedirectResolver","lastNotifiedUid","settings","appVerificationDisabledForTesting","clientVersion","sdkClientVersion","_initializeWithPersistence","popupRedirectResolver","persistenceManager","_shouldInitProactively","_initialize","initializeCurrentUser","assertedPersistence","_currentUser","_updateCurrentUser","previouslyStoredUser","futureCurrentUser","needsTocheckMiddleware","authDomain","getOrInitRedirectPersistenceManager","redirectUserEventId","storedUserEventId","tryRedirectSignIn","directlySetCurrentUser","_overrideRedirectResult","reloadAndSetCurrentUserOrClear","redirectResolver","_completeRedirectFn","_setRedirectUser","useDeviceLanguage","navigatorLanguage","languages","language","_getUserLanguage","updateCurrentUser","userExtern","skipBeforeStateCallbacks","notifyAuthListeners","redirectPersistenceManager","initializeRecaptchaConfig","_getRecaptchaConfig","_getPersistence","_updateErrorMap","onAuthStateChanged","completed","registerStateListener","beforeAuthStateChanged","onIdTokenChanged","redirectManager","resolver","_redirectPersistence","_redirectUserForId","currentUid","subscription","cb","addObserver","_logFramework","framework","_getFrameworks","heartbeatsHeader","appCheckToken","_getAppCheckToken","appCheckTokenResult","_logWarn","proxy","createSubscribe","extractProtocol","protocolEnd","substr","parsePort","portStr","AuthCredential","signInMethod","_getIdTokenResponse","_auth","_linkToIdToken","_idToken","_getReauthenticationResolver","signInWithPassword","EmailAuthCredential","_email","_password","_tenantId","_fromEmailAndPassword","password","_fromEmailAndCode","oobCode","returnSecureToken","requestWithRecaptcha","signInWithEmailLink$1","updateEmailPassword","signInWithEmailLinkForLinking","signInWithIdp","OAuthCredential","pendingToken","_fromParams","cred","nonce","oauthToken","oauthTokenSecret","secret","autoCreate","requestUri","postBody","VERIFY_PHONE_NUMBER_FOR_EXISTING_ERROR_MAP_","PhoneAuthCredential","_fromVerification","verificationId","verificationCode","_fromTokenResponse","temporaryProof","signInWithPhoneNumber$1","_makeVerificationRequest","linkWithPhoneNumber$1","operation","verifyPhoneNumberForExisting","sessionInfo","ActionCodeURL","actionLink","parseMode","continueUrl","parseLink","link","doubleDeepLink","iOSDeepLink","parseDeepLink","EmailAuthProvider","PROVIDER_ID","credential","credentialWithLink","emailLink","actionCodeUrl","EMAIL_PASSWORD_SIGN_IN_METHOD","EMAIL_LINK_SIGN_IN_METHOD","FederatedAuthProvider","defaultLanguageCode","customParameters","setDefaultLanguage","setCustomParameters","customOAuthParameters","getCustomParameters","BaseOAuthProvider","scopes","addScope","scope","getScopes","FacebookAuthProvider","FACEBOOK_SIGN_IN_METHOD","credentialFromResult","userCredential","credentialFromTaggedObject","credentialFromError","tokenResponse","oauthAccessToken","GoogleAuthProvider","GOOGLE_SIGN_IN_METHOD","oauthIdToken","GithubAuthProvider","GITHUB_SIGN_IN_METHOD","TwitterAuthProvider","TWITTER_SIGN_IN_METHOD","UserCredentialImpl","operationType","providerIdForResponse","_forOperation","MultiFactorError","_fromErrorAndOperation","_processCredentialSavingMfaContextIfNecessary","STORAGE_AVAILABLE_KEY","BrowserPersistenceClass","storageRetriever","setItem","removeItem","getItem","BrowserLocalPersistence","localStorage","onStorageEvent","localCache","pollTimer","safariLocalStorageNotSynced","_iframeCannotSyncWebStorage","top","_isIframe","fallbackToPolling","forAllChangedKeys","oldValue","_oldValue","notifyListeners","detachListener","stopPolling","storedValue","triggerListeners","isIE","documentMode","startPolling","setInterval","StorageEvent","clearInterval","attachListener","browserLocalPersistence","BrowserSessionPersistence","sessionStorage","browserSessionPersistence","Receiver","eventTarget","handlersMap","handleEvent","receivers","isListeningto","newInstance","messageEvent","eventId","eventType","handlers","ports","postMessage","handler","origin","fulfilled","_allSettled","_subscribe","eventHandler","_unsubscribe","_generateEventId","digits","Sender","removeMessageHandler","messageChannel","port1","onMessage","_send","MessageChannel","completionTimer","ackTimer","port2","_window","_isWorker","DB_OBJECTSTORE_NAME","DB_DATA_KEYPATH","DBPromise","toPromise","getObjectStore","isReadWrite","_openDatabase","keyPath","contains","_deleteDatabase","_putObject","_deleteObject","IndexedDBLocalPersistence","pendingWrites","sender","serviceWorkerReceiverAvailable","activeServiceWorker","_workerInitializationPromise","initializeServiceWorkerMessaging","_openDb","_withRetries","op","numAttempts","initializeReceiver","initializeSender","_origin","keyProcessed","_poll","_data","serviceWorker","active","_getActiveServiceWorker","notifyServiceWorker","_getServiceWorkerController","_withPendingWrite","write","getObject","getAllRequest","getAll","keysInResult","fbase_key","localKey","indexedDBLocalPersistence","PhoneAuthProvider","verifyPhoneNumber","phoneOptions","applicationVerifier","recaptchaToken","phoneInfoOptions","session","startEnrollPhoneMfa","phoneEnrollmentInfo","phoneSessionInfo","mfaEnrollmentId","multiFactorHint","multiFactorUid","startSignInPhoneMfa","mfaPendingCredential","phoneSignInInfo","phoneResponseInfo","sendPhoneVerificationCode","_reset","_verifyPhoneNumber","_withDefaultResolver","resolverOverride","PHONE_SIGN_IN_METHOD","IdpCredential","_buildIdpRequest","sessionId","returnIdpCredential","_signIn","_signInWithCredential","_reauth","_reauthenticate","_link","_link$1","AbstractPopupRedirectOperation","pendingPromise","eventManager","onExecution","registerConsumer","onAuthEvent","urlResponse","getIdpTask","onError","unregisterAndCleanUp","unregisterConsumer","cleanUp","_POLL_WINDOW_CLOSE_TIMEOUT","PopupOperation","authWindow","pollId","currentPopupAction","executeNotNull","_openPopup","associatedEvent","_originValidation","_isIframeWebStorageSupported","isSupported","pollUserCancellation","closed","PENDING_REDIRECT_KEY","redirectOutcomeMap","RedirectAction","readyOutcome","pendingRedirectKey","resolverPersistence","hasPendingRedirect","_getAndClearPendingRedirectStatus","_getRedirectResult","resolverExtern","authInternal","AuthEventManager","cachedEventUids","consumers","queuedRedirectEvent","hasHandledPotentialRedirect","lastProcessedEventTime","authEventConsumer","isEventForConsumer","sendToConsumer","saveEventToCache","onEvent","hasEventBeenHandled","handled","consumer","isNullRedirectEvent","isRedirectEvent","eventIdMatches","clear","eventUid","IP_ADDRESS_REGEX","HTTP_REGEX","matchDomain","expected","currentUrl","hostname","ceUrl","escapedDomainPattern","RegExp","NETWORK_TIMEOUT","resetUnloadedGapiModules","beacon","___jsl","H","hint","L","CP","cachedGApiLoader","_loadGapi","loadGapiIframe","gapi","load","iframes","getContext","ontimeout","Iframe","cbName","loadGapi","PING_TIMEOUT","IFRAME_ATTRIBUTES","style","position","width","height","tabindex","EID_FROM_APIHOST","getIframeUrl","eid","fw","BASE_POPUP_OPTIONS","resizable","statusbar","toolbar","AuthPopup","FIREBASE_APP_CHECK_FRAGMENT_ID","_getRedirectUrl","authType","redirectUrl","additionalParams","isEmpty","tid","paramsDict","appCheckTokenFragment","getHandlerBase","WEB_STORAGE_SUPPORT_KEY","browserPopupRedirectResolver","eventManagers","originValidationPromises","screen","availHeight","availWidth","scrollbars","optionsString","reduce","accum","standalone","_isIOSStandalone","click","createEvent","initMouseEvent","dispatchEvent","openAsNewWindowIOS","newWin","focus","_open","_openRedirect","initAndGetManager","iframe","context","where","messageHandlersFilter","CROSS_ORIGIN_IFRAMES_FILTER","attributes","dontclear","restyle","setHideOnLeave","networkError","networkErrorTimer","clearTimerAndResolve","ping","_openIframe","register","iframeEvent","authEvent","send","authorizedDomains","_getProjectConfig","domain","_validateOrigin","AuthInterop","internalListeners","getUid","assertAuthConfigured","addAuthTokenListener","unsubscribe","updateProactiveRefresh","removeAuthTokenListener","authIdTokenMaxAge","lastPostedIdToken","mintCookieFactory","idTokenResult","idTokenAge","getAuth","deps","initializeAuth","authTokenSyncUrl","mintCookie","authEmulatorHost","disableWarnings","authority","hostAndPort","bracketedIPv6","extractHostAndPort","freeze","attachBanner","sty","innerText","backgroundColor","border","color","bottom","margin","zIndex","textAlign","classList","readyState","emitEmulatorWarning","connectAuthEmulator","authInstance","hierarchy","_initializeAuthInstance","_instanceIdentifier","_instance","getVersionForPlatform","commonjsGlobal","global","esm","goog","aa","ca","da","ea","fa","d","unshift","q","ha","$","ac","h","sa","N","ka","ma","na","w","defaultPrevented","oa","pa","qa","za","Da","ta","z","va","wa","xa","ya","Aa","Ba","Ca","Fa","A","relatedTarget","button","screenY","screenX","clientY","clientX","metaKey","shiftKey","altKey","ctrlKey","pointerId","pointerType","changedTouches","srcElement","nodeName","fromElement","toElement","pageX","pageY","Ga","preventDefault","returnValue","Ha","Ia","Ja","src","capture","la","ia","Ka","Na","Pa","Qa","Ra","Sa","Ua","Ta","Va","Wa","Ya","Za","$a","O","ab","bb","eb","attachEvent","addListener","removeListener","P","fb","gb","detachEvent","B","S","J","C","ib","concat","jb","lb","mb","ob","pb","reset","qb","rb","sb","tb","vb","ub","wb","xb","ga","T","yb","zb","m","Ab","Bb","Cb","Db","Fb","Gb","D","Jb","Ea","E","Lb","Mb","Nb","Ob","Pb","STAT_EVENT","stat","F","Qb","Rb","Sb","NO_ERROR","Eb","TIMEOUT","Ib","Tb","Kb","$b","Ub","Vb","Wb","Xb","OPEN","Hb","Yb","Zb","bc","W","U","cc","V","I","G","Y","M","ba","K","dc","XMLHttpRequest","ec","fc","gc","hc","ic","jc","kc","lc","nb","oc","rc","uc","qc","vc","pc","wc","nc","sc","xc","yc","zc","Ac","Bc","ra","La","Ma","getResponseHeader","Cc","Dc","Ec","Fc","Gc","Hc","Kc","Z","Jc","Ic","ja","mc","getAllResponseHeaders","Oa","tc","Lc","Nc","Oc","Pc","Qc","Rc","$c","Xc","Sc","Yc","abs","decodeURI","encodeURI","Zc","Tc","Uc","Vc","Wc","Mc","ad","bd","cd","dd","PerformanceNavigationTiming","performance","getEntriesByType","nextHopProtocol","ed","fd","gd","hd","kd","onabort","ld","md","nd","responseType","responseText","statusText","onreadystatechange","qd","Xa","pd","od","credentials","cache","setRequestHeader","rd","sd","td","ud","vd","yd","zd","Ad","wd","mozResponseArrayBuffer","Bd","Cd","Dd","internalChannelParams","Ed","xmlHttpFactory","supportsCrossDomainXhr","concurrentRequestLimit","fastHandshake","encodeInitMessageHeaders","forceLongPolling","detectBufferingProxy","longPollingTimeout","Fd","Gd","sendBeacon","Image","Hd","Ld","Kd","round","Jd","Md","Id","isActive","jd","Nd","Od","Q","messageUrlParams","messageHeaders","clientProtocolHeaderRequired","initMessageHeaders","messageContentType","sendRawJson","httpSessionIdParam","R","Pd","__headers__","statusCode","__status__","__sm__","Qd","blockSize","Sd","getPrototypeOf","withCredentials","xd","kb","__data__","Td","isFinite","Ud","Wd","Xd","X","Zd","$d","ae","Yd","be","ceil","LN2","and","or","xor","createWebChannel","HTTP_ERROR","COMPLETE","EventType","CLOSE","MESSAGE","listen","listenOnce","getLastError","getLastErrorCode","getStatus","getResponseJson","getResponseText","setWithCredentials","digest","multiply","modulo","compare","toNumber","getBits","fromNumber","fromString","Vd","createWebChannelTransport","getStatEventTarget","ErrorCode","Event","Stat","PROXY","NOPROXY","FetchXmlHttpFactory","WebChannel","XhrIo","Md5","Integer","isAuthenticated","toKey","isEqual","UNAUTHENTICATED","GOOGLE_CREDENTIALS","FIRST_PARTY","MOCK_USER","OK","CANCELLED","UNKNOWN","INVALID_ARGUMENT","DEADLINE_EXCEEDED","NOT_FOUND","ALREADY_EXISTS","PERMISSION_DENIED","RESOURCE_EXHAUSTED","FAILED_PRECONDITION","ABORTED","OUT_OF_RANGE","UNIMPLEMENTED","UNAVAILABLE","DATA_LOSS","invalidateToken","enqueueRetryable","shutdown","changeListener","appCheck","addTokenListener","removeTokenListener","crypto","msCrypto","getRandomValues","tt","et","nt","it","nanoseconds","fromMillis","fromDate","toDate","toMillis","_compareTo","padStart","rt","timestamp","fromTimestamp","compareTo","toMicroseconds","toTimestamp","ot","segments","offset","len","comparator","child","construct","popFirst","popLast","firstSegment","lastSegment","isPrefixOf","isImmediateParentOf","toArray","ut","canonicalString","emptyPath","ct","isValidIdentifier","isKeyField","keyField","fromServerFormat","ht","fromPath","fromName","empty","collectionGroup","hasCollectionId","getCollectionGroup","getCollectionPath","isDocumentKey","fromSegments","pt","It","readTime","documentKey","largestBatchId","Tt","Et","At","onCommittedListeners","addOnCommittedListener","raiseOnCommittedEvent","vt","Rt","nextCallback","catchCallback","isDone","callbackAttached","wrapFailure","wrapSuccess","wrapUserFunction","waitFor","mapArray","doWhile","Dt","Ot","previousValue","sequenceNumberHandler","writeSequenceNumber","Ft","Bt","me","ge","ye","pe","root","Te","EMPTY","insert","copy","BLACK","remove","minKey","maxKey","inorderTraversal","reverseTraversal","getIterator","Ie","getIteratorFrom","getReverseIterator","getReverseIteratorFrom","isReverse","nodeStack","getNext","hasNext","peek","RED","fixUp","removeMin","isRed","moveRedLeft","rotateRight","moveRedRight","rotateLeft","colorFlip","checkMaxDepth","check","Ee","first","last","forEachInRange","forEachWhile","firstAfterOrEqual","Ae","unionWith","Re","fields","covers","Pe","Ve","binaryString","fromBase64String","fromUint8Array","toBase64","toUint8Array","approximateByteSize","EMPTY_BYTE_STRING","Se","De","nanos","Ce","xe","Ne","mapValue","__type__","stringValue","ke","__previous_value__","Me","__local_write_time__","timestampValue","$e","databaseId","persistenceKey","ssl","autoDetectLongPolling","longPollingOptions","useFetchStreams","Oe","database","isDefaultDatabase","Fe","Le","en","qe","booleanValue","bytesValue","referenceValue","geoPointValue","latitude","longitude","integerValue","doubleValue","arrayValue","Ue","Ke","Ge","Qe","je","We","He","Je","Ye","Xe","Ze","tn","un","field","getFieldsMap","setAll","applyChanges","clone","cn","an","documentType","createTime","documentState","newInvalidDocument","newFoundDocument","newNoDocument","newUnknownDocument","convertToFoundDocument","convertToNoDocument","convertToUnknownDocument","setHasCommittedMutations","setHasLocalMutations","setReadTime","hasLocalMutations","hasCommittedMutations","hasPendingWrites","isValidDocument","isFoundDocument","isNoDocument","isUnknownDocument","mutableCopy","hn","inclusive","ln","dir","dn","wn","_n","mn","createKeyFieldInFilter","Pn","Dn","Cn","xn","Nn","bn","Vn","matchesComparison","isInequality","getFlattenedFilters","getFilters","getFirstInequalityField","gn","filters","lt","yn","ft","In","Tn","En","An","Rn","Sn","nullValue","kn","orderBy","startAt","endAt","dt","Mn","$n","On","Fn","Un","explicitOrderBy","limitType","wt","_t","Gn","Qn","jn","zn","Wn","Hn","Jn","Yn","Xn","Zn","ts","es","ns","is","rs","mapKeyFn","equalsFn","inner","innerSize","us","cs","as","hs","ls","overlayedDocument","fs","ws","ds","_s","gs","ys","Is","useProto3Json","Ts","Es","MAX_SAFE_INTEGER","MIN_SAFE_INTEGER","Lt","As","vs","bs","Vs","Ss","Ds","Cs","Ps","Ns","gt","serializer","Rs","xs","elements","ks","Ms","Os","transformResults","Fs","updateTime","exists","none","isNone","Bs","Ls","qs","Ys","js","zs","Us","Hs","fieldTransforms","precondition","Ws","Ks","Js","fieldMask","Gs","Qs","$s","getFieldMask","Xs","Zs","localWriteTime","baseMutations","mutations","applyToRemoteDocument","mutationResults","applyToLocalView","applyToLocalDocumentSet","mutatedFields","ti","commitVersion","docVersions","ei","mutation","getKey","si","count","unchangedNames","ii","ri","ui","ci","onExistenceFilterMismatchCallbacks","ai","getOrCreateInstance","onExistenceFilterMismatch","notifyOnExistenceFilterMismatch","li","fi","di","getUint32","wi","bitmap","padding","hashCount","_i","mi","snapshotVersion","targetChanges","targetMismatches","documentUpdates","resolvedLimboDocuments","createSynthesizedRemoteEventForCurrentChange","gi","createSynthesizedTargetChangeForCurrentChange","resumeToken","current","addedDocuments","modifiedDocuments","removedDocuments","yi","Pt","removedTargetIds","bt","pi","targetId","Vt","Ii","targetIds","Ti","St","vi","Ct","xt","Nt","kt","Mt","$t","qt","Ut","Kt","Ei","Gt","Qt","jt","zt","Ai","Wt","Ht","Jt","Yt","Xt","forEachTarget","Zt","te","removeTarget","ee","ne","se","ie","localCacheCount","existenceFilterCount","bloomFilter","applied","bitmapLength","oe","getRemoteKeysForTarget","ue","ce","he","le","Ri","asc","desc","Pi","in","bi","Vi","Si","Di","Ci","xi","Ni","ki","Mi","ur","$i","Oi","qi","Fi","Li","Ui","Hi","documents","Ji","structuredQuery","parent","collectionId","allDescendants","rr","sr","direction","tr","before","Yi","Bi","Zi","ir","Kn","unaryFilter","fieldFilter","compositeFilter","er","nr","fieldPath","fieldPaths","cr","sequenceNumber","lastLimboFreeSnapshotVersion","expectedCount","withSequenceNumber","withResumeToken","withExpectedCount","withLastLimboFreeSnapshotVersion","ar","fe","yr","br","ve","zr","rn","Wr","addToCollectionParentIndex","getCollectionParents","getEntries","addFieldIndex","deleteFieldIndex","getDocumentsMatchingTarget","getIndexType","getFieldIndexes","getNextCollectionGroupToUpdate","getMinOffset","getMinOffsetFromCollectionGroup","updateCollectionGroup","updateIndexEntries","so","cacheSizeCollectionThreshold","percentileToCollect","maximumSequenceNumbersToCollect","withCacheSize","DEFAULT_COLLECTION_PERCENTILE","DEFAULT_MAX_SEQUENCE_NUMBERS_TO_COLLECT","DEFAULT","DISABLED","lo","vo","changes","changesApplied","addEntry","assertNotApplied","removeEntry","getEntry","getFromCache","getAllFromCache","No","ko","remoteDocumentCache","mutationQueue","documentOverlayCache","indexManager","getDocument","getOverlay","getDocuments","getLocalViewOfDocuments","populateOverlays","computeViews","getOverlayedDocuments","getOverlays","recalculateAndSaveOverlays","getAllMutationBatchesAffectingDocumentKeys","saveOverlays","recalculateAndSaveOverlaysForDocumentKeys","getDocumentsMatchingQuery","getDocumentsMatchingDocumentQuery","getDocumentsMatchingCollectionGroupQuery","getDocumentsMatchingCollectionQuery","getNextDocuments","getAllFromCollectionGroup","getOverlaysForCollectionGroup","getOverlaysForCollection","Mo","getBundleMetadata","saveBundleMetadata","getNamedQuery","saveNamedQuery","bundledQuery","$o","overlays","we","removeOverlaysForBatchId","Oo","Fo","addReference","removeReference","ps","containsKey","Bo","referenceDelegate","checkEmpty","addMutationBatch","lookupMutationBatch","getNextMutationBatchAfterBatchId","getHighestUnacknowledgedBatchId","getAllMutationBatches","getAllMutationBatchesAffectingDocumentKey","POSITIVE_INFINITY","getAllMutationBatchesAffectingQuery","removeMutationBatch","markPotentiallyOrphaned","performConsistencyCheck","Lo","docs","setIndexManager","newChangeBuffer","qo","getSize","Uo","lastRemoteSnapshotVersion","highestTargetId","targetCount","getLastRemoteSnapshotVersion","getHighestSequenceNumber","allocateTargetId","setTargetsMetadata","addTargetData","updateTargetData","removeTargetData","removeTargets","removeMatchingKeysForTargetId","getTargetCount","getTargetData","addMatchingKeys","removeMatchingKeys","getMatchingKeysForTargetId","Ko","started","setDatabaseDeletedListener","setNetworkEnabled","getIndexManager","getDocumentOverlayCache","getMutationQueue","getTargetCache","getRemoteDocumentCache","getBundleCache","runTransaction","Go","currentSequenceNumber","Qo","updateLimboDocument","tu","fromCache","docChanges","doc","eu","Ki","Gi","Qi","ji","zi","Wi","yt","nu","Xi","localDocuments","collectGarbage","collect","iu","removedBatchIds","addedBatchIds","ou","au","lu","fu","_u","ss","Ru","activeTargetIds","lr","dr","hr","updateTimeMs","bu","Hr","Jr","onlineStateHandler","addPendingMutation","updateMutationState","addLocalQueryTarget","updateQueryState","removeLocalQueryTarget","isLocalQueryTarget","clearQueryState","getAllActiveQueryTargets","isActiveQueryTarget","handleUserChange","setOnlineState","notifyBundleLoaded","Vu","Yr","Su","Xr","Zr","eo","no","io","Du","Cu","xu","BatchGetDocuments","Commit","RunQuery","RunAggregationQuery","Nu","ro","oo","uo","co","ao","ho","fo","wo","_o","ku","Mu","databaseInfo","mo","yo","po","Io","To","Eo","Ao","Ro","forwardChannelRequestTimeoutMs","Ou","Fu","Bu","Po","bo","Vo","So","Do","Co","xo","enqueueAfterDelay","skipDelay","Lu","connection","authCredentialsProvider","appCheckCredentialsProvider","stop","jo","zo","Wo","Ho","Jo","Yo","Xo","Zo","enqueueAndForget","qu","targetChange","targetChangeType","documentChange","documentDelete","documentRemove","su","addTarget","labels","Uu","ru","lastStreamToken","uu","streamToken","writeResults","commitTime","cu","hu","writes","updateMask","updateTransforms","setToServerValue","appendMissingElements","removeAllFromArray","increment","currentDocument","Ku","authCredentials","appCheckCredentials","terminate","Qu","asyncQueue","wu","mu","gu","yu","pu","Iu","Tu","ju","localStore","datastore","remoteSyncer","Eu","Au","vu","Pu","Wu","zu","Hu","Zu","Yu","Ju","Xu","rejectListen","applyRemoteEvent","applySuccessfulWrite","oi","rejectFailedWrite","verifyOperationInProgress","handleCredentialChange","targetTimeMs","removalCallback","createAndSchedule","timerHandle","handleDelayElapsed","keyedMap","sortedSet","emptySet","track","oldDocs","mutatedKeys","syncStateChanged","excludesMetadataChanges","hasCachedResults","fromInitialDocuments","queries","onlineState","$u","includeMetadataChanges","view","remoteStore","sharedClientState","maxConcurrentLimboResolutions","isPrimaryClient","trackRemovals","synchronizeTabs","createSharedClientState","createPersistence","createLocalStore","gcScheduler","createGarbageCollectionScheduler","indexBackfillerScheduler","createIndexBackfillerScheduler","initialUser","createDatastore","createRemoteStore","createEventManager","syncEngine","createSyncEngine","muted","clientId","authCredentialListener","appCheckCredentialListener","getConfiguration","setCredentialChangeListener","setAppCheckTokenChangeListener","verifyNotTerminated","isShuttingDown","enterRestrictedMode","enqueueAndForgetEvenWhileRestricted","_onlineComponents","_offlineComponents","_uninitializedComponentsProvider","_offline","_online","onListen","onUnlisten","th","eh","nh","ih","rh","oh","uh","ah","ignoreUndefinedProperties","cacheSizeBytes","sh","experimentalForceLongPolling","experimentalAutoDetectLongPolling","experimentalLongPollingOptions","hh","_authCredentials","_appCheckCredentials","_databaseId","_app","_persistenceKey","_settings","_settingsFrozen","_initialized","_terminated","_terminateTask","_setSettings","sessionIndex","iamToken","authTokenFactory","_getSettings","_freezeSettings","_terminate","fh","converter","firestore","_path","wh","withConverter","dh","_query","gh","Ih","visibilityState","stack","Th","vh","_queue","_firestoreClient","Vh","Ph","mockUserToken","lh","bh","_offlineComponentProvider","_onlineComponentProvider","_offlineKind","Uh","_byteString","Kh","_internalPath","Qh","_methodName","jh","_lat","_long","zh","Wh","toMutation","Hh","Jh","Yh","gl","methodName","Xh","Zh","tl","merge","mergeFields","dl","ll","wl","yl","_toFieldTransform","sl","hl","fl","ml","_l","pl","_firestore","_userDataWriter","_document","_converter","ref","Il","fromFirestore","convertValue","Tl","Al","vl","Pl","_field","_op","_value","_create","_apply","_parse","Ql","Gl","Kl","al","Vl","_queryConstraints","_getOperator","_getQueryConstraints","Cl","_direction","jl","Nl","_limit","_limitType","Wl","convertTimestamp","convertServerTimestamp","convertBytes","convertReference","convertGeoPoint","convertArray","convertObject","convertObjectMap","convertDocumentKey","Hl","toFirestore","nf","sf","_firestoreImpl","rf","serverTimestamps","of","_snapshot","_cachedChanges","_cachedChangesIncludeMetadataChanges","oldIndex","newIndex","uf","hf","mf","Ef","gf","cl","ul","pf","Gf","DEFAULT_HOST","CONFIG_STORAGE_BUCKET_KEY","StorageError","status_","prependCode","_baseMessage","_codeEquals","StorageErrorCode","unknown","retryLimitExceeded","RETRY_LIMIT_EXCEEDED","canceled","CANCELED","cannotSliceBlob","CANNOT_SLICE_BLOB","invalidArgument","appDeleted","APP_DELETED","invalidFormat","INVALID_FORMAT","internalError","INTERNAL_ERROR","Location","bucket","path_","isRoot","fullServerUrl","bucketOnlyServerUrl","makeFromBucketSpec","bucketString","bucketLocation","makeFromUrl","INVALID_DEFAULT_BUCKET","bucketDomain","gsRegex","httpModify","loc","firebaseStorageHost","groups","regex","postModify","group","captures","bucketValue","pathValue","INVALID_URL","invalidUrl","FailRequest","promise_","getPromise","_appDelete","isString","isNativeBlob","isNativeBlobDefined","forceEnvironment","isNode","validateNumber","argument","minValue","maxValue","makeUrl","urlPart","makeQueryString","queryPart","isRetryStatusCode","additionalRetryCodes","isFiveHundredCode","isExtraRetryCode","isAdditionalRetryCode","NetworkRequest","url_","method_","headers_","body_","successCodes_","additionalRetryCodes_","callback_","errorCallback_","timeout_","progressCallback_","connectionFactory_","retry","pendingConnection_","backoffId_","canceled_","appDelete_","resolve_","reject_","start_","backoffDone","requestWentThrough","wasSuccessCode","getResponse","isJustDef","getErrorText","RequestEndStatus","doRequest","backoffCompleteCb","waitSeconds","retryTimeoutId","globalTimeoutId","hitTimeout","cancelState","triggeredCallback","triggerCallback","callWithDelay","millis","responseHandler","clearGlobalTimeout","waitMillis","stopped","wasTimeout","backoffCallback","progressListener","progressEvent","loaded","lengthComputable","addUploadProgressListener","removeUploadProgressListener","hitServer","getErrorCode","wasCanceled","ABORT","successCode","appDelete","getBlobBuilder","BlobBuilder","WebKitBlobBuilder","getBlob$1","getBlob","UNSUPPORTED_ENVIRONMENT","StringFormat","RAW","BASE64","BASE64URL","DATA_URL","StringData","utf8Bytes_","base64Bytes_","hasMinus","hasUnder","hasPlus","hasSlash","encoded","decodeBase64","DataURLParts","dataURL","middle","end","FbsBlob","elideCopy","blobType","data_","size_","type_","startByte","endByte","sliced","webkitSlice","mozSlice","blobby","uint8Arrays","stringData","dataUrl","percentEncodedBytes_","dataURLBytes_","dataFromString","finalLength","merged","uploadData","jsonObjectOrNull","isNonArrayObject","lastComponent","noXform_","Mapping","server","local","xform","mappings_","getMappings","mappings","nameMapping","_metadata","fullPath","xformPath","sizeMapping","fromResourceString","resourceString","resource","mapping","_makeStorageReference","addRef","fromResource","toResourceString","RequestInfo","urlParams","errorHandler","progressCallback","successCodes","handlerCheck","cndn","metadataHandler","xhr","sharedErrorHandler","newErr","UNAUTHORIZED_APP","QUOTA_EXCEEDED","UNAUTHORIZED","objectErrorHandler","shared","OBJECT_NOT_FOUND","metadataForUpload_","metadataClone","determineContentType_","ResumableUploadStatus","checkResumeHeader_","allowed","RESUMABLE_UPLOAD_CHUNK_SIZE","TaskState","taskStateFromInternalTaskState","Observer","asFunctions","isFunction","argsToForward","textFactoryOverride","XhrConnection","sent_","xhr_","initXhr","errorCode_","sendPromise_","NETWORK_ERROR","XhrTextConnection","newTextConnection","UploadTask","_transferred","_needToFetchStatus","_needToFetchMetadata","_observers","_error","_uploadUrl","_request","_chunkMultiplier","_resolve","_reject","_ref","_blob","_mappings","_resumable","_shouldDoResumable","_state","_errorHandler","completeTransitions_","backoffExpired","isExponentialBackoffExpired","sleepTime","_transition","_metadataErrorHandler","maxSleepTime","maxUploadRetryTime","_promise","_makeProgressCallback","sizeBefore","_updateProgress","_createResumable","_fetchStatus","_fetchMetadata","pendingTimeout","_continueUpload","_oneShotUpload","_resolveToken","_getAuthToken","authToken","requestInfo","metadataForUpload","_protocol","createResumableUpload","_location","createRequest","_makeRequest","sizeString","getResumableUploadStatus","statusRequest","chunkSize","SERVER_FILE_WRONG_SIZE","bytesLeft","bytesToUpload","uploadCommand","uploadStatus","newCurrent","continueResumableUpload","uploadRequest","newStatus","_increaseMultiplier","maxOperationRetryTime","getMetadata$2","metadataRequest","boundary","genBoundary","metadata_","preBlobPart","postBlobPart","multipartUpload","multipartRequest","transferred","old","_notifyObservers","wasPaused","externalState","bytesTransferred","totalBytes","_addObserver","_removeObserver","onFulfilled","onRejected","_notifyObserver","_finishPromise","triggered","resume","valid","pause","Reference","_service","_newRef","newPath","_throwIfRoot","INVALID_ROOT_OPERATION","invalidRootOperation","getDownloadURL$1","tokens","alt","downloadUrlFromResourceString","downloadUrlHandler","getDownloadUrl","makeRequestWithTokens","NO_DOWNLOAD_URL","refFromPath","FirebaseStorageImpl","_bucket","NO_DEFAULT_BUCKET","reference","childPath","canonicalChildPath","_getChild$1","extractBucket","_authProvider","_appCheckProvider","_url","_firebaseVersion","_host","_appId","_maxOperationRetryTime","_maxUploadRetryTime","_requests","time","_overrideAuthToken","tokenData","requestFactory","firebaseVersion","addGmpidHeader_","addAuthHeader_","addVersionHeader_","addAppCheckHeader_","STORAGE_TYPE","authProvider","appCheckProvider","PENDING_TIMEOUT_MS","PACKAGE_VERSION","INTERNAL_AUTH_VERSION","INSTALLATIONS_API_URL","TOKEN_EXPIRATION_BUFFER","isServerError","getInstallationsEndpoint","extractAuthTokenInfoFromResponse","requestStatus","responseExpiresIn","getErrorFromResponse","requestName","errorData","serverCode","serverMessage","serverStatus","getHeaders","retryIfServerError","VALID_FID_PATTERN","INVALID_FID","generateFid","fidByteArray","fid","appConfig","fidChangeCallbacks","fidChanged","callFidChangeCallbacks","channel","broadcastChannel","BroadcastChannel","onmessage","broadcastFidChange","DATABASE_NAME","DATABASE_VERSION","OBJECT_STORE_NAME","updateFn","getInstallationEntry","installations","registrationPromise","installationEntry","oldEntry","clearTimedOutRequest","registrationStatus","updateOrCreateInstallationEntry","entryWithPromise","inProgressEntry","registrationTime","registeredInstallationEntry","endpoint","heartbeatService","authVersion","sdkVersion","responseValue","createInstallationRequest","registerInstallation","waitUntilFidRegistration","triggerRegistrationIfNecessary","updateInstallationRequest","generateAuthTokenRequest","getGenerateAuthTokenEndpoint","getAuthorizationHeader","getHeadersWithAuth","installation","refreshAuthToken","tokenPromise","isEntryRegistered","oldAuthToken","isAuthTokenExpired","updateAuthTokenRequest","waitUntilAuthTokenRequest","inProgressAuthToken","requestTime","makeAuthTokenRequestInProgressEntry","updatedInstallationEntry","fetchAuthTokenFromServer","getMissingValueError","valueName","INSTALLATIONS_NAME","configKeys","keyName","extractAppConfig","getId","installationsImpl","completeInstallationRegistration","DEFAULT_SW_PATH","DEFAULT_SW_SCOPE","DEFAULT_VAPID_KEY","ENDPOINT","CONSOLE_CAMPAIGN_ID","CONSOLE_CAMPAIGN_NAME","CONSOLE_CAMPAIGN_TIME","MessageType$1","MessageType","arrayToBase64","uint8Array","base64ToArray","base64String","rawData","outputArray","OLD_DB_NAME","OLD_DB_VERSION","OLD_OBJECT_STORE_NAME","upgradeDb","dbGet","firebaseDependencies","tokenDetails","oldTokenDetails","senderId","dbNames","databases","upgradeTransaction","oldDetails","p256dh","fcmToken","subscriptionOptions","swScope","vapidKey","checkTokenDetails","migrateOldDatabase","dbSet","requestDeleteToken","unsubscribeOptions","getEndpoint","responseData","errorInfo","getBody","web","applicationPubKey","TOKEN_EXPIRATION_MS","getTokenInternal","messaging","pushSubscription","swRegistration","pushManager","getSubscription","userVisibleOnly","applicationServerKey","getPushSubscription","dbOptions","currentOptions","isVapidKeyEqual","isEndpointEqual","isAuthEqual","isP256dhEqual","isTokenValid","updatedToken","updateOptions","requestUpdateToken","updatedTokenDetails","dbRemove","deleteTokenInternal","updateToken","getNewToken","subscribeOptions","requestGetToken","externalizePayload","internalPayload","collapseKey","collapse_key","fcmMessageId","messagePayloadInternal","notification","title","image","icon","propagateNotificationPayload","propagateDataPayload","fcmOptions","click_action","analyticsLabel","analytics_label","propagateFcmOptions","_mergeStrings","s1","s2","resultArray","MessagingService","analyticsProvider","deliveryMetricsExportedToBigQueryEnabled","onBackgroundMessageHandler","onMessageHandler","logEvents","isLogServiceStarted","messagingSenderId","getToken$1","Notification","permission","requestPermission","updateVapidKey","browserErrorMessage","registerDefaultSw","ServiceWorkerRegistration","updateSwReg","serviceWorkerRegistration","messageEventListener","isFirebaseMessaging","messageType","PUSH_RECEIVED","dataPayload","NOTIFICATION_CLICKED","getEventType","logEvent","message_id","message_name","message_time","message_device_time","logToScion","getMessagingInWindow","PushSubscription","isWindowSupported","TRACE_MEASURE_PREFIX","OOB_TRACE_PAGE_LOAD_PREFIX","FIRST_CONTENTFUL_PAINT_COUNTER_NAME","FIRST_INPUT_DELAY_COUNTER_NAME","CONFIG_LOCAL_STORAGE_KEY","CONFIG_EXPIRY_LOCAL_STORAGE_KEY","consoleLogger","apiInstance","windowInstance","iid","settingsServiceInstance","Api","PerformanceObserver","windowLocation","perfMetrics","onFirstInputDelay","getUrl","mark","measure","measureName","mark1","mark2","getEntriesByName","getTimeOrigin","timeOrigin","timing","navigationStart","requiredApisAvailable","setupObserver","entryType","observe","entryTypes","getInstance","getIid","mergeStrings","part1","part2","sizeDiff","SettingsService","instrumentationEnabled","dataCollectionEnabled","loggingEnabled","tracesSamplingRate","networkRequestsSamplingRate","logEndPointUrl","flTransportEndpointUrl","transportKey","logSource","logTraceAfterSampling","logNetworkAfterSampling","configTimeToLive","getFlTransportFullUrl","VisibilityState","RESERVED_ATTRIBUTE_PREFIXES","ATTRIBUTE_FORMAT_REGEX","getServiceWorkerStatus","getVisibilityState","VISIBLE","HIDDEN","getEffectiveConnectionType","navigatorConnection","effectiveType","getAppId","firebaseApp","REMOTE_CONFIG_SDK_VERSION","DEFAULT_CONFIGS","FIS_AUTH_PREFIX","COULD_NOT_GET_CONFIG_MSG","processConfig","fpr_enabled","fpr_log_source","fpr_log_endpoint_url","fpr_log_transport_key","fpr_vc_network_request_sampling_rate","fpr_vc_trace_sampling_rate","shouldLogAfterSampling","samplingRate","initializationPromise","initializationStatus","getInitializationPromise","performanceController","getDocumentReadyComplete","installationsService","iidPromise","iidVal","getIidPromise","expiryString","expiry","configStringified","getStoredConfig","authTokenPromise","authTokenVal","getAuthTokenPromise","getProjectId","getApiKey","app_instance_id","app_instance_id_token","app_id","app_version","sdk_version","getRemoteConfig","storeConfig","getConfig","changeInitializationStatus","initializePerf","DEFAULT_SEND_INTERVAL_MS","remainingTries","isTransportSetup","processQueue","timeOffset","staged","log_event","evt","source_extension_json_proto3","event_time_ms","eventTime","flTransportFullUrl","postToFlEndpoint","res","transportWait","nextRequestWaitMillis","requestOffset","logResponseDetails","responseAction","sendEventsToFl","request_time_ms","client_info","client_type","js_client_info","log_source","dispatchQueueEvents","sendLog","resourceType","addToQueue","transportHandler","logTrace","trace","settingsService","isAuto","sendTraceLog","networkRequest","networkRequestMetric","http_method","httpMethod","http_response_code","response_payload_bytes","responsePayloadBytes","client_start_time_us","startTimeUs","time_to_response_initiated_us","timeToResponseInitiatedUs","time_to_response_completed_us","timeToResponseCompletedUs","perfMetric","application_info","getApplicationInfo","network_request_metric","serializeNetworkRequest","traceMetric","is_auto","duration_us","durationUs","counters","customAttributes","getAttributes","custom_attributes","trace_metric","serializeTrace","google_app_id","web_app_info","page_url","service_worker_status","visibility_state","effective_connection_type","application_process_state","oobMetrics","Trace","traceMeasureName","api","randomId","traceStartMark","traceStopMark","traceMeasure","calculateTraceMetrics","traceName","record","startTime","duration","metrics","metricName","incrementMetric","counter","numAsInteger","putMetric","customMetricName","providedValue","valueAsInteger","convertMetricValueToInteger","getMetric","putAttribute","attr","isValidName","isValidValue","isValidCustomAttributeValue","attributeName","attributeValue","getAttribute","removeAttribute","setStartTime","setDuration","perfMeasureEntries","perfMeasureEntry","createOobTrace","navigationTimings","paintTimings","firstInputDelay","route","timeOriginUs","domInteractive","domContentLoadedEventEnd","loadEventEnd","firstPaint","paintObject","firstContentfulPaint","createUserTimingTrace","createNetworkRequestEntry","performanceEntry","responseStart","responseEnd","networkRequestUrl","logEndpointUrl","flEndpointUrl","logNetworkRequest","transferSize","setupOobResources","timeoutId","setupOobTraces","resources","setupNetworkRequests","measures","setupUserTimingTraces","PerformanceController","initialized","_init","isAvailable","setupApi","perfInstance","storageBucket","measurementId","signIn","_assertInstanceOf","resolverInternal","signInWithPopup","getProfilePicUrl","getUserName","getChucVu","getElementById","textContent","isUserSignedIn","loadMessages","idTopic","mainChat","_ChatPath","Af","El","ch","change","div","parentNode","removeChild","deleteMessage","displayMessage","userid","chucvu","profilePicUrl","imageUrl","_ChatPathUser","loadingAI","display","saveImageMessage","messageRef","LOADING_IMAGE_URL","filePath","newImageRef","serviceOrRef","bucketUrl","storageInstance","connectStorageEmulator$1","connectStorageEmulator","getStorage","pathOrUrl","ref$1","fileSnapshot","uploadBytesResumable$1","publicImageUrl","getDownloadURL","storageUri","saveMessagingDeviceToken","currentToken","onMessage$1","tokenRef","requestNotificationsPermissions","checkSignedInWithMessage","MESSAGE_TEMPLATE","MY_MESSAGE_TEMPLATE","addSizeToGoogleProfilePic","picUrl","innerHTML","firstChild","existingMessages","messageListElement","children","messageListNode","messageListNodeTime","nextSibling","insertBefore","createAndInsertMessage","querySelector","backgroundImage","messageElement","urlify","scrollTop","scrollHeight","messageInputElement","toggleButton","submitButtonElement","_assistant_id","binchat","idtopic","subnamechat","toastLiveExample","toast","bootstrap","Offcanvas","show","confirm","classnameChat","getElementsByClassName","signInButtonElement","messageFormElement","imageButtonElement","imageFormElement","mediaCaptureElement","userPicElement","userNameElement","signOutButtonElement","getFirebaseConfig","getPerformance","userName","messageText","asstId","incoming","assistant_id","_content","run_response","MakeAssistantAI","MakeChatAI","saveMessagetoPic"],"sourceRoot":""}