{"version":3,"file":"form_component-BWqfMEZD.js","sources":["../../../node_modules/@slideslive/fuse-kit/dist/utils/map/map_to_object.js","../../../node_modules/@slideslive/fuse-kit/dist/utils/utilities/export_csv.js","../../../node_modules/@slideslive/fuse-kit/dist/utils/utilities/check_delayed_result_with_promise.js","../../../app/frontend/library/javascript/choices_speaker_controller.js","../../../app/frontend/library/javascript/share_popup_controller.js","../../../node_modules/base45/lib/base45.js","../../../node_modules/base45/index.js","../../../node_modules/cbor-x/decode.js","../../../node_modules/cbor-x/encode.js","../../../node_modules/jsqr-es6/dist/jsQR.js","../../../node_modules/pako/dist/pako.esm.mjs","../../../app/components/library/account_edit/alex/covid19_cert_tab_component/covid19_cert_tab_component.js","../../../app/components/library/account_edit/alex/hourly_rates_tab_component/hourly_rates_tab_component.js","../../../app/components/library/account_edit/alex/payout_methods_component/payout_methods_component.js","../../../app/components/library/account_edit/alex/recording_radius_tab_component/recording_radius_tab_component.js","../../../app/components/library/account_edit/basic_tab_component/basic_tab_component.js","../../../app/components/library/account_edit/change_password_modal_component/change_password_modal_component.js","../../../app/components/library/account_edit/form_component/form_component.js","../../../app/components/library/account_show/header_component/header_component.js","../../../app/components/library/account_super/subordinate_accounts_component/subordinate_accounts_component.js","../../../app/components/library/box_with_text_component/box_with_text_component.js","../../../app/components/library/devise/bg_component/bg_component.js","../../../app/components/library/embed/body_component/body_component.js","../../../node_modules/resize-observer-polyfill/dist/ResizeObserver.es.js","../../../app/components/library/embed/box_background_component/box_background_component.js","../../../app/components/library/embed/player_component/player_component.js","../../../app/components/library/fire_empty_component/fire_empty_component.js","../../../app/components/library/fire_empty_container_component/fire_empty_container_component.js","../../../app/components/library/follow_component/follow_component.js","../../../app/components/library/home/onboarding/follow_component/follow_component.js","../../../app/components/library/home/onboarding/sign_up_component/sign_up_component.js","../../../app/components/library/issue_reports/form_component/form_component.js","../../../app/components/library/log_in_modal_component/log_in_modal_component.js","../../../app/components/library/offline_player/presentation_show_component/presentation_show_component.js","../../../app/frontend/modules/permanent_player/index.js","../../../app/components/library/permanent_player_component/permanent_player_component.js","../../../app/components/library/player_base_component/player_base_component.js","../../../app/components/library/presentation_edit/form_component/form_component.js","../../../app/components/library/presentation_edit/player_component/player_component.js","../../../app/components/library/presentation_edit/security_privacy_tab_component/security_privacy_tab_component.js","../../../app/components/library/presentation_edit/speaker_component/speaker_component.js","../../../app/components/library/presentation_edit/task_content_component/task_content_component.js","../../../app/components/library/presentation_edit/thumbnail_component/thumbnail_component.js","../../../app/components/library/presentation_edit_component/presentation_edit_component.js","../../../app/components/library/presentation_show/box_component/box_component.js","../../../app/components/library/presentation_show/box_playlist_loader_component/box_playlist_loader_component.js","../../../node_modules/@firebase/util/dist/index.esm2017.js","../../../node_modules/@firebase/component/dist/esm/index.esm2017.js","../../../node_modules/@firebase/logger/dist/esm/index.esm2017.js","../../../node_modules/idb/build/wrap-idb-value.js","../../../node_modules/idb/build/index.js","../../../node_modules/@firebase/app/dist/esm/index.esm2017.js","../../../node_modules/@firebase/app-compat/dist/esm/index.esm2017.js","../../../node_modules/firebase/compat/app/dist/esm/index.esm.js","../../../node_modules/@firebase/database/dist/index.esm2017.js","../../../node_modules/@firebase/database-compat/dist/index.esm2017.js","../../../app/components/library/presentation_show/comments_section_component/comments_section_component.js","../../../app/components/library/presentation_show/impression_component/impression_component.js","../../../app/components/library/presentation_show/player_component/player_component.js","../../../app/components/library/presentation_show/share_modal_component/share_modal_component.js","../../../app/components/library/presentation_show/sharing_section_component/sharing_section_component.js","../../../app/components/library/presentation_show/sign_up_interruption/modal_component/modal_component.js","../../../app/components/library/presentation_show/sign_up_interruption/password_required_component/password_required_component.js","../../../app/components/library/presentation_show/sign_up_interruption/success_component/success_component.js","../../../app/components/library/presentation_show_component/presentation_show_component.js","../../../app/components/library/presentation_stream_edit/edit_server_modal_component/edit_server_modal_component.js","../../../app/components/library/presentation_stream_edit/finish_stream_modal_component/finish_stream_modal_component.js","../../../app/components/library/presentation_stream_edit/form_component/form_component.js","../../../app/components/library/presentation_stream_edit/live_servers_component/live_servers_component.js","../../../app/components/library/presentation_stream_edit/monitoring_tab_component/monitoring_tab_component.js","../../../app/components/library/presentation_stream_edit/recording_app_monitoring_tab_component/recording_app_monitoring_tab_component.js","../../../app/components/library/presentation_stream_edit/restart_wowza_transcript_modal_component/restart_wowza_transcript_modal_component.js","../../../app/components/library/presentation_stream_edit/stream_tab_component/stream_tab_component.js","../../../app/components/library/presentation_video_upload/file_component/file_component.js","../../../app/components/library/presentation_video_upload/upload_component/upload_component.js","../../../app/components/library/presentation_video_upload/upload_exports_modal_component/upload_exports_modal_component.js","../../../app/components/library/presentation_video_upload/upload_videos_to_append_modal_component/upload_videos_to_append_modal_component.js","../../../app/components/library/protected_content/log_in_form_component/log_in_form_component.js","../../../app/components/library/search_show/categories_component/categories_component.js","../../../app/components/library/search_show/content_component/content_component.js","../../../app/components/library/user_access_control/add_form_component/add_form_component.js","../../../app/components/library/user_access_control/item_component/item_component.js","../../../app/components/library/viewer_registration_edit/form_component/form_component.js"],"sourcesContent":["import isArray from \"../utilities/is_array.js\";\nfunction mapToObject(map) {\n  function convert(m) {\n    return Array.from(m).reduce((acc, [key, value]) => {\n      if (value instanceof Map) {\n        acc[key] = convert(value);\n      } else if (isArray(value)) {\n        acc[key] = value.map((entry) => convert(entry));\n      } else {\n        acc[key] = value;\n      }\n      return acc;\n    }, {});\n  }\n  return convert(map);\n}\nexport {\n  mapToObject as default\n};\n","import isVariableDefinedNotNull from \"./is_variable_defined_not_null.js\";\nfunction exportCsv(filename, rows) {\n  const processRow = (row) => {\n    let finalVal = \"\";\n    for (let j = 0; j < row.length; j++) {\n      let innerValue = !isVariableDefinedNotNull(row[j]) ? \"\" : row[j].toString();\n      if (row[j] instanceof Date) {\n        innerValue = row[j].toLocaleString();\n      }\n      let result = innerValue.replace(/\"/g, '\"\"');\n      if (result.search(/(\"|,|\\n)/g) >= 0) result = `\"${result}\"`;\n      if (j > 0) finalVal += \",\";\n      finalVal += result;\n    }\n    return `${finalVal}\n`;\n  };\n  let csvFile = \"\";\n  for (let i = 0; i < rows.length; i++) {\n    csvFile += processRow(rows[i]);\n  }\n  const blob = new Blob([csvFile], { type: \"text/csv;charset=utf-8;\" });\n  if (navigator.msSaveBlob) {\n    navigator.msSaveBlob(blob, filename);\n  } else {\n    const link = document.createElement(\"a\");\n    if (link.download !== void 0) {\n      const url = URL.createObjectURL(blob);\n      link.setAttribute(\"href\", url);\n      link.setAttribute(\"download\", filename);\n      link.style.visibility = \"hidden\";\n      document.body.appendChild(link);\n      link.click();\n      document.body.removeChild(link);\n    }\n  }\n}\nexport {\n  exportCsv as default\n};\n","import checkDelayedResult from \"./check_delayed_result.js\";\nfunction checkDelayedResultWithPromise(urlOrDelayedResultId, checkInterval) {\n  return new Promise((resolve, reject) => {\n    checkDelayedResult(\n      urlOrDelayedResultId,\n      (result) => resolve(result),\n      checkInterval,\n      (errors) => reject(errors)\n    );\n  });\n}\nexport {\n  checkDelayedResultWithPromise as default\n};\n","import ChoicesAutocompleteController from '@/fuse/javascript/choices_autocomplete_controller';\nimport { addClasses, createElementFromHTML } from '@slideslive/fuse-kit/utils';\n\nexport default class extends ChoicesAutocompleteController {\n  initialize() {\n    if (this.element.firstElementChild && this.element.firstElementChild.value === '') {\n      this.element.firstElementChild.disabled = true;\n      this.element.firstElementChild.setAttribute('placeholder', true);\n    }\n\n    super.initialize();\n  }\n\n  destroyChoices() {\n    super.destroyChoices();\n\n    if (this.element.firstElementChild && this.element.firstElementChild.value === '') {\n      this.element.firstElementChild.disabled = false;\n      this.element.firstElementChild.removeAttribute('placeholder');\n    }\n  }\n\n  optionCustomPropertiesFor(data) {\n    return { description: data.description };\n  }\n\n  additionalOptionsForQuery(query) {\n    if (!query) {\n      return null;\n    }\n\n    return [\n      {\n        label: query,\n        value: '0',\n        customProperties: {\n          labelTemplate: 'Create new speaker — <span class=\"tw-text-bold\">%label%</span>',\n        },\n      },\n    ];\n  }\n\n  renderChoice({ classNames: globalClasses }, data, itemSelectText) {\n    const role = data.groupId > 0 ? 'role=\"treeitem\"' : 'role=\"option\"';\n    const localClasses = addClasses(globalClasses.item, globalClasses.itemChoice, {\n      [globalClasses.itemDisabled]: data.disabled,\n      [globalClasses.itemSelectable]: !data.disabled,\n      [globalClasses.placeholder]: data.placeholder,\n    }).join(' ');\n\n    let html;\n\n    if (data.customProperties && data.customProperties.labelTemplate) {\n      html = data.customProperties.labelTemplate.replace(/%label%/g, data.label);\n    } else {\n      html = data.label;\n      html += `<div class=\"tw-text-white/68 tw-text-sm\">ID: ${data.value}</div>`;\n    }\n\n    return createElementFromHTML(`\n      <div\n        class=\"${localClasses}\"\n        data-select-text=\"${itemSelectText}\"\n        data-choice\n        data-id=\"${data.id}\"\n        data-value=\"${data.value}\"\n        ${data.disabled ? 'data-choice-disabled aria-disabled=\"true\"' : 'data-choice-selectable'}\n        id=\"${data.elementId}\"\n        ${role}\n        >\n        ${html}\n      </div>\n    `);\n  }\n\n  get showSelectedValuesInDropdown() {\n    return true;\n  }\n\n  get createTemplates() {\n    return {\n      choice: this.renderChoice.bind(this),\n    };\n  }\n\n  get labelField() {\n    return 'name';\n  }\n\n  get valueField() {\n    return 'id';\n  }\n}\n","import ApplicationController from 'modules/application_controller';\n\nexport default class extends ApplicationController {\n  open(event) {\n    event.preventDefault();\n\n    const target = event.currentTarget;\n    const url = target.getAttribute('href');\n    const name = `SlidesLive ${target.getAttribute('title')} Share`;\n\n    const width = 575;\n    const height = 400;\n\n    this.openPopup(width, height, url, name);\n  }\n\n  openPopup(width, height, url, name) {\n    const left = (window.outerWidth - width) / 2;\n    const top = (window.outerHeight - height) / 2;\n\n    let opts = 'menubar=no,toolbar=no,resizable=yes,scrollbars=yes';\n    opts += `,width=${width}`;\n    opts += `,height=${height}`;\n    opts += `,top=${top}`;\n    opts += `,left=${left}`;\n\n    window.open(url, name, opts);\n  }\n}\n","const charset = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ $%*+-./:'\nconst divmod = (x, y) => [Math.floor(x / y), x % y]\n\n// Encode a buffer (or uint8array) to base45-encoded string\nconst encode = (buffer) => {\n  if (typeof (buffer) === 'string') buffer = Buffer.from(buffer)\n  let res = ''\n  for (let i = 0; i < buffer.length; i = i + 2) {\n    if (buffer.length - i > 1) {\n      const x = (buffer[i] << 8) + buffer[i + 1]\n      const [e, rest] = divmod(x, 45 * 45)\n      const [d, c] = divmod(rest, 45)\n      res += charset[c] + charset[d] + charset[e]\n    } else {\n      const [d, c] = divmod(buffer[i], 45)\n      res += charset[c] + charset[d]\n    }\n  }\n  return res\n}\n\n// Decode base45-encoded input\nconst decode = (input) => {\n  const buffer = Array.from(input).map(c => charset.indexOf(c))\n  const res = []\n  for (let i = 0; i < buffer.length; i = i + 3) {\n    if (buffer.length - i >= 3) {\n      const x = buffer[i] + buffer[i + 1] * 45 + buffer[i + 2] * 45 * 45\n      if (x > 0xFFFF) {\n        throw new Error(\"Invalid base45 string\")\n      }\n      res.push(...divmod(x, 256))\n    } else {\n      const x = buffer[i] + buffer[i + 1] * 45\n      if (x > 0xFF) {\n        throw new Error(\"Invalid base45 string\")\n      }\n      res.push(x)\n    }\n  }\n  return Buffer.from(res)\n}\n\nmodule.exports = {\n  encode,\n  decode\n}\n","module.exports = require('./lib/base45')\n","let decoder\ntry {\n\tdecoder = new TextDecoder()\n} catch(error) {}\nlet src\nlet srcEnd\nlet position = 0\nlet alreadySet\nconst EMPTY_ARRAY = []\nconst LEGACY_RECORD_INLINE_ID = 105\nconst RECORD_DEFINITIONS_ID = 0xdffe\nconst RECORD_INLINE_ID = 0xdfff // temporary first-come first-serve tag // proposed tag: 0x7265 // 're'\nconst BUNDLED_STRINGS_ID = 0xdff9\nconst PACKED_TABLE_TAG_ID = 51\nconst PACKED_REFERENCE_TAG_ID = 6\nconst STOP_CODE = {}\nlet maxArraySize = 112810000 // This is the maximum array size in V8. We would potentially detect and set it higher\n// for JSC, but this is pretty large and should be sufficient for most use cases\nlet maxMapSize = 16810000 // JavaScript has a fixed maximum map size of about 16710000, but JS itself enforces this,\n// so we don't need to\n\nlet maxObjectSize = 16710000; // This is the maximum number of keys in a Map. It takes over a minute to create this\n// many keys in an object, so also probably a reasonable choice there.\nlet strings = EMPTY_ARRAY\nlet stringPosition = 0\nlet currentDecoder = {}\nlet currentStructures\nlet srcString\nlet srcStringStart = 0\nlet srcStringEnd = 0\nlet bundledStrings\nlet referenceMap\nlet currentExtensions = []\nlet currentExtensionRanges = []\nlet packedValues\nlet dataView\nlet restoreMapsAsObject\nlet defaultOptions = {\n\tuseRecords: false,\n\tmapsAsObjects: true\n}\nlet sequentialMode = false\nlet inlineObjectReadThreshold = 2;\nvar BlockedFunction // we use search and replace to change the next call to BlockedFunction to avoid CSP issues for\n// no-eval build\ntry {\n\tnew Function('')\n} catch(error) {\n\t// if eval variants are not supported, do not create inline object readers ever\n\tinlineObjectReadThreshold = Infinity\n}\n\n\n\nexport class Decoder {\n\tconstructor(options) {\n\t\tif (options) {\n\t\t\tif ((options.keyMap || options._keyMap) && !options.useRecords) {\n\t\t\t\toptions.useRecords = false\n\t\t\t\toptions.mapsAsObjects = true\n\t\t\t}\n\t\t\tif (options.useRecords === false && options.mapsAsObjects === undefined)\n\t\t\t\toptions.mapsAsObjects = true\n\t\t\tif (options.getStructures)\n\t\t\t\toptions.getShared = options.getStructures\n\t\t\tif (options.getShared && !options.structures)\n\t\t\t\t(options.structures = []).uninitialized = true // this is what we use to denote an uninitialized structures\n\t\t\tif (options.keyMap) {\n\t\t\t\tthis.mapKey = new Map()\n\t\t\t\tfor (let [k,v] of Object.entries(options.keyMap)) this.mapKey.set(v,k)\n\t\t\t}\n\t\t}\n\t\tObject.assign(this, options)\n\t}\n\t/*\n\tdecodeKey(key) {\n\t\treturn this.keyMap\n\t\t\t? Object.keys(this.keyMap)[Object.values(this.keyMap).indexOf(key)] || key\n\t\t\t: key\n\t}\n\t*/\n\tdecodeKey(key) {\n\t\treturn this.keyMap ? this.mapKey.get(key) || key : key\n\t}\n\t\n\tencodeKey(key) {\n\t\treturn this.keyMap && this.keyMap.hasOwnProperty(key) ? this.keyMap[key] : key\n\t}\n\n\tencodeKeys(rec) {\n\t\tif (!this._keyMap) return rec\n\t\tlet map = new Map()\n\t\tfor (let [k,v] of Object.entries(rec)) map.set((this._keyMap.hasOwnProperty(k) ? this._keyMap[k] : k), v)\n\t\treturn map\n\t}\n\n\tdecodeKeys(map) {\n\t\tif (!this._keyMap || map.constructor.name != 'Map') return map\n\t\tif (!this._mapKey) {\n\t\t\tthis._mapKey = new Map()\n\t\t\tfor (let [k,v] of Object.entries(this._keyMap)) this._mapKey.set(v,k)\n\t\t}\n\t\tlet res = {}\n\t\t//map.forEach((v,k) => res[Object.keys(this._keyMap)[Object.values(this._keyMap).indexOf(k)] || k] = v)\n\t\tmap.forEach((v,k) => res[safeKey(this._mapKey.has(k) ? this._mapKey.get(k) : k)] =  v)\n\t\treturn res\n\t}\n\t\n\tmapDecode(source, end) {\n\t\n\t\tlet res = this.decode(source)\n\t\tif (this._keyMap) { \n\t\t\t//Experiemntal support for Optimised KeyMap  decoding \n\t\t\tswitch (res.constructor.name) {\n\t\t\t\tcase 'Array': return res.map(r => this.decodeKeys(r))\n\t\t\t\t//case 'Map': return this.decodeKeys(res)\n\t\t\t}\n\t\t}\n\t\treturn res\n\t}\n\n\tdecode(source, end) {\n\t\tif (src) {\n\t\t\t// re-entrant execution, save the state and restore it after we do this decode\n\t\t\treturn saveState(() => {\n\t\t\t\tclearSource()\n\t\t\t\treturn this ? this.decode(source, end) : Decoder.prototype.decode.call(defaultOptions, source, end)\n\t\t\t})\n\t\t}\n\t\tsrcEnd = end > -1 ? end : source.length\n\t\tposition = 0\n\t\tstringPosition = 0\n\t\tsrcStringEnd = 0\n\t\tsrcString = null\n\t\tstrings = EMPTY_ARRAY\n\t\tbundledStrings = null\n\t\tsrc = source\n\t\t// this provides cached access to the data view for a buffer if it is getting reused, which is a recommend\n\t\t// technique for getting data from a database where it can be copied into an existing buffer instead of creating\n\t\t// new ones\n\t\ttry {\n\t\t\tdataView = source.dataView || (source.dataView = new DataView(source.buffer, source.byteOffset, source.byteLength))\n\t\t} catch(error) {\n\t\t\t// if it doesn't have a buffer, maybe it is the wrong type of object\n\t\t\tsrc = null\n\t\t\tif (source instanceof Uint8Array)\n\t\t\t\tthrow error\n\t\t\tthrow new Error('Source must be a Uint8Array or Buffer but was a ' + ((source && typeof source == 'object') ? source.constructor.name : typeof source))\n\t\t}\n\t\tif (this instanceof Decoder) {\n\t\t\tcurrentDecoder = this\n\t\t\tpackedValues = this.sharedValues &&\n\t\t\t\t(this.pack ? new Array(this.maxPrivatePackedValues || 16).concat(this.sharedValues) :\n\t\t\t\tthis.sharedValues)\n\t\t\tif (this.structures) {\n\t\t\t\tcurrentStructures = this.structures\n\t\t\t\treturn checkedRead()\n\t\t\t} else if (!currentStructures || currentStructures.length > 0) {\n\t\t\t\tcurrentStructures = []\n\t\t\t}\n\t\t} else {\n\t\t\tcurrentDecoder = defaultOptions\n\t\t\tif (!currentStructures || currentStructures.length > 0)\n\t\t\t\tcurrentStructures = []\n\t\t\tpackedValues = null\n\t\t}\n\t\treturn checkedRead()\n\t}\n\tdecodeMultiple(source, forEach) {\n\t\tlet values, lastPosition = 0\n\t\ttry {\n\t\t\tlet size = source.length\n\t\t\tsequentialMode = true\n\t\t\tlet value = this ? this.decode(source, size) : defaultDecoder.decode(source, size)\n\t\t\tif (forEach) {\n\t\t\t\tif (forEach(value) === false) {\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t\twhile(position < size) {\n\t\t\t\t\tlastPosition = position\n\t\t\t\t\tif (forEach(checkedRead()) === false) {\n\t\t\t\t\t\treturn\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\telse {\n\t\t\t\tvalues = [ value ]\n\t\t\t\twhile(position < size) {\n\t\t\t\t\tlastPosition = position\n\t\t\t\t\tvalues.push(checkedRead())\n\t\t\t\t}\n\t\t\t\treturn values\n\t\t\t}\n\t\t} catch(error) {\n\t\t\terror.lastPosition = lastPosition\n\t\t\terror.values = values\n\t\t\tthrow error\n\t\t} finally {\n\t\t\tsequentialMode = false\n\t\t\tclearSource()\n\t\t}\n\t}\n}\nexport function getPosition() {\n\treturn position\n}\nexport function checkedRead() {\n\ttry {\n\t\tlet result = read()\n\t\tif (bundledStrings) {\n\t\t\tif (position >= bundledStrings.postBundlePosition) {\n\t\t\t\tlet error = new Error('Unexpected bundle position');\n\t\t\t\terror.incomplete = true;\n\t\t\t\tthrow error\n\t\t\t}\n\t\t\t// bundled strings to skip past\n\t\t\tposition = bundledStrings.postBundlePosition;\n\t\t\tbundledStrings = null;\n\t\t}\n\n\t\tif (position == srcEnd) {\n\t\t\t// finished reading this source, cleanup references\n\t\t\tcurrentStructures = null\n\t\t\tsrc = null\n\t\t\tif (referenceMap)\n\t\t\t\treferenceMap = null\n\t\t} else if (position > srcEnd) {\n\t\t\t// over read\n\t\t\tlet error = new Error('Unexpected end of CBOR data')\n\t\t\terror.incomplete = true\n\t\t\tthrow error\n\t\t} else if (!sequentialMode) {\n\t\t\tthrow new Error('Data read, but end of buffer not reached')\n\t\t}\n\t\t// else more to read, but we are reading sequentially, so don't clear source yet\n\t\treturn result\n\t} catch(error) {\n\t\tclearSource()\n\t\tif (error instanceof RangeError || error.message.startsWith('Unexpected end of buffer')) {\n\t\t\terror.incomplete = true\n\t\t}\n\t\tthrow error\n\t}\n}\n\nexport function read() {\n\tlet token = src[position++]\n\tlet majorType = token >> 5\n\ttoken = token & 0x1f\n\tif (token > 0x17) {\n\t\tswitch (token) {\n\t\t\tcase 0x18:\n\t\t\t\ttoken = src[position++]\n\t\t\t\tbreak\n\t\t\tcase 0x19:\n\t\t\t\tif (majorType == 7) {\n\t\t\t\t\treturn getFloat16()\n\t\t\t\t}\n\t\t\t\ttoken = dataView.getUint16(position)\n\t\t\t\tposition += 2\n\t\t\t\tbreak\n\t\t\tcase 0x1a:\n\t\t\t\tif (majorType == 7) {\n\t\t\t\t\tlet value = dataView.getFloat32(position)\n\t\t\t\t\tif (currentDecoder.useFloat32 > 2) {\n\t\t\t\t\t\t// this does rounding of numbers that were encoded in 32-bit float to nearest significant decimal digit that could be preserved\n\t\t\t\t\t\tlet multiplier = mult10[((src[position] & 0x7f) << 1) | (src[position + 1] >> 7)]\n\t\t\t\t\t\tposition += 4\n\t\t\t\t\t\treturn ((multiplier * value + (value > 0 ? 0.5 : -0.5)) >> 0) / multiplier\n\t\t\t\t\t}\n\t\t\t\t\tposition += 4\n\t\t\t\t\treturn value\n\t\t\t\t}\n\t\t\t\ttoken = dataView.getUint32(position)\n\t\t\t\tposition += 4\n\t\t\t\tbreak\n\t\t\tcase 0x1b:\n\t\t\t\tif (majorType == 7) {\n\t\t\t\t\tlet value = dataView.getFloat64(position)\n\t\t\t\t\tposition += 8\n\t\t\t\t\treturn value\n\t\t\t\t}\n\t\t\t\tif (majorType > 1) {\n\t\t\t\t\tif (dataView.getUint32(position) > 0)\n\t\t\t\t\t\tthrow new Error('JavaScript does not support arrays, maps, or strings with length over 4294967295')\n\t\t\t\t\ttoken = dataView.getUint32(position + 4)\n\t\t\t\t} else if (currentDecoder.int64AsNumber) {\n\t\t\t\t\ttoken = dataView.getUint32(position) * 0x100000000\n\t\t\t\t\ttoken += dataView.getUint32(position + 4)\n\t\t\t\t} else\n\t\t\t\t\ttoken = dataView.getBigUint64(position)\n\t\t\t\tposition += 8\n\t\t\t\tbreak\n\t\t\tcase 0x1f: \n\t\t\t\t// indefinite length\n\t\t\t\tswitch(majorType) {\n\t\t\t\t\tcase 2: // byte string\n\t\t\t\t\tcase 3: // text string\n\t\t\t\t\t\tthrow new Error('Indefinite length not supported for byte or text strings')\n\t\t\t\t\tcase 4: // array\n\t\t\t\t\t\tlet array = []\n\t\t\t\t\t\tlet value, i = 0\n\t\t\t\t\t\twhile ((value = read()) != STOP_CODE) {\n\t\t\t\t\t\t\tif (i >= maxArraySize) throw new Error(`Array length exceeds ${maxArraySize}`)\n\t\t\t\t\t\t\tarray[i++] = value\n\t\t\t\t\t\t}\n\t\t\t\t\t\treturn majorType == 4 ? array : majorType == 3 ? array.join('') : Buffer.concat(array)\n\t\t\t\t\tcase 5: // map\n\t\t\t\t\t\tlet key\n\t\t\t\t\t\tif (currentDecoder.mapsAsObjects) {\n\t\t\t\t\t\t\tlet object = {}\n\t\t\t\t\t\t\tlet i = 0;\n\t\t\t\t\t\t\tif (currentDecoder.keyMap) {\n\t\t\t\t\t\t\t\twhile((key = read()) != STOP_CODE) {\n\t\t\t\t\t\t\t\t\tif (i++ >= maxMapSize) throw new Error(`Property count exceeds ${maxMapSize}`)\n\t\t\t\t\t\t\t\t\tobject[safeKey(currentDecoder.decodeKey(key))] = read()\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\telse {\n\t\t\t\t\t\t\t\twhile ((key = read()) != STOP_CODE) {\n\t\t\t\t\t\t\t\t\tif (i++ >= maxMapSize) throw new Error(`Property count exceeds ${maxMapSize}`)\n\t\t\t\t\t\t\t\t\tobject[safeKey(key)] = read()\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\treturn object\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tif (restoreMapsAsObject) {\n\t\t\t\t\t\t\t\tcurrentDecoder.mapsAsObjects = true\n\t\t\t\t\t\t\t\trestoreMapsAsObject = false\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tlet map = new Map()\n\t\t\t\t\t\t\tif (currentDecoder.keyMap) {\n\t\t\t\t\t\t\t\tlet i = 0;\n\t\t\t\t\t\t\t\twhile((key = read()) != STOP_CODE) {\n\t\t\t\t\t\t\t\t\tif (i++ >= maxMapSize) {\n\t\t\t\t\t\t\t\t\t\tthrow new Error(`Map size exceeds ${maxMapSize}`);\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\tmap.set(currentDecoder.decodeKey(key), read())\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\telse {\n\t\t\t\t\t\t\t\tlet i = 0;\n\t\t\t\t\t\t\t\twhile ((key = read()) != STOP_CODE) {\n\t\t\t\t\t\t\t\t\tif (i++ >= maxMapSize) {\n\t\t\t\t\t\t\t\t\t\tthrow new Error(`Map size exceeds ${maxMapSize}`);\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\tmap.set(key, read())\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\treturn map\n\t\t\t\t\t\t}\n\t\t\t\t\tcase 7:\n\t\t\t\t\t\treturn STOP_CODE\n\t\t\t\t\tdefault:\n\t\t\t\t\t\tthrow new Error('Invalid major type for indefinite length ' + majorType)\n\t\t\t\t}\n\t\t\tdefault:\n\t\t\t\tthrow new Error('Unknown token ' + token)\n\t\t}\n\t}\n\tswitch (majorType) {\n\t\tcase 0: // positive int\n\t\t\treturn token\n\t\tcase 1: // negative int\n\t\t\treturn ~token\n\t\tcase 2: // buffer\n\t\t\treturn readBin(token)\n\t\tcase 3: // string\n\t\t\tif (srcStringEnd >= position) {\n\t\t\t\treturn srcString.slice(position - srcStringStart, (position += token) - srcStringStart)\n\t\t\t}\n\t\t\tif (srcStringEnd == 0 && srcEnd < 140 && token < 32) {\n\t\t\t\t// for small blocks, avoiding the overhead of the extract call is helpful\n\t\t\t\tlet string = token < 16 ? shortStringInJS(token) : longStringInJS(token)\n\t\t\t\tif (string != null)\n\t\t\t\t\treturn string\n\t\t\t}\n\t\t\treturn readFixedString(token)\n\t\tcase 4: // array\n\t\t\tif (token >= maxArraySize) throw new Error(`Array length exceeds ${maxArraySize}`)\n\t\t\tlet array = new Array(token)\n\t\t  //if (currentDecoder.keyMap) for (let i = 0; i < token; i++) array[i] = currentDecoder.decodeKey(read())\t\n\t\t\t//else \n\t\t\tfor (let i = 0; i < token; i++) array[i] = read()\n\t\t\treturn array\n\t\tcase 5: // map\n\t\t\tif (token >= maxMapSize) throw new Error(`Map size exceeds ${maxArraySize}`)\n\t\t\tif (currentDecoder.mapsAsObjects) {\n\t\t\t\tlet object = {}\n\t\t\t\tif (currentDecoder.keyMap) for (let i = 0; i < token; i++) object[safeKey(currentDecoder.decodeKey(read()))] = read()\n\t\t\t\telse for (let i = 0; i < token; i++) object[safeKey(read())] = read()\n\t\t\t\treturn object\n\t\t\t} else {\n\t\t\t\tif (restoreMapsAsObject) {\n\t\t\t\t\tcurrentDecoder.mapsAsObjects = true\n\t\t\t\t\trestoreMapsAsObject = false\n\t\t\t\t}\n\t\t\t\tlet map = new Map()\n\t\t\t\tif (currentDecoder.keyMap) for (let i = 0; i < token; i++) map.set(currentDecoder.decodeKey(read()),read())\n\t\t\t\telse for (let i = 0; i < token; i++) map.set(read(), read())\n\t\t\t\treturn map\n\t\t\t}\n\t\tcase 6: // extension\n\t\t\tif (token >= BUNDLED_STRINGS_ID) {\n\t\t\t\tlet structure = currentStructures[token & 0x1fff] // check record structures first\n\t\t\t\t// At some point we may provide an option for dynamic tag assignment with a range like token >= 8 && (token < 16 || (token > 0x80 && token < 0xc0) || (token > 0x130 && token < 0x4000))\n\t\t\t\tif (structure) {\n\t\t\t\t\tif (!structure.read) structure.read = createStructureReader(structure)\n\t\t\t\t\treturn structure.read()\n\t\t\t\t}\n\t\t\t\tif (token < 0x10000) {\n\t\t\t\t\tif (token == RECORD_INLINE_ID) { // we do a special check for this so that we can keep the\n\t\t\t\t\t\t// currentExtensions as densely stored array (v8 stores arrays densely under about 3000 elements)\n\t\t\t\t\t\tlet length = readJustLength()\n\t\t\t\t\t\tlet id = read()\n\t\t\t\t\t\tlet structure = read()\n\t\t\t\t\t\trecordDefinition(id, structure)\n\t\t\t\t\t\tlet object = {}\n\t\t\t\t\t\tif (currentDecoder.keyMap) for (let i = 2; i < length; i++) {\n\t\t\t\t\t\t\tlet key = currentDecoder.decodeKey(structure[i - 2])\n\t\t\t\t\t\t\tobject[safeKey(key)] = read()\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse for (let i = 2; i < length; i++) {\n\t\t\t\t\t\t\tlet key = structure[i - 2]\n\t\t\t\t\t\t\tobject[safeKey(key)] = read()\n\t\t\t\t\t\t}\n\t\t\t\t\t\treturn object\n\t\t\t\t\t}\n\t\t\t\t\telse if (token == RECORD_DEFINITIONS_ID) {\n\t\t\t\t\t\tlet length = readJustLength()\n\t\t\t\t\t\tlet id = read()\n\t\t\t\t\t\tfor (let i = 2; i < length; i++) {\n\t\t\t\t\t\t\trecordDefinition(id++, read())\n\t\t\t\t\t\t}\n\t\t\t\t\t\treturn read()\n\t\t\t\t\t} else if (token == BUNDLED_STRINGS_ID) {\n\t\t\t\t\t\treturn readBundleExt()\n\t\t\t\t\t}\n\t\t\t\t\tif (currentDecoder.getShared) {\n\t\t\t\t\t\tloadShared()\n\t\t\t\t\t\tstructure = currentStructures[token & 0x1fff]\n\t\t\t\t\t\tif (structure) {\n\t\t\t\t\t\t\tif (!structure.read)\n\t\t\t\t\t\t\t\tstructure.read = createStructureReader(structure)\n\t\t\t\t\t\t\treturn structure.read()\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tlet extension = currentExtensions[token]\n\t\t\tif (extension) {\n\t\t\t\tif (extension.handlesRead)\n\t\t\t\t\treturn extension(read)\n\t\t\t\telse\n\t\t\t\t\treturn extension(read())\n\t\t\t} else {\n\t\t\t\tlet input = read()\n\t\t\t\tfor (let i = 0; i < currentExtensionRanges.length; i++) {\n\t\t\t\t\tlet value = currentExtensionRanges[i](token, input)\n\t\t\t\t\tif (value !== undefined)\n\t\t\t\t\t\treturn value\n\t\t\t\t}\n\t\t\t\treturn new Tag(input, token)\n\t\t\t}\n\t\tcase 7: // fixed value\n\t\t\tswitch (token) {\n\t\t\t\tcase 0x14: return false\n\t\t\t\tcase 0x15: return true\n\t\t\t\tcase 0x16: return null\n\t\t\t\tcase 0x17: return; // undefined\n\t\t\t\tcase 0x1f:\n\t\t\t\tdefault:\n\t\t\t\t\tlet packedValue = (packedValues || getPackedValues())[token]\n\t\t\t\t\tif (packedValue !== undefined)\n\t\t\t\t\t\treturn packedValue\n\t\t\t\t\tthrow new Error('Unknown token ' + token)\n\t\t\t}\n\t\tdefault: // negative int\n\t\t\tif (isNaN(token)) {\n\t\t\t\tlet error = new Error('Unexpected end of CBOR data')\n\t\t\t\terror.incomplete = true\n\t\t\t\tthrow error\n\t\t\t}\n\t\t\tthrow new Error('Unknown CBOR token ' + token)\n\t}\n}\nconst validName = /^[a-zA-Z_$][a-zA-Z\\d_$]*$/\nfunction createStructureReader(structure) {\n\tif (!structure) throw new Error('Structure is required in record definition');\n\tfunction readObject() {\n\t\t// get the array size from the header\n\t\tlet length = src[position++]\n\t\t//let majorType = token >> 5\n\t\tlength = length & 0x1f\n\t\tif (length > 0x17) {\n\t\t\tswitch (length) {\n\t\t\t\tcase 0x18:\n\t\t\t\t\tlength = src[position++]\n\t\t\t\t\tbreak\n\t\t\t\tcase 0x19:\n\t\t\t\t\tlength = dataView.getUint16(position)\n\t\t\t\t\tposition += 2\n\t\t\t\t\tbreak\n\t\t\t\tcase 0x1a:\n\t\t\t\t\tlength = dataView.getUint32(position)\n\t\t\t\t\tposition += 4\n\t\t\t\t\tbreak\n\t\t\t\tdefault:\n\t\t\t\t\tthrow new Error('Expected array header, but got ' + src[position - 1])\n\t\t\t}\n\t\t}\n\t\t// This initial function is quick to instantiate, but runs slower. After several iterations pay the cost to build the faster function\n\t\tlet compiledReader = this.compiledReader // first look to see if we have the fast compiled function\n\t\twhile(compiledReader) {\n\t\t\t// we have a fast compiled object literal reader\n\t\t\tif (compiledReader.propertyCount === length)\n\t\t\t\treturn compiledReader(read) // with the right length, so we use it\n\t\t\tcompiledReader = compiledReader.next // see if there is another reader with the right length\n\t\t}\n\t\tif (this.slowReads++ >= inlineObjectReadThreshold) { // create a fast compiled reader\n\t\t\tlet array = this.length == length ? this : this.slice(0, length)\n\t\t\tcompiledReader = currentDecoder.keyMap \n\t\t\t? new Function('r', 'return {' + array.map(k => currentDecoder.decodeKey(k)).map(k => validName.test(k) ? safeKey(k) + ':r()' : ('[' + JSON.stringify(k) + ']:r()')).join(',') + '}')\n\t\t\t: new Function('r', 'return {' + array.map(key => validName.test(key) ? safeKey(key) + ':r()' : ('[' + JSON.stringify(key) + ']:r()')).join(',') + '}')\n\t\t\tif (this.compiledReader)\n\t\t\t\tcompiledReader.next = this.compiledReader // if there is an existing one, we store multiple readers as a linked list because it is usually pretty rare to have multiple readers (of different length) for the same structure\n\t\t\tcompiledReader.propertyCount = length\n\t\t\tthis.compiledReader = compiledReader\n\t\t\treturn compiledReader(read)\n\t\t}\n\t\tlet object = {}\n\t\tif (currentDecoder.keyMap) for (let i = 0; i < length; i++) object[safeKey(currentDecoder.decodeKey(this[i]))] = read()\n\t\telse for (let i = 0; i < length; i++) {\n\t\t\tobject[safeKey(this[i])] = read();\n\t\t}\n\t\treturn object\n\t}\n\tstructure.slowReads = 0\n\treturn readObject\n}\n\nfunction safeKey(key) {\n\t// protect against prototype pollution\n\tif (typeof key === 'string') return key === '__proto__' ? '__proto_' : key\n\tif (typeof key === 'number' || typeof key === 'boolean' || typeof key === 'bigint') return key.toString();\n\tif (key == null) return key + '';\n\t// protect against expensive (DoS) string conversions\n\tthrow new Error('Invalid property name type ' + typeof key);\n}\n\nlet readFixedString = readStringJS\nlet readString8 = readStringJS\nlet readString16 = readStringJS\nlet readString32 = readStringJS\n\nexport let isNativeAccelerationEnabled = false\nexport function setExtractor(extractStrings) {\n\tisNativeAccelerationEnabled = true\n\treadFixedString = readString(1)\n\treadString8 = readString(2)\n\treadString16 = readString(3)\n\treadString32 = readString(5)\n\tfunction readString(headerLength) {\n\t\treturn function readString(length) {\n\t\t\tlet string = strings[stringPosition++]\n\t\t\tif (string == null) {\n\t\t\t\tif (bundledStrings)\n\t\t\t\t\treturn readStringJS(length)\n\t\t\t\tlet extraction = extractStrings(position, srcEnd, length, src)\n\t\t\t\tif (typeof extraction == 'string') {\n\t\t\t\t\tstring = extraction\n\t\t\t\t\tstrings = EMPTY_ARRAY\n\t\t\t\t} else {\n\t\t\t\t\tstrings = extraction\n\t\t\t\t\tstringPosition = 1\n\t\t\t\t\tsrcStringEnd = 1 // even if a utf-8 string was decoded, must indicate we are in the midst of extracted strings and can't skip strings\n\t\t\t\t\tstring = strings[0]\n\t\t\t\t\tif (string === undefined)\n\t\t\t\t\t\tthrow new Error('Unexpected end of buffer')\n\t\t\t\t}\n\t\t\t}\n\t\t\tlet srcStringLength = string.length\n\t\t\tif (srcStringLength <= length) {\n\t\t\t\tposition += length\n\t\t\t\treturn string\n\t\t\t}\n\t\t\tsrcString = string\n\t\t\tsrcStringStart = position\n\t\t\tsrcStringEnd = position + srcStringLength\n\t\t\tposition += length\n\t\t\treturn string.slice(0, length) // we know we just want the beginning\n\t\t}\n\t}\n}\nfunction readStringJS(length) {\n\tlet result\n\tif (length < 16) {\n\t\tif (result = shortStringInJS(length))\n\t\t\treturn result\n\t}\n\tif (length > 64 && decoder)\n\t\treturn decoder.decode(src.subarray(position, position += length))\n\tconst end = position + length\n\tconst units = []\n\tresult = ''\n\twhile (position < end) {\n\t\tconst byte1 = src[position++]\n\t\tif ((byte1 & 0x80) === 0) {\n\t\t\t// 1 byte\n\t\t\tunits.push(byte1)\n\t\t} else if ((byte1 & 0xe0) === 0xc0) {\n\t\t\t// 2 bytes\n\t\t\tconst byte2 = src[position++] & 0x3f\n\t\t\tunits.push(((byte1 & 0x1f) << 6) | byte2)\n\t\t} else if ((byte1 & 0xf0) === 0xe0) {\n\t\t\t// 3 bytes\n\t\t\tconst byte2 = src[position++] & 0x3f\n\t\t\tconst byte3 = src[position++] & 0x3f\n\t\t\tunits.push(((byte1 & 0x1f) << 12) | (byte2 << 6) | byte3)\n\t\t} else if ((byte1 & 0xf8) === 0xf0) {\n\t\t\t// 4 bytes\n\t\t\tconst byte2 = src[position++] & 0x3f\n\t\t\tconst byte3 = src[position++] & 0x3f\n\t\t\tconst byte4 = src[position++] & 0x3f\n\t\t\tlet unit = ((byte1 & 0x07) << 0x12) | (byte2 << 0x0c) | (byte3 << 0x06) | byte4\n\t\t\tif (unit > 0xffff) {\n\t\t\t\tunit -= 0x10000\n\t\t\t\tunits.push(((unit >>> 10) & 0x3ff) | 0xd800)\n\t\t\t\tunit = 0xdc00 | (unit & 0x3ff)\n\t\t\t}\n\t\t\tunits.push(unit)\n\t\t} else {\n\t\t\tunits.push(byte1)\n\t\t}\n\n\t\tif (units.length >= 0x1000) {\n\t\t\tresult += fromCharCode.apply(String, units)\n\t\t\tunits.length = 0\n\t\t}\n\t}\n\n\tif (units.length > 0) {\n\t\tresult += fromCharCode.apply(String, units)\n\t}\n\n\treturn result\n}\nlet fromCharCode = String.fromCharCode\nfunction longStringInJS(length) {\n\tlet start = position\n\tlet bytes = new Array(length)\n\tfor (let i = 0; i < length; i++) {\n\t\tconst byte = src[position++];\n\t\tif ((byte & 0x80) > 0) {\n\t\t\tposition = start\n    \t\t\treturn\n    \t\t}\n    \t\tbytes[i] = byte\n    \t}\n    \treturn fromCharCode.apply(String, bytes)\n}\nfunction shortStringInJS(length) {\n\tif (length < 4) {\n\t\tif (length < 2) {\n\t\t\tif (length === 0)\n\t\t\t\treturn ''\n\t\t\telse {\n\t\t\t\tlet a = src[position++]\n\t\t\t\tif ((a & 0x80) > 1) {\n\t\t\t\t\tposition -= 1\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t\treturn fromCharCode(a)\n\t\t\t}\n\t\t} else {\n\t\t\tlet a = src[position++]\n\t\t\tlet b = src[position++]\n\t\t\tif ((a & 0x80) > 0 || (b & 0x80) > 0) {\n\t\t\t\tposition -= 2\n\t\t\t\treturn\n\t\t\t}\n\t\t\tif (length < 3)\n\t\t\t\treturn fromCharCode(a, b)\n\t\t\tlet c = src[position++]\n\t\t\tif ((c & 0x80) > 0) {\n\t\t\t\tposition -= 3\n\t\t\t\treturn\n\t\t\t}\n\t\t\treturn fromCharCode(a, b, c)\n\t\t}\n\t} else {\n\t\tlet a = src[position++]\n\t\tlet b = src[position++]\n\t\tlet c = src[position++]\n\t\tlet d = src[position++]\n\t\tif ((a & 0x80) > 0 || (b & 0x80) > 0 || (c & 0x80) > 0 || (d & 0x80) > 0) {\n\t\t\tposition -= 4\n\t\t\treturn\n\t\t}\n\t\tif (length < 6) {\n\t\t\tif (length === 4)\n\t\t\t\treturn fromCharCode(a, b, c, d)\n\t\t\telse {\n\t\t\t\tlet e = src[position++]\n\t\t\t\tif ((e & 0x80) > 0) {\n\t\t\t\t\tposition -= 5\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t\treturn fromCharCode(a, b, c, d, e)\n\t\t\t}\n\t\t} else if (length < 8) {\n\t\t\tlet e = src[position++]\n\t\t\tlet f = src[position++]\n\t\t\tif ((e & 0x80) > 0 || (f & 0x80) > 0) {\n\t\t\t\tposition -= 6\n\t\t\t\treturn\n\t\t\t}\n\t\t\tif (length < 7)\n\t\t\t\treturn fromCharCode(a, b, c, d, e, f)\n\t\t\tlet g = src[position++]\n\t\t\tif ((g & 0x80) > 0) {\n\t\t\t\tposition -= 7\n\t\t\t\treturn\n\t\t\t}\n\t\t\treturn fromCharCode(a, b, c, d, e, f, g)\n\t\t} else {\n\t\t\tlet e = src[position++]\n\t\t\tlet f = src[position++]\n\t\t\tlet g = src[position++]\n\t\t\tlet h = src[position++]\n\t\t\tif ((e & 0x80) > 0 || (f & 0x80) > 0 || (g & 0x80) > 0 || (h & 0x80) > 0) {\n\t\t\t\tposition -= 8\n\t\t\t\treturn\n\t\t\t}\n\t\t\tif (length < 10) {\n\t\t\t\tif (length === 8)\n\t\t\t\t\treturn fromCharCode(a, b, c, d, e, f, g, h)\n\t\t\t\telse {\n\t\t\t\t\tlet i = src[position++]\n\t\t\t\t\tif ((i & 0x80) > 0) {\n\t\t\t\t\t\tposition -= 9\n\t\t\t\t\t\treturn\n\t\t\t\t\t}\n\t\t\t\t\treturn fromCharCode(a, b, c, d, e, f, g, h, i)\n\t\t\t\t}\n\t\t\t} else if (length < 12) {\n\t\t\t\tlet i = src[position++]\n\t\t\t\tlet j = src[position++]\n\t\t\t\tif ((i & 0x80) > 0 || (j & 0x80) > 0) {\n\t\t\t\t\tposition -= 10\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t\tif (length < 11)\n\t\t\t\t\treturn fromCharCode(a, b, c, d, e, f, g, h, i, j)\n\t\t\t\tlet k = src[position++]\n\t\t\t\tif ((k & 0x80) > 0) {\n\t\t\t\t\tposition -= 11\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t\treturn fromCharCode(a, b, c, d, e, f, g, h, i, j, k)\n\t\t\t} else {\n\t\t\t\tlet i = src[position++]\n\t\t\t\tlet j = src[position++]\n\t\t\t\tlet k = src[position++]\n\t\t\t\tlet l = src[position++]\n\t\t\t\tif ((i & 0x80) > 0 || (j & 0x80) > 0 || (k & 0x80) > 0 || (l & 0x80) > 0) {\n\t\t\t\t\tposition -= 12\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t\tif (length < 14) {\n\t\t\t\t\tif (length === 12)\n\t\t\t\t\t\treturn fromCharCode(a, b, c, d, e, f, g, h, i, j, k, l)\n\t\t\t\t\telse {\n\t\t\t\t\t\tlet m = src[position++]\n\t\t\t\t\t\tif ((m & 0x80) > 0) {\n\t\t\t\t\t\t\tposition -= 13\n\t\t\t\t\t\t\treturn\n\t\t\t\t\t\t}\n\t\t\t\t\t\treturn fromCharCode(a, b, c, d, e, f, g, h, i, j, k, l, m)\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\tlet m = src[position++]\n\t\t\t\t\tlet n = src[position++]\n\t\t\t\t\tif ((m & 0x80) > 0 || (n & 0x80) > 0) {\n\t\t\t\t\t\tposition -= 14\n\t\t\t\t\t\treturn\n\t\t\t\t\t}\n\t\t\t\t\tif (length < 15)\n\t\t\t\t\t\treturn fromCharCode(a, b, c, d, e, f, g, h, i, j, k, l, m, n)\n\t\t\t\t\tlet o = src[position++]\n\t\t\t\t\tif ((o & 0x80) > 0) {\n\t\t\t\t\t\tposition -= 15\n\t\t\t\t\t\treturn\n\t\t\t\t\t}\n\t\t\t\t\treturn fromCharCode(a, b, c, d, e, f, g, h, i, j, k, l, m, n, o)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}\n\nfunction readBin(length) {\n\treturn currentDecoder.copyBuffers ?\n\t\t// specifically use the copying slice (not the node one)\n\t\tUint8Array.prototype.slice.call(src, position, position += length) :\n\t\tsrc.subarray(position, position += length)\n}\nfunction readExt(length) {\n\tlet type = src[position++]\n\tif (currentExtensions[type]) {\n\t\treturn currentExtensions[type](src.subarray(position, position += length))\n\t}\n\telse\n\t\tthrow new Error('Unknown extension type ' + type)\n}\nlet f32Array = new Float32Array(1)\nlet u8Array = new Uint8Array(f32Array.buffer, 0, 4)\nfunction getFloat16() {\n\tlet byte0 = src[position++]\n\tlet byte1 = src[position++]\n\tlet exponent = (byte0 & 0x7f) >> 2;\n\tif (exponent === 0x1f) { // specials\n\t\tif (byte1 || (byte0 & 3))\n\t\t\treturn NaN;\n\t\treturn (byte0 & 0x80) ? -Infinity : Infinity;\n\t}\n\tif (exponent === 0) { // sub-normals\n\t\t// significand with 10 fractional bits and divided by 2^14\n\t\tlet abs = (((byte0 & 3) << 8) | byte1) / (1 << 24)\n\t\treturn (byte0 & 0x80) ? -abs : abs\n\t}\n\n\tu8Array[3] = (byte0 & 0x80) | // sign bit\n\t\t((exponent >> 1) + 56) // 4 of 5 of the exponent bits, re-offset-ed\n\tu8Array[2] = ((byte0 & 7) << 5) | // last exponent bit and first two mantissa bits\n\t\t(byte1 >> 3) // next 5 bits of mantissa\n\tu8Array[1] = byte1 << 5; // last three bits of mantissa\n\tu8Array[0] = 0;\n\treturn f32Array[0];\n}\n\nlet keyCache = new Array(4096)\nfunction readKey() {\n\tlet length = src[position++]\n\tif (length >= 0x60 && length < 0x78) {\n\t\t// fixstr, potentially use key cache\n\t\tlength = length - 0x60\n\t\tif (srcStringEnd >= position) // if it has been extracted, must use it (and faster anyway)\n\t\t\treturn srcString.slice(position - srcStringStart, (position += length) - srcStringStart)\n\t\telse if (!(srcStringEnd == 0 && srcEnd < 180))\n\t\t\treturn readFixedString(length)\n\t} else { // not cacheable, go back and do a standard read\n\t\tposition--\n\t\treturn read()\n\t}\n\tlet key = ((length << 5) ^ (length > 1 ? dataView.getUint16(position) : length > 0 ? src[position] : 0)) & 0xfff\n\tlet entry = keyCache[key]\n\tlet checkPosition = position\n\tlet end = position + length - 3\n\tlet chunk\n\tlet i = 0\n\tif (entry && entry.bytes == length) {\n\t\twhile (checkPosition < end) {\n\t\t\tchunk = dataView.getUint32(checkPosition)\n\t\t\tif (chunk != entry[i++]) {\n\t\t\t\tcheckPosition = 0x70000000\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tcheckPosition += 4\n\t\t}\n\t\tend += 3\n\t\twhile (checkPosition < end) {\n\t\t\tchunk = src[checkPosition++]\n\t\t\tif (chunk != entry[i++]) {\n\t\t\t\tcheckPosition = 0x70000000\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t\tif (checkPosition === end) {\n\t\t\tposition = checkPosition\n\t\t\treturn entry.string\n\t\t}\n\t\tend -= 3\n\t\tcheckPosition = position\n\t}\n\tentry = []\n\tkeyCache[key] = entry\n\tentry.bytes = length\n\twhile (checkPosition < end) {\n\t\tchunk = dataView.getUint32(checkPosition)\n\t\tentry.push(chunk)\n\t\tcheckPosition += 4\n\t}\n\tend += 3\n\twhile (checkPosition < end) {\n\t\tchunk = src[checkPosition++]\n\t\tentry.push(chunk)\n\t}\n\t// for small blocks, avoiding the overhead of the extract call is helpful\n\tlet string = length < 16 ? shortStringInJS(length) : longStringInJS(length)\n\tif (string != null)\n\t\treturn entry.string = string\n\treturn entry.string = readFixedString(length)\n}\n\nexport class Tag {\n\tconstructor(value, tag) {\n\t\tthis.value = value\n\t\tthis.tag = tag\n\t}\n}\n\ncurrentExtensions[0] = (dateString) => {\n\t// string date extension\n\treturn new Date(dateString)\n}\n\ncurrentExtensions[1] = (epochSec) => {\n\t// numeric date extension\n\treturn new Date(Math.round(epochSec * 1000))\n}\n\ncurrentExtensions[2] = (buffer) => {\n\t// bigint extension\n\tlet value = BigInt(0)\n\tfor (let i = 0, l = buffer.byteLength; i < l; i++) {\n\t\tvalue = BigInt(buffer[i]) + (value << BigInt(8))\n\t}\n\treturn value\n}\n\ncurrentExtensions[3] = (buffer) => {\n\t// negative bigint extension\n\treturn BigInt(-1) - currentExtensions[2](buffer)\n}\ncurrentExtensions[4] = (fraction) => {\n\t// best to reparse to maintain accuracy\n\treturn +(fraction[1] + 'e' + fraction[0])\n}\n\ncurrentExtensions[5] = (fraction) => {\n\t// probably not sufficiently accurate\n\treturn fraction[1] * Math.exp(fraction[0] * Math.log(2))\n}\n\n// the registration of the record definition extension\nconst recordDefinition = (id, structure) => {\n\tid = id - 0xe000\n\tlet existingStructure = currentStructures[id]\n\tif (existingStructure && existingStructure.isShared) {\n\t\t(currentStructures.restoreStructures || (currentStructures.restoreStructures = []))[id] = existingStructure\n\t}\n\tcurrentStructures[id] = structure\n\n\tstructure.read = createStructureReader(structure)\n}\ncurrentExtensions[LEGACY_RECORD_INLINE_ID] = (data) => {\n\tlet length = data.length\n\tlet structure = data[1]\n\trecordDefinition(data[0], structure)\n\tlet object = {}\n\tfor (let i = 2; i < length; i++) {\n\t\tlet key = structure[i - 2]\n\t\tobject[safeKey(key)] = data[i]\n\t}\n\treturn object\n}\ncurrentExtensions[14] = (value) => {\n\tif (bundledStrings)\n\t\treturn bundledStrings[0].slice(bundledStrings.position0, bundledStrings.position0 += value)\n\treturn new Tag(value, 14)\n}\ncurrentExtensions[15] = (value) => {\n\tif (bundledStrings)\n\t\treturn bundledStrings[1].slice(bundledStrings.position1, bundledStrings.position1 += value)\n\treturn new Tag(value, 15)\n}\nlet glbl = { Error, RegExp }\ncurrentExtensions[27] = (data) => { // http://cbor.schmorp.de/generic-object\n\treturn (glbl[data[0]] || Error)(data[1], data[2])\n}\nconst packedTable = (read) => {\n\tif (src[position++] != 0x84) {\n\t\tlet error = new Error('Packed values structure must be followed by a 4 element array')\n\t\tif (src.length < position)\n\t\t\terror.incomplete = true\n\t\tthrow error\n\t}\n\tlet newPackedValues = read() // packed values\n\tif (!newPackedValues || !newPackedValues.length) {\n\t\tlet error = new Error('Packed values structure must be followed by a 4 element array')\n\t\terror.incomplete = true\n\t\tthrow error\n\t}\n\tpackedValues = packedValues ? newPackedValues.concat(packedValues.slice(newPackedValues.length)) : newPackedValues\n\tpackedValues.prefixes = read()\n\tpackedValues.suffixes = read()\n\treturn read() // read the rump\n}\npackedTable.handlesRead = true\ncurrentExtensions[51] = packedTable\n\ncurrentExtensions[PACKED_REFERENCE_TAG_ID] = (data) => { // packed reference\n\tif (!packedValues) {\n\t\tif (currentDecoder.getShared)\n\t\t\tloadShared()\n\t\telse\n\t\t\treturn new Tag(data, PACKED_REFERENCE_TAG_ID)\n\t}\n\tif (typeof data == 'number')\n\t\treturn packedValues[16 + (data >= 0 ? 2 * data : (-2 * data - 1))]\n\tlet error = new Error('No support for non-integer packed references yet')\n\tif (data === undefined)\n\t\terror.incomplete = true\n\tthrow error\n}\n\n// The following code is an incomplete implementation of http://cbor.schmorp.de/stringref\n// the real thing would need to implemennt more logic to populate the stringRefs table and\n// maintain a stack of stringRef \"namespaces\".\n//\n// currentExtensions[25] = (id) => {\n// \treturn stringRefs[id]\n// }\n// currentExtensions[256] = (read) => {\n// \tstringRefs = []\n// \ttry {\n// \t\treturn read()\n// \t} finally {\n// \t\tstringRefs = null\n// \t}\n// }\n// currentExtensions[256].handlesRead = true\n\ncurrentExtensions[28] = (read) => { \n\t// shareable http://cbor.schmorp.de/value-sharing (for structured clones)\n\tif (!referenceMap) {\n\t\treferenceMap = new Map()\n\t\treferenceMap.id = 0\n\t}\n\tlet id = referenceMap.id++\n\tlet startingPosition = position\n\tlet token = src[position]\n\tlet target\n\t// TODO: handle Maps, Sets, and other types that can cycle; this is complicated, because you potentially need to read\n\t// ahead past references to record structure definitions\n\tif ((token >> 5) == 4)\n\t\ttarget = []\n\telse\n\t\ttarget = {}\n\n\tlet refEntry = { target } // a placeholder object\n\treferenceMap.set(id, refEntry)\n\tlet targetProperties = read() // read the next value as the target object to id\n\tif (refEntry.used) {// there is a cycle, so we have to assign properties to original target\n\t\tif (Object.getPrototypeOf(target) !== Object.getPrototypeOf(targetProperties)) {\n\t\t\t// this means that the returned target does not match the targetProperties, so we need rerun the read to\n\t\t\t// have the correctly create instance be assigned as a reference, then we do the copy the properties back to the\n\t\t\t// target\n\t\t\t// reset the position so that the read can be repeated\n\t\t\tposition = startingPosition\n\t\t\t// the returned instance is our new target for references\n\t\t\ttarget = targetProperties\n\t\t\treferenceMap.set(id, { target })\n\t\t\ttargetProperties = read()\n\t\t}\n\t\treturn Object.assign(target, targetProperties)\n\t}\n\trefEntry.target = targetProperties // the placeholder wasn't used, replace with the deserialized one\n\treturn targetProperties // no cycle, can just use the returned read object\n}\ncurrentExtensions[28].handlesRead = true\n\ncurrentExtensions[29] = (id) => {\n\t// sharedref http://cbor.schmorp.de/value-sharing (for structured clones)\n\tlet refEntry = referenceMap.get(id)\n\trefEntry.used = true\n\treturn refEntry.target\n}\n\ncurrentExtensions[258] = (array) => new Set(array); // https://github.com/input-output-hk/cbor-sets-spec/blob/master/CBOR_SETS.md\n(currentExtensions[259] = (read) => {\n\t// https://github.com/shanewholloway/js-cbor-codec/blob/master/docs/CBOR-259-spec\n\t// for decoding as a standard Map\n\tif (currentDecoder.mapsAsObjects) {\n\t\tcurrentDecoder.mapsAsObjects = false\n\t\trestoreMapsAsObject = true\n\t}\n\treturn read()\n}).handlesRead = true\nfunction combine(a, b) {\n\tif (typeof a === 'string')\n\t\treturn a + b\n\tif (a instanceof Array)\n\t\treturn a.concat(b)\n\treturn Object.assign({}, a, b)\n}\nfunction getPackedValues() {\n\tif (!packedValues) {\n\t\tif (currentDecoder.getShared)\n\t\t\tloadShared()\n\t\telse\n\t\t\tthrow new Error('No packed values available')\n\t}\n\treturn packedValues\n}\nconst SHARED_DATA_TAG_ID = 0x53687264 // ascii 'Shrd'\ncurrentExtensionRanges.push((tag, input) => {\n\tif (tag >= 225 && tag <= 255)\n\t\treturn combine(getPackedValues().prefixes[tag - 224], input)\n\tif (tag >= 28704 && tag <= 32767)\n\t\treturn combine(getPackedValues().prefixes[tag - 28672], input)\n\tif (tag >= 1879052288 && tag <= 2147483647)\n\t\treturn combine(getPackedValues().prefixes[tag - 1879048192], input)\n\tif (tag >= 216 && tag <= 223)\n\t\treturn combine(input, getPackedValues().suffixes[tag - 216])\n\tif (tag >= 27647 && tag <= 28671)\n\t\treturn combine(input, getPackedValues().suffixes[tag - 27639])\n\tif (tag >= 1811940352 && tag <= 1879048191)\n\t\treturn combine(input, getPackedValues().suffixes[tag - 1811939328])\n\tif (tag == SHARED_DATA_TAG_ID) {// we do a special check for this so that we can keep the currentExtensions as densely stored array (v8 stores arrays densely under about 3000 elements)\n\t\treturn {\n\t\t\tpackedValues: packedValues,\n\t\t\tstructures: currentStructures.slice(0),\n\t\t\tversion: input,\n\t\t}\n\t}\n\tif (tag == 55799) // self-descriptive CBOR tag, just return input value\n\t\treturn input\n})\n\nconst isLittleEndianMachine = new Uint8Array(new Uint16Array([1]).buffer)[0] == 1\nexport const typedArrays = [Uint8Array, Uint8ClampedArray, Uint16Array, Uint32Array,\n\ttypeof BigUint64Array == 'undefined' ? { name:'BigUint64Array' } : BigUint64Array, Int8Array, Int16Array, Int32Array,\n\ttypeof BigInt64Array == 'undefined' ? { name:'BigInt64Array' } : BigInt64Array, Float32Array, Float64Array]\nconst typedArrayTags = [64, 68, 69, 70, 71, 72, 77, 78, 79, 85, 86]\nfor (let i = 0; i < typedArrays.length; i++) {\n\tregisterTypedArray(typedArrays[i], typedArrayTags[i])\n}\nfunction registerTypedArray(TypedArray, tag) {\n\tlet dvMethod = 'get' + TypedArray.name.slice(0, -5)\n\tlet bytesPerElement;\n\tif (typeof TypedArray === 'function')\n\t\tbytesPerElement = TypedArray.BYTES_PER_ELEMENT;\n\telse\n\t\tTypedArray = null;\n\tfor (let littleEndian = 0; littleEndian < 2; littleEndian++) {\n\t\tif (!littleEndian && bytesPerElement == 1)\n\t\t\tcontinue\n\t\tlet sizeShift = bytesPerElement == 2 ? 1 : bytesPerElement == 4 ? 2 : bytesPerElement == 8 ? 3 : 0\n\t\tcurrentExtensions[littleEndian ? tag : (tag - 4)] = (bytesPerElement == 1 || littleEndian == isLittleEndianMachine) ? (buffer) => {\n\t\t\tif (!TypedArray)\n\t\t\t\tthrow new Error('Could not find typed array for code ' + tag)\n\t\t\tif (!currentDecoder.copyBuffers) {\n\t\t\t\t// try provide a direct view, but will only work if we are byte-aligned\n\t\t\t\tif (bytesPerElement === 1 ||\n\t\t\t\t\tbytesPerElement === 2 && !(buffer.byteOffset & 1) ||\n\t\t\t\t\tbytesPerElement === 4 && !(buffer.byteOffset & 3) ||\n\t\t\t\t\tbytesPerElement === 8 && !(buffer.byteOffset & 7))\n\t\t\t\t\treturn new TypedArray(buffer.buffer, buffer.byteOffset, buffer.byteLength >> sizeShift);\n\t\t\t}\n\t\t\t// we have to slice/copy here to get a new ArrayBuffer, if we are not word/byte aligned\n\t\t\treturn new TypedArray(Uint8Array.prototype.slice.call(buffer, 0).buffer)\n\t\t} : buffer => {\n\t\t\tif (!TypedArray)\n\t\t\t\tthrow new Error('Could not find typed array for code ' + tag)\n\t\t\tlet dv = new DataView(buffer.buffer, buffer.byteOffset, buffer.byteLength)\n\t\t\tlet elements = buffer.length >> sizeShift\n\t\t\tlet ta = new TypedArray(elements)\n\t\t\tlet method = dv[dvMethod]\n\t\t\tfor (let i = 0; i < elements; i++) {\n\t\t\t\tta[i] = method.call(dv, i << sizeShift, littleEndian)\n\t\t\t}\n\t\t\treturn ta\n\t\t}\n\t}\n}\n\nfunction readBundleExt() {\n\tlet length = readJustLength()\n\tlet bundlePosition = position + read()\n\tfor (let i = 2; i < length; i++) {\n\t\t// skip past bundles that were already read\n\t\tlet bundleLength = readJustLength() // this will increment position, so must add to position afterwards\n\t\tposition += bundleLength\n\t}\n\tlet dataPosition = position\n\tposition = bundlePosition\n\tbundledStrings = [readStringJS(readJustLength()), readStringJS(readJustLength())]\n\tbundledStrings.position0 = 0\n\tbundledStrings.position1 = 0\n\tbundledStrings.postBundlePosition = position\n\tposition = dataPosition\n\treturn read()\n}\n\nfunction readJustLength() {\n\tlet token = src[position++] & 0x1f\n\tif (token > 0x17) {\n\t\tswitch (token) {\n\t\t\tcase 0x18:\n\t\t\t\ttoken = src[position++]\n\t\t\t\tbreak\n\t\t\tcase 0x19:\n\t\t\t\ttoken = dataView.getUint16(position)\n\t\t\t\tposition += 2\n\t\t\t\tbreak\n\t\t\tcase 0x1a:\n\t\t\t\ttoken = dataView.getUint32(position)\n\t\t\t\tposition += 4\n\t\t\t\tbreak\n\t\t}\n\t}\n\treturn token\n}\n\nfunction loadShared() {\n\tif (currentDecoder.getShared) {\n\t\tlet sharedData = saveState(() => {\n\t\t\t// save the state in case getShared modifies our buffer\n\t\t\tsrc = null\n\t\t\treturn currentDecoder.getShared()\n\t\t}) || {}\n\t\tlet updatedStructures = sharedData.structures || []\n\t\tcurrentDecoder.sharedVersion = sharedData.version\n\t\tpackedValues = currentDecoder.sharedValues = sharedData.packedValues\n\t\tif (currentStructures === true)\n\t\t\tcurrentDecoder.structures = currentStructures = updatedStructures\n\t\telse\n\t\t\tcurrentStructures.splice.apply(currentStructures, [0, updatedStructures.length].concat(updatedStructures))\n\t}\n}\n\nfunction saveState(callback) {\n\tlet savedSrcEnd = srcEnd\n\tlet savedPosition = position\n\tlet savedStringPosition = stringPosition\n\tlet savedSrcStringStart = srcStringStart\n\tlet savedSrcStringEnd = srcStringEnd\n\tlet savedSrcString = srcString\n\tlet savedStrings = strings\n\tlet savedReferenceMap = referenceMap\n\tlet savedBundledStrings = bundledStrings\n\n\t// TODO: We may need to revisit this if we do more external calls to user code (since it could be slow)\n\tlet savedSrc = new Uint8Array(src.slice(0, srcEnd)) // we copy the data in case it changes while external data is processed\n\tlet savedStructures = currentStructures\n\tlet savedDecoder = currentDecoder\n\tlet savedSequentialMode = sequentialMode\n\tlet value = callback()\n\tsrcEnd = savedSrcEnd\n\tposition = savedPosition\n\tstringPosition = savedStringPosition\n\tsrcStringStart = savedSrcStringStart\n\tsrcStringEnd = savedSrcStringEnd\n\tsrcString = savedSrcString\n\tstrings = savedStrings\n\treferenceMap = savedReferenceMap\n\tbundledStrings = savedBundledStrings\n\tsrc = savedSrc\n\tsequentialMode = savedSequentialMode\n\tcurrentStructures = savedStructures\n\tcurrentDecoder = savedDecoder\n\tdataView = new DataView(src.buffer, src.byteOffset, src.byteLength)\n\treturn value\n}\nexport function clearSource() {\n\tsrc = null\n\treferenceMap = null\n\tcurrentStructures = null\n}\n\nexport function addExtension(extension) {\n\tcurrentExtensions[extension.tag] = extension.decode\n}\n\nexport function setSizeLimits(limits) {\n\tif (limits.maxMapSize) maxMapSize = limits.maxMapSize;\n\tif (limits.maxArraySize) maxArraySize = limits.maxArraySize;\n\tif (limits.maxObjectSize) maxObjectSize = limits.maxObjectSize;\n}\n\nexport const mult10 = new Array(147) // this is a table matching binary exponents to the multiplier to determine significant digit rounding\nfor (let i = 0; i < 256; i++) {\n\tmult10[i] = +('1e' + Math.floor(45.15 - i * 0.30103))\n}\nlet defaultDecoder = new Decoder({ useRecords: false })\nexport const decode = defaultDecoder.decode\nexport const decodeMultiple = defaultDecoder.decodeMultiple\nexport const FLOAT32_OPTIONS = {\n\tNEVER: 0,\n\tALWAYS: 1,\n\tDECIMAL_ROUND: 3,\n\tDECIMAL_FIT: 4\n}\nexport function roundFloat32(float32Number) {\n\tf32Array[0] = float32Number\n\tlet multiplier = mult10[((u8Array[3] & 0x7f) << 1) | (u8Array[2] >> 7)]\n\treturn ((multiplier * float32Number + (float32Number > 0 ? 0.5 : -0.5)) >> 0) / multiplier\n}\n","import { Decoder, mult10, Tag, typedArrays, addExtension as decodeAddExtension } from './decode.js'\nlet textEncoder\ntry {\n\ttextEncoder = new TextEncoder()\n} catch (error) {}\nlet extensions, extensionClasses\nconst Buffer = typeof globalThis === 'object' && globalThis.Buffer;\nconst hasNodeBuffer = typeof Buffer !== 'undefined'\nconst ByteArrayAllocate = hasNodeBuffer ? Buffer.allocUnsafeSlow : Uint8Array\nconst ByteArray = hasNodeBuffer ? Buffer : Uint8Array\nconst MAX_STRUCTURES = 0x100\nconst MAX_BUFFER_SIZE = hasNodeBuffer ? 0x100000000 : 0x7fd00000\nlet serializationId = 1\nlet throwOnIterable\nlet target\nlet targetView\nlet position = 0\nlet safeEnd\nlet bundledStrings = null\nconst MAX_BUNDLE_SIZE = 0xf000\nconst hasNonLatin = /[\\u0080-\\uFFFF]/\nconst RECORD_SYMBOL = Symbol('record-id')\nexport class Encoder extends Decoder {\n\tconstructor(options) {\n\t\tsuper(options)\n\t\tthis.offset = 0\n\t\tlet typeBuffer\n\t\tlet start\n\t\tlet sharedStructures\n\t\tlet hasSharedUpdate\n\t\tlet structures\n\t\tlet referenceMap\n\t\toptions = options || {}\n\t\tlet encodeUtf8 = ByteArray.prototype.utf8Write ? function(string, position, maxBytes) {\n\t\t\treturn target.utf8Write(string, position, maxBytes)\n\t\t} : (textEncoder && textEncoder.encodeInto) ?\n\t\t\tfunction(string, position) {\n\t\t\t\treturn textEncoder.encodeInto(string, target.subarray(position)).written\n\t\t\t} : false\n\n\t\tlet encoder = this\n\t\tlet hasSharedStructures = options.structures || options.saveStructures\n\t\tlet maxSharedStructures = options.maxSharedStructures\n\t\tif (maxSharedStructures == null)\n\t\t\tmaxSharedStructures = hasSharedStructures ? 128 : 0\n\t\tif (maxSharedStructures > 8190)\n\t\t\tthrow new Error('Maximum maxSharedStructure is 8190')\n\t\tlet isSequential = options.sequential\n\t\tif (isSequential) {\n\t\t\tmaxSharedStructures = 0\n\t\t}\n\t\tif (!this.structures)\n\t\t\tthis.structures = []\n\t\tif (this.saveStructures)\n\t\t\tthis.saveShared = this.saveStructures\n\t\tlet samplingPackedValues, packedObjectMap, sharedValues = options.sharedValues\n\t\tlet sharedPackedObjectMap\n\t\tif (sharedValues) {\n\t\t\tsharedPackedObjectMap = Object.create(null)\n\t\t\tfor (let i = 0, l = sharedValues.length; i < l; i++) {\n\t\t\t\tsharedPackedObjectMap[sharedValues[i]] = i\n\t\t\t}\n\t\t}\n\t\tlet recordIdsToRemove = []\n\t\tlet transitionsCount = 0\n\t\tlet serializationsSinceTransitionRebuild = 0\n\t\t\n\t\tthis.mapEncode = function(value, encodeOptions) {\n\t\t\t// Experimental support for premapping keys using _keyMap instad of keyMap - not optiimised yet)\n\t\t\tif (this._keyMap && !this._mapped) {\n\t\t\t\t//console.log('encoding ', value)\n\t\t\t\tswitch (value.constructor.name) {\n\t\t\t\t\tcase 'Array': \n\t\t\t\t\t\tvalue = value.map(r => this.encodeKeys(r))\n\t\t\t\t\t\tbreak\n\t\t\t\t\t//case 'Map': \n\t\t\t\t\t//\tvalue = this.encodeKeys(value)\n\t\t\t\t\t//\tbreak\n\t\t\t\t}\n\t\t\t\t//this._mapped = true\n\t\t\t}\n\t\t\treturn this.encode(value, encodeOptions)\n\t\t}\n\t\t\n\t\tthis.encode = function(value, encodeOptions)\t{\n\t\t\tif (!target) {\n\t\t\t\ttarget = new ByteArrayAllocate(8192)\n\t\t\t\ttargetView = new DataView(target.buffer, 0, 8192)\n\t\t\t\tposition = 0\n\t\t\t}\n\t\t\tsafeEnd = target.length - 10\n\t\t\tif (safeEnd - position < 0x800) {\n\t\t\t\t// don't start too close to the end, \n\t\t\t\ttarget = new ByteArrayAllocate(target.length)\n\t\t\t\ttargetView = new DataView(target.buffer, 0, target.length)\n\t\t\t\tsafeEnd = target.length - 10\n\t\t\t\tposition = 0\n\t\t\t} else if (encodeOptions === REUSE_BUFFER_MODE)\n\t\t\t\tposition = (position + 7) & 0x7ffffff8 // Word align to make any future copying of this buffer faster\n\t\t\tstart = position\n\t\t\tif (encoder.useSelfDescribedHeader) {\n\t\t\t\ttargetView.setUint32(position, 0xd9d9f700) // tag two byte, then self-descriptive tag\n\t\t\t\tposition += 3\n\t\t\t}\n\t\t\treferenceMap = encoder.structuredClone ? new Map() : null\n\t\t\tif (encoder.bundleStrings && typeof value !== 'string') {\n\t\t\t\tbundledStrings = []\n\t\t\t\tbundledStrings.size = Infinity // force a new bundle start on first string\n\t\t\t} else\n\t\t\t\tbundledStrings = null\n\n\t\t\tsharedStructures = encoder.structures\n\t\t\tif (sharedStructures) {\n\t\t\t\tif (sharedStructures.uninitialized) {\n\t\t\t\t\tlet sharedData = encoder.getShared() || {}\n\t\t\t\t\tencoder.structures = sharedStructures = sharedData.structures || []\n\t\t\t\t\tencoder.sharedVersion = sharedData.version\n\t\t\t\t\tlet sharedValues = encoder.sharedValues = sharedData.packedValues\n\t\t\t\t\tif (sharedValues) {\n\t\t\t\t\t\tsharedPackedObjectMap = {}\n\t\t\t\t\t\tfor (let i = 0, l = sharedValues.length; i < l; i++)\n\t\t\t\t\t\t\tsharedPackedObjectMap[sharedValues[i]] = i\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tlet sharedStructuresLength = sharedStructures.length\n\t\t\t\tif (sharedStructuresLength > maxSharedStructures && !isSequential)\n\t\t\t\t\tsharedStructuresLength = maxSharedStructures\n\t\t\t\tif (!sharedStructures.transitions) {\n\t\t\t\t\t// rebuild our structure transitions\n\t\t\t\t\tsharedStructures.transitions = Object.create(null)\n\t\t\t\t\tfor (let i = 0; i < sharedStructuresLength; i++) {\n\t\t\t\t\t\tlet keys = sharedStructures[i]\n\t\t\t\t\t\t//console.log('shared struct keys:', keys)\n\t\t\t\t\t\tif (!keys)\n\t\t\t\t\t\t\tcontinue\n\t\t\t\t\t\tlet nextTransition, transition = sharedStructures.transitions\n\t\t\t\t\t\tfor (let j = 0, l = keys.length; j < l; j++) {\n\t\t\t\t\t\t\tif (transition[RECORD_SYMBOL] === undefined)\n\t\t\t\t\t\t\t\ttransition[RECORD_SYMBOL] = i\n\t\t\t\t\t\t\tlet key = keys[j]\n\t\t\t\t\t\t\tnextTransition = transition[key]\n\t\t\t\t\t\t\tif (!nextTransition) {\n\t\t\t\t\t\t\t\tnextTransition = transition[key] = Object.create(null)\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\ttransition = nextTransition\n\t\t\t\t\t\t}\n\t\t\t\t\t\ttransition[RECORD_SYMBOL] = i | 0x100000\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif (!isSequential)\n\t\t\t\t\tsharedStructures.nextId = sharedStructuresLength\n\t\t\t}\n\t\t\tif (hasSharedUpdate)\n\t\t\t\thasSharedUpdate = false\n\t\t\tstructures = sharedStructures || []\n\t\t\tpackedObjectMap = sharedPackedObjectMap\n\t\t\tif (options.pack) {\n\t\t\t\tlet packedValues = new Map()\n\t\t\t\tpackedValues.values = []\n\t\t\t\tpackedValues.encoder = encoder\n\t\t\t\tpackedValues.maxValues = options.maxPrivatePackedValues || (sharedPackedObjectMap ? 16 : Infinity)\n\t\t\t\tpackedValues.objectMap = sharedPackedObjectMap || false\n\t\t\t\tpackedValues.samplingPackedValues = samplingPackedValues\n\t\t\t\tfindRepetitiveStrings(value, packedValues)\n\t\t\t\tif (packedValues.values.length > 0) {\n\t\t\t\t\ttarget[position++] = 0xd8 // one-byte tag\n\t\t\t\t\ttarget[position++] = 51 // tag 51 for packed shared structures https://www.potaroo.net/ietf/ids/draft-ietf-cbor-packed-03.txt\n\t\t\t\t\twriteArrayHeader(4)\n\t\t\t\t\tlet valuesArray = packedValues.values\n\t\t\t\t\tencode(valuesArray)\n\t\t\t\t\twriteArrayHeader(0) // prefixes\n\t\t\t\t\twriteArrayHeader(0) // suffixes\n\t\t\t\t\tpackedObjectMap = Object.create(sharedPackedObjectMap || null)\n\t\t\t\t\tfor (let i = 0, l = valuesArray.length; i < l; i++) {\n\t\t\t\t\t\tpackedObjectMap[valuesArray[i]] = i\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tthrowOnIterable = encodeOptions & THROW_ON_ITERABLE;\n\t\t\ttry {\n\t\t\t\tif (throwOnIterable)\n\t\t\t\t\treturn;\n\t\t\t\tencode(value)\n\t\t\t\tif (bundledStrings) {\n\t\t\t\t\twriteBundles(start, encode)\n\t\t\t\t}\n\t\t\t\tencoder.offset = position // update the offset so next serialization doesn't write over our buffer, but can continue writing to same buffer sequentially\n\t\t\t\tif (referenceMap && referenceMap.idsToInsert) {\n\t\t\t\t\tposition += referenceMap.idsToInsert.length * 2\n\t\t\t\t\tif (position > safeEnd)\n\t\t\t\t\t\tmakeRoom(position)\n\t\t\t\t\tencoder.offset = position\n\t\t\t\t\tlet serialized = insertIds(target.subarray(start, position), referenceMap.idsToInsert)\n\t\t\t\t\treferenceMap = null\n\t\t\t\t\treturn serialized\n\t\t\t\t}\n\t\t\t\tif (encodeOptions & REUSE_BUFFER_MODE) {\n\t\t\t\t\ttarget.start = start\n\t\t\t\t\ttarget.end = position\n\t\t\t\t\treturn target\n\t\t\t\t}\n\t\t\t\treturn target.subarray(start, position) // position can change if we call encode again in saveShared, so we get the buffer now\n\t\t\t} finally {\n\t\t\t\tif (sharedStructures) {\n\t\t\t\t\tif (serializationsSinceTransitionRebuild < 10)\n\t\t\t\t\t\tserializationsSinceTransitionRebuild++\n\t\t\t\t\tif (sharedStructures.length > maxSharedStructures)\n\t\t\t\t\t\tsharedStructures.length = maxSharedStructures\n\t\t\t\t\tif (transitionsCount > 10000) {\n\t\t\t\t\t\t// force a rebuild occasionally after a lot of transitions so it can get cleaned up\n\t\t\t\t\t\tsharedStructures.transitions = null\n\t\t\t\t\t\tserializationsSinceTransitionRebuild = 0\n\t\t\t\t\t\ttransitionsCount = 0\n\t\t\t\t\t\tif (recordIdsToRemove.length > 0)\n\t\t\t\t\t\t\trecordIdsToRemove = []\n\t\t\t\t\t} else if (recordIdsToRemove.length > 0 && !isSequential) {\n\t\t\t\t\t\tfor (let i = 0, l = recordIdsToRemove.length; i < l; i++) {\n\t\t\t\t\t\t\trecordIdsToRemove[i][RECORD_SYMBOL] = undefined\n\t\t\t\t\t\t}\n\t\t\t\t\t\trecordIdsToRemove = []\n\t\t\t\t\t\t//sharedStructures.nextId = maxSharedStructures\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif (hasSharedUpdate && encoder.saveShared) {\n\t\t\t\t\tif (encoder.structures.length > maxSharedStructures) {\n\t\t\t\t\t\tencoder.structures = encoder.structures.slice(0, maxSharedStructures)\n\t\t\t\t\t}\n\t\t\t\t\t// we can't rely on start/end with REUSE_BUFFER_MODE since they will (probably) change when we save\n\t\t\t\t\tlet returnBuffer = target.subarray(start, position)\n\t\t\t\t\tif (encoder.updateSharedData() === false)\n\t\t\t\t\t\treturn encoder.encode(value) // re-encode if it fails\n\t\t\t\t\treturn returnBuffer\n\t\t\t\t}\n\t\t\t\tif (encodeOptions & RESET_BUFFER_MODE)\n\t\t\t\t\tposition = start\n\t\t\t}\n\t\t}\n\t\tthis.findCommonStringsToPack = () => {\n\t\t\tsamplingPackedValues = new Map()\n\t\t\tif (!sharedPackedObjectMap)\n\t\t\t\tsharedPackedObjectMap = Object.create(null)\n\t\t\treturn (options) => {\n\t\t\t\tlet threshold = options && options.threshold || 4\n\t\t\t\tlet position = this.pack ? options.maxPrivatePackedValues || 16 : 0\n\t\t\t\tif (!sharedValues)\n\t\t\t\t\tsharedValues = this.sharedValues = []\n\t\t\t\tfor (let [ key, status ] of samplingPackedValues) {\n\t\t\t\t\tif (status.count > threshold) {\n\t\t\t\t\t\tsharedPackedObjectMap[key] = position++\n\t\t\t\t\t\tsharedValues.push(key)\n\t\t\t\t\t\thasSharedUpdate = true\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\twhile (this.saveShared && this.updateSharedData() === false) {}\n\t\t\t\tsamplingPackedValues = null\n\t\t\t}\n\t\t}\n\t\tconst encode = (value) => {\n\t\t\tif (position > safeEnd)\n\t\t\t\ttarget = makeRoom(position)\n\n\t\t\tvar type = typeof value\n\t\t\tvar length\n\t\t\tif (type === 'string') {\n\t\t\t\tif (packedObjectMap) {\n\t\t\t\t\tlet packedPosition = packedObjectMap[value]\n\t\t\t\t\tif (packedPosition >= 0) {\n\t\t\t\t\t\tif (packedPosition < 16)\n\t\t\t\t\t\t\ttarget[position++] = packedPosition + 0xe0 // simple values, defined in https://www.potaroo.net/ietf/ids/draft-ietf-cbor-packed-03.txt\n\t\t\t\t\t\telse {\n\t\t\t\t\t\t\ttarget[position++] = 0xc6 // tag 6 defined in https://www.potaroo.net/ietf/ids/draft-ietf-cbor-packed-03.txt\n\t\t\t\t\t\t\tif (packedPosition & 1)\n\t\t\t\t\t\t\t\tencode((15 - packedPosition) >> 1)\n\t\t\t\t\t\t\telse\n\t\t\t\t\t\t\t\tencode((packedPosition - 16) >> 1)\n\t\t\t\t\t\t}\n\t\t\t\t\t\treturn\n/*\t\t\t\t\t\t} else if (packedStatus.serializationId != serializationId) {\n\t\t\t\t\t\t\tpackedStatus.serializationId = serializationId\n\t\t\t\t\t\t\tpackedStatus.count = 1\n\t\t\t\t\t\t\tif (options.sharedPack) {\n\t\t\t\t\t\t\t\tlet sharedCount = packedStatus.sharedCount = (packedStatus.sharedCount || 0) + 1\n\t\t\t\t\t\t\t\tif (shareCount > (options.sharedPack.threshold || 5)) {\n\t\t\t\t\t\t\t\t\tlet sharedPosition = packedStatus.position = packedStatus.nextSharedPosition\n\t\t\t\t\t\t\t\t\thasSharedUpdate = true\n\t\t\t\t\t\t\t\t\tif (sharedPosition < 16)\n\t\t\t\t\t\t\t\t\t\ttarget[position++] = sharedPosition + 0xc0\n\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t} // else any in-doc incrementation?*/\n\t\t\t\t\t} else if (samplingPackedValues && !options.pack) {\n\t\t\t\t\t\tlet status = samplingPackedValues.get(value)\n\t\t\t\t\t\tif (status)\n\t\t\t\t\t\t\tstatus.count++\n\t\t\t\t\t\telse\n\t\t\t\t\t\t\tsamplingPackedValues.set(value, {\n\t\t\t\t\t\t\t\tcount: 1,\n\t\t\t\t\t\t\t})\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tlet strLength = value.length\n\t\t\t\tif (bundledStrings && strLength >= 4 && strLength < 0x400) {\n\t\t\t\t\tif ((bundledStrings.size += strLength) > MAX_BUNDLE_SIZE) {\n\t\t\t\t\t\tlet extStart\n\t\t\t\t\t\tlet maxBytes = (bundledStrings[0] ? bundledStrings[0].length * 3 + bundledStrings[1].length : 0) + 10\n\t\t\t\t\t\tif (position + maxBytes > safeEnd)\n\t\t\t\t\t\t\ttarget = makeRoom(position + maxBytes)\n\t\t\t\t\t\ttarget[position++] = 0xd9 // tag 16-bit\n\t\t\t\t\t\ttarget[position++] = 0xdf // tag 0xdff9\n\t\t\t\t\t\ttarget[position++] = 0xf9\n\t\t\t\t\t\t// TODO: If we only have one bundle with any string data, only write one string bundle\n\t\t\t\t\t\ttarget[position++] = bundledStrings.position ? 0x84 : 0x82 // array of 4 or 2 elements depending on if we write bundles\n\t\t\t\t\t\ttarget[position++] = 0x1a // 32-bit unsigned int\n\t\t\t\t\t\textStart = position - start\n\t\t\t\t\t\tposition += 4 // reserve for writing bundle reference\n\t\t\t\t\t\tif (bundledStrings.position) {\n\t\t\t\t\t\t\twriteBundles(start, encode) // write the last bundles\n\t\t\t\t\t\t}\n\t\t\t\t\t\tbundledStrings = ['', ''] // create new ones\n\t\t\t\t\t\tbundledStrings.size = 0\n\t\t\t\t\t\tbundledStrings.position = extStart\n\t\t\t\t\t}\n\t\t\t\t\tlet twoByte = hasNonLatin.test(value)\n\t\t\t\t\tbundledStrings[twoByte ? 0 : 1] += value\n\t\t\t\t\ttarget[position++] = twoByte ? 0xce : 0xcf\n\t\t\t\t\tencode(strLength);\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t\tlet headerSize\n\t\t\t\t// first we estimate the header size, so we can write to the correct location\n\t\t\t\tif (strLength < 0x20) {\n\t\t\t\t\theaderSize = 1\n\t\t\t\t} else if (strLength < 0x100) {\n\t\t\t\t\theaderSize = 2\n\t\t\t\t} else if (strLength < 0x10000) {\n\t\t\t\t\theaderSize = 3\n\t\t\t\t} else {\n\t\t\t\t\theaderSize = 5\n\t\t\t\t}\n\t\t\t\tlet maxBytes = strLength * 3\n\t\t\t\tif (position + maxBytes > safeEnd)\n\t\t\t\t\ttarget = makeRoom(position + maxBytes)\n\n\t\t\t\tif (strLength < 0x40 || !encodeUtf8) {\n\t\t\t\t\tlet i, c1, c2, strPosition = position + headerSize\n\t\t\t\t\tfor (i = 0; i < strLength; i++) {\n\t\t\t\t\t\tc1 = value.charCodeAt(i)\n\t\t\t\t\t\tif (c1 < 0x80) {\n\t\t\t\t\t\t\ttarget[strPosition++] = c1\n\t\t\t\t\t\t} else if (c1 < 0x800) {\n\t\t\t\t\t\t\ttarget[strPosition++] = c1 >> 6 | 0xc0\n\t\t\t\t\t\t\ttarget[strPosition++] = c1 & 0x3f | 0x80\n\t\t\t\t\t\t} else if (\n\t\t\t\t\t\t\t(c1 & 0xfc00) === 0xd800 &&\n\t\t\t\t\t\t\t((c2 = value.charCodeAt(i + 1)) & 0xfc00) === 0xdc00\n\t\t\t\t\t\t) {\n\t\t\t\t\t\t\tc1 = 0x10000 + ((c1 & 0x03ff) << 10) + (c2 & 0x03ff)\n\t\t\t\t\t\t\ti++\n\t\t\t\t\t\t\ttarget[strPosition++] = c1 >> 18 | 0xf0\n\t\t\t\t\t\t\ttarget[strPosition++] = c1 >> 12 & 0x3f | 0x80\n\t\t\t\t\t\t\ttarget[strPosition++] = c1 >> 6 & 0x3f | 0x80\n\t\t\t\t\t\t\ttarget[strPosition++] = c1 & 0x3f | 0x80\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\ttarget[strPosition++] = c1 >> 12 | 0xe0\n\t\t\t\t\t\t\ttarget[strPosition++] = c1 >> 6 & 0x3f | 0x80\n\t\t\t\t\t\t\ttarget[strPosition++] = c1 & 0x3f | 0x80\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tlength = strPosition - position - headerSize\n\t\t\t\t} else {\n\t\t\t\t\tlength = encodeUtf8(value, position + headerSize, maxBytes)\n\t\t\t\t}\n\n\t\t\t\tif (length < 0x18) {\n\t\t\t\t\ttarget[position++] = 0x60 | length\n\t\t\t\t} else if (length < 0x100) {\n\t\t\t\t\tif (headerSize < 2) {\n\t\t\t\t\t\ttarget.copyWithin(position + 2, position + 1, position + 1 + length)\n\t\t\t\t\t}\n\t\t\t\t\ttarget[position++] = 0x78\n\t\t\t\t\ttarget[position++] = length\n\t\t\t\t} else if (length < 0x10000) {\n\t\t\t\t\tif (headerSize < 3) {\n\t\t\t\t\t\ttarget.copyWithin(position + 3, position + 2, position + 2 + length)\n\t\t\t\t\t}\n\t\t\t\t\ttarget[position++] = 0x79\n\t\t\t\t\ttarget[position++] = length >> 8\n\t\t\t\t\ttarget[position++] = length & 0xff\n\t\t\t\t} else {\n\t\t\t\t\tif (headerSize < 5) {\n\t\t\t\t\t\ttarget.copyWithin(position + 5, position + 3, position + 3 + length)\n\t\t\t\t\t}\n\t\t\t\t\ttarget[position++] = 0x7a\n\t\t\t\t\ttargetView.setUint32(position, length)\n\t\t\t\t\tposition += 4\n\t\t\t\t}\n\t\t\t\tposition += length\n\t\t\t} else if (type === 'number') {\n\t\t\t\tif (!this.alwaysUseFloat && value >>> 0 === value) {// positive integer, 32-bit or less\n\t\t\t\t\t// positive uint\n\t\t\t\t\tif (value < 0x18) {\n\t\t\t\t\t\ttarget[position++] = value\n\t\t\t\t\t} else if (value < 0x100) {\n\t\t\t\t\t\ttarget[position++] = 0x18\n\t\t\t\t\t\ttarget[position++] = value\n\t\t\t\t\t} else if (value < 0x10000) {\n\t\t\t\t\t\ttarget[position++] = 0x19\n\t\t\t\t\t\ttarget[position++] = value >> 8\n\t\t\t\t\t\ttarget[position++] = value & 0xff\n\t\t\t\t\t} else {\n\t\t\t\t\t\ttarget[position++] = 0x1a\n\t\t\t\t\t\ttargetView.setUint32(position, value)\n\t\t\t\t\t\tposition += 4\n\t\t\t\t\t}\n\t\t\t\t} else if (!this.alwaysUseFloat && value >> 0 === value) { // negative integer\n\t\t\t\t\tif (value >= -0x18) {\n\t\t\t\t\t\ttarget[position++] = 0x1f - value\n\t\t\t\t\t} else if (value >= -0x100) {\n\t\t\t\t\t\ttarget[position++] = 0x38\n\t\t\t\t\t\ttarget[position++] = ~value\n\t\t\t\t\t} else if (value >= -0x10000) {\n\t\t\t\t\t\ttarget[position++] = 0x39\n\t\t\t\t\t\ttargetView.setUint16(position, ~value)\n\t\t\t\t\t\tposition += 2\n\t\t\t\t\t} else {\n\t\t\t\t\t\ttarget[position++] = 0x3a\n\t\t\t\t\t\ttargetView.setUint32(position, ~value)\n\t\t\t\t\t\tposition += 4\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\tlet useFloat32\n\t\t\t\t\tif ((useFloat32 = this.useFloat32) > 0 && value < 0x100000000 && value >= -0x80000000) {\n\t\t\t\t\t\ttarget[position++] = 0xfa\n\t\t\t\t\t\ttargetView.setFloat32(position, value)\n\t\t\t\t\t\tlet xShifted\n\t\t\t\t\t\tif (useFloat32 < 4 ||\n\t\t\t\t\t\t\t\t// this checks for rounding of numbers that were encoded in 32-bit float to nearest significant decimal digit that could be preserved\n\t\t\t\t\t\t\t\t((xShifted = value * mult10[((target[position] & 0x7f) << 1) | (target[position + 1] >> 7)]) >> 0) === xShifted) {\n\t\t\t\t\t\t\tposition += 4\n\t\t\t\t\t\t\treturn\n\t\t\t\t\t\t} else\n\t\t\t\t\t\t\tposition-- // move back into position for writing a double\n\t\t\t\t\t}\n\t\t\t\t\ttarget[position++] = 0xfb\n\t\t\t\t\ttargetView.setFloat64(position, value)\n\t\t\t\t\tposition += 8\n\t\t\t\t}\n\t\t\t} else if (type === 'object') {\n\t\t\t\tif (!value)\n\t\t\t\t\ttarget[position++] = 0xf6\n\t\t\t\telse {\n\t\t\t\t\tif (referenceMap) {\n\t\t\t\t\t\tlet referee = referenceMap.get(value)\n\t\t\t\t\t\tif (referee) {\n\t\t\t\t\t\t\ttarget[position++] = 0xd8\n\t\t\t\t\t\t\ttarget[position++] = 29 // http://cbor.schmorp.de/value-sharing\n\t\t\t\t\t\t\ttarget[position++] = 0x19 // 16-bit uint\n\t\t\t\t\t\t\tif (!referee.references) {\n\t\t\t\t\t\t\t\tlet idsToInsert = referenceMap.idsToInsert || (referenceMap.idsToInsert = [])\n\t\t\t\t\t\t\t\treferee.references = []\n\t\t\t\t\t\t\t\tidsToInsert.push(referee)\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\treferee.references.push(position - start)\n\t\t\t\t\t\t\tposition += 2 // TODO: also support 32-bit\n\t\t\t\t\t\t\treturn\n\t\t\t\t\t\t} else \n\t\t\t\t\t\t\treferenceMap.set(value, { offset: position - start })\n\t\t\t\t\t}\n\t\t\t\t\tlet constructor = value.constructor\n\t\t\t\t\tif (constructor === Object) {\n\t\t\t\t\t\twriteObject(value)\n\t\t\t\t\t} else if (constructor === Array) {\n\t\t\t\t\t\tlength = value.length\n\t\t\t\t\t\tif (length < 0x18) {\n\t\t\t\t\t\t\ttarget[position++] = 0x80 | length\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\twriteArrayHeader(length)\n\t\t\t\t\t\t}\n\t\t\t\t\t\tfor (let i = 0; i < length; i++) {\n\t\t\t\t\t\t\tencode(value[i])\n\t\t\t\t\t\t}\n\t\t\t\t\t} else if (constructor === Map) {\n\t\t\t\t\t\tif (this.mapsAsObjects ? this.useTag259ForMaps !== false : this.useTag259ForMaps) {\n\t\t\t\t\t\t\t// use Tag 259 (https://github.com/shanewholloway/js-cbor-codec/blob/master/docs/CBOR-259-spec--explicit-maps.md) for maps if the user wants it that way\n\t\t\t\t\t\t\ttarget[position++] = 0xd9\n\t\t\t\t\t\t\ttarget[position++] = 1\n\t\t\t\t\t\t\ttarget[position++] = 3\n\t\t\t\t\t\t}\n\t\t\t\t\t\tlength = value.size\n\t\t\t\t\t\tif (length < 0x18) {\n\t\t\t\t\t\t\ttarget[position++] = 0xa0 | length\n\t\t\t\t\t\t} else if (length < 0x100) {\n\t\t\t\t\t\t\ttarget[position++] = 0xb8\n\t\t\t\t\t\t\ttarget[position++] = length\n\t\t\t\t\t\t} else if (length < 0x10000) {\n\t\t\t\t\t\t\ttarget[position++] = 0xb9\n\t\t\t\t\t\t\ttarget[position++] = length >> 8\n\t\t\t\t\t\t\ttarget[position++] = length & 0xff\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\ttarget[position++] = 0xba\n\t\t\t\t\t\t\ttargetView.setUint32(position, length)\n\t\t\t\t\t\t\tposition += 4\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (encoder.keyMap) { \n\t\t\t\t\t\t\tfor (let [ key, entryValue ] of value) {\n\t\t\t\t\t\t\t\tencode(encoder.encodeKey(key))\n\t\t\t\t\t\t\t\tencode(entryValue)\n\t\t\t\t\t\t\t} \n\t\t\t\t\t\t} else { \n\t\t\t\t\t\t\tfor (let [ key, entryValue ] of value) {\n\t\t\t\t\t\t\t\tencode(key) \n\t\t\t\t\t\t\t\tencode(entryValue)\n\t\t\t\t\t\t\t} \t\n\t\t\t\t\t\t}\n\t\t\t\t\t} else {\n\t\t\t\t\t\tfor (let i = 0, l = extensions.length; i < l; i++) {\n\t\t\t\t\t\t\tlet extensionClass = extensionClasses[i]\n\t\t\t\t\t\t\tif (value instanceof extensionClass) {\n\t\t\t\t\t\t\t\tlet extension = extensions[i]\n\t\t\t\t\t\t\t\tlet tag = extension.tag\n\t\t\t\t\t\t\t\tif (tag == undefined)\n\t\t\t\t\t\t\t\t\ttag = extension.getTag && extension.getTag.call(this, value)\n\t\t\t\t\t\t\t\tif (tag < 0x18) {\n\t\t\t\t\t\t\t\t\ttarget[position++] = 0xc0 | tag\n\t\t\t\t\t\t\t\t} else if (tag < 0x100) {\n\t\t\t\t\t\t\t\t\ttarget[position++] = 0xd8\n\t\t\t\t\t\t\t\t\ttarget[position++] = tag\n\t\t\t\t\t\t\t\t} else if (tag < 0x10000) {\n\t\t\t\t\t\t\t\t\ttarget[position++] = 0xd9\n\t\t\t\t\t\t\t\t\ttarget[position++] = tag >> 8\n\t\t\t\t\t\t\t\t\ttarget[position++] = tag & 0xff\n\t\t\t\t\t\t\t\t} else if (tag > -1) {\n\t\t\t\t\t\t\t\t\ttarget[position++] = 0xda\n\t\t\t\t\t\t\t\t\ttargetView.setUint32(position, tag)\n\t\t\t\t\t\t\t\t\tposition += 4\n\t\t\t\t\t\t\t\t} // else undefined, don't write tag\n\t\t\t\t\t\t\t\textension.encode.call(this, value, encode, makeRoom)\n\t\t\t\t\t\t\t\treturn\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (value[Symbol.iterator]) {\n\t\t\t\t\t\t\tif (throwOnIterable) {\n\t\t\t\t\t\t\t\tlet error = new Error('Iterable should be serialized as iterator')\n\t\t\t\t\t\t\t\terror.iteratorNotHandled = true;\n\t\t\t\t\t\t\t\tthrow error;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\ttarget[position++] = 0x9f // indefinite length array\n\t\t\t\t\t\t\tfor (let entry of value) {\n\t\t\t\t\t\t\t\tencode(entry)\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\ttarget[position++] = 0xff // stop-code\n\t\t\t\t\t\t\treturn\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (value[Symbol.asyncIterator] || isBlob(value)) {\n\t\t\t\t\t\t\tlet error = new Error('Iterable/blob should be serialized as iterator')\n\t\t\t\t\t\t\terror.iteratorNotHandled = true;\n\t\t\t\t\t\t\tthrow error;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (this.useToJSON && value.toJSON) {\n\t\t\t\t\t\t\tconst json = value.toJSON()\n\t\t\t\t\t\t\t// if for some reason value.toJSON returns itself it'll loop forever\n\t\t\t\t\t\t\tif (json !== value)\n\t\t\t\t\t\t\t\treturn encode(json)\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\t// no extension found, write as a plain object\n\t\t\t\t\t\twriteObject(value)\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t} else if (type === 'boolean') {\n\t\t\t\ttarget[position++] = value ? 0xf5 : 0xf4\n\t\t\t} else if (type === 'bigint') {\n\t\t\t\tif (value < (BigInt(1)<<BigInt(64)) && value >= 0) {\n\t\t\t\t\t// use an unsigned int as long as it fits\n\t\t\t\t\ttarget[position++] = 0x1b\n\t\t\t\t\ttargetView.setBigUint64(position, value)\n\t\t\t\t} else if (value > -(BigInt(1)<<BigInt(64)) && value < 0) {\n\t\t\t\t\t// if we can fit an unsigned int, use that\n\t\t\t\t\ttarget[position++] = 0x3b\n\t\t\t\t\ttargetView.setBigUint64(position, -value - BigInt(1))\n\t\t\t\t} else {\n\t\t\t\t\t// overflow\n\t\t\t\t\tif (this.largeBigIntToFloat) {\n\t\t\t\t\t\ttarget[position++] = 0xfb\n\t\t\t\t\t\ttargetView.setFloat64(position, Number(value))\n\t\t\t\t\t} else {\n\t\t\t\t\t\tif (value >= BigInt(0))\n\t\t\t\t\t\t\ttarget[position++] = 0xc2 // tag 2\n\t\t\t\t\t\telse {\n\t\t\t\t\t\t\ttarget[position++] = 0xc3 // tag 2\n\t\t\t\t\t\t\tvalue = BigInt(-1) - value;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tlet bytes = [];\n\t\t\t\t\t\twhile (value) {\n\t\t\t\t\t\t\tbytes.push(Number(value & BigInt(0xff)));\n\t\t\t\t\t\t\tvalue >>= BigInt(8);\n\t\t\t\t\t\t}\n\t\t\t\t\t\twriteBuffer(new Uint8Array(bytes.reverse()), makeRoom);\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tposition += 8\n\t\t\t} else if (type === 'undefined') {\n\t\t\t\ttarget[position++] = 0xf7\n\t\t\t} else {\n\t\t\t\tthrow new Error('Unknown type: ' + type)\n\t\t\t}\n\t\t}\n\n\t\tconst writeObject = this.useRecords === false ? this.variableMapSize ? (object) => {\n\t\t\t// this method is slightly slower, but generates \"preferred serialization\" (optimally small for smaller objects)\n\t\t\tlet keys = Object.keys(object)\n\t\t\tlet vals = Object.values(object)\n\t\t\tlet length = keys.length\n\t\t\tif (length < 0x18) {\n\t\t\t\ttarget[position++] = 0xa0 | length\n\t\t\t} else if (length < 0x100) {\n\t\t\t\ttarget[position++] = 0xb8\n\t\t\t\ttarget[position++] = length\n\t\t\t} else if (length < 0x10000) {\n\t\t\t\ttarget[position++] = 0xb9\n\t\t\t\ttarget[position++] = length >> 8\n\t\t\t\ttarget[position++] = length & 0xff\n\t\t\t} else {\n\t\t\t\ttarget[position++] = 0xba\n\t\t\t\ttargetView.setUint32(position, length)\n\t\t\t\tposition += 4\n\t\t\t}\n\t\t\tlet key\n\t\t\tif (encoder.keyMap) { \n\t\t\t\tfor (let i = 0; i < length; i++) {\n\t\t\t\t\tencode(encoder.encodeKey(keys[i]))\n\t\t\t\t\tencode(vals[i])\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tfor (let i = 0; i < length; i++) {\n\t\t\t\t\tencode(keys[i])\n\t\t\t\t\tencode(vals[i])\n\t\t\t\t}\n\t\t\t}\n\t\t} :\n\t\t(object) => {\n\t\t\ttarget[position++] = 0xb9 // always use map 16, so we can preallocate and set the length afterwards\n\t\t\tlet objectOffset = position - start\n\t\t\tposition += 2\n\t\t\tlet size = 0\n\t\t\tif (encoder.keyMap) {\n\t\t\t\tfor (let key in object) if (typeof object.hasOwnProperty !== 'function' || object.hasOwnProperty(key)) {\n\t\t\t\t\tencode(encoder.encodeKey(key))\n\t\t\t\t\tencode(object[key])\n\t\t\t\t\tsize++\n\t\t\t\t}\n\t\t\t} else { \n\t\t\t\tfor (let key in object) if (typeof object.hasOwnProperty !== 'function' || object.hasOwnProperty(key)) {\n\t\t\t\t\t\tencode(key)\n\t\t\t\t\t\tencode(object[key])\n\t\t\t\t\tsize++\n\t\t\t\t}\n\t\t\t}\n\t\t\ttarget[objectOffset++ + start] = size >> 8\n\t\t\ttarget[objectOffset + start] = size & 0xff\n\t\t} :\n\t\t(object, skipValues) => {\n\t\t\tlet nextTransition, transition = structures.transitions || (structures.transitions = Object.create(null))\n\t\t\tlet newTransitions = 0\n\t\t\tlet length = 0\n\t\t\tlet parentRecordId\n\t\t\tlet keys\n\t\t\tif (this.keyMap) {\n\t\t\t\tkeys = Object.keys(object).map(k => this.encodeKey(k))\n\t\t\t\tlength = keys.length\n\t\t\t\tfor (let i = 0; i < length; i++) {\n\t\t\t\t\tlet key = keys[i]\n\t\t\t\t\tnextTransition = transition[key]\n\t\t\t\t\tif (!nextTransition) {\n\t\t\t\t\t\tnextTransition = transition[key] = Object.create(null)\n\t\t\t\t\t\tnewTransitions++\n\t\t\t\t\t}\n\t\t\t\t\ttransition = nextTransition\n\t\t\t\t}\t\t\t\t\n\t\t\t} else {\n\t\t\t\tfor (let key in object) if (typeof object.hasOwnProperty !== 'function' || object.hasOwnProperty(key)) {\n\t\t\t\t\tnextTransition = transition[key]\n\t\t\t\t\tif (!nextTransition) {\n\t\t\t\t\t\tif (transition[RECORD_SYMBOL] & 0x100000) {// this indicates it is a brancheable/extendable terminal node, so we will use this record id and extend it\n\t\t\t\t\t\t\tparentRecordId = transition[RECORD_SYMBOL] & 0xffff\n\t\t\t\t\t\t}\n\t\t\t\t\t\tnextTransition = transition[key] = Object.create(null)\n\t\t\t\t\t\tnewTransitions++\n\t\t\t\t\t}\n\t\t\t\t\ttransition = nextTransition\n\t\t\t\t\tlength++\n\t\t\t\t}\n\t\t\t}\n\t\t\tlet recordId = transition[RECORD_SYMBOL]\n\t\t\tif (recordId !== undefined) {\n\t\t\t\trecordId &= 0xffff\n\t\t\t\ttarget[position++] = 0xd9\n\t\t\t\ttarget[position++] = (recordId >> 8) | 0xe0\n\t\t\t\ttarget[position++] = recordId & 0xff\n\t\t\t} else {\n\t\t\t\tif (!keys)\n\t\t\t\t\tkeys = transition.__keys__ || (transition.__keys__ = Object.keys(object))\n\t\t\t\tif (parentRecordId === undefined) {\n\t\t\t\t\trecordId = structures.nextId++\n\t\t\t\t\tif (!recordId) {\n\t\t\t\t\t\trecordId = 0\n\t\t\t\t\t\tstructures.nextId = 1\n\t\t\t\t\t}\n\t\t\t\t\tif (recordId >= MAX_STRUCTURES) {// cycle back around\n\t\t\t\t\t\tstructures.nextId = (recordId = maxSharedStructures) + 1\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\trecordId = parentRecordId\n\t\t\t\t}\n\t\t\t\tstructures[recordId] = keys\n\t\t\t\tif (recordId < maxSharedStructures) {\n\t\t\t\t\ttarget[position++] = 0xd9\n\t\t\t\t\ttarget[position++] = (recordId >> 8) | 0xe0\n\t\t\t\t\ttarget[position++] = recordId & 0xff\n\t\t\t\t\ttransition = structures.transitions\n\t\t\t\t\tfor (let i = 0; i < length; i++) {\n\t\t\t\t\t\tif (transition[RECORD_SYMBOL] === undefined || (transition[RECORD_SYMBOL] & 0x100000))\n\t\t\t\t\t\t\ttransition[RECORD_SYMBOL] = recordId\n\t\t\t\t\t\ttransition = transition[keys[i]]\n\t\t\t\t\t}\n\t\t\t\t\ttransition[RECORD_SYMBOL] = recordId | 0x100000 // indicates it is a extendable terminal\n\t\t\t\t\thasSharedUpdate = true\n\t\t\t\t} else {\n\t\t\t\t\ttransition[RECORD_SYMBOL] = recordId\n\t\t\t\t\ttargetView.setUint32(position, 0xd9dfff00) // tag two byte, then record definition id\n\t\t\t\t\tposition += 3\n\t\t\t\t\tif (newTransitions)\n\t\t\t\t\t\ttransitionsCount += serializationsSinceTransitionRebuild * newTransitions\n\t\t\t\t\t// record the removal of the id, we can maintain our shared structure\n\t\t\t\t\tif (recordIdsToRemove.length >= MAX_STRUCTURES - maxSharedStructures)\n\t\t\t\t\t\trecordIdsToRemove.shift()[RECORD_SYMBOL] = undefined // we are cycling back through, and have to remove old ones\n\t\t\t\t\trecordIdsToRemove.push(transition)\n\t\t\t\t\twriteArrayHeader(length + 2)\n\t\t\t\t\tencode(0xe000 + recordId)\n\t\t\t\t\tencode(keys)\n\t\t\t\t\tif (skipValues) return; // special exit for iterator\n\t\t\t\t\tfor (let key in object)\n\t\t\t\t\t\tif (typeof object.hasOwnProperty !== 'function' || object.hasOwnProperty(key))\n\t\t\t\t\t\t\tencode(object[key])\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (length < 0x18) { // write the array header\n\t\t\t\ttarget[position++] = 0x80 | length\n\t\t\t} else {\n\t\t\t\twriteArrayHeader(length)\n\t\t\t}\n\t\t\tif (skipValues) return; // special exit for iterator\n\t\t\tfor (let key in object)\n\t\t\t\tif (typeof object.hasOwnProperty !== 'function' || object.hasOwnProperty(key))\n\t\t\t\t\tencode(object[key])\n\t\t}\n\t\tconst makeRoom = (end) => {\n\t\t\tlet newSize\n\t\t\tif (end > 0x1000000) {\n\t\t\t\t// special handling for really large buffers\n\t\t\t\tif ((end - start) > MAX_BUFFER_SIZE)\n\t\t\t\t\tthrow new Error('Encoded buffer would be larger than maximum buffer size')\n\t\t\t\tnewSize = Math.min(MAX_BUFFER_SIZE,\n\t\t\t\t\tMath.round(Math.max((end - start) * (end > 0x4000000 ? 1.25 : 2), 0x400000) / 0x1000) * 0x1000)\n\t\t\t} else // faster handling for smaller buffers\n\t\t\t\tnewSize = ((Math.max((end - start) << 2, target.length - 1) >> 12) + 1) << 12\n\t\t\tlet newBuffer = new ByteArrayAllocate(newSize)\n\t\t\ttargetView = new DataView(newBuffer.buffer, 0, newSize)\n\t\t\tif (target.copy)\n\t\t\t\ttarget.copy(newBuffer, 0, start, end)\n\t\t\telse\n\t\t\t\tnewBuffer.set(target.slice(start, end))\n\t\t\tposition -= start\n\t\t\tstart = 0\n\t\t\tsafeEnd = newBuffer.length - 10\n\t\t\treturn target = newBuffer\n\t\t}\n\t\tlet chunkThreshold = 100;\n\t\tlet continuedChunkThreshold = 1000;\n\t\tthis.encodeAsIterable = function(value, options) {\n\t\t\treturn startEncoding(value, options, encodeObjectAsIterable);\n\t\t}\n\t\tthis.encodeAsAsyncIterable = function(value, options) {\n\t\t\treturn startEncoding(value, options, encodeObjectAsAsyncIterable);\n\t\t}\n\n\t\tfunction* encodeObjectAsIterable(object, iterateProperties, finalIterable) {\n\t\t\tlet constructor = object.constructor;\n\t\t\tif (constructor === Object) {\n\t\t\t\tlet useRecords = encoder.useRecords !== false;\n\t\t\t\tif (useRecords)\n\t\t\t\t\twriteObject(object, true); // write the record identifier\n\t\t\t\telse\n\t\t\t\t\twriteEntityLength(Object.keys(object).length, 0xa0);\n\t\t\t\tfor (let key in object) {\n\t\t\t\t\tlet value = object[key];\n\t\t\t\t\tif (!useRecords) encode(key);\n\t\t\t\t\tif (value && typeof value === 'object') {\n\t\t\t\t\t\tif (iterateProperties[key])\n\t\t\t\t\t\t\tyield* encodeObjectAsIterable(value, iterateProperties[key]);\n\t\t\t\t\t\telse\n\t\t\t\t\t\t\tyield* tryEncode(value, iterateProperties, key);\n\t\t\t\t\t} else encode(value);\n\t\t\t\t}\n\t\t\t} else if (constructor === Array) {\n\t\t\t\tlet length = object.length;\n\t\t\t\twriteArrayHeader(length);\n\t\t\t\tfor (let i = 0; i < length; i++) {\n\t\t\t\t\tlet value = object[i];\n\t\t\t\t\tif (value && (typeof value === 'object' || position - start > chunkThreshold)) {\n\t\t\t\t\t\tif (iterateProperties.element)\n\t\t\t\t\t\t\tyield* encodeObjectAsIterable(value, iterateProperties.element);\n\t\t\t\t\t\telse\n\t\t\t\t\t\t\tyield* tryEncode(value, iterateProperties, 'element');\n\t\t\t\t\t} else encode(value);\n\t\t\t\t}\n\t\t\t} else if (object[Symbol.iterator] && !object.buffer) { // iterator, but exclude typed arrays\n\t\t\t\ttarget[position++] = 0x9f; // start indefinite array\n\t\t\t\tfor (let value of object) {\n\t\t\t\t\tif (value && (typeof value === 'object' || position - start > chunkThreshold)) {\n\t\t\t\t\t\tif (iterateProperties.element)\n\t\t\t\t\t\t\tyield* encodeObjectAsIterable(value, iterateProperties.element);\n\t\t\t\t\t\telse\n\t\t\t\t\t\t\tyield* tryEncode(value, iterateProperties, 'element');\n\t\t\t\t\t} else encode(value);\n\t\t\t\t}\n\t\t\t\ttarget[position++] = 0xff; // stop byte\n\t\t\t} else if (isBlob(object)){\n\t\t\t\twriteEntityLength(object.size, 0x40); // encode as binary data\n\t\t\t\tyield target.subarray(start, position);\n\t\t\t\tyield object; // directly return blobs, they have to be encoded asynchronously\n\t\t\t\trestartEncoding();\n\t\t\t} else if (object[Symbol.asyncIterator]) {\n\t\t\t\ttarget[position++] = 0x9f; // start indefinite array\n\t\t\t\tyield target.subarray(start, position);\n\t\t\t\tyield object; // directly return async iterators, they have to be encoded asynchronously\n\t\t\t\trestartEncoding();\n\t\t\t\ttarget[position++] = 0xff; // stop byte\n\t\t\t} else {\n\t\t\t\tencode(object);\n\t\t\t}\n\t\t\tif (finalIterable && position > start) yield target.subarray(start, position);\n\t\t\telse if (position - start > chunkThreshold) {\n\t\t\t\tyield target.subarray(start, position);\n\t\t\t\trestartEncoding();\n\t\t\t}\n\t\t}\n\t\tfunction* tryEncode(value, iterateProperties, key) {\n\t\t\tlet restart = position - start;\n\t\t\ttry {\n\t\t\t\tencode(value);\n\t\t\t\tif (position - start > chunkThreshold) {\n\t\t\t\t\tyield target.subarray(start, position);\n\t\t\t\t\trestartEncoding();\n\t\t\t\t}\n\t\t\t} catch (error) {\n\t\t\t\tif (error.iteratorNotHandled) {\n\t\t\t\t\titerateProperties[key] = {};\n\t\t\t\t\tposition = start + restart; // restart our position so we don't have partial data from last encode\n\t\t\t\t\tyield* encodeObjectAsIterable.call(this, value, iterateProperties[key]);\n\t\t\t\t} else throw error;\n\t\t\t}\n\t\t}\n\t\tfunction restartEncoding() {\n\t\t\tchunkThreshold = continuedChunkThreshold;\n\t\t\tencoder.encode(null, THROW_ON_ITERABLE); // restart encoding\n\t\t}\n\t\tfunction startEncoding(value, options, encodeIterable) {\n\t\t\tif (options && options.chunkThreshold) // explicitly specified chunk sizes\n\t\t\t\tchunkThreshold = continuedChunkThreshold = options.chunkThreshold;\n\t\t\telse // we start with a smaller threshold to get initial bytes sent quickly\n\t\t\t\tchunkThreshold = 100;\n\t\t\tif (value && typeof value === 'object') {\n\t\t\t\tencoder.encode(null, THROW_ON_ITERABLE); // start encoding\n\t\t\t\treturn encodeIterable(value, encoder.iterateProperties || (encoder.iterateProperties = {}), true);\n\t\t\t}\n\t\t\treturn [encoder.encode(value)];\n\t\t}\n\n\t\tasync function* encodeObjectAsAsyncIterable(value, iterateProperties) {\n\t\t\tfor (let encodedValue of encodeObjectAsIterable(value, iterateProperties, true)) {\n\t\t\t\tlet constructor = encodedValue.constructor;\n\t\t\t\tif (constructor === ByteArray || constructor === Uint8Array)\n\t\t\t\t\tyield encodedValue;\n\t\t\t\telse if (isBlob(encodedValue)) {\n\t\t\t\t\tlet reader = encodedValue.stream().getReader();\n\t\t\t\t\tlet next;\n\t\t\t\t\twhile (!(next = await reader.read()).done) {\n\t\t\t\t\t\tyield next.value;\n\t\t\t\t\t}\n\t\t\t\t} else if (encodedValue[Symbol.asyncIterator]) {\n\t\t\t\t\tfor await (let asyncValue of encodedValue) {\n\t\t\t\t\t\trestartEncoding();\n\t\t\t\t\t\tif (asyncValue)\n\t\t\t\t\t\t\tyield* encodeObjectAsAsyncIterable(asyncValue, iterateProperties.async || (iterateProperties.async = {}));\n\t\t\t\t\t\telse yield encoder.encode(asyncValue);\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\tyield encodedValue;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\tuseBuffer(buffer) {\n\t\t// this means we are finished using our own buffer and we can write over it safely\n\t\ttarget = buffer\n\t\ttargetView = new DataView(target.buffer, target.byteOffset, target.byteLength)\n\t\tposition = 0\n\t}\n\tclearSharedData() {\n\t\tif (this.structures)\n\t\t\tthis.structures = []\n\t\tif (this.sharedValues)\n\t\t\tthis.sharedValues = undefined\n\t}\n\tupdateSharedData() {\n\t\tlet lastVersion = this.sharedVersion || 0\n\t\tthis.sharedVersion = lastVersion + 1\n\t\tlet structuresCopy = this.structures.slice(0)\n\t\tlet sharedData = new SharedData(structuresCopy, this.sharedValues, this.sharedVersion)\n\t\tlet saveResults = this.saveShared(sharedData,\n\t\t\t\texistingShared => (existingShared && existingShared.version || 0) == lastVersion)\n\t\tif (saveResults === false) {\n\t\t\t// get updated structures and try again if the update failed\n\t\t\tsharedData = this.getShared() || {}\n\t\t\tthis.structures = sharedData.structures || []\n\t\t\tthis.sharedValues = sharedData.packedValues\n\t\t\tthis.sharedVersion = sharedData.version\n\t\t\tthis.structures.nextId = this.structures.length\n\t\t} else {\n\t\t\t// restore structures\n\t\t\tstructuresCopy.forEach((structure, i) => this.structures[i] = structure)\n\t\t}\n\t\t// saveShared may fail to write and reload, or may have reloaded to check compatibility and overwrite saved data, either way load the correct shared data\n\t\treturn saveResults\n\t}\n}\nfunction writeEntityLength(length, majorValue) {\n\tif (length < 0x18)\n\t\ttarget[position++] = majorValue | length\n\telse if (length < 0x100) {\n\t\ttarget[position++] = majorValue | 0x18\n\t\ttarget[position++] = length\n\t} else if (length < 0x10000) {\n\t\ttarget[position++] = majorValue | 0x19\n\t\ttarget[position++] = length >> 8\n\t\ttarget[position++] = length & 0xff\n\t} else {\n\t\ttarget[position++] = majorValue | 0x1a\n\t\ttargetView.setUint32(position, length)\n\t\tposition += 4\n\t}\n\n}\nclass SharedData {\n\tconstructor(structures, values, version) {\n\t\tthis.structures = structures\n\t\tthis.packedValues = values\n\t\tthis.version = version\n\t}\n}\n\nfunction writeArrayHeader(length) {\n\tif (length < 0x18)\n\t\ttarget[position++] = 0x80 | length\n\telse if (length < 0x100) {\n\t\ttarget[position++] = 0x98\n\t\ttarget[position++] = length\n\t} else if (length < 0x10000) {\n\t\ttarget[position++] = 0x99\n\t\ttarget[position++] = length >> 8\n\t\ttarget[position++] = length & 0xff\n\t} else {\n\t\ttarget[position++] = 0x9a\n\t\ttargetView.setUint32(position, length)\n\t\tposition += 4\n\t}\n}\n\nconst BlobConstructor = typeof Blob === 'undefined' ? function(){} : Blob;\nfunction isBlob(object) {\n\tif (object instanceof BlobConstructor)\n\t\treturn true;\n\tlet tag = object[Symbol.toStringTag];\n\treturn tag === 'Blob' || tag === 'File';\n}\nfunction findRepetitiveStrings(value, packedValues) {\n\tswitch(typeof value) {\n\t\tcase 'string':\n\t\t\tif (value.length > 3) {\n\t\t\t\tif (packedValues.objectMap[value] > -1 || packedValues.values.length >= packedValues.maxValues)\n\t\t\t\t\treturn\n\t\t\t\tlet packedStatus = packedValues.get(value)\n\t\t\t\tif (packedStatus) {\n\t\t\t\t\tif (++packedStatus.count == 2) {\n\t\t\t\t\t\tpackedValues.values.push(value)\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\tpackedValues.set(value, {\n\t\t\t\t\t\tcount: 1,\n\t\t\t\t\t})\n\t\t\t\t\tif (packedValues.samplingPackedValues) {\n\t\t\t\t\t\tlet status = packedValues.samplingPackedValues.get(value)\n\t\t\t\t\t\tif (status)\n\t\t\t\t\t\t\tstatus.count++\n\t\t\t\t\t\telse\n\t\t\t\t\t\t\tpackedValues.samplingPackedValues.set(value, {\n\t\t\t\t\t\t\t\tcount: 1,\n\t\t\t\t\t\t\t})\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tbreak\n\t\tcase 'object':\n\t\t\tif (value) {\n\t\t\t\tif (value instanceof Array) {\n\t\t\t\t\tfor (let i = 0, l = value.length; i < l; i++) {\n\t\t\t\t\t\tfindRepetitiveStrings(value[i], packedValues)\n\t\t\t\t\t}\n\n\t\t\t\t} else {\n\t\t\t\t\tlet includeKeys = !packedValues.encoder.useRecords\n\t\t\t\t\tfor (var key in value) {\n\t\t\t\t\t\tif (value.hasOwnProperty(key)) {\n\t\t\t\t\t\t\tif (includeKeys)\n\t\t\t\t\t\t\t\tfindRepetitiveStrings(key, packedValues)\n\t\t\t\t\t\t\tfindRepetitiveStrings(value[key], packedValues)\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tbreak\n\t\tcase 'function': console.log(value)\n\t}\n}\nconst isLittleEndianMachine = new Uint8Array(new Uint16Array([1]).buffer)[0] == 1\nextensionClasses = [ Date, Set, Error, RegExp, Tag, ArrayBuffer,\n\tUint8Array, Uint8ClampedArray, Uint16Array, Uint32Array,\n\ttypeof BigUint64Array == 'undefined' ? function() {} : BigUint64Array, Int8Array, Int16Array, Int32Array,\n\ttypeof BigInt64Array == 'undefined' ? function() {} : BigInt64Array,\n\tFloat32Array, Float64Array, SharedData ]\n\n//Object.getPrototypeOf(Uint8Array.prototype).constructor /*TypedArray*/\nextensions = [{ // Date\n\ttag: 1,\n\tencode(date, encode) {\n\t\tlet seconds = date.getTime() / 1000\n\t\tif ((this.useTimestamp32 || date.getMilliseconds() === 0) && seconds >= 0 && seconds < 0x100000000) {\n\t\t\t// Timestamp 32\n\t\t\ttarget[position++] = 0x1a\n\t\t\ttargetView.setUint32(position, seconds)\n\t\t\tposition += 4\n\t\t} else {\n\t\t\t// Timestamp float64\n\t\t\ttarget[position++] = 0xfb\n\t\t\ttargetView.setFloat64(position, seconds)\n\t\t\tposition += 8\n\t\t}\n\t}\n}, { // Set\n\ttag: 258, // https://github.com/input-output-hk/cbor-sets-spec/blob/master/CBOR_SETS.md\n\tencode(set, encode) {\n\t\tlet array = Array.from(set)\n\t\tencode(array)\n\t}\n}, { // Error\n\ttag: 27, // http://cbor.schmorp.de/generic-object\n\tencode(error, encode) {\n\t\tencode([ error.name, error.message ])\n\t}\n}, { // RegExp\n\ttag: 27, // http://cbor.schmorp.de/generic-object\n\tencode(regex, encode) {\n\t\tencode([ 'RegExp', regex.source, regex.flags ])\n\t}\n}, { // Tag\n\tgetTag(tag) {\n\t\treturn tag.tag\n\t},\n\tencode(tag, encode) {\n\t\tencode(tag.value)\n\t}\n}, { // ArrayBuffer\n\tencode(arrayBuffer, encode, makeRoom) {\n\t\twriteBuffer(arrayBuffer, makeRoom)\n\t}\n}, { // Uint8Array\n\tgetTag(typedArray) {\n\t\tif (typedArray.constructor === Uint8Array) {\n\t\t\tif (this.tagUint8Array || hasNodeBuffer && this.tagUint8Array !== false)\n\t\t\t\treturn 64;\n\t\t} // else no tag\n\t},\n\tencode(typedArray, encode, makeRoom) {\n\t\twriteBuffer(typedArray, makeRoom)\n\t}\n},\n\ttypedArrayEncoder(68, 1),\n\ttypedArrayEncoder(69, 2),\n\ttypedArrayEncoder(70, 4),\n\ttypedArrayEncoder(71, 8),\n\ttypedArrayEncoder(72, 1),\n\ttypedArrayEncoder(77, 2),\n\ttypedArrayEncoder(78, 4),\n\ttypedArrayEncoder(79, 8),\n\ttypedArrayEncoder(85, 4),\n\ttypedArrayEncoder(86, 8),\n{\n\tencode(sharedData, encode) { // write SharedData\n\t\tlet packedValues = sharedData.packedValues || []\n\t\tlet sharedStructures = sharedData.structures || []\n\t\tif (packedValues.values.length > 0) {\n\t\t\ttarget[position++] = 0xd8 // one-byte tag\n\t\t\ttarget[position++] = 51 // tag 51 for packed shared structures https://www.potaroo.net/ietf/ids/draft-ietf-cbor-packed-03.txt\n\t\t\twriteArrayHeader(4)\n\t\t\tlet valuesArray = packedValues.values\n\t\t\tencode(valuesArray)\n\t\t\twriteArrayHeader(0) // prefixes\n\t\t\twriteArrayHeader(0) // suffixes\n\t\t\tpackedObjectMap = Object.create(sharedPackedObjectMap || null)\n\t\t\tfor (let i = 0, l = valuesArray.length; i < l; i++) {\n\t\t\t\tpackedObjectMap[valuesArray[i]] = i\n\t\t\t}\n\t\t}\n\t\tif (sharedStructures) {\n\t\t\ttargetView.setUint32(position, 0xd9dffe00)\n\t\t\tposition += 3\n\t\t\tlet definitions = sharedStructures.slice(0)\n\t\t\tdefinitions.unshift(0xe000)\n\t\t\tdefinitions.push(new Tag(sharedData.version, 0x53687264))\n\t\t\tencode(definitions)\n\t\t} else\n\t\t\tencode(new Tag(sharedData.version, 0x53687264))\n\t\t}\n\t}]\nfunction typedArrayEncoder(tag, size) {\n\tif (!isLittleEndianMachine && size > 1)\n\t\ttag -= 4 // the big endian equivalents are 4 less\n\treturn {\n\t\ttag: tag,\n\t\tencode: function writeExtBuffer(typedArray, encode) {\n\t\t\tlet length = typedArray.byteLength\n\t\t\tlet offset = typedArray.byteOffset || 0\n\t\t\tlet buffer = typedArray.buffer || typedArray\n\t\t\tencode(hasNodeBuffer ? Buffer.from(buffer, offset, length) :\n\t\t\t\tnew Uint8Array(buffer, offset, length))\n\t\t}\n\t}\n}\nfunction writeBuffer(buffer, makeRoom) {\n\tlet length = buffer.byteLength\n\tif (length < 0x18) {\n\t\ttarget[position++] = 0x40 + length\n\t} else if (length < 0x100) {\n\t\ttarget[position++] = 0x58\n\t\ttarget[position++] = length\n\t} else if (length < 0x10000) {\n\t\ttarget[position++] = 0x59\n\t\ttarget[position++] = length >> 8\n\t\ttarget[position++] = length & 0xff\n\t} else {\n\t\ttarget[position++] = 0x5a\n\t\ttargetView.setUint32(position, length)\n\t\tposition += 4\n\t}\n\tif (position + length >= target.length) {\n\t\tmakeRoom(position + length)\n\t}\n\t// if it is already a typed array (has an ArrayBuffer), use that, but if it is an ArrayBuffer itself,\n\t// must wrap it to set it.\n\ttarget.set(buffer.buffer ? buffer : new Uint8Array(buffer), position)\n\tposition += length\n}\n\nfunction insertIds(serialized, idsToInsert) {\n\t// insert the ids that need to be referenced for structured clones\n\tlet nextId\n\tlet distanceToMove = idsToInsert.length * 2\n\tlet lastEnd = serialized.length - distanceToMove\n\tidsToInsert.sort((a, b) => a.offset > b.offset ? 1 : -1)\n\tfor (let id = 0; id < idsToInsert.length; id++) {\n\t\tlet referee = idsToInsert[id]\n\t\treferee.id = id\n\t\tfor (let position of referee.references) {\n\t\t\tserialized[position++] = id >> 8\n\t\t\tserialized[position] = id & 0xff\n\t\t}\n\t}\n\twhile (nextId = idsToInsert.pop()) {\n\t\tlet offset = nextId.offset\n\t\tserialized.copyWithin(offset + distanceToMove, offset, lastEnd)\n\t\tdistanceToMove -= 2\n\t\tlet position = offset + distanceToMove\n\t\tserialized[position++] = 0xd8\n\t\tserialized[position++] = 28 // http://cbor.schmorp.de/value-sharing\n\t\tlastEnd = offset\n\t}\n\treturn serialized\n}\nfunction writeBundles(start, encode) {\n\ttargetView.setUint32(bundledStrings.position + start, position - bundledStrings.position - start + 1) // the offset to bundle\n\tlet writeStrings = bundledStrings\n\tbundledStrings = null\n\tencode(writeStrings[0])\n\tencode(writeStrings[1])\n}\n\nexport function addExtension(extension) {\n\tif (extension.Class) {\n\t\tif (!extension.encode)\n\t\t\tthrow new Error('Extension has no encode function')\n\t\textensionClasses.unshift(extension.Class)\n\t\textensions.unshift(extension)\n\t}\n\tdecodeAddExtension(extension)\n}\nlet defaultEncoder = new Encoder({ useRecords: false })\nexport const encode = defaultEncoder.encode\nexport const encodeAsIterable = defaultEncoder.encodeAsIterable\nexport const encodeAsAsyncIterable = defaultEncoder.encodeAsAsyncIterable\nexport { FLOAT32_OPTIONS } from './decode.js'\nimport { FLOAT32_OPTIONS } from './decode.js'\nexport const { NEVER, ALWAYS, DECIMAL_ROUND, DECIMAL_FIT } = FLOAT32_OPTIONS\nexport const REUSE_BUFFER_MODE = 512\nexport const RESET_BUFFER_MODE = 1024\nexport const THROW_ON_ITERABLE = 2048\n\n\n","class BitMatrix {\n    constructor(data, width) {\n        this.width = width;\n        this.height = data.length / width;\n        this.data = data;\n    }\n    static createEmpty(width, height) {\n        return new BitMatrix(new Uint8ClampedArray(width * height), width);\n    }\n    get(x, y) {\n        if (x < 0 || x >= this.width || y < 0 || y >= this.height) {\n            return false;\n        }\n        return !!this.data[y * this.width + x];\n    }\n    set(x, y, v) {\n        this.data[y * this.width + x] = v ? 1 : 0;\n    }\n    setRegion(left, top, width, height, v) {\n        for (let y = top; y < top + height; y++) {\n            for (let x = left; x < left + width; x++) {\n                this.set(x, y, !!v);\n            }\n        }\n    }\n}\n\nconst REGION_SIZE = 8;\nconst MIN_DYNAMIC_RANGE = 24;\nfunction numBetween(value, min, max) {\n    return value < min ? min : value > max ? max : value;\n}\n// Like BitMatrix but accepts arbitry Uint8 values\nclass Matrix {\n    constructor(width, height, buffer) {\n        this.width = width;\n        const bufferSize = width * height;\n        if (buffer && buffer.length !== bufferSize) {\n            throw new Error(\"Wrong buffer size\");\n        }\n        this.data = buffer || new Uint8ClampedArray(bufferSize);\n    }\n    get(x, y) {\n        return this.data[y * this.width + x];\n    }\n    set(x, y, value) {\n        this.data[y * this.width + x] = value;\n    }\n}\nfunction binarize(data, width, height, returnInverted, greyscaleWeights, canOverwriteImage) {\n    const pixelCount = width * height;\n    if (data.length !== pixelCount * 4) {\n        throw new Error(\"Malformed data passed to binarizer.\");\n    }\n    // assign the greyscale and binary image within the rgba buffer as the rgba image will not be needed after conversion\n    let bufferOffset = 0;\n    // Convert image to greyscale\n    let greyscaleBuffer;\n    if (canOverwriteImage) {\n        greyscaleBuffer = new Uint8ClampedArray(data.buffer, bufferOffset, pixelCount);\n        bufferOffset += pixelCount;\n    }\n    const greyscalePixels = new Matrix(width, height, greyscaleBuffer);\n    if (greyscaleWeights.useIntegerApproximation) {\n        for (let y = 0; y < height; y++) {\n            for (let x = 0; x < width; x++) {\n                const pixelPosition = (y * width + x) * 4;\n                const r = data[pixelPosition];\n                const g = data[pixelPosition + 1];\n                const b = data[pixelPosition + 2];\n                greyscalePixels.set(x, y, \n                // tslint:disable-next-line no-bitwise\n                (greyscaleWeights.red * r + greyscaleWeights.green * g + greyscaleWeights.blue * b + 128) >> 8);\n            }\n        }\n    }\n    else {\n        for (let y = 0; y < height; y++) {\n            for (let x = 0; x < width; x++) {\n                const pixelPosition = (y * width + x) * 4;\n                const r = data[pixelPosition];\n                const g = data[pixelPosition + 1];\n                const b = data[pixelPosition + 2];\n                greyscalePixels.set(x, y, greyscaleWeights.red * r + greyscaleWeights.green * g + greyscaleWeights.blue * b);\n            }\n        }\n    }\n    const horizontalRegionCount = Math.ceil(width / REGION_SIZE);\n    const verticalRegionCount = Math.ceil(height / REGION_SIZE);\n    const blackPointsCount = horizontalRegionCount * verticalRegionCount;\n    let blackPointsBuffer;\n    if (canOverwriteImage) {\n        blackPointsBuffer = new Uint8ClampedArray(data.buffer, bufferOffset, blackPointsCount);\n        bufferOffset += blackPointsCount;\n    }\n    const blackPoints = new Matrix(horizontalRegionCount, verticalRegionCount, blackPointsBuffer);\n    for (let verticalRegion = 0; verticalRegion < verticalRegionCount; verticalRegion++) {\n        for (let hortizontalRegion = 0; hortizontalRegion < horizontalRegionCount; hortizontalRegion++) {\n            let min = Infinity;\n            let max = 0;\n            for (let y = 0; y < REGION_SIZE; y++) {\n                for (let x = 0; x < REGION_SIZE; x++) {\n                    const pixelLumosity = greyscalePixels.get(hortizontalRegion * REGION_SIZE + x, verticalRegion * REGION_SIZE + y);\n                    min = Math.min(min, pixelLumosity);\n                    max = Math.max(max, pixelLumosity);\n                }\n            }\n            // We could also compute the real average of all pixels but following the assumption that the qr code consists\n            // of bright and dark pixels and essentially not much in between, by (min + max)/2 we make the cut really between\n            // those two classes. If using the average over all pixel in a block of mostly bright pixels and few dark pixels,\n            // the avg would tend to the bright side and darker bright pixels could be interpreted as dark.\n            let average = (min + max) / 2;\n            // Small bias towards black by moving the threshold up. We do this, as in the finder patterns white holes tend\n            // to appear which makes them undetectable.\n            const blackBias = 1.11;\n            average = Math.min(255, average * blackBias);\n            if (max - min <= MIN_DYNAMIC_RANGE) {\n                // If variation within the block is low, assume this is a block with only light or only\n                // dark pixels. In that case we do not want to use the average, as it would divide this\n                // low contrast area into black and white pixels, essentially creating data out of noise.\n                //\n                // Default the blackpoint for these blocks to be half the min - effectively white them out\n                average = min / 2;\n                if (verticalRegion > 0 && hortizontalRegion > 0) {\n                    // Correct the \"white background\" assumption for blocks that have neighbors by comparing\n                    // the pixels in this block to the previously calculated black points. This is based on\n                    // the fact that dark barcode symbology is always surrounded by some amount of light\n                    // background for which reasonable black point estimates were made. The bp estimated at\n                    // the boundaries is used for the interior.\n                    // The (min < bp) is arbitrary but works better than other heuristics that were tried.\n                    const averageNeighborBlackPoint = (blackPoints.get(hortizontalRegion, verticalRegion - 1) +\n                        (2 * blackPoints.get(hortizontalRegion - 1, verticalRegion)) +\n                        blackPoints.get(hortizontalRegion - 1, verticalRegion - 1)) / 4;\n                    if (min < averageNeighborBlackPoint) {\n                        average = averageNeighborBlackPoint; // no need to apply black bias as already applied to neighbors\n                    }\n                }\n            }\n            blackPoints.set(hortizontalRegion, verticalRegion, average);\n        }\n    }\n    let binarized;\n    if (canOverwriteImage) {\n        const binarizedBuffer = new Uint8ClampedArray(data.buffer, bufferOffset, pixelCount);\n        bufferOffset += pixelCount;\n        binarized = new BitMatrix(binarizedBuffer, width);\n    }\n    else {\n        binarized = BitMatrix.createEmpty(width, height);\n    }\n    let inverted = null;\n    if (returnInverted) {\n        if (canOverwriteImage) {\n            const invertedBuffer = new Uint8ClampedArray(data.buffer, bufferOffset, pixelCount);\n            inverted = new BitMatrix(invertedBuffer, width);\n        }\n        else {\n            inverted = BitMatrix.createEmpty(width, height);\n        }\n    }\n    for (let verticalRegion = 0; verticalRegion < verticalRegionCount; verticalRegion++) {\n        for (let hortizontalRegion = 0; hortizontalRegion < horizontalRegionCount; hortizontalRegion++) {\n            const left = numBetween(hortizontalRegion, 2, horizontalRegionCount - 3);\n            const top = numBetween(verticalRegion, 2, verticalRegionCount - 3);\n            let sum = 0;\n            for (let xRegion = -2; xRegion <= 2; xRegion++) {\n                for (let yRegion = -2; yRegion <= 2; yRegion++) {\n                    sum += blackPoints.get(left + xRegion, top + yRegion);\n                }\n            }\n            const threshold = sum / 25;\n            for (let xRegion = 0; xRegion < REGION_SIZE; xRegion++) {\n                for (let yRegion = 0; yRegion < REGION_SIZE; yRegion++) {\n                    const x = hortizontalRegion * REGION_SIZE + xRegion;\n                    const y = verticalRegion * REGION_SIZE + yRegion;\n                    const lum = greyscalePixels.get(x, y);\n                    binarized.set(x, y, lum <= threshold);\n                    if (returnInverted) {\n                        inverted.set(x, y, !(lum <= threshold));\n                    }\n                }\n            }\n        }\n    }\n    if (returnInverted) {\n        return { binarized, inverted };\n    }\n    return { binarized };\n}\n\n// tslint:disable:no-bitwise\nclass BitStream {\n    constructor(bytes) {\n        this.byteOffset = 0;\n        this.bitOffset = 0;\n        this.bytes = bytes;\n    }\n    readBits(numBits) {\n        if (numBits < 1 || numBits > 32 || numBits > this.available()) {\n            throw new Error(\"Cannot read \" + numBits.toString() + \" bits\");\n        }\n        let result = 0;\n        // First, read remainder from current byte\n        if (this.bitOffset > 0) {\n            const bitsLeft = 8 - this.bitOffset;\n            const toRead = numBits < bitsLeft ? numBits : bitsLeft;\n            const bitsToNotRead = bitsLeft - toRead;\n            const mask = (0xFF >> (8 - toRead)) << bitsToNotRead;\n            result = (this.bytes[this.byteOffset] & mask) >> bitsToNotRead;\n            numBits -= toRead;\n            this.bitOffset += toRead;\n            if (this.bitOffset === 8) {\n                this.bitOffset = 0;\n                this.byteOffset++;\n            }\n        }\n        // Next read whole bytes\n        if (numBits > 0) {\n            while (numBits >= 8) {\n                result = (result << 8) | (this.bytes[this.byteOffset] & 0xFF);\n                this.byteOffset++;\n                numBits -= 8;\n            }\n            // Finally read a partial byte\n            if (numBits > 0) {\n                const bitsToNotRead = 8 - numBits;\n                const mask = (0xFF >> bitsToNotRead) << bitsToNotRead;\n                result = (result << numBits) | ((this.bytes[this.byteOffset] & mask) >> bitsToNotRead);\n                this.bitOffset += numBits;\n            }\n        }\n        return result;\n    }\n    available() {\n        return 8 * (this.bytes.length - this.byteOffset) - this.bitOffset;\n    }\n}\n\n// tslint:disable:no-bitwise\nvar Mode;\n(function (Mode) {\n    Mode[\"Numeric\"] = \"numeric\";\n    Mode[\"Alphanumeric\"] = \"alphanumeric\";\n    Mode[\"Byte\"] = \"byte\";\n    Mode[\"Kanji\"] = \"kanji\";\n    Mode[\"ECI\"] = \"eci\";\n    Mode[\"StructuredAppend\"] = \"structuredappend\";\n})(Mode || (Mode = {}));\nvar ModeByte;\n(function (ModeByte) {\n    ModeByte[ModeByte[\"Terminator\"] = 0] = \"Terminator\";\n    ModeByte[ModeByte[\"Numeric\"] = 1] = \"Numeric\";\n    ModeByte[ModeByte[\"Alphanumeric\"] = 2] = \"Alphanumeric\";\n    ModeByte[ModeByte[\"Byte\"] = 4] = \"Byte\";\n    ModeByte[ModeByte[\"Kanji\"] = 8] = \"Kanji\";\n    ModeByte[ModeByte[\"ECI\"] = 7] = \"ECI\";\n    ModeByte[ModeByte[\"StructuredAppend\"] = 3] = \"StructuredAppend\";\n    // FNC1FirstPosition = 0x5,\n    // FNC1SecondPosition = 0x9,\n})(ModeByte || (ModeByte = {}));\nfunction decodeNumeric(stream, size) {\n    const bytes = [];\n    let text = \"\";\n    const characterCountSize = [10, 12, 14][size];\n    let length = stream.readBits(characterCountSize);\n    // Read digits in groups of 3\n    while (length >= 3) {\n        const num = stream.readBits(10);\n        if (num >= 1000) {\n            throw new Error(\"Invalid numeric value above 999\");\n        }\n        const a = Math.floor(num / 100);\n        const b = Math.floor(num / 10) % 10;\n        const c = num % 10;\n        bytes.push(48 + a, 48 + b, 48 + c);\n        text += a.toString() + b.toString() + c.toString();\n        length -= 3;\n    }\n    // If the number of digits aren't a multiple of 3, the remaining digits are special cased.\n    if (length === 2) {\n        const num = stream.readBits(7);\n        if (num >= 100) {\n            throw new Error(\"Invalid numeric value above 99\");\n        }\n        const a = Math.floor(num / 10);\n        const b = num % 10;\n        bytes.push(48 + a, 48 + b);\n        text += a.toString() + b.toString();\n    }\n    else if (length === 1) {\n        const num = stream.readBits(4);\n        if (num >= 10) {\n            throw new Error(\"Invalid numeric value above 9\");\n        }\n        bytes.push(48 + num);\n        text += num.toString();\n    }\n    return { bytes, text };\n}\nconst AlphanumericCharacterCodes = [\n    \"0\", \"1\", \"2\", \"3\", \"4\", \"5\", \"6\", \"7\", \"8\",\n    \"9\", \"A\", \"B\", \"C\", \"D\", \"E\", \"F\", \"G\", \"H\",\n    \"I\", \"J\", \"K\", \"L\", \"M\", \"N\", \"O\", \"P\", \"Q\",\n    \"R\", \"S\", \"T\", \"U\", \"V\", \"W\", \"X\", \"Y\", \"Z\",\n    \" \", \"$\", \"%\", \"*\", \"+\", \"-\", \".\", \"/\", \":\",\n];\nfunction decodeAlphanumeric(stream, size) {\n    const bytes = [];\n    let text = \"\";\n    const characterCountSize = [9, 11, 13][size];\n    let length = stream.readBits(characterCountSize);\n    while (length >= 2) {\n        const v = stream.readBits(11);\n        const a = Math.floor(v / 45);\n        const b = v % 45;\n        bytes.push(AlphanumericCharacterCodes[a].charCodeAt(0), AlphanumericCharacterCodes[b].charCodeAt(0));\n        text += AlphanumericCharacterCodes[a] + AlphanumericCharacterCodes[b];\n        length -= 2;\n    }\n    if (length === 1) {\n        const a = stream.readBits(6);\n        bytes.push(AlphanumericCharacterCodes[a].charCodeAt(0));\n        text += AlphanumericCharacterCodes[a];\n    }\n    return { bytes, text };\n}\nfunction decodeByte(stream, size) {\n    const bytes = [];\n    let text = \"\";\n    const characterCountSize = [8, 16, 16][size];\n    const length = stream.readBits(characterCountSize);\n    for (let i = 0; i < length; i++) {\n        const b = stream.readBits(8);\n        bytes.push(b);\n    }\n    try {\n        text += decodeURIComponent(bytes.map(b => `%${(\"0\" + b.toString(16)).substr(-2)}`).join(\"\"));\n    }\n    catch (_a) {\n        // failed to decode\n    }\n    return { bytes, text };\n}\nfunction decodeKanji(stream, size) {\n    const bytes = [];\n    const characterCountSize = [8, 10, 12][size];\n    const length = stream.readBits(characterCountSize);\n    for (let i = 0; i < length; i++) {\n        const k = stream.readBits(13);\n        let c = (Math.floor(k / 0xC0) << 8) | (k % 0xC0);\n        if (c < 0x1F00) {\n            c += 0x8140;\n        }\n        else {\n            c += 0xC140;\n        }\n        bytes.push(c >> 8, c & 0xFF);\n    }\n    const text = new TextDecoder(\"shift-jis\").decode(Uint8Array.from(bytes));\n    return { bytes, text };\n}\nfunction decode$2(data, version) {\n    const stream = new BitStream(data);\n    // There are 3 'sizes' based on the version. 1-9 is small (0), 10-26 is medium (1) and 27-40 is large (2).\n    const size = version <= 9 ? 0 : version <= 26 ? 1 : 2;\n    const result = {\n        text: \"\",\n        bytes: [],\n        chunks: [],\n        version,\n    };\n    while (stream.available() >= 4) {\n        const mode = stream.readBits(4);\n        if (mode === ModeByte.Terminator) {\n            return result;\n        }\n        else if (mode === ModeByte.ECI) {\n            if (stream.readBits(1) === 0) {\n                result.chunks.push({\n                    type: Mode.ECI,\n                    assignmentNumber: stream.readBits(7),\n                });\n            }\n            else if (stream.readBits(1) === 0) {\n                result.chunks.push({\n                    type: Mode.ECI,\n                    assignmentNumber: stream.readBits(14),\n                });\n            }\n            else if (stream.readBits(1) === 0) {\n                result.chunks.push({\n                    type: Mode.ECI,\n                    assignmentNumber: stream.readBits(21),\n                });\n            }\n            else {\n                // ECI data seems corrupted\n                result.chunks.push({\n                    type: Mode.ECI,\n                    assignmentNumber: -1,\n                });\n            }\n        }\n        else if (mode === ModeByte.Numeric) {\n            const numericResult = decodeNumeric(stream, size);\n            result.text += numericResult.text;\n            result.bytes.push(...numericResult.bytes);\n            result.chunks.push({\n                type: Mode.Numeric,\n                text: numericResult.text,\n            });\n        }\n        else if (mode === ModeByte.Alphanumeric) {\n            const alphanumericResult = decodeAlphanumeric(stream, size);\n            result.text += alphanumericResult.text;\n            result.bytes.push(...alphanumericResult.bytes);\n            result.chunks.push({\n                type: Mode.Alphanumeric,\n                text: alphanumericResult.text,\n            });\n        }\n        else if (mode === ModeByte.Byte) {\n            const byteResult = decodeByte(stream, size);\n            result.text += byteResult.text;\n            result.bytes.push(...byteResult.bytes);\n            result.chunks.push({\n                type: Mode.Byte,\n                bytes: byteResult.bytes,\n                text: byteResult.text,\n            });\n        }\n        else if (mode === ModeByte.Kanji) {\n            const kanjiResult = decodeKanji(stream, size);\n            result.text += kanjiResult.text;\n            result.bytes.push(...kanjiResult.bytes);\n            result.chunks.push({\n                type: Mode.Kanji,\n                bytes: kanjiResult.bytes,\n                text: kanjiResult.text,\n            });\n        }\n        else if (mode === ModeByte.StructuredAppend) {\n            result.chunks.push({\n                type: Mode.StructuredAppend,\n                currentSequence: stream.readBits(4),\n                totalSequence: stream.readBits(4),\n                parity: stream.readBits(8),\n            });\n        }\n    }\n    // If there is no data left, or the remaining bits are all 0, then that counts as a termination marker\n    if (stream.available() === 0 || stream.readBits(stream.available()) === 0) {\n        return result;\n    }\n}\n\nclass GenericGFPoly {\n    constructor(field, coefficients) {\n        if (coefficients.length === 0) {\n            throw new Error(\"No coefficients.\");\n        }\n        this.field = field;\n        const coefficientsLength = coefficients.length;\n        if (coefficientsLength > 1 && coefficients[0] === 0) {\n            // Leading term must be non-zero for anything except the constant polynomial \"0\"\n            let firstNonZero = 1;\n            while (firstNonZero < coefficientsLength && coefficients[firstNonZero] === 0) {\n                firstNonZero++;\n            }\n            if (firstNonZero === coefficientsLength) {\n                this.coefficients = field.zero.coefficients;\n            }\n            else {\n                this.coefficients = new Uint8ClampedArray(coefficientsLength - firstNonZero);\n                for (let i = 0; i < this.coefficients.length; i++) {\n                    this.coefficients[i] = coefficients[firstNonZero + i];\n                }\n            }\n        }\n        else {\n            this.coefficients = coefficients;\n        }\n    }\n    degree() {\n        return this.coefficients.length - 1;\n    }\n    isZero() {\n        return this.coefficients[0] === 0;\n    }\n    getCoefficient(degree) {\n        return this.coefficients[this.coefficients.length - 1 - degree];\n    }\n    addOrSubtract(other) {\n        if (this.isZero()) {\n            return other;\n        }\n        if (other.isZero()) {\n            return this;\n        }\n        let smallerCoefficients = this.coefficients;\n        let largerCoefficients = other.coefficients;\n        if (smallerCoefficients.length > largerCoefficients.length) {\n            [smallerCoefficients, largerCoefficients] = [largerCoefficients, smallerCoefficients];\n        }\n        const sumDiff = new Uint8ClampedArray(largerCoefficients.length);\n        const lengthDiff = largerCoefficients.length - smallerCoefficients.length;\n        for (let i = 0; i < lengthDiff; i++) {\n            sumDiff[i] = largerCoefficients[i];\n        }\n        for (let i = lengthDiff; i < largerCoefficients.length; i++) {\n            sumDiff[i] = addOrSubtractGF(smallerCoefficients[i - lengthDiff], largerCoefficients[i]);\n        }\n        return new GenericGFPoly(this.field, sumDiff);\n    }\n    multiply(scalar) {\n        if (scalar === 0) {\n            return this.field.zero;\n        }\n        if (scalar === 1) {\n            return this;\n        }\n        const size = this.coefficients.length;\n        const product = new Uint8ClampedArray(size);\n        for (let i = 0; i < size; i++) {\n            product[i] = this.field.multiply(this.coefficients[i], scalar);\n        }\n        return new GenericGFPoly(this.field, product);\n    }\n    multiplyPoly(other) {\n        if (this.isZero() || other.isZero()) {\n            return this.field.zero;\n        }\n        const aCoefficients = this.coefficients;\n        const aLength = aCoefficients.length;\n        const bCoefficients = other.coefficients;\n        const bLength = bCoefficients.length;\n        const product = new Uint8ClampedArray(aLength + bLength - 1);\n        for (let i = 0; i < aLength; i++) {\n            const aCoeff = aCoefficients[i];\n            for (let j = 0; j < bLength; j++) {\n                product[i + j] = addOrSubtractGF(product[i + j], this.field.multiply(aCoeff, bCoefficients[j]));\n            }\n        }\n        return new GenericGFPoly(this.field, product);\n    }\n    multiplyByMonomial(degree, coefficient) {\n        if (degree < 0) {\n            throw new Error(\"Invalid degree less than 0\");\n        }\n        if (coefficient === 0) {\n            return this.field.zero;\n        }\n        const size = this.coefficients.length;\n        const product = new Uint8ClampedArray(size + degree);\n        for (let i = 0; i < size; i++) {\n            product[i] = this.field.multiply(this.coefficients[i], coefficient);\n        }\n        return new GenericGFPoly(this.field, product);\n    }\n    evaluateAt(a) {\n        let result = 0;\n        if (a === 0) {\n            // Just return the x^0 coefficient\n            return this.getCoefficient(0);\n        }\n        const size = this.coefficients.length;\n        if (a === 1) {\n            // Just the sum of the coefficients\n            this.coefficients.forEach((coefficient) => {\n                result = addOrSubtractGF(result, coefficient);\n            });\n            return result;\n        }\n        result = this.coefficients[0];\n        for (let i = 1; i < size; i++) {\n            result = addOrSubtractGF(this.field.multiply(a, result), this.coefficients[i]);\n        }\n        return result;\n    }\n}\n\nfunction addOrSubtractGF(a, b) {\n    return a ^ b; // tslint:disable-line:no-bitwise\n}\nclass GenericGF {\n    constructor(primitive, size, genBase) {\n        this.primitive = primitive;\n        this.size = size;\n        this.generatorBase = genBase;\n        this.expTable = new Array(this.size);\n        this.logTable = new Array(this.size);\n        let x = 1;\n        for (let i = 0; i < this.size; i++) {\n            this.expTable[i] = x;\n            x = x * 2;\n            if (x >= this.size) {\n                x = (x ^ this.primitive) & (this.size - 1); // tslint:disable-line:no-bitwise\n            }\n        }\n        for (let i = 0; i < this.size - 1; i++) {\n            this.logTable[this.expTable[i]] = i;\n        }\n        this.zero = new GenericGFPoly(this, Uint8ClampedArray.from([0]));\n        this.one = new GenericGFPoly(this, Uint8ClampedArray.from([1]));\n    }\n    multiply(a, b) {\n        if (a === 0 || b === 0) {\n            return 0;\n        }\n        return this.expTable[(this.logTable[a] + this.logTable[b]) % (this.size - 1)];\n    }\n    inverse(a) {\n        if (a === 0) {\n            throw new Error(\"Can't invert 0\");\n        }\n        return this.expTable[this.size - this.logTable[a] - 1];\n    }\n    buildMonomial(degree, coefficient) {\n        if (degree < 0) {\n            throw new Error(\"Invalid monomial degree less than 0\");\n        }\n        if (coefficient === 0) {\n            return this.zero;\n        }\n        const coefficients = new Uint8ClampedArray(degree + 1);\n        coefficients[0] = coefficient;\n        return new GenericGFPoly(this, coefficients);\n    }\n    log(a) {\n        if (a === 0) {\n            throw new Error(\"Can't take log(0)\");\n        }\n        return this.logTable[a];\n    }\n    exp(a) {\n        return this.expTable[a];\n    }\n}\n\nfunction runEuclideanAlgorithm(field, a, b, R) {\n    // Assume a's degree is >= b's\n    if (a.degree() < b.degree()) {\n        [a, b] = [b, a];\n    }\n    let rLast = a;\n    let r = b;\n    let tLast = field.zero;\n    let t = field.one;\n    // Run Euclidean algorithm until r's degree is less than R/2\n    while (r.degree() >= R / 2) {\n        const rLastLast = rLast;\n        const tLastLast = tLast;\n        rLast = r;\n        tLast = t;\n        // Divide rLastLast by rLast, with quotient in q and remainder in r\n        if (rLast.isZero()) {\n            // Euclidean algorithm already terminated?\n            return null;\n        }\n        r = rLastLast;\n        let q = field.zero;\n        const denominatorLeadingTerm = rLast.getCoefficient(rLast.degree());\n        const dltInverse = field.inverse(denominatorLeadingTerm);\n        while (r.degree() >= rLast.degree() && !r.isZero()) {\n            const degreeDiff = r.degree() - rLast.degree();\n            const scale = field.multiply(r.getCoefficient(r.degree()), dltInverse);\n            q = q.addOrSubtract(field.buildMonomial(degreeDiff, scale));\n            r = r.addOrSubtract(rLast.multiplyByMonomial(degreeDiff, scale));\n        }\n        t = q.multiplyPoly(tLast).addOrSubtract(tLastLast);\n        if (r.degree() >= rLast.degree()) {\n            return null;\n        }\n    }\n    const sigmaTildeAtZero = t.getCoefficient(0);\n    if (sigmaTildeAtZero === 0) {\n        return null;\n    }\n    const inverse = field.inverse(sigmaTildeAtZero);\n    return [t.multiply(inverse), r.multiply(inverse)];\n}\nfunction findErrorLocations(field, errorLocator) {\n    // This is a direct application of Chien's search\n    const numErrors = errorLocator.degree();\n    if (numErrors === 1) {\n        return [errorLocator.getCoefficient(1)];\n    }\n    const result = new Array(numErrors);\n    let errorCount = 0;\n    for (let i = 1; i < field.size && errorCount < numErrors; i++) {\n        if (errorLocator.evaluateAt(i) === 0) {\n            result[errorCount] = field.inverse(i);\n            errorCount++;\n        }\n    }\n    if (errorCount !== numErrors) {\n        return null;\n    }\n    return result;\n}\nfunction findErrorMagnitudes(field, errorEvaluator, errorLocations) {\n    // This is directly applying Forney's Formula\n    const s = errorLocations.length;\n    const result = new Array(s);\n    for (let i = 0; i < s; i++) {\n        const xiInverse = field.inverse(errorLocations[i]);\n        let denominator = 1;\n        for (let j = 0; j < s; j++) {\n            if (i !== j) {\n                denominator = field.multiply(denominator, addOrSubtractGF(1, field.multiply(errorLocations[j], xiInverse)));\n            }\n        }\n        result[i] = field.multiply(errorEvaluator.evaluateAt(xiInverse), field.inverse(denominator));\n        if (field.generatorBase !== 0) {\n            result[i] = field.multiply(result[i], xiInverse);\n        }\n    }\n    return result;\n}\nfunction decode$1(bytes, twoS) {\n    const outputBytes = new Uint8ClampedArray(bytes.length);\n    outputBytes.set(bytes);\n    const field = new GenericGF(0x011D, 256, 0); // x^8 + x^4 + x^3 + x^2 + 1\n    const poly = new GenericGFPoly(field, outputBytes);\n    const syndromeCoefficients = new Uint8ClampedArray(twoS);\n    let error = false;\n    for (let s = 0; s < twoS; s++) {\n        const evaluation = poly.evaluateAt(field.exp(s + field.generatorBase));\n        syndromeCoefficients[syndromeCoefficients.length - 1 - s] = evaluation;\n        if (evaluation !== 0) {\n            error = true;\n        }\n    }\n    if (!error) {\n        return outputBytes;\n    }\n    const syndrome = new GenericGFPoly(field, syndromeCoefficients);\n    const sigmaOmega = runEuclideanAlgorithm(field, field.buildMonomial(twoS, 1), syndrome, twoS);\n    if (sigmaOmega === null) {\n        return null;\n    }\n    const errorLocations = findErrorLocations(field, sigmaOmega[0]);\n    if (errorLocations == null) {\n        return null;\n    }\n    const errorMagnitudes = findErrorMagnitudes(field, sigmaOmega[1], errorLocations);\n    for (let i = 0; i < errorLocations.length; i++) {\n        const position = outputBytes.length - 1 - field.log(errorLocations[i]);\n        if (position < 0) {\n            return null;\n        }\n        outputBytes[position] = addOrSubtractGF(outputBytes[position], errorMagnitudes[i]);\n    }\n    return outputBytes;\n}\n\nconst VERSIONS = [\n    {\n        infoBits: null,\n        versionNumber: 1,\n        alignmentPatternCenters: [],\n        errorCorrectionLevels: [\n            {\n                ecCodewordsPerBlock: 7,\n                ecBlocks: [{ numBlocks: 1, dataCodewordsPerBlock: 19 }],\n            },\n            {\n                ecCodewordsPerBlock: 10,\n                ecBlocks: [{ numBlocks: 1, dataCodewordsPerBlock: 16 }],\n            },\n            {\n                ecCodewordsPerBlock: 13,\n                ecBlocks: [{ numBlocks: 1, dataCodewordsPerBlock: 13 }],\n            },\n            {\n                ecCodewordsPerBlock: 17,\n                ecBlocks: [{ numBlocks: 1, dataCodewordsPerBlock: 9 }],\n            },\n        ],\n    },\n    {\n        infoBits: null,\n        versionNumber: 2,\n        alignmentPatternCenters: [6, 18],\n        errorCorrectionLevels: [\n            {\n                ecCodewordsPerBlock: 10,\n                ecBlocks: [{ numBlocks: 1, dataCodewordsPerBlock: 34 }],\n            },\n            {\n                ecCodewordsPerBlock: 16,\n                ecBlocks: [{ numBlocks: 1, dataCodewordsPerBlock: 28 }],\n            },\n            {\n                ecCodewordsPerBlock: 22,\n                ecBlocks: [{ numBlocks: 1, dataCodewordsPerBlock: 22 }],\n            },\n            {\n                ecCodewordsPerBlock: 28,\n                ecBlocks: [{ numBlocks: 1, dataCodewordsPerBlock: 16 }],\n            },\n        ],\n    },\n    {\n        infoBits: null,\n        versionNumber: 3,\n        alignmentPatternCenters: [6, 22],\n        errorCorrectionLevels: [\n            {\n                ecCodewordsPerBlock: 15,\n                ecBlocks: [{ numBlocks: 1, dataCodewordsPerBlock: 55 }],\n            },\n            {\n                ecCodewordsPerBlock: 26,\n                ecBlocks: [{ numBlocks: 1, dataCodewordsPerBlock: 44 }],\n            },\n            {\n                ecCodewordsPerBlock: 18,\n                ecBlocks: [{ numBlocks: 2, dataCodewordsPerBlock: 17 }],\n            },\n            {\n                ecCodewordsPerBlock: 22,\n                ecBlocks: [{ numBlocks: 2, dataCodewordsPerBlock: 13 }],\n            },\n        ],\n    },\n    {\n        infoBits: null,\n        versionNumber: 4,\n        alignmentPatternCenters: [6, 26],\n        errorCorrectionLevels: [\n            {\n                ecCodewordsPerBlock: 20,\n                ecBlocks: [{ numBlocks: 1, dataCodewordsPerBlock: 80 }],\n            },\n            {\n                ecCodewordsPerBlock: 18,\n                ecBlocks: [{ numBlocks: 2, dataCodewordsPerBlock: 32 }],\n            },\n            {\n                ecCodewordsPerBlock: 26,\n                ecBlocks: [{ numBlocks: 2, dataCodewordsPerBlock: 24 }],\n            },\n            {\n                ecCodewordsPerBlock: 16,\n                ecBlocks: [{ numBlocks: 4, dataCodewordsPerBlock: 9 }],\n            },\n        ],\n    },\n    {\n        infoBits: null,\n        versionNumber: 5,\n        alignmentPatternCenters: [6, 30],\n        errorCorrectionLevels: [\n            {\n                ecCodewordsPerBlock: 26,\n                ecBlocks: [{ numBlocks: 1, dataCodewordsPerBlock: 108 }],\n            },\n            {\n                ecCodewordsPerBlock: 24,\n                ecBlocks: [{ numBlocks: 2, dataCodewordsPerBlock: 43 }],\n            },\n            {\n                ecCodewordsPerBlock: 18,\n                ecBlocks: [\n                    { numBlocks: 2, dataCodewordsPerBlock: 15 },\n                    { numBlocks: 2, dataCodewordsPerBlock: 16 },\n                ],\n            },\n            {\n                ecCodewordsPerBlock: 22,\n                ecBlocks: [\n                    { numBlocks: 2, dataCodewordsPerBlock: 11 },\n                    { numBlocks: 2, dataCodewordsPerBlock: 12 },\n                ],\n            },\n        ],\n    },\n    {\n        infoBits: null,\n        versionNumber: 6,\n        alignmentPatternCenters: [6, 34],\n        errorCorrectionLevels: [\n            {\n                ecCodewordsPerBlock: 18,\n                ecBlocks: [{ numBlocks: 2, dataCodewordsPerBlock: 68 }],\n            },\n            {\n                ecCodewordsPerBlock: 16,\n                ecBlocks: [{ numBlocks: 4, dataCodewordsPerBlock: 27 }],\n            },\n            {\n                ecCodewordsPerBlock: 24,\n                ecBlocks: [{ numBlocks: 4, dataCodewordsPerBlock: 19 }],\n            },\n            {\n                ecCodewordsPerBlock: 28,\n                ecBlocks: [{ numBlocks: 4, dataCodewordsPerBlock: 15 }],\n            },\n        ],\n    },\n    {\n        infoBits: 0x07C94,\n        versionNumber: 7,\n        alignmentPatternCenters: [6, 22, 38],\n        errorCorrectionLevels: [\n            {\n                ecCodewordsPerBlock: 20,\n                ecBlocks: [{ numBlocks: 2, dataCodewordsPerBlock: 78 }],\n            },\n            {\n                ecCodewordsPerBlock: 18,\n                ecBlocks: [{ numBlocks: 4, dataCodewordsPerBlock: 31 }],\n            },\n            {\n                ecCodewordsPerBlock: 18,\n                ecBlocks: [\n                    { numBlocks: 2, dataCodewordsPerBlock: 14 },\n                    { numBlocks: 4, dataCodewordsPerBlock: 15 },\n                ],\n            },\n            {\n                ecCodewordsPerBlock: 26,\n                ecBlocks: [\n                    { numBlocks: 4, dataCodewordsPerBlock: 13 },\n                    { numBlocks: 1, dataCodewordsPerBlock: 14 },\n                ],\n            },\n        ],\n    },\n    {\n        infoBits: 0x085BC,\n        versionNumber: 8,\n        alignmentPatternCenters: [6, 24, 42],\n        errorCorrectionLevels: [\n            {\n                ecCodewordsPerBlock: 24,\n                ecBlocks: [{ numBlocks: 2, dataCodewordsPerBlock: 97 }],\n            },\n            {\n                ecCodewordsPerBlock: 22,\n                ecBlocks: [\n                    { numBlocks: 2, dataCodewordsPerBlock: 38 },\n                    { numBlocks: 2, dataCodewordsPerBlock: 39 },\n                ],\n            },\n            {\n                ecCodewordsPerBlock: 22,\n                ecBlocks: [\n                    { numBlocks: 4, dataCodewordsPerBlock: 18 },\n                    { numBlocks: 2, dataCodewordsPerBlock: 19 },\n                ],\n            },\n            {\n                ecCodewordsPerBlock: 26,\n                ecBlocks: [\n                    { numBlocks: 4, dataCodewordsPerBlock: 14 },\n                    { numBlocks: 2, dataCodewordsPerBlock: 15 },\n                ],\n            },\n        ],\n    },\n    {\n        infoBits: 0x09A99,\n        versionNumber: 9,\n        alignmentPatternCenters: [6, 26, 46],\n        errorCorrectionLevels: [\n            {\n                ecCodewordsPerBlock: 30,\n                ecBlocks: [{ numBlocks: 2, dataCodewordsPerBlock: 116 }],\n            },\n            {\n                ecCodewordsPerBlock: 22,\n                ecBlocks: [\n                    { numBlocks: 3, dataCodewordsPerBlock: 36 },\n                    { numBlocks: 2, dataCodewordsPerBlock: 37 },\n                ],\n            },\n            {\n                ecCodewordsPerBlock: 20,\n                ecBlocks: [\n                    { numBlocks: 4, dataCodewordsPerBlock: 16 },\n                    { numBlocks: 4, dataCodewordsPerBlock: 17 },\n                ],\n            },\n            {\n                ecCodewordsPerBlock: 24,\n                ecBlocks: [\n                    { numBlocks: 4, dataCodewordsPerBlock: 12 },\n                    { numBlocks: 4, dataCodewordsPerBlock: 13 },\n                ],\n            },\n        ],\n    },\n    {\n        infoBits: 0x0A4D3,\n        versionNumber: 10,\n        alignmentPatternCenters: [6, 28, 50],\n        errorCorrectionLevels: [\n            {\n                ecCodewordsPerBlock: 18,\n                ecBlocks: [\n                    { numBlocks: 2, dataCodewordsPerBlock: 68 },\n                    { numBlocks: 2, dataCodewordsPerBlock: 69 },\n                ],\n            },\n            {\n                ecCodewordsPerBlock: 26,\n                ecBlocks: [\n                    { numBlocks: 4, dataCodewordsPerBlock: 43 },\n                    { numBlocks: 1, dataCodewordsPerBlock: 44 },\n                ],\n            },\n            {\n                ecCodewordsPerBlock: 24,\n                ecBlocks: [\n                    { numBlocks: 6, dataCodewordsPerBlock: 19 },\n                    { numBlocks: 2, dataCodewordsPerBlock: 20 },\n                ],\n            },\n            {\n                ecCodewordsPerBlock: 28,\n                ecBlocks: [\n                    { numBlocks: 6, dataCodewordsPerBlock: 15 },\n                    { numBlocks: 2, dataCodewordsPerBlock: 16 },\n                ],\n            },\n        ],\n    },\n    {\n        infoBits: 0x0BBF6,\n        versionNumber: 11,\n        alignmentPatternCenters: [6, 30, 54],\n        errorCorrectionLevels: [\n            {\n                ecCodewordsPerBlock: 20,\n                ecBlocks: [{ numBlocks: 4, dataCodewordsPerBlock: 81 }],\n            },\n            {\n                ecCodewordsPerBlock: 30,\n                ecBlocks: [\n                    { numBlocks: 1, dataCodewordsPerBlock: 50 },\n                    { numBlocks: 4, dataCodewordsPerBlock: 51 },\n                ],\n            },\n            {\n                ecCodewordsPerBlock: 28,\n                ecBlocks: [\n                    { numBlocks: 4, dataCodewordsPerBlock: 22 },\n                    { numBlocks: 4, dataCodewordsPerBlock: 23 },\n                ],\n            },\n            {\n                ecCodewordsPerBlock: 24,\n                ecBlocks: [\n                    { numBlocks: 3, dataCodewordsPerBlock: 12 },\n                    { numBlocks: 8, dataCodewordsPerBlock: 13 },\n                ],\n            },\n        ],\n    },\n    {\n        infoBits: 0x0C762,\n        versionNumber: 12,\n        alignmentPatternCenters: [6, 32, 58],\n        errorCorrectionLevels: [\n            {\n                ecCodewordsPerBlock: 24,\n                ecBlocks: [\n                    { numBlocks: 2, dataCodewordsPerBlock: 92 },\n                    { numBlocks: 2, dataCodewordsPerBlock: 93 },\n                ],\n            },\n            {\n                ecCodewordsPerBlock: 22,\n                ecBlocks: [\n                    { numBlocks: 6, dataCodewordsPerBlock: 36 },\n                    { numBlocks: 2, dataCodewordsPerBlock: 37 },\n                ],\n            },\n            {\n                ecCodewordsPerBlock: 26,\n                ecBlocks: [\n                    { numBlocks: 4, dataCodewordsPerBlock: 20 },\n                    { numBlocks: 6, dataCodewordsPerBlock: 21 },\n                ],\n            },\n            {\n                ecCodewordsPerBlock: 28,\n                ecBlocks: [\n                    { numBlocks: 7, dataCodewordsPerBlock: 14 },\n                    { numBlocks: 4, dataCodewordsPerBlock: 15 },\n                ],\n            },\n        ],\n    },\n    {\n        infoBits: 0x0D847,\n        versionNumber: 13,\n        alignmentPatternCenters: [6, 34, 62],\n        errorCorrectionLevels: [\n            {\n                ecCodewordsPerBlock: 26,\n                ecBlocks: [{ numBlocks: 4, dataCodewordsPerBlock: 107 }],\n            },\n            {\n                ecCodewordsPerBlock: 22,\n                ecBlocks: [\n                    { numBlocks: 8, dataCodewordsPerBlock: 37 },\n                    { numBlocks: 1, dataCodewordsPerBlock: 38 },\n                ],\n            },\n            {\n                ecCodewordsPerBlock: 24,\n                ecBlocks: [\n                    { numBlocks: 8, dataCodewordsPerBlock: 20 },\n                    { numBlocks: 4, dataCodewordsPerBlock: 21 },\n                ],\n            },\n            {\n                ecCodewordsPerBlock: 22,\n                ecBlocks: [\n                    { numBlocks: 12, dataCodewordsPerBlock: 11 },\n                    { numBlocks: 4, dataCodewordsPerBlock: 12 },\n                ],\n            },\n        ],\n    },\n    {\n        infoBits: 0x0E60D,\n        versionNumber: 14,\n        alignmentPatternCenters: [6, 26, 46, 66],\n        errorCorrectionLevels: [\n            {\n                ecCodewordsPerBlock: 30,\n                ecBlocks: [\n                    { numBlocks: 3, dataCodewordsPerBlock: 115 },\n                    { numBlocks: 1, dataCodewordsPerBlock: 116 },\n                ],\n            },\n            {\n                ecCodewordsPerBlock: 24,\n                ecBlocks: [\n                    { numBlocks: 4, dataCodewordsPerBlock: 40 },\n                    { numBlocks: 5, dataCodewordsPerBlock: 41 },\n                ],\n            },\n            {\n                ecCodewordsPerBlock: 20,\n                ecBlocks: [\n                    { numBlocks: 11, dataCodewordsPerBlock: 16 },\n                    { numBlocks: 5, dataCodewordsPerBlock: 17 },\n                ],\n            },\n            {\n                ecCodewordsPerBlock: 24,\n                ecBlocks: [\n                    { numBlocks: 11, dataCodewordsPerBlock: 12 },\n                    { numBlocks: 5, dataCodewordsPerBlock: 13 },\n                ],\n            },\n        ],\n    },\n    {\n        infoBits: 0x0F928,\n        versionNumber: 15,\n        alignmentPatternCenters: [6, 26, 48, 70],\n        errorCorrectionLevels: [\n            {\n                ecCodewordsPerBlock: 22,\n                ecBlocks: [\n                    { numBlocks: 5, dataCodewordsPerBlock: 87 },\n                    { numBlocks: 1, dataCodewordsPerBlock: 88 },\n                ],\n            },\n            {\n                ecCodewordsPerBlock: 24,\n                ecBlocks: [\n                    { numBlocks: 5, dataCodewordsPerBlock: 41 },\n                    { numBlocks: 5, dataCodewordsPerBlock: 42 },\n                ],\n            },\n            {\n                ecCodewordsPerBlock: 30,\n                ecBlocks: [\n                    { numBlocks: 5, dataCodewordsPerBlock: 24 },\n                    { numBlocks: 7, dataCodewordsPerBlock: 25 },\n                ],\n            },\n            {\n                ecCodewordsPerBlock: 24,\n                ecBlocks: [\n                    { numBlocks: 11, dataCodewordsPerBlock: 12 },\n                    { numBlocks: 7, dataCodewordsPerBlock: 13 },\n                ],\n            },\n        ],\n    },\n    {\n        infoBits: 0x10B78,\n        versionNumber: 16,\n        alignmentPatternCenters: [6, 26, 50, 74],\n        errorCorrectionLevels: [\n            {\n                ecCodewordsPerBlock: 24,\n                ecBlocks: [\n                    { numBlocks: 5, dataCodewordsPerBlock: 98 },\n                    { numBlocks: 1, dataCodewordsPerBlock: 99 },\n                ],\n            },\n            {\n                ecCodewordsPerBlock: 28,\n                ecBlocks: [\n                    { numBlocks: 7, dataCodewordsPerBlock: 45 },\n                    { numBlocks: 3, dataCodewordsPerBlock: 46 },\n                ],\n            },\n            {\n                ecCodewordsPerBlock: 24,\n                ecBlocks: [\n                    { numBlocks: 15, dataCodewordsPerBlock: 19 },\n                    { numBlocks: 2, dataCodewordsPerBlock: 20 },\n                ],\n            },\n            {\n                ecCodewordsPerBlock: 30,\n                ecBlocks: [\n                    { numBlocks: 3, dataCodewordsPerBlock: 15 },\n                    { numBlocks: 13, dataCodewordsPerBlock: 16 },\n                ],\n            },\n        ],\n    },\n    {\n        infoBits: 0x1145D,\n        versionNumber: 17,\n        alignmentPatternCenters: [6, 30, 54, 78],\n        errorCorrectionLevels: [\n            {\n                ecCodewordsPerBlock: 28,\n                ecBlocks: [\n                    { numBlocks: 1, dataCodewordsPerBlock: 107 },\n                    { numBlocks: 5, dataCodewordsPerBlock: 108 },\n                ],\n            },\n            {\n                ecCodewordsPerBlock: 28,\n                ecBlocks: [\n                    { numBlocks: 10, dataCodewordsPerBlock: 46 },\n                    { numBlocks: 1, dataCodewordsPerBlock: 47 },\n                ],\n            },\n            {\n                ecCodewordsPerBlock: 28,\n                ecBlocks: [\n                    { numBlocks: 1, dataCodewordsPerBlock: 22 },\n                    { numBlocks: 15, dataCodewordsPerBlock: 23 },\n                ],\n            },\n            {\n                ecCodewordsPerBlock: 28,\n                ecBlocks: [\n                    { numBlocks: 2, dataCodewordsPerBlock: 14 },\n                    { numBlocks: 17, dataCodewordsPerBlock: 15 },\n                ],\n            },\n        ],\n    },\n    {\n        infoBits: 0x12A17,\n        versionNumber: 18,\n        alignmentPatternCenters: [6, 30, 56, 82],\n        errorCorrectionLevels: [\n            {\n                ecCodewordsPerBlock: 30,\n                ecBlocks: [\n                    { numBlocks: 5, dataCodewordsPerBlock: 120 },\n                    { numBlocks: 1, dataCodewordsPerBlock: 121 },\n                ],\n            },\n            {\n                ecCodewordsPerBlock: 26,\n                ecBlocks: [\n                    { numBlocks: 9, dataCodewordsPerBlock: 43 },\n                    { numBlocks: 4, dataCodewordsPerBlock: 44 },\n                ],\n            },\n            {\n                ecCodewordsPerBlock: 28,\n                ecBlocks: [\n                    { numBlocks: 17, dataCodewordsPerBlock: 22 },\n                    { numBlocks: 1, dataCodewordsPerBlock: 23 },\n                ],\n            },\n            {\n                ecCodewordsPerBlock: 28,\n                ecBlocks: [\n                    { numBlocks: 2, dataCodewordsPerBlock: 14 },\n                    { numBlocks: 19, dataCodewordsPerBlock: 15 },\n                ],\n            },\n        ],\n    },\n    {\n        infoBits: 0x13532,\n        versionNumber: 19,\n        alignmentPatternCenters: [6, 30, 58, 86],\n        errorCorrectionLevels: [\n            {\n                ecCodewordsPerBlock: 28,\n                ecBlocks: [\n                    { numBlocks: 3, dataCodewordsPerBlock: 113 },\n                    { numBlocks: 4, dataCodewordsPerBlock: 114 },\n                ],\n            },\n            {\n                ecCodewordsPerBlock: 26,\n                ecBlocks: [\n                    { numBlocks: 3, dataCodewordsPerBlock: 44 },\n                    { numBlocks: 11, dataCodewordsPerBlock: 45 },\n                ],\n            },\n            {\n                ecCodewordsPerBlock: 26,\n                ecBlocks: [\n                    { numBlocks: 17, dataCodewordsPerBlock: 21 },\n                    { numBlocks: 4, dataCodewordsPerBlock: 22 },\n                ],\n            },\n            {\n                ecCodewordsPerBlock: 26,\n                ecBlocks: [\n                    { numBlocks: 9, dataCodewordsPerBlock: 13 },\n                    { numBlocks: 16, dataCodewordsPerBlock: 14 },\n                ],\n            },\n        ],\n    },\n    {\n        infoBits: 0x149A6,\n        versionNumber: 20,\n        alignmentPatternCenters: [6, 34, 62, 90],\n        errorCorrectionLevels: [\n            {\n                ecCodewordsPerBlock: 28,\n                ecBlocks: [\n                    { numBlocks: 3, dataCodewordsPerBlock: 107 },\n                    { numBlocks: 5, dataCodewordsPerBlock: 108 },\n                ],\n            },\n            {\n                ecCodewordsPerBlock: 26,\n                ecBlocks: [\n                    { numBlocks: 3, dataCodewordsPerBlock: 41 },\n                    { numBlocks: 13, dataCodewordsPerBlock: 42 },\n                ],\n            },\n            {\n                ecCodewordsPerBlock: 30,\n                ecBlocks: [\n                    { numBlocks: 15, dataCodewordsPerBlock: 24 },\n                    { numBlocks: 5, dataCodewordsPerBlock: 25 },\n                ],\n            },\n            {\n                ecCodewordsPerBlock: 28,\n                ecBlocks: [\n                    { numBlocks: 15, dataCodewordsPerBlock: 15 },\n                    { numBlocks: 10, dataCodewordsPerBlock: 16 },\n                ],\n            },\n        ],\n    },\n    {\n        infoBits: 0x15683,\n        versionNumber: 21,\n        alignmentPatternCenters: [6, 28, 50, 72, 94],\n        errorCorrectionLevels: [\n            {\n                ecCodewordsPerBlock: 28,\n                ecBlocks: [\n                    { numBlocks: 4, dataCodewordsPerBlock: 116 },\n                    { numBlocks: 4, dataCodewordsPerBlock: 117 },\n                ],\n            },\n            {\n                ecCodewordsPerBlock: 26,\n                ecBlocks: [{ numBlocks: 17, dataCodewordsPerBlock: 42 }],\n            },\n            {\n                ecCodewordsPerBlock: 28,\n                ecBlocks: [\n                    { numBlocks: 17, dataCodewordsPerBlock: 22 },\n                    { numBlocks: 6, dataCodewordsPerBlock: 23 },\n                ],\n            },\n            {\n                ecCodewordsPerBlock: 30,\n                ecBlocks: [\n                    { numBlocks: 19, dataCodewordsPerBlock: 16 },\n                    { numBlocks: 6, dataCodewordsPerBlock: 17 },\n                ],\n            },\n        ],\n    },\n    {\n        infoBits: 0x168C9,\n        versionNumber: 22,\n        alignmentPatternCenters: [6, 26, 50, 74, 98],\n        errorCorrectionLevels: [\n            {\n                ecCodewordsPerBlock: 28,\n                ecBlocks: [\n                    { numBlocks: 2, dataCodewordsPerBlock: 111 },\n                    { numBlocks: 7, dataCodewordsPerBlock: 112 },\n                ],\n            },\n            {\n                ecCodewordsPerBlock: 28,\n                ecBlocks: [{ numBlocks: 17, dataCodewordsPerBlock: 46 }],\n            },\n            {\n                ecCodewordsPerBlock: 30,\n                ecBlocks: [\n                    { numBlocks: 7, dataCodewordsPerBlock: 24 },\n                    { numBlocks: 16, dataCodewordsPerBlock: 25 },\n                ],\n            },\n            {\n                ecCodewordsPerBlock: 24,\n                ecBlocks: [{ numBlocks: 34, dataCodewordsPerBlock: 13 }],\n            },\n        ],\n    },\n    {\n        infoBits: 0x177EC,\n        versionNumber: 23,\n        alignmentPatternCenters: [6, 30, 54, 74, 102],\n        errorCorrectionLevels: [\n            {\n                ecCodewordsPerBlock: 30,\n                ecBlocks: [\n                    { numBlocks: 4, dataCodewordsPerBlock: 121 },\n                    { numBlocks: 5, dataCodewordsPerBlock: 122 },\n                ],\n            },\n            {\n                ecCodewordsPerBlock: 28,\n                ecBlocks: [\n                    { numBlocks: 4, dataCodewordsPerBlock: 47 },\n                    { numBlocks: 14, dataCodewordsPerBlock: 48 },\n                ],\n            },\n            {\n                ecCodewordsPerBlock: 30,\n                ecBlocks: [\n                    { numBlocks: 11, dataCodewordsPerBlock: 24 },\n                    { numBlocks: 14, dataCodewordsPerBlock: 25 },\n                ],\n            },\n            {\n                ecCodewordsPerBlock: 30,\n                ecBlocks: [\n                    { numBlocks: 16, dataCodewordsPerBlock: 15 },\n                    { numBlocks: 14, dataCodewordsPerBlock: 16 },\n                ],\n            },\n        ],\n    },\n    {\n        infoBits: 0x18EC4,\n        versionNumber: 24,\n        alignmentPatternCenters: [6, 28, 54, 80, 106],\n        errorCorrectionLevels: [\n            {\n                ecCodewordsPerBlock: 30,\n                ecBlocks: [\n                    { numBlocks: 6, dataCodewordsPerBlock: 117 },\n                    { numBlocks: 4, dataCodewordsPerBlock: 118 },\n                ],\n            },\n            {\n                ecCodewordsPerBlock: 28,\n                ecBlocks: [\n                    { numBlocks: 6, dataCodewordsPerBlock: 45 },\n                    { numBlocks: 14, dataCodewordsPerBlock: 46 },\n                ],\n            },\n            {\n                ecCodewordsPerBlock: 30,\n                ecBlocks: [\n                    { numBlocks: 11, dataCodewordsPerBlock: 24 },\n                    { numBlocks: 16, dataCodewordsPerBlock: 25 },\n                ],\n            },\n            {\n                ecCodewordsPerBlock: 30,\n                ecBlocks: [\n                    { numBlocks: 30, dataCodewordsPerBlock: 16 },\n                    { numBlocks: 2, dataCodewordsPerBlock: 17 },\n                ],\n            },\n        ],\n    },\n    {\n        infoBits: 0x191E1,\n        versionNumber: 25,\n        alignmentPatternCenters: [6, 32, 58, 84, 110],\n        errorCorrectionLevels: [\n            {\n                ecCodewordsPerBlock: 26,\n                ecBlocks: [\n                    { numBlocks: 8, dataCodewordsPerBlock: 106 },\n                    { numBlocks: 4, dataCodewordsPerBlock: 107 },\n                ],\n            },\n            {\n                ecCodewordsPerBlock: 28,\n                ecBlocks: [\n                    { numBlocks: 8, dataCodewordsPerBlock: 47 },\n                    { numBlocks: 13, dataCodewordsPerBlock: 48 },\n                ],\n            },\n            {\n                ecCodewordsPerBlock: 30,\n                ecBlocks: [\n                    { numBlocks: 7, dataCodewordsPerBlock: 24 },\n                    { numBlocks: 22, dataCodewordsPerBlock: 25 },\n                ],\n            },\n            {\n                ecCodewordsPerBlock: 30,\n                ecBlocks: [\n                    { numBlocks: 22, dataCodewordsPerBlock: 15 },\n                    { numBlocks: 13, dataCodewordsPerBlock: 16 },\n                ],\n            },\n        ],\n    },\n    {\n        infoBits: 0x1AFAB,\n        versionNumber: 26,\n        alignmentPatternCenters: [6, 30, 58, 86, 114],\n        errorCorrectionLevels: [\n            {\n                ecCodewordsPerBlock: 28,\n                ecBlocks: [\n                    { numBlocks: 10, dataCodewordsPerBlock: 114 },\n                    { numBlocks: 2, dataCodewordsPerBlock: 115 },\n                ],\n            },\n            {\n                ecCodewordsPerBlock: 28,\n                ecBlocks: [\n                    { numBlocks: 19, dataCodewordsPerBlock: 46 },\n                    { numBlocks: 4, dataCodewordsPerBlock: 47 },\n                ],\n            },\n            {\n                ecCodewordsPerBlock: 28,\n                ecBlocks: [\n                    { numBlocks: 28, dataCodewordsPerBlock: 22 },\n                    { numBlocks: 6, dataCodewordsPerBlock: 23 },\n                ],\n            },\n            {\n                ecCodewordsPerBlock: 30,\n                ecBlocks: [\n                    { numBlocks: 33, dataCodewordsPerBlock: 16 },\n                    { numBlocks: 4, dataCodewordsPerBlock: 17 },\n                ],\n            },\n        ],\n    },\n    {\n        infoBits: 0x1B08E,\n        versionNumber: 27,\n        alignmentPatternCenters: [6, 34, 62, 90, 118],\n        errorCorrectionLevels: [\n            {\n                ecCodewordsPerBlock: 30,\n                ecBlocks: [\n                    { numBlocks: 8, dataCodewordsPerBlock: 122 },\n                    { numBlocks: 4, dataCodewordsPerBlock: 123 },\n                ],\n            },\n            {\n                ecCodewordsPerBlock: 28,\n                ecBlocks: [\n                    { numBlocks: 22, dataCodewordsPerBlock: 45 },\n                    { numBlocks: 3, dataCodewordsPerBlock: 46 },\n                ],\n            },\n            {\n                ecCodewordsPerBlock: 30,\n                ecBlocks: [\n                    { numBlocks: 8, dataCodewordsPerBlock: 23 },\n                    { numBlocks: 26, dataCodewordsPerBlock: 24 },\n                ],\n            },\n            {\n                ecCodewordsPerBlock: 30,\n                ecBlocks: [\n                    { numBlocks: 12, dataCodewordsPerBlock: 15 },\n                    { numBlocks: 28, dataCodewordsPerBlock: 16 },\n                ],\n            },\n        ],\n    },\n    {\n        infoBits: 0x1CC1A,\n        versionNumber: 28,\n        alignmentPatternCenters: [6, 26, 50, 74, 98, 122],\n        errorCorrectionLevels: [\n            {\n                ecCodewordsPerBlock: 30,\n                ecBlocks: [\n                    { numBlocks: 3, dataCodewordsPerBlock: 117 },\n                    { numBlocks: 10, dataCodewordsPerBlock: 118 },\n                ],\n            },\n            {\n                ecCodewordsPerBlock: 28,\n                ecBlocks: [\n                    { numBlocks: 3, dataCodewordsPerBlock: 45 },\n                    { numBlocks: 23, dataCodewordsPerBlock: 46 },\n                ],\n            },\n            {\n                ecCodewordsPerBlock: 30,\n                ecBlocks: [\n                    { numBlocks: 4, dataCodewordsPerBlock: 24 },\n                    { numBlocks: 31, dataCodewordsPerBlock: 25 },\n                ],\n            },\n            {\n                ecCodewordsPerBlock: 30,\n                ecBlocks: [\n                    { numBlocks: 11, dataCodewordsPerBlock: 15 },\n                    { numBlocks: 31, dataCodewordsPerBlock: 16 },\n                ],\n            },\n        ],\n    },\n    {\n        infoBits: 0x1D33F,\n        versionNumber: 29,\n        alignmentPatternCenters: [6, 30, 54, 78, 102, 126],\n        errorCorrectionLevels: [\n            {\n                ecCodewordsPerBlock: 30,\n                ecBlocks: [\n                    { numBlocks: 7, dataCodewordsPerBlock: 116 },\n                    { numBlocks: 7, dataCodewordsPerBlock: 117 },\n                ],\n            },\n            {\n                ecCodewordsPerBlock: 28,\n                ecBlocks: [\n                    { numBlocks: 21, dataCodewordsPerBlock: 45 },\n                    { numBlocks: 7, dataCodewordsPerBlock: 46 },\n                ],\n            },\n            {\n                ecCodewordsPerBlock: 30,\n                ecBlocks: [\n                    { numBlocks: 1, dataCodewordsPerBlock: 23 },\n                    { numBlocks: 37, dataCodewordsPerBlock: 24 },\n                ],\n            },\n            {\n                ecCodewordsPerBlock: 30,\n                ecBlocks: [\n                    { numBlocks: 19, dataCodewordsPerBlock: 15 },\n                    { numBlocks: 26, dataCodewordsPerBlock: 16 },\n                ],\n            },\n        ],\n    },\n    {\n        infoBits: 0x1ED75,\n        versionNumber: 30,\n        alignmentPatternCenters: [6, 26, 52, 78, 104, 130],\n        errorCorrectionLevels: [\n            {\n                ecCodewordsPerBlock: 30,\n                ecBlocks: [\n                    { numBlocks: 5, dataCodewordsPerBlock: 115 },\n                    { numBlocks: 10, dataCodewordsPerBlock: 116 },\n                ],\n            },\n            {\n                ecCodewordsPerBlock: 28,\n                ecBlocks: [\n                    { numBlocks: 19, dataCodewordsPerBlock: 47 },\n                    { numBlocks: 10, dataCodewordsPerBlock: 48 },\n                ],\n            },\n            {\n                ecCodewordsPerBlock: 30,\n                ecBlocks: [\n                    { numBlocks: 15, dataCodewordsPerBlock: 24 },\n                    { numBlocks: 25, dataCodewordsPerBlock: 25 },\n                ],\n            },\n            {\n                ecCodewordsPerBlock: 30,\n                ecBlocks: [\n                    { numBlocks: 23, dataCodewordsPerBlock: 15 },\n                    { numBlocks: 25, dataCodewordsPerBlock: 16 },\n                ],\n            },\n        ],\n    },\n    {\n        infoBits: 0x1F250,\n        versionNumber: 31,\n        alignmentPatternCenters: [6, 30, 56, 82, 108, 134],\n        errorCorrectionLevels: [\n            {\n                ecCodewordsPerBlock: 30,\n                ecBlocks: [\n                    { numBlocks: 13, dataCodewordsPerBlock: 115 },\n                    { numBlocks: 3, dataCodewordsPerBlock: 116 },\n                ],\n            },\n            {\n                ecCodewordsPerBlock: 28,\n                ecBlocks: [\n                    { numBlocks: 2, dataCodewordsPerBlock: 46 },\n                    { numBlocks: 29, dataCodewordsPerBlock: 47 },\n                ],\n            },\n            {\n                ecCodewordsPerBlock: 30,\n                ecBlocks: [\n                    { numBlocks: 42, dataCodewordsPerBlock: 24 },\n                    { numBlocks: 1, dataCodewordsPerBlock: 25 },\n                ],\n            },\n            {\n                ecCodewordsPerBlock: 30,\n                ecBlocks: [\n                    { numBlocks: 23, dataCodewordsPerBlock: 15 },\n                    { numBlocks: 28, dataCodewordsPerBlock: 16 },\n                ],\n            },\n        ],\n    },\n    {\n        infoBits: 0x209D5,\n        versionNumber: 32,\n        alignmentPatternCenters: [6, 34, 60, 86, 112, 138],\n        errorCorrectionLevels: [\n            {\n                ecCodewordsPerBlock: 30,\n                ecBlocks: [{ numBlocks: 17, dataCodewordsPerBlock: 115 }],\n            },\n            {\n                ecCodewordsPerBlock: 28,\n                ecBlocks: [\n                    { numBlocks: 10, dataCodewordsPerBlock: 46 },\n                    { numBlocks: 23, dataCodewordsPerBlock: 47 },\n                ],\n            },\n            {\n                ecCodewordsPerBlock: 30,\n                ecBlocks: [\n                    { numBlocks: 10, dataCodewordsPerBlock: 24 },\n                    { numBlocks: 35, dataCodewordsPerBlock: 25 },\n                ],\n            },\n            {\n                ecCodewordsPerBlock: 30,\n                ecBlocks: [\n                    { numBlocks: 19, dataCodewordsPerBlock: 15 },\n                    { numBlocks: 35, dataCodewordsPerBlock: 16 },\n                ],\n            },\n        ],\n    },\n    {\n        infoBits: 0x216F0,\n        versionNumber: 33,\n        alignmentPatternCenters: [6, 30, 58, 86, 114, 142],\n        errorCorrectionLevels: [\n            {\n                ecCodewordsPerBlock: 30,\n                ecBlocks: [\n                    { numBlocks: 17, dataCodewordsPerBlock: 115 },\n                    { numBlocks: 1, dataCodewordsPerBlock: 116 },\n                ],\n            },\n            {\n                ecCodewordsPerBlock: 28,\n                ecBlocks: [\n                    { numBlocks: 14, dataCodewordsPerBlock: 46 },\n                    { numBlocks: 21, dataCodewordsPerBlock: 47 },\n                ],\n            },\n            {\n                ecCodewordsPerBlock: 30,\n                ecBlocks: [\n                    { numBlocks: 29, dataCodewordsPerBlock: 24 },\n                    { numBlocks: 19, dataCodewordsPerBlock: 25 },\n                ],\n            },\n            {\n                ecCodewordsPerBlock: 30,\n                ecBlocks: [\n                    { numBlocks: 11, dataCodewordsPerBlock: 15 },\n                    { numBlocks: 46, dataCodewordsPerBlock: 16 },\n                ],\n            },\n        ],\n    },\n    {\n        infoBits: 0x228BA,\n        versionNumber: 34,\n        alignmentPatternCenters: [6, 34, 62, 90, 118, 146],\n        errorCorrectionLevels: [\n            {\n                ecCodewordsPerBlock: 30,\n                ecBlocks: [\n                    { numBlocks: 13, dataCodewordsPerBlock: 115 },\n                    { numBlocks: 6, dataCodewordsPerBlock: 116 },\n                ],\n            },\n            {\n                ecCodewordsPerBlock: 28,\n                ecBlocks: [\n                    { numBlocks: 14, dataCodewordsPerBlock: 46 },\n                    { numBlocks: 23, dataCodewordsPerBlock: 47 },\n                ],\n            },\n            {\n                ecCodewordsPerBlock: 30,\n                ecBlocks: [\n                    { numBlocks: 44, dataCodewordsPerBlock: 24 },\n                    { numBlocks: 7, dataCodewordsPerBlock: 25 },\n                ],\n            },\n            {\n                ecCodewordsPerBlock: 30,\n                ecBlocks: [\n                    { numBlocks: 59, dataCodewordsPerBlock: 16 },\n                    { numBlocks: 1, dataCodewordsPerBlock: 17 },\n                ],\n            },\n        ],\n    },\n    {\n        infoBits: 0x2379F,\n        versionNumber: 35,\n        alignmentPatternCenters: [6, 30, 54, 78, 102, 126, 150],\n        errorCorrectionLevels: [\n            {\n                ecCodewordsPerBlock: 30,\n                ecBlocks: [\n                    { numBlocks: 12, dataCodewordsPerBlock: 121 },\n                    { numBlocks: 7, dataCodewordsPerBlock: 122 },\n                ],\n            },\n            {\n                ecCodewordsPerBlock: 28,\n                ecBlocks: [\n                    { numBlocks: 12, dataCodewordsPerBlock: 47 },\n                    { numBlocks: 26, dataCodewordsPerBlock: 48 },\n                ],\n            },\n            {\n                ecCodewordsPerBlock: 30,\n                ecBlocks: [\n                    { numBlocks: 39, dataCodewordsPerBlock: 24 },\n                    { numBlocks: 14, dataCodewordsPerBlock: 25 },\n                ],\n            },\n            {\n                ecCodewordsPerBlock: 30,\n                ecBlocks: [\n                    { numBlocks: 22, dataCodewordsPerBlock: 15 },\n                    { numBlocks: 41, dataCodewordsPerBlock: 16 },\n                ],\n            },\n        ],\n    },\n    {\n        infoBits: 0x24B0B,\n        versionNumber: 36,\n        alignmentPatternCenters: [6, 24, 50, 76, 102, 128, 154],\n        errorCorrectionLevels: [\n            {\n                ecCodewordsPerBlock: 30,\n                ecBlocks: [\n                    { numBlocks: 6, dataCodewordsPerBlock: 121 },\n                    { numBlocks: 14, dataCodewordsPerBlock: 122 },\n                ],\n            },\n            {\n                ecCodewordsPerBlock: 28,\n                ecBlocks: [\n                    { numBlocks: 6, dataCodewordsPerBlock: 47 },\n                    { numBlocks: 34, dataCodewordsPerBlock: 48 },\n                ],\n            },\n            {\n                ecCodewordsPerBlock: 30,\n                ecBlocks: [\n                    { numBlocks: 46, dataCodewordsPerBlock: 24 },\n                    { numBlocks: 10, dataCodewordsPerBlock: 25 },\n                ],\n            },\n            {\n                ecCodewordsPerBlock: 30,\n                ecBlocks: [\n                    { numBlocks: 2, dataCodewordsPerBlock: 15 },\n                    { numBlocks: 64, dataCodewordsPerBlock: 16 },\n                ],\n            },\n        ],\n    },\n    {\n        infoBits: 0x2542E,\n        versionNumber: 37,\n        alignmentPatternCenters: [6, 28, 54, 80, 106, 132, 158],\n        errorCorrectionLevels: [\n            {\n                ecCodewordsPerBlock: 30,\n                ecBlocks: [\n                    { numBlocks: 17, dataCodewordsPerBlock: 122 },\n                    { numBlocks: 4, dataCodewordsPerBlock: 123 },\n                ],\n            },\n            {\n                ecCodewordsPerBlock: 28,\n                ecBlocks: [\n                    { numBlocks: 29, dataCodewordsPerBlock: 46 },\n                    { numBlocks: 14, dataCodewordsPerBlock: 47 },\n                ],\n            },\n            {\n                ecCodewordsPerBlock: 30,\n                ecBlocks: [\n                    { numBlocks: 49, dataCodewordsPerBlock: 24 },\n                    { numBlocks: 10, dataCodewordsPerBlock: 25 },\n                ],\n            },\n            {\n                ecCodewordsPerBlock: 30,\n                ecBlocks: [\n                    { numBlocks: 24, dataCodewordsPerBlock: 15 },\n                    { numBlocks: 46, dataCodewordsPerBlock: 16 },\n                ],\n            },\n        ],\n    },\n    {\n        infoBits: 0x26A64,\n        versionNumber: 38,\n        alignmentPatternCenters: [6, 32, 58, 84, 110, 136, 162],\n        errorCorrectionLevels: [\n            {\n                ecCodewordsPerBlock: 30,\n                ecBlocks: [\n                    { numBlocks: 4, dataCodewordsPerBlock: 122 },\n                    { numBlocks: 18, dataCodewordsPerBlock: 123 },\n                ],\n            },\n            {\n                ecCodewordsPerBlock: 28,\n                ecBlocks: [\n                    { numBlocks: 13, dataCodewordsPerBlock: 46 },\n                    { numBlocks: 32, dataCodewordsPerBlock: 47 },\n                ],\n            },\n            {\n                ecCodewordsPerBlock: 30,\n                ecBlocks: [\n                    { numBlocks: 48, dataCodewordsPerBlock: 24 },\n                    { numBlocks: 14, dataCodewordsPerBlock: 25 },\n                ],\n            },\n            {\n                ecCodewordsPerBlock: 30,\n                ecBlocks: [\n                    { numBlocks: 42, dataCodewordsPerBlock: 15 },\n                    { numBlocks: 32, dataCodewordsPerBlock: 16 },\n                ],\n            },\n        ],\n    },\n    {\n        infoBits: 0x27541,\n        versionNumber: 39,\n        alignmentPatternCenters: [6, 26, 54, 82, 110, 138, 166],\n        errorCorrectionLevels: [\n            {\n                ecCodewordsPerBlock: 30,\n                ecBlocks: [\n                    { numBlocks: 20, dataCodewordsPerBlock: 117 },\n                    { numBlocks: 4, dataCodewordsPerBlock: 118 },\n                ],\n            },\n            {\n                ecCodewordsPerBlock: 28,\n                ecBlocks: [\n                    { numBlocks: 40, dataCodewordsPerBlock: 47 },\n                    { numBlocks: 7, dataCodewordsPerBlock: 48 },\n                ],\n            },\n            {\n                ecCodewordsPerBlock: 30,\n                ecBlocks: [\n                    { numBlocks: 43, dataCodewordsPerBlock: 24 },\n                    { numBlocks: 22, dataCodewordsPerBlock: 25 },\n                ],\n            },\n            {\n                ecCodewordsPerBlock: 30,\n                ecBlocks: [\n                    { numBlocks: 10, dataCodewordsPerBlock: 15 },\n                    { numBlocks: 67, dataCodewordsPerBlock: 16 },\n                ],\n            },\n        ],\n    },\n    {\n        infoBits: 0x28C69,\n        versionNumber: 40,\n        alignmentPatternCenters: [6, 30, 58, 86, 114, 142, 170],\n        errorCorrectionLevels: [\n            {\n                ecCodewordsPerBlock: 30,\n                ecBlocks: [\n                    { numBlocks: 19, dataCodewordsPerBlock: 118 },\n                    { numBlocks: 6, dataCodewordsPerBlock: 119 },\n                ],\n            },\n            {\n                ecCodewordsPerBlock: 28,\n                ecBlocks: [\n                    { numBlocks: 18, dataCodewordsPerBlock: 47 },\n                    { numBlocks: 31, dataCodewordsPerBlock: 48 },\n                ],\n            },\n            {\n                ecCodewordsPerBlock: 30,\n                ecBlocks: [\n                    { numBlocks: 34, dataCodewordsPerBlock: 24 },\n                    { numBlocks: 34, dataCodewordsPerBlock: 25 },\n                ],\n            },\n            {\n                ecCodewordsPerBlock: 30,\n                ecBlocks: [\n                    { numBlocks: 20, dataCodewordsPerBlock: 15 },\n                    { numBlocks: 61, dataCodewordsPerBlock: 16 },\n                ],\n            },\n        ],\n    },\n];\n\n// tslint:disable:no-bitwise\nfunction numBitsDiffering(x, y) {\n    let z = x ^ y;\n    let bitCount = 0;\n    while (z) {\n        bitCount++;\n        z &= z - 1;\n    }\n    return bitCount;\n}\nfunction pushBit(bit, byte) {\n    return (byte << 1) | bit;\n}\n// tslint:enable:no-bitwise\nconst FORMAT_INFO_TABLE = [\n    { bits: 0x5412, formatInfo: { errorCorrectionLevel: 1, dataMask: 0 } },\n    { bits: 0x5125, formatInfo: { errorCorrectionLevel: 1, dataMask: 1 } },\n    { bits: 0x5E7C, formatInfo: { errorCorrectionLevel: 1, dataMask: 2 } },\n    { bits: 0x5B4B, formatInfo: { errorCorrectionLevel: 1, dataMask: 3 } },\n    { bits: 0x45F9, formatInfo: { errorCorrectionLevel: 1, dataMask: 4 } },\n    { bits: 0x40CE, formatInfo: { errorCorrectionLevel: 1, dataMask: 5 } },\n    { bits: 0x4F97, formatInfo: { errorCorrectionLevel: 1, dataMask: 6 } },\n    { bits: 0x4AA0, formatInfo: { errorCorrectionLevel: 1, dataMask: 7 } },\n    { bits: 0x77C4, formatInfo: { errorCorrectionLevel: 0, dataMask: 0 } },\n    { bits: 0x72F3, formatInfo: { errorCorrectionLevel: 0, dataMask: 1 } },\n    { bits: 0x7DAA, formatInfo: { errorCorrectionLevel: 0, dataMask: 2 } },\n    { bits: 0x789D, formatInfo: { errorCorrectionLevel: 0, dataMask: 3 } },\n    { bits: 0x662F, formatInfo: { errorCorrectionLevel: 0, dataMask: 4 } },\n    { bits: 0x6318, formatInfo: { errorCorrectionLevel: 0, dataMask: 5 } },\n    { bits: 0x6C41, formatInfo: { errorCorrectionLevel: 0, dataMask: 6 } },\n    { bits: 0x6976, formatInfo: { errorCorrectionLevel: 0, dataMask: 7 } },\n    { bits: 0x1689, formatInfo: { errorCorrectionLevel: 3, dataMask: 0 } },\n    { bits: 0x13BE, formatInfo: { errorCorrectionLevel: 3, dataMask: 1 } },\n    { bits: 0x1CE7, formatInfo: { errorCorrectionLevel: 3, dataMask: 2 } },\n    { bits: 0x19D0, formatInfo: { errorCorrectionLevel: 3, dataMask: 3 } },\n    { bits: 0x0762, formatInfo: { errorCorrectionLevel: 3, dataMask: 4 } },\n    { bits: 0x0255, formatInfo: { errorCorrectionLevel: 3, dataMask: 5 } },\n    { bits: 0x0D0C, formatInfo: { errorCorrectionLevel: 3, dataMask: 6 } },\n    { bits: 0x083B, formatInfo: { errorCorrectionLevel: 3, dataMask: 7 } },\n    { bits: 0x355F, formatInfo: { errorCorrectionLevel: 2, dataMask: 0 } },\n    { bits: 0x3068, formatInfo: { errorCorrectionLevel: 2, dataMask: 1 } },\n    { bits: 0x3F31, formatInfo: { errorCorrectionLevel: 2, dataMask: 2 } },\n    { bits: 0x3A06, formatInfo: { errorCorrectionLevel: 2, dataMask: 3 } },\n    { bits: 0x24B4, formatInfo: { errorCorrectionLevel: 2, dataMask: 4 } },\n    { bits: 0x2183, formatInfo: { errorCorrectionLevel: 2, dataMask: 5 } },\n    { bits: 0x2EDA, formatInfo: { errorCorrectionLevel: 2, dataMask: 6 } },\n    { bits: 0x2BED, formatInfo: { errorCorrectionLevel: 2, dataMask: 7 } },\n];\nconst DATA_MASKS = [\n    (p) => ((p.y + p.x) % 2) === 0,\n    (p) => (p.y % 2) === 0,\n    (p) => p.x % 3 === 0,\n    (p) => (p.y + p.x) % 3 === 0,\n    (p) => (Math.floor(p.y / 2) + Math.floor(p.x / 3)) % 2 === 0,\n    (p) => ((p.x * p.y) % 2) + ((p.x * p.y) % 3) === 0,\n    (p) => ((((p.y * p.x) % 2) + (p.y * p.x) % 3) % 2) === 0,\n    (p) => ((((p.y + p.x) % 2) + (p.y * p.x) % 3) % 2) === 0,\n];\nfunction buildFunctionPatternMask(version) {\n    const dimension = 17 + 4 * version.versionNumber;\n    const matrix = BitMatrix.createEmpty(dimension, dimension);\n    matrix.setRegion(0, 0, 9, 9, true); // Top left finder pattern + separator + format\n    matrix.setRegion(dimension - 8, 0, 8, 9, true); // Top right finder pattern + separator + format\n    matrix.setRegion(0, dimension - 8, 9, 8, true); // Bottom left finder pattern + separator + format\n    // Alignment patterns\n    for (const x of version.alignmentPatternCenters) {\n        for (const y of version.alignmentPatternCenters) {\n            if (!(x === 6 && y === 6 || x === 6 && y === dimension - 7 || x === dimension - 7 && y === 6)) {\n                matrix.setRegion(x - 2, y - 2, 5, 5, true);\n            }\n        }\n    }\n    matrix.setRegion(6, 9, 1, dimension - 17, true); // Vertical timing pattern\n    matrix.setRegion(9, 6, dimension - 17, 1, true); // Horizontal timing pattern\n    if (version.versionNumber > 6) {\n        matrix.setRegion(dimension - 11, 0, 3, 6, true); // Version info, top right\n        matrix.setRegion(0, dimension - 11, 6, 3, true); // Version info, bottom left\n    }\n    return matrix;\n}\nfunction readCodewords(matrix, version, formatInfo) {\n    const dataMask = DATA_MASKS[formatInfo.dataMask];\n    const dimension = matrix.height;\n    const functionPatternMask = buildFunctionPatternMask(version);\n    const codewords = [];\n    let currentByte = 0;\n    let bitsRead = 0;\n    // Read columns in pairs, from right to left\n    let readingUp = true;\n    for (let columnIndex = dimension - 1; columnIndex > 0; columnIndex -= 2) {\n        if (columnIndex === 6) { // Skip whole column with vertical alignment pattern;\n            columnIndex--;\n        }\n        for (let i = 0; i < dimension; i++) {\n            const y = readingUp ? dimension - 1 - i : i;\n            for (let columnOffset = 0; columnOffset < 2; columnOffset++) {\n                const x = columnIndex - columnOffset;\n                if (!functionPatternMask.get(x, y)) {\n                    bitsRead++;\n                    let bit = matrix.get(x, y);\n                    if (dataMask({ y, x })) {\n                        bit = !bit;\n                    }\n                    currentByte = pushBit(bit, currentByte);\n                    if (bitsRead === 8) { // Whole bytes\n                        codewords.push(currentByte);\n                        bitsRead = 0;\n                        currentByte = 0;\n                    }\n                }\n            }\n        }\n        readingUp = !readingUp;\n    }\n    return codewords;\n}\nfunction readVersion(matrix) {\n    const dimension = matrix.height;\n    const provisionalVersion = Math.floor((dimension - 17) / 4);\n    if (provisionalVersion <= 6) { // 6 and under dont have version info in the QR code\n        return VERSIONS[provisionalVersion - 1];\n    }\n    let topRightVersionBits = 0;\n    for (let y = 5; y >= 0; y--) {\n        for (let x = dimension - 9; x >= dimension - 11; x--) {\n            topRightVersionBits = pushBit(matrix.get(x, y), topRightVersionBits);\n        }\n    }\n    let bottomLeftVersionBits = 0;\n    for (let x = 5; x >= 0; x--) {\n        for (let y = dimension - 9; y >= dimension - 11; y--) {\n            bottomLeftVersionBits = pushBit(matrix.get(x, y), bottomLeftVersionBits);\n        }\n    }\n    let bestDifference = Infinity;\n    let bestVersion;\n    for (const version of VERSIONS) {\n        if (version.infoBits === topRightVersionBits || version.infoBits === bottomLeftVersionBits) {\n            return version;\n        }\n        let difference = numBitsDiffering(topRightVersionBits, version.infoBits);\n        if (difference < bestDifference) {\n            bestVersion = version;\n            bestDifference = difference;\n        }\n        difference = numBitsDiffering(bottomLeftVersionBits, version.infoBits);\n        if (difference < bestDifference) {\n            bestVersion = version;\n            bestDifference = difference;\n        }\n    }\n    // We can tolerate up to 3 bits of error since no two version info codewords will\n    // differ in less than 8 bits.\n    if (bestDifference <= 3) {\n        return bestVersion;\n    }\n}\nfunction readFormatInformation(matrix) {\n    let topLeftFormatInfoBits = 0;\n    for (let x = 0; x <= 8; x++) {\n        if (x !== 6) { // Skip timing pattern bit\n            topLeftFormatInfoBits = pushBit(matrix.get(x, 8), topLeftFormatInfoBits);\n        }\n    }\n    for (let y = 7; y >= 0; y--) {\n        if (y !== 6) { // Skip timing pattern bit\n            topLeftFormatInfoBits = pushBit(matrix.get(8, y), topLeftFormatInfoBits);\n        }\n    }\n    const dimension = matrix.height;\n    let topRightBottomRightFormatInfoBits = 0;\n    for (let y = dimension - 1; y >= dimension - 7; y--) { // bottom left\n        topRightBottomRightFormatInfoBits = pushBit(matrix.get(8, y), topRightBottomRightFormatInfoBits);\n    }\n    for (let x = dimension - 8; x < dimension; x++) { // top right\n        topRightBottomRightFormatInfoBits = pushBit(matrix.get(x, 8), topRightBottomRightFormatInfoBits);\n    }\n    let bestDifference = Infinity;\n    let bestFormatInfo = null;\n    for (const { bits, formatInfo } of FORMAT_INFO_TABLE) {\n        if (bits === topLeftFormatInfoBits || bits === topRightBottomRightFormatInfoBits) {\n            return formatInfo;\n        }\n        let difference = numBitsDiffering(topLeftFormatInfoBits, bits);\n        if (difference < bestDifference) {\n            bestFormatInfo = formatInfo;\n            bestDifference = difference;\n        }\n        if (topLeftFormatInfoBits !== topRightBottomRightFormatInfoBits) { // also try the other option\n            difference = numBitsDiffering(topRightBottomRightFormatInfoBits, bits);\n            if (difference < bestDifference) {\n                bestFormatInfo = formatInfo;\n                bestDifference = difference;\n            }\n        }\n    }\n    // Hamming distance of the 32 masked codes is 7, by construction, so <= 3 bits differing means we found a match\n    if (bestDifference <= 3) {\n        return bestFormatInfo;\n    }\n    return null;\n}\nfunction getDataBlocks(codewords, version, ecLevel) {\n    const ecInfo = version.errorCorrectionLevels[ecLevel];\n    const dataBlocks = [];\n    let totalCodewords = 0;\n    ecInfo.ecBlocks.forEach(block => {\n        for (let i = 0; i < block.numBlocks; i++) {\n            dataBlocks.push({ numDataCodewords: block.dataCodewordsPerBlock, codewords: [] });\n            totalCodewords += block.dataCodewordsPerBlock + ecInfo.ecCodewordsPerBlock;\n        }\n    });\n    // In some cases the QR code will be malformed enough that we pull off more or less than we should.\n    // If we pull off less there's nothing we can do.\n    // If we pull off more we can safely truncate\n    if (codewords.length < totalCodewords) {\n        return null;\n    }\n    codewords = codewords.slice(0, totalCodewords);\n    const shortBlockSize = ecInfo.ecBlocks[0].dataCodewordsPerBlock;\n    // Pull codewords to fill the blocks up to the minimum size\n    for (let i = 0; i < shortBlockSize; i++) {\n        for (const dataBlock of dataBlocks) {\n            dataBlock.codewords.push(codewords.shift());\n        }\n    }\n    // If there are any large blocks, pull codewords to fill the last element of those\n    if (ecInfo.ecBlocks.length > 1) {\n        const smallBlockCount = ecInfo.ecBlocks[0].numBlocks;\n        const largeBlockCount = ecInfo.ecBlocks[1].numBlocks;\n        for (let i = 0; i < largeBlockCount; i++) {\n            dataBlocks[smallBlockCount + i].codewords.push(codewords.shift());\n        }\n    }\n    // Add the rest of the codewords to the blocks. These are the error correction codewords.\n    while (codewords.length > 0) {\n        for (const dataBlock of dataBlocks) {\n            dataBlock.codewords.push(codewords.shift());\n        }\n    }\n    return dataBlocks;\n}\nfunction decodeMatrix(matrix) {\n    const version = readVersion(matrix);\n    if (!version) {\n        return null;\n    }\n    const formatInfo = readFormatInformation(matrix);\n    if (!formatInfo) {\n        return null;\n    }\n    const codewords = readCodewords(matrix, version, formatInfo);\n    const dataBlocks = getDataBlocks(codewords, version, formatInfo.errorCorrectionLevel);\n    if (!dataBlocks) {\n        return null;\n    }\n    // Count total number of data bytes\n    const totalBytes = dataBlocks.reduce((a, b) => a + b.numDataCodewords, 0);\n    const resultBytes = new Uint8ClampedArray(totalBytes);\n    let resultIndex = 0;\n    for (const dataBlock of dataBlocks) {\n        const correctedBytes = decode$1(dataBlock.codewords, dataBlock.codewords.length - dataBlock.numDataCodewords);\n        if (!correctedBytes) {\n            return null;\n        }\n        for (let i = 0; i < dataBlock.numDataCodewords; i++) {\n            resultBytes[resultIndex++] = correctedBytes[i];\n        }\n    }\n    try {\n        return decode$2(resultBytes, version.versionNumber);\n    }\n    catch (_a) {\n        return null;\n    }\n}\nfunction decode(matrix) {\n    if (matrix == null) {\n        return null;\n    }\n    const result = decodeMatrix(matrix);\n    if (result) {\n        return result;\n    }\n    // Decoding didn't work, try mirroring the QR across the topLeft -> bottomRight line.\n    for (let x = 0; x < matrix.width; x++) {\n        for (let y = x + 1; y < matrix.height; y++) {\n            if (matrix.get(x, y) !== matrix.get(y, x)) {\n                matrix.set(x, y, !matrix.get(x, y));\n                matrix.set(y, x, !matrix.get(y, x));\n            }\n        }\n    }\n    return decodeMatrix(matrix);\n}\n\nfunction squareToQuadrilateral(p1, p2, p3, p4) {\n    const dx3 = p1.x - p2.x + p3.x - p4.x;\n    const dy3 = p1.y - p2.y + p3.y - p4.y;\n    if (dx3 === 0 && dy3 === 0) { // Affine\n        return {\n            a11: p2.x - p1.x,\n            a12: p2.y - p1.y,\n            a13: 0,\n            a21: p3.x - p2.x,\n            a22: p3.y - p2.y,\n            a23: 0,\n            a31: p1.x,\n            a32: p1.y,\n            a33: 1,\n        };\n    }\n    else {\n        const dx1 = p2.x - p3.x;\n        const dx2 = p4.x - p3.x;\n        const dy1 = p2.y - p3.y;\n        const dy2 = p4.y - p3.y;\n        const denominator = dx1 * dy2 - dx2 * dy1;\n        const a13 = (dx3 * dy2 - dx2 * dy3) / denominator;\n        const a23 = (dx1 * dy3 - dx3 * dy1) / denominator;\n        return {\n            a11: p2.x - p1.x + a13 * p2.x,\n            a12: p2.y - p1.y + a13 * p2.y,\n            a13,\n            a21: p4.x - p1.x + a23 * p4.x,\n            a22: p4.y - p1.y + a23 * p4.y,\n            a23,\n            a31: p1.x,\n            a32: p1.y,\n            a33: 1,\n        };\n    }\n}\nfunction quadrilateralToSquare(p1, p2, p3, p4) {\n    // Here, the adjoint serves as the inverse:\n    const sToQ = squareToQuadrilateral(p1, p2, p3, p4);\n    return {\n        a11: sToQ.a22 * sToQ.a33 - sToQ.a23 * sToQ.a32,\n        a12: sToQ.a13 * sToQ.a32 - sToQ.a12 * sToQ.a33,\n        a13: sToQ.a12 * sToQ.a23 - sToQ.a13 * sToQ.a22,\n        a21: sToQ.a23 * sToQ.a31 - sToQ.a21 * sToQ.a33,\n        a22: sToQ.a11 * sToQ.a33 - sToQ.a13 * sToQ.a31,\n        a23: sToQ.a13 * sToQ.a21 - sToQ.a11 * sToQ.a23,\n        a31: sToQ.a21 * sToQ.a32 - sToQ.a22 * sToQ.a31,\n        a32: sToQ.a12 * sToQ.a31 - sToQ.a11 * sToQ.a32,\n        a33: sToQ.a11 * sToQ.a22 - sToQ.a12 * sToQ.a21,\n    };\n}\nfunction times(a, b) {\n    return {\n        a11: a.a11 * b.a11 + a.a21 * b.a12 + a.a31 * b.a13,\n        a12: a.a12 * b.a11 + a.a22 * b.a12 + a.a32 * b.a13,\n        a13: a.a13 * b.a11 + a.a23 * b.a12 + a.a33 * b.a13,\n        a21: a.a11 * b.a21 + a.a21 * b.a22 + a.a31 * b.a23,\n        a22: a.a12 * b.a21 + a.a22 * b.a22 + a.a32 * b.a23,\n        a23: a.a13 * b.a21 + a.a23 * b.a22 + a.a33 * b.a23,\n        a31: a.a11 * b.a31 + a.a21 * b.a32 + a.a31 * b.a33,\n        a32: a.a12 * b.a31 + a.a22 * b.a32 + a.a32 * b.a33,\n        a33: a.a13 * b.a31 + a.a23 * b.a32 + a.a33 * b.a33,\n    };\n}\nfunction extract(image, location) {\n    const qToS = quadrilateralToSquare({ x: 3.5, y: 3.5 }, { x: location.dimension - 3.5, y: 3.5 }, { x: location.dimension - 6.5, y: location.dimension - 6.5 }, { x: 3.5, y: location.dimension - 3.5 });\n    const sToQ = squareToQuadrilateral(location.topLeft, location.topRight, location.alignmentPattern, location.bottomLeft);\n    const transform = times(sToQ, qToS);\n    const matrix = BitMatrix.createEmpty(location.dimension, location.dimension);\n    const mappingFunction = (x, y) => {\n        const denominator = transform.a13 * x + transform.a23 * y + transform.a33;\n        return {\n            x: (transform.a11 * x + transform.a21 * y + transform.a31) / denominator,\n            y: (transform.a12 * x + transform.a22 * y + transform.a32) / denominator,\n        };\n    };\n    for (let y = 0; y < location.dimension; y++) {\n        for (let x = 0; x < location.dimension; x++) {\n            const xValue = x + 0.5;\n            const yValue = y + 0.5;\n            const sourcePixel = mappingFunction(xValue, yValue);\n            matrix.set(x, y, image.get(Math.floor(sourcePixel.x), Math.floor(sourcePixel.y)));\n        }\n    }\n    return {\n        matrix,\n        mappingFunction,\n    };\n}\n\nconst MAX_FINDERPATTERNS_TO_SEARCH = 5;\nconst MIN_QUAD_RATIO = 0.5;\nconst MAX_QUAD_RATIO = 1.5;\nconst distance = (a, b) => Math.sqrt(Math.pow((b.x - a.x), 2) + Math.pow((b.y - a.y), 2));\nfunction sum(values) {\n    return values.reduce((a, b) => a + b);\n}\n// Takes three finder patterns and organizes them into topLeft, topRight, etc\nfunction reorderFinderPatterns(pattern1, pattern2, pattern3) {\n    // Find distances between pattern centers\n    const oneTwoDistance = distance(pattern1, pattern2);\n    const twoThreeDistance = distance(pattern2, pattern3);\n    const oneThreeDistance = distance(pattern1, pattern3);\n    let bottomLeft;\n    let topLeft;\n    let topRight;\n    // Assume one closest to other two is B; A and C will just be guesses at first\n    if (twoThreeDistance >= oneTwoDistance && twoThreeDistance >= oneThreeDistance) {\n        [bottomLeft, topLeft, topRight] = [pattern2, pattern1, pattern3];\n    }\n    else if (oneThreeDistance >= twoThreeDistance && oneThreeDistance >= oneTwoDistance) {\n        [bottomLeft, topLeft, topRight] = [pattern1, pattern2, pattern3];\n    }\n    else {\n        [bottomLeft, topLeft, topRight] = [pattern1, pattern3, pattern2];\n    }\n    // Use cross product to figure out whether bottomLeft (A) and topRight (C) are correct or flipped in relation to topLeft (B)\n    // This asks whether BC x BA has a positive z component, which is the arrangement we want. If it's negative, then\n    // we've got it flipped around and should swap topRight and bottomLeft.\n    if (((topRight.x - topLeft.x) * (bottomLeft.y - topLeft.y)) - ((topRight.y - topLeft.y) * (bottomLeft.x - topLeft.x)) < 0) {\n        [bottomLeft, topRight] = [topRight, bottomLeft];\n    }\n    return { bottomLeft, topLeft, topRight };\n}\n// Computes the dimension (number of modules on a side) of the QR Code based on the position of the finder patterns\nfunction computeDimension(topLeft, topRight, bottomLeft, matrix) {\n    const moduleSize = (sum(countBlackWhiteRun(topLeft, bottomLeft, matrix, 5)) / 7 + // Divide by 7 since the ratio is 1:1:3:1:1\n        sum(countBlackWhiteRun(topLeft, topRight, matrix, 5)) / 7 +\n        sum(countBlackWhiteRun(bottomLeft, topLeft, matrix, 5)) / 7 +\n        sum(countBlackWhiteRun(topRight, topLeft, matrix, 5)) / 7) / 4;\n    if (moduleSize < 1) {\n        throw new Error(\"Invalid module size\");\n    }\n    const topDimension = Math.round(distance(topLeft, topRight) / moduleSize);\n    const sideDimension = Math.round(distance(topLeft, bottomLeft) / moduleSize);\n    let dimension = Math.floor((topDimension + sideDimension) / 2) + 7;\n    switch (dimension % 4) {\n        case 0:\n            dimension++;\n            break;\n        case 2:\n            dimension--;\n            break;\n    }\n    return { dimension, moduleSize };\n}\n// Takes an origin point and an end point and counts the sizes of the black white run from the origin towards the end point.\n// Returns an array of elements, representing the pixel size of the black white run.\n// Uses a variant of http://en.wikipedia.org/wiki/Bresenham's_line_algorithm\nfunction countBlackWhiteRunTowardsPoint(origin, end, matrix, length) {\n    const switchPoints = [{ x: Math.floor(origin.x), y: Math.floor(origin.y) }];\n    const steep = Math.abs(end.y - origin.y) > Math.abs(end.x - origin.x);\n    let fromX;\n    let fromY;\n    let toX;\n    let toY;\n    if (steep) {\n        fromX = Math.floor(origin.y);\n        fromY = Math.floor(origin.x);\n        toX = Math.floor(end.y);\n        toY = Math.floor(end.x);\n    }\n    else {\n        fromX = Math.floor(origin.x);\n        fromY = Math.floor(origin.y);\n        toX = Math.floor(end.x);\n        toY = Math.floor(end.y);\n    }\n    const dx = Math.abs(toX - fromX);\n    const dy = Math.abs(toY - fromY);\n    let error = Math.floor(-dx / 2);\n    const xStep = fromX < toX ? 1 : -1;\n    const yStep = fromY < toY ? 1 : -1;\n    let currentPixel = true;\n    // Loop up until x == toX, but not beyond\n    for (let x = fromX, y = fromY; x !== toX + xStep; x += xStep) {\n        // Does current pixel mean we have moved white to black or vice versa?\n        // Scanning black in state 0,2 and white in state 1, so if we find the wrong\n        // color, advance to next state or end if we are in state 2 already\n        const realX = steep ? y : x;\n        const realY = steep ? x : y;\n        if (matrix.get(realX, realY) !== currentPixel) {\n            currentPixel = !currentPixel;\n            switchPoints.push({ x: realX, y: realY });\n            if (switchPoints.length === length + 1) {\n                break;\n            }\n        }\n        error += dy;\n        if (error > 0) {\n            if (y === toY) {\n                break;\n            }\n            y += yStep;\n            error -= dx;\n        }\n    }\n    const distances = [];\n    for (let i = 0; i < length; i++) {\n        if (switchPoints[i] && switchPoints[i + 1]) {\n            distances.push(distance(switchPoints[i], switchPoints[i + 1]));\n        }\n        else {\n            distances.push(0);\n        }\n    }\n    return distances;\n}\n// Takes an origin point and an end point and counts the sizes of the black white run in the origin point\n// along the line that intersects with the end point. Returns an array of elements, representing the pixel sizes\n// of the black white run. Takes a length which represents the number of switches from black to white to look for.\nfunction countBlackWhiteRun(origin, end, matrix, length) {\n    const rise = end.y - origin.y;\n    const run = end.x - origin.x;\n    const towardsEnd = countBlackWhiteRunTowardsPoint(origin, end, matrix, Math.ceil(length / 2));\n    const awayFromEnd = countBlackWhiteRunTowardsPoint(origin, { x: origin.x - run, y: origin.y - rise }, matrix, Math.ceil(length / 2));\n    const middleValue = towardsEnd.shift() + awayFromEnd.shift() - 1; // Substract one so we don't double count a pixel\n    return awayFromEnd.concat(middleValue).concat(...towardsEnd);\n}\n// Takes in a black white run and an array of expected ratios. Returns the average size of the run as well as the \"error\" -\n// that is the amount the run diverges from the expected ratio\nfunction scoreBlackWhiteRun(sequence, ratios) {\n    const averageSize = sum(sequence) / sum(ratios);\n    let error = 0;\n    ratios.forEach((ratio, i) => {\n        error += Math.pow((sequence[i] - ratio * averageSize), 2);\n    });\n    return { averageSize, error };\n}\n// Takes an X,Y point and an array of sizes and scores the point against those ratios.\n// For example for a finder pattern takes the ratio list of 1:1:3:1:1 and checks horizontal, vertical and diagonal ratios\n// against that.\nfunction scorePattern(point, ratios, matrix) {\n    try {\n        const horizontalRun = countBlackWhiteRun(point, { x: -1, y: point.y }, matrix, ratios.length);\n        const verticalRun = countBlackWhiteRun(point, { x: point.x, y: -1 }, matrix, ratios.length);\n        const topLeftPoint = {\n            x: Math.max(0, point.x - point.y) - 1,\n            y: Math.max(0, point.y - point.x) - 1,\n        };\n        const topLeftBottomRightRun = countBlackWhiteRun(point, topLeftPoint, matrix, ratios.length);\n        const bottomLeftPoint = {\n            x: Math.min(matrix.width, point.x + point.y) + 1,\n            y: Math.min(matrix.height, point.y + point.x) + 1,\n        };\n        const bottomLeftTopRightRun = countBlackWhiteRun(point, bottomLeftPoint, matrix, ratios.length);\n        const horzError = scoreBlackWhiteRun(horizontalRun, ratios);\n        const vertError = scoreBlackWhiteRun(verticalRun, ratios);\n        const diagDownError = scoreBlackWhiteRun(topLeftBottomRightRun, ratios);\n        const diagUpError = scoreBlackWhiteRun(bottomLeftTopRightRun, ratios);\n        const ratioError = Math.sqrt(horzError.error * horzError.error +\n            vertError.error * vertError.error +\n            diagDownError.error * diagDownError.error +\n            diagUpError.error * diagUpError.error);\n        const avgSize = (horzError.averageSize + vertError.averageSize + diagDownError.averageSize + diagUpError.averageSize) / 4;\n        const sizeError = (Math.pow((horzError.averageSize - avgSize), 2) +\n            Math.pow((vertError.averageSize - avgSize), 2) +\n            Math.pow((diagDownError.averageSize - avgSize), 2) +\n            Math.pow((diagUpError.averageSize - avgSize), 2)) / avgSize;\n        return ratioError + sizeError;\n    }\n    catch (_a) {\n        return Infinity;\n    }\n}\nfunction recenterLocation(matrix, p) {\n    let leftX = Math.round(p.x);\n    while (matrix.get(leftX, Math.round(p.y))) {\n        leftX--;\n    }\n    let rightX = Math.round(p.x);\n    while (matrix.get(rightX, Math.round(p.y))) {\n        rightX++;\n    }\n    const x = (leftX + rightX) / 2;\n    let topY = Math.round(p.y);\n    while (matrix.get(Math.round(x), topY)) {\n        topY--;\n    }\n    let bottomY = Math.round(p.y);\n    while (matrix.get(Math.round(x), bottomY)) {\n        bottomY++;\n    }\n    const y = (topY + bottomY) / 2;\n    return { x, y };\n}\nfunction locate(matrix) {\n    const finderPatternQuads = [];\n    let activeFinderPatternQuads = [];\n    const alignmentPatternQuads = [];\n    let activeAlignmentPatternQuads = [];\n    for (let y = 0; y <= matrix.height; y++) {\n        let length = 0;\n        let lastBit = false;\n        let scans = [0, 0, 0, 0, 0];\n        for (let x = -1; x <= matrix.width; x++) {\n            const v = matrix.get(x, y);\n            if (v === lastBit) {\n                length++;\n            }\n            else {\n                scans = [scans[1], scans[2], scans[3], scans[4], length];\n                length = 1;\n                lastBit = v;\n                // Do the last 5 color changes ~ match the expected ratio for a finder pattern? 1:1:3:1:1 of b:w:b:w:b\n                const averageFinderPatternBlocksize = sum(scans) / 7;\n                const validFinderPattern = Math.abs(scans[0] - averageFinderPatternBlocksize) < averageFinderPatternBlocksize &&\n                    Math.abs(scans[1] - averageFinderPatternBlocksize) < averageFinderPatternBlocksize &&\n                    Math.abs(scans[2] - 3 * averageFinderPatternBlocksize) < 3 * averageFinderPatternBlocksize &&\n                    Math.abs(scans[3] - averageFinderPatternBlocksize) < averageFinderPatternBlocksize &&\n                    Math.abs(scans[4] - averageFinderPatternBlocksize) < averageFinderPatternBlocksize &&\n                    !v; // And make sure the current pixel is white since finder patterns are bordered in white\n                // Do the last 3 color changes ~ match the expected ratio for an alignment pattern? 1:1:1 of w:b:w\n                const averageAlignmentPatternBlocksize = sum(scans.slice(-3)) / 3;\n                const validAlignmentPattern = Math.abs(scans[2] - averageAlignmentPatternBlocksize) < averageAlignmentPatternBlocksize &&\n                    Math.abs(scans[3] - averageAlignmentPatternBlocksize) < averageAlignmentPatternBlocksize &&\n                    Math.abs(scans[4] - averageAlignmentPatternBlocksize) < averageAlignmentPatternBlocksize &&\n                    v; // Is the current pixel black since alignment patterns are bordered in black\n                if (validFinderPattern) {\n                    // Compute the start and end x values of the large center black square\n                    const endX = x - scans[3] - scans[4];\n                    const startX = endX - scans[2];\n                    const line = { startX, endX, y };\n                    // Is there a quad directly above the current spot? If so, extend it with the new line. Otherwise, create a new quad with\n                    // that line as the starting point.\n                    const matchingQuads = activeFinderPatternQuads.filter(q => (startX >= q.bottom.startX && startX <= q.bottom.endX) ||\n                        (endX >= q.bottom.startX && startX <= q.bottom.endX) ||\n                        (startX <= q.bottom.startX && endX >= q.bottom.endX && ((scans[2] / (q.bottom.endX - q.bottom.startX)) < MAX_QUAD_RATIO &&\n                            (scans[2] / (q.bottom.endX - q.bottom.startX)) > MIN_QUAD_RATIO)));\n                    if (matchingQuads.length > 0) {\n                        matchingQuads[0].bottom = line;\n                    }\n                    else {\n                        activeFinderPatternQuads.push({ top: line, bottom: line });\n                    }\n                }\n                if (validAlignmentPattern) {\n                    // Compute the start and end x values of the center black square\n                    const endX = x - scans[4];\n                    const startX = endX - scans[3];\n                    const line = { startX, y, endX };\n                    // Is there a quad directly above the current spot? If so, extend it with the new line. Otherwise, create a new quad with\n                    // that line as the starting point.\n                    const matchingQuads = activeAlignmentPatternQuads.filter(q => (startX >= q.bottom.startX && startX <= q.bottom.endX) ||\n                        (endX >= q.bottom.startX && startX <= q.bottom.endX) ||\n                        (startX <= q.bottom.startX && endX >= q.bottom.endX && ((scans[2] / (q.bottom.endX - q.bottom.startX)) < MAX_QUAD_RATIO &&\n                            (scans[2] / (q.bottom.endX - q.bottom.startX)) > MIN_QUAD_RATIO)));\n                    if (matchingQuads.length > 0) {\n                        matchingQuads[0].bottom = line;\n                    }\n                    else {\n                        activeAlignmentPatternQuads.push({ top: line, bottom: line });\n                    }\n                }\n            }\n        }\n        finderPatternQuads.push(...activeFinderPatternQuads.filter(q => q.bottom.y !== y && q.bottom.y - q.top.y >= 2));\n        activeFinderPatternQuads = activeFinderPatternQuads.filter(q => q.bottom.y === y);\n        alignmentPatternQuads.push(...activeAlignmentPatternQuads.filter(q => q.bottom.y !== y));\n        activeAlignmentPatternQuads = activeAlignmentPatternQuads.filter(q => q.bottom.y === y);\n    }\n    finderPatternQuads.push(...activeFinderPatternQuads.filter(q => q.bottom.y - q.top.y >= 2));\n    alignmentPatternQuads.push(...activeAlignmentPatternQuads);\n    // Refactored from cozmo/jsQR to (hopefully) circumvent an issue in Safari 13+ on both Mac and iOS (also including\n    // iOS Chrome and other Safari iOS derivatives). Safari was very occasionally and apparently not deterministically\n    // throwing a \"RangeError: Array size is not a small enough positive integer.\" exception seemingly within the second\n    // .map of the original code (here the second for-loop). This second .map contained a nested .map call over the same\n    // array instance which was the chained result from previous calls to .map, .filter and .sort which potentially caused\n    // this bug in Safari?\n    // Also see https://github.com/cozmo/jsQR/issues/157 and https://bugs.webkit.org/show_bug.cgi?id=211619#c3\n    const scoredFinderPatternPositions = [];\n    for (const quad of finderPatternQuads) {\n        if (quad.bottom.y - quad.top.y < 2) {\n            // All quads must be at least 2px tall since the center square is larger than a block\n            continue;\n        }\n        // calculate quad center\n        const x = (quad.top.startX + quad.top.endX + quad.bottom.startX + quad.bottom.endX) / 4;\n        const y = (quad.top.y + quad.bottom.y + 1) / 2;\n        if (!matrix.get(Math.round(x), Math.round(y))) {\n            continue;\n        }\n        const lengths = [quad.top.endX - quad.top.startX, quad.bottom.endX - quad.bottom.startX, quad.bottom.y - quad.top.y + 1];\n        const size = sum(lengths) / lengths.length;\n        // Initial scoring of finder pattern quads by looking at their ratios, not taking into account position\n        const score = scorePattern({ x: Math.round(x), y: Math.round(y) }, [1, 1, 3, 1, 1], matrix);\n        scoredFinderPatternPositions.push({ score, x, y, size });\n    }\n    if (scoredFinderPatternPositions.length < 3) {\n        // A QR code has 3 finder patterns, therefore we need at least 3 candidates.\n        return null;\n    }\n    scoredFinderPatternPositions.sort((a, b) => a.score - b.score);\n    // Now take the top finder pattern options and try to find 2 other options with a similar size.\n    const finderPatternGroups = [];\n    for (let i = 0; i < Math.min(scoredFinderPatternPositions.length, MAX_FINDERPATTERNS_TO_SEARCH); ++i) {\n        const point = scoredFinderPatternPositions[i];\n        const otherPoints = [];\n        for (const otherPoint of scoredFinderPatternPositions) {\n            if (otherPoint === point) {\n                continue;\n            }\n            otherPoints.push(Object.assign(Object.assign({}, otherPoint), { score: otherPoint.score + (Math.pow((otherPoint.size - point.size), 2)) / point.size }));\n        }\n        otherPoints.sort((a, b) => a.score - b.score);\n        finderPatternGroups.push({\n            points: [point, otherPoints[0], otherPoints[1]],\n            score: point.score + otherPoints[0].score + otherPoints[1].score, // total combined score of the three points in the group\n        });\n    }\n    finderPatternGroups.sort((a, b) => a.score - b.score);\n    const bestFinderPatternGroup = finderPatternGroups[0];\n    const { topRight, topLeft, bottomLeft } = reorderFinderPatterns(...bestFinderPatternGroup.points);\n    const alignment = findAlignmentPattern(matrix, alignmentPatternQuads, topRight, topLeft, bottomLeft);\n    const result = [];\n    if (alignment) {\n        result.push({\n            alignmentPattern: { x: alignment.alignmentPattern.x, y: alignment.alignmentPattern.y },\n            bottomLeft: { x: bottomLeft.x, y: bottomLeft.y },\n            dimension: alignment.dimension,\n            topLeft: { x: topLeft.x, y: topLeft.y },\n            topRight: { x: topRight.x, y: topRight.y },\n        });\n    }\n    // We normally use the center of the quads as the location of the tracking points, which is optimal for most cases and will account\n    // for a skew in the image. However, In some cases, a slight skew might not be real and instead be caused by image compression\n    // errors and/or low resolution. For those cases, we'd be better off centering the point exactly in the middle of the black area. We\n    // compute and return the location data for the naively centered points as it is little additional work and allows for multiple\n    // attempts at decoding harder images.\n    const midTopRight = recenterLocation(matrix, topRight);\n    const midTopLeft = recenterLocation(matrix, topLeft);\n    const midBottomLeft = recenterLocation(matrix, bottomLeft);\n    const centeredAlignment = findAlignmentPattern(matrix, alignmentPatternQuads, midTopRight, midTopLeft, midBottomLeft);\n    if (centeredAlignment) {\n        result.push({\n            alignmentPattern: { x: centeredAlignment.alignmentPattern.x, y: centeredAlignment.alignmentPattern.y },\n            bottomLeft: { x: midBottomLeft.x, y: midBottomLeft.y },\n            topLeft: { x: midTopLeft.x, y: midTopLeft.y },\n            topRight: { x: midTopRight.x, y: midTopRight.y },\n            dimension: centeredAlignment.dimension,\n        });\n    }\n    if (result.length === 0) {\n        return null;\n    }\n    return result;\n}\nfunction findAlignmentPattern(matrix, alignmentPatternQuads, topRight, topLeft, bottomLeft) {\n    // Now that we've found the three finder patterns we can determine the blockSize and the size of the QR code.\n    // We'll use these to help find the alignment pattern but also later when we do the extraction.\n    let dimension;\n    let moduleSize;\n    try {\n        ({ dimension, moduleSize } = computeDimension(topLeft, topRight, bottomLeft, matrix));\n    }\n    catch (e) {\n        return null;\n    }\n    // Now find the alignment pattern\n    const bottomRightFinderPattern = {\n        x: topRight.x - topLeft.x + bottomLeft.x,\n        y: topRight.y - topLeft.y + bottomLeft.y,\n    };\n    const modulesBetweenFinderPatterns = ((distance(topLeft, bottomLeft) + distance(topLeft, topRight)) / 2 / moduleSize);\n    const correctionToTopLeft = 1 - (3 / modulesBetweenFinderPatterns);\n    const expectedAlignmentPattern = {\n        x: topLeft.x + correctionToTopLeft * (bottomRightFinderPattern.x - topLeft.x),\n        y: topLeft.y + correctionToTopLeft * (bottomRightFinderPattern.y - topLeft.y),\n    };\n    const alignmentPatterns = alignmentPatternQuads\n        .map(q => {\n        const x = (q.top.startX + q.top.endX + q.bottom.startX + q.bottom.endX) / 4;\n        const y = (q.top.y + q.bottom.y + 1) / 2;\n        if (!matrix.get(Math.floor(x), Math.floor(y))) {\n            return;\n        }\n        const sizeScore = scorePattern({ x: Math.floor(x), y: Math.floor(y) }, [1, 1, 1], matrix);\n        const score = sizeScore + distance({ x, y }, expectedAlignmentPattern);\n        return { x, y, score };\n    })\n        .filter(v => !!v)\n        .sort((a, b) => a.score - b.score);\n    // If there are less than 15 modules between finder patterns it's a version 1 QR code and as such has no alignmemnt pattern\n    // so we can only use our best guess.\n    const alignmentPattern = modulesBetweenFinderPatterns >= 15 && alignmentPatterns.length ? alignmentPatterns[0] : expectedAlignmentPattern;\n    return { alignmentPattern, dimension };\n}\n\nfunction scan(matrix) {\n    const locations = locate(matrix);\n    if (!locations) {\n        return null;\n    }\n    for (const location of locations) {\n        const extracted = extract(matrix, location);\n        const decoded = decode(extracted.matrix);\n        if (decoded) {\n            return {\n                binaryData: decoded.bytes,\n                data: decoded.text,\n                chunks: decoded.chunks,\n                version: decoded.version,\n                location: {\n                    topRightCorner: extracted.mappingFunction(location.dimension, 0),\n                    topLeftCorner: extracted.mappingFunction(0, 0),\n                    bottomRightCorner: extracted.mappingFunction(location.dimension, location.dimension),\n                    bottomLeftCorner: extracted.mappingFunction(0, location.dimension),\n                    topRightFinderPattern: location.topRight,\n                    topLeftFinderPattern: location.topLeft,\n                    bottomLeftFinderPattern: location.bottomLeft,\n                    bottomRightAlignmentPattern: location.alignmentPattern,\n                },\n                matrix: extracted.matrix,\n            };\n        }\n    }\n    return null;\n}\nconst defaultOptions = {\n    inversionAttempts: \"attemptBoth\",\n    greyScaleWeights: {\n        red: 0.2126,\n        green: 0.7152,\n        blue: 0.0722,\n        useIntegerApproximation: false,\n    },\n    canOverwriteImage: true,\n};\nfunction mergeObject(target, src) {\n    Object.keys(src).forEach(opt => {\n        target[opt] = src[opt];\n    });\n}\nfunction jsQR(data, width, height, providedOptions = {}) {\n    const options = Object.create(null);\n    mergeObject(options, defaultOptions);\n    mergeObject(options, providedOptions);\n    const tryInvertedFirst = options.inversionAttempts === \"onlyInvert\" || options.inversionAttempts === \"invertFirst\";\n    const shouldInvert = options.inversionAttempts === \"attemptBoth\" || tryInvertedFirst;\n    const { binarized, inverted } = binarize(data, width, height, shouldInvert, options.greyScaleWeights, options.canOverwriteImage);\n    let result = scan(tryInvertedFirst ? inverted : binarized);\n    if (!result && (options.inversionAttempts === \"attemptBoth\" || options.inversionAttempts === \"invertFirst\")) {\n        result = scan(tryInvertedFirst ? binarized : inverted);\n    }\n    return result;\n}\njsQR.default = jsQR;\n\nexport { jsQR as default };\n//# sourceMappingURL=jsQR.js.map\n","\n/*! pako 2.1.0 https://github.com/nodeca/pako @license (MIT AND Zlib) */\n// (C) 1995-2013 Jean-loup Gailly and Mark Adler\n// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin\n//\n// This software is provided 'as-is', without any express or implied\n// warranty. In no event will the authors be held liable for any damages\n// arising from the use of this software.\n//\n// Permission is granted to anyone to use this software for any purpose,\n// including commercial applications, and to alter it and redistribute it\n// freely, subject to the following restrictions:\n//\n// 1. The origin of this software must not be misrepresented; you must not\n//   claim that you wrote the original software. If you use this software\n//   in a product, an acknowledgment in the product documentation would be\n//   appreciated but is not required.\n// 2. Altered source versions must be plainly marked as such, and must not be\n//   misrepresented as being the original software.\n// 3. This notice may not be removed or altered from any source distribution.\n\n/* eslint-disable space-unary-ops */\n\n/* Public constants ==========================================================*/\n/* ===========================================================================*/\n\n\n//const Z_FILTERED          = 1;\n//const Z_HUFFMAN_ONLY      = 2;\n//const Z_RLE               = 3;\nconst Z_FIXED$1               = 4;\n//const Z_DEFAULT_STRATEGY  = 0;\n\n/* Possible values of the data_type field (though see inflate()) */\nconst Z_BINARY              = 0;\nconst Z_TEXT                = 1;\n//const Z_ASCII             = 1; // = Z_TEXT\nconst Z_UNKNOWN$1             = 2;\n\n/*============================================================================*/\n\n\nfunction zero$1(buf) { let len = buf.length; while (--len >= 0) { buf[len] = 0; } }\n\n// From zutil.h\n\nconst STORED_BLOCK = 0;\nconst STATIC_TREES = 1;\nconst DYN_TREES    = 2;\n/* The three kinds of block type */\n\nconst MIN_MATCH$1    = 3;\nconst MAX_MATCH$1    = 258;\n/* The minimum and maximum match lengths */\n\n// From deflate.h\n/* ===========================================================================\n * Internal compression state.\n */\n\nconst LENGTH_CODES$1  = 29;\n/* number of length codes, not counting the special END_BLOCK code */\n\nconst LITERALS$1      = 256;\n/* number of literal bytes 0..255 */\n\nconst L_CODES$1       = LITERALS$1 + 1 + LENGTH_CODES$1;\n/* number of Literal or Length codes, including the END_BLOCK code */\n\nconst D_CODES$1       = 30;\n/* number of distance codes */\n\nconst BL_CODES$1      = 19;\n/* number of codes used to transfer the bit lengths */\n\nconst HEAP_SIZE$1     = 2 * L_CODES$1 + 1;\n/* maximum heap size */\n\nconst MAX_BITS$1      = 15;\n/* All codes must not exceed MAX_BITS bits */\n\nconst Buf_size      = 16;\n/* size of bit buffer in bi_buf */\n\n\n/* ===========================================================================\n * Constants\n */\n\nconst MAX_BL_BITS = 7;\n/* Bit length codes must not exceed MAX_BL_BITS bits */\n\nconst END_BLOCK   = 256;\n/* end of block literal code */\n\nconst REP_3_6     = 16;\n/* repeat previous bit length 3-6 times (2 bits of repeat count) */\n\nconst REPZ_3_10   = 17;\n/* repeat a zero length 3-10 times  (3 bits of repeat count) */\n\nconst REPZ_11_138 = 18;\n/* repeat a zero length 11-138 times  (7 bits of repeat count) */\n\n/* eslint-disable comma-spacing,array-bracket-spacing */\nconst extra_lbits =   /* extra bits for each length code */\n  new Uint8Array([0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0]);\n\nconst extra_dbits =   /* extra bits for each distance code */\n  new Uint8Array([0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13]);\n\nconst extra_blbits =  /* extra bits for each bit length code */\n  new Uint8Array([0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7]);\n\nconst bl_order =\n  new Uint8Array([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]);\n/* eslint-enable comma-spacing,array-bracket-spacing */\n\n/* The lengths of the bit length codes are sent in order of decreasing\n * probability, to avoid transmitting the lengths for unused bit length codes.\n */\n\n/* ===========================================================================\n * Local data. These are initialized only once.\n */\n\n// We pre-fill arrays with 0 to avoid uninitialized gaps\n\nconst DIST_CODE_LEN = 512; /* see definition of array dist_code below */\n\n// !!!! Use flat array instead of structure, Freq = i*2, Len = i*2+1\nconst static_ltree  = new Array((L_CODES$1 + 2) * 2);\nzero$1(static_ltree);\n/* The static literal tree. Since the bit lengths are imposed, there is no\n * need for the L_CODES extra codes used during heap construction. However\n * The codes 286 and 287 are needed to build a canonical tree (see _tr_init\n * below).\n */\n\nconst static_dtree  = new Array(D_CODES$1 * 2);\nzero$1(static_dtree);\n/* The static distance tree. (Actually a trivial tree since all codes use\n * 5 bits.)\n */\n\nconst _dist_code    = new Array(DIST_CODE_LEN);\nzero$1(_dist_code);\n/* Distance codes. The first 256 values correspond to the distances\n * 3 .. 258, the last 256 values correspond to the top 8 bits of\n * the 15 bit distances.\n */\n\nconst _length_code  = new Array(MAX_MATCH$1 - MIN_MATCH$1 + 1);\nzero$1(_length_code);\n/* length code for each normalized match length (0 == MIN_MATCH) */\n\nconst base_length   = new Array(LENGTH_CODES$1);\nzero$1(base_length);\n/* First normalized length for each code (0 = MIN_MATCH) */\n\nconst base_dist     = new Array(D_CODES$1);\nzero$1(base_dist);\n/* First normalized distance for each code (0 = distance of 1) */\n\n\nfunction StaticTreeDesc(static_tree, extra_bits, extra_base, elems, max_length) {\n\n  this.static_tree  = static_tree;  /* static tree or NULL */\n  this.extra_bits   = extra_bits;   /* extra bits for each code or NULL */\n  this.extra_base   = extra_base;   /* base index for extra_bits */\n  this.elems        = elems;        /* max number of elements in the tree */\n  this.max_length   = max_length;   /* max bit length for the codes */\n\n  // show if `static_tree` has data or dummy - needed for monomorphic objects\n  this.has_stree    = static_tree && static_tree.length;\n}\n\n\nlet static_l_desc;\nlet static_d_desc;\nlet static_bl_desc;\n\n\nfunction TreeDesc(dyn_tree, stat_desc) {\n  this.dyn_tree = dyn_tree;     /* the dynamic tree */\n  this.max_code = 0;            /* largest code with non zero frequency */\n  this.stat_desc = stat_desc;   /* the corresponding static tree */\n}\n\n\n\nconst d_code = (dist) => {\n\n  return dist < 256 ? _dist_code[dist] : _dist_code[256 + (dist >>> 7)];\n};\n\n\n/* ===========================================================================\n * Output a short LSB first on the stream.\n * IN assertion: there is enough room in pendingBuf.\n */\nconst put_short = (s, w) => {\n//    put_byte(s, (uch)((w) & 0xff));\n//    put_byte(s, (uch)((ush)(w) >> 8));\n  s.pending_buf[s.pending++] = (w) & 0xff;\n  s.pending_buf[s.pending++] = (w >>> 8) & 0xff;\n};\n\n\n/* ===========================================================================\n * Send a value on a given number of bits.\n * IN assertion: length <= 16 and value fits in length bits.\n */\nconst send_bits = (s, value, length) => {\n\n  if (s.bi_valid > (Buf_size - length)) {\n    s.bi_buf |= (value << s.bi_valid) & 0xffff;\n    put_short(s, s.bi_buf);\n    s.bi_buf = value >> (Buf_size - s.bi_valid);\n    s.bi_valid += length - Buf_size;\n  } else {\n    s.bi_buf |= (value << s.bi_valid) & 0xffff;\n    s.bi_valid += length;\n  }\n};\n\n\nconst send_code = (s, c, tree) => {\n\n  send_bits(s, tree[c * 2]/*.Code*/, tree[c * 2 + 1]/*.Len*/);\n};\n\n\n/* ===========================================================================\n * Reverse the first len bits of a code, using straightforward code (a faster\n * method would use a table)\n * IN assertion: 1 <= len <= 15\n */\nconst bi_reverse = (code, len) => {\n\n  let res = 0;\n  do {\n    res |= code & 1;\n    code >>>= 1;\n    res <<= 1;\n  } while (--len > 0);\n  return res >>> 1;\n};\n\n\n/* ===========================================================================\n * Flush the bit buffer, keeping at most 7 bits in it.\n */\nconst bi_flush = (s) => {\n\n  if (s.bi_valid === 16) {\n    put_short(s, s.bi_buf);\n    s.bi_buf = 0;\n    s.bi_valid = 0;\n\n  } else if (s.bi_valid >= 8) {\n    s.pending_buf[s.pending++] = s.bi_buf & 0xff;\n    s.bi_buf >>= 8;\n    s.bi_valid -= 8;\n  }\n};\n\n\n/* ===========================================================================\n * Compute the optimal bit lengths for a tree and update the total bit length\n * for the current block.\n * IN assertion: the fields freq and dad are set, heap[heap_max] and\n *    above are the tree nodes sorted by increasing frequency.\n * OUT assertions: the field len is set to the optimal bit length, the\n *     array bl_count contains the frequencies for each bit length.\n *     The length opt_len is updated; static_len is also updated if stree is\n *     not null.\n */\nconst gen_bitlen = (s, desc) => {\n//    deflate_state *s;\n//    tree_desc *desc;    /* the tree descriptor */\n\n  const tree            = desc.dyn_tree;\n  const max_code        = desc.max_code;\n  const stree           = desc.stat_desc.static_tree;\n  const has_stree       = desc.stat_desc.has_stree;\n  const extra           = desc.stat_desc.extra_bits;\n  const base            = desc.stat_desc.extra_base;\n  const max_length      = desc.stat_desc.max_length;\n  let h;              /* heap index */\n  let n, m;           /* iterate over the tree elements */\n  let bits;           /* bit length */\n  let xbits;          /* extra bits */\n  let f;              /* frequency */\n  let overflow = 0;   /* number of elements with bit length too large */\n\n  for (bits = 0; bits <= MAX_BITS$1; bits++) {\n    s.bl_count[bits] = 0;\n  }\n\n  /* In a first pass, compute the optimal bit lengths (which may\n   * overflow in the case of the bit length tree).\n   */\n  tree[s.heap[s.heap_max] * 2 + 1]/*.Len*/ = 0; /* root of the heap */\n\n  for (h = s.heap_max + 1; h < HEAP_SIZE$1; h++) {\n    n = s.heap[h];\n    bits = tree[tree[n * 2 + 1]/*.Dad*/ * 2 + 1]/*.Len*/ + 1;\n    if (bits > max_length) {\n      bits = max_length;\n      overflow++;\n    }\n    tree[n * 2 + 1]/*.Len*/ = bits;\n    /* We overwrite tree[n].Dad which is no longer needed */\n\n    if (n > max_code) { continue; } /* not a leaf node */\n\n    s.bl_count[bits]++;\n    xbits = 0;\n    if (n >= base) {\n      xbits = extra[n - base];\n    }\n    f = tree[n * 2]/*.Freq*/;\n    s.opt_len += f * (bits + xbits);\n    if (has_stree) {\n      s.static_len += f * (stree[n * 2 + 1]/*.Len*/ + xbits);\n    }\n  }\n  if (overflow === 0) { return; }\n\n  // Tracev((stderr,\"\\nbit length overflow\\n\"));\n  /* This happens for example on obj2 and pic of the Calgary corpus */\n\n  /* Find the first bit length which could increase: */\n  do {\n    bits = max_length - 1;\n    while (s.bl_count[bits] === 0) { bits--; }\n    s.bl_count[bits]--;      /* move one leaf down the tree */\n    s.bl_count[bits + 1] += 2; /* move one overflow item as its brother */\n    s.bl_count[max_length]--;\n    /* The brother of the overflow item also moves one step up,\n     * but this does not affect bl_count[max_length]\n     */\n    overflow -= 2;\n  } while (overflow > 0);\n\n  /* Now recompute all bit lengths, scanning in increasing frequency.\n   * h is still equal to HEAP_SIZE. (It is simpler to reconstruct all\n   * lengths instead of fixing only the wrong ones. This idea is taken\n   * from 'ar' written by Haruhiko Okumura.)\n   */\n  for (bits = max_length; bits !== 0; bits--) {\n    n = s.bl_count[bits];\n    while (n !== 0) {\n      m = s.heap[--h];\n      if (m > max_code) { continue; }\n      if (tree[m * 2 + 1]/*.Len*/ !== bits) {\n        // Tracev((stderr,\"code %d bits %d->%d\\n\", m, tree[m].Len, bits));\n        s.opt_len += (bits - tree[m * 2 + 1]/*.Len*/) * tree[m * 2]/*.Freq*/;\n        tree[m * 2 + 1]/*.Len*/ = bits;\n      }\n      n--;\n    }\n  }\n};\n\n\n/* ===========================================================================\n * Generate the codes for a given tree and bit counts (which need not be\n * optimal).\n * IN assertion: the array bl_count contains the bit length statistics for\n * the given tree and the field len is set for all tree elements.\n * OUT assertion: the field code is set for all tree elements of non\n *     zero code length.\n */\nconst gen_codes = (tree, max_code, bl_count) => {\n//    ct_data *tree;             /* the tree to decorate */\n//    int max_code;              /* largest code with non zero frequency */\n//    ushf *bl_count;            /* number of codes at each bit length */\n\n  const next_code = new Array(MAX_BITS$1 + 1); /* next code value for each bit length */\n  let code = 0;              /* running code value */\n  let bits;                  /* bit index */\n  let n;                     /* code index */\n\n  /* The distribution counts are first used to generate the code values\n   * without bit reversal.\n   */\n  for (bits = 1; bits <= MAX_BITS$1; bits++) {\n    code = (code + bl_count[bits - 1]) << 1;\n    next_code[bits] = code;\n  }\n  /* Check that the bit counts in bl_count are consistent. The last code\n   * must be all ones.\n   */\n  //Assert (code + bl_count[MAX_BITS]-1 == (1<<MAX_BITS)-1,\n  //        \"inconsistent bit counts\");\n  //Tracev((stderr,\"\\ngen_codes: max_code %d \", max_code));\n\n  for (n = 0;  n <= max_code; n++) {\n    let len = tree[n * 2 + 1]/*.Len*/;\n    if (len === 0) { continue; }\n    /* Now reverse the bits */\n    tree[n * 2]/*.Code*/ = bi_reverse(next_code[len]++, len);\n\n    //Tracecv(tree != static_ltree, (stderr,\"\\nn %3d %c l %2d c %4x (%x) \",\n    //     n, (isgraph(n) ? n : ' '), len, tree[n].Code, next_code[len]-1));\n  }\n};\n\n\n/* ===========================================================================\n * Initialize the various 'constant' tables.\n */\nconst tr_static_init = () => {\n\n  let n;        /* iterates over tree elements */\n  let bits;     /* bit counter */\n  let length;   /* length value */\n  let code;     /* code value */\n  let dist;     /* distance index */\n  const bl_count = new Array(MAX_BITS$1 + 1);\n  /* number of codes at each bit length for an optimal tree */\n\n  // do check in _tr_init()\n  //if (static_init_done) return;\n\n  /* For some embedded targets, global variables are not initialized: */\n/*#ifdef NO_INIT_GLOBAL_POINTERS\n  static_l_desc.static_tree = static_ltree;\n  static_l_desc.extra_bits = extra_lbits;\n  static_d_desc.static_tree = static_dtree;\n  static_d_desc.extra_bits = extra_dbits;\n  static_bl_desc.extra_bits = extra_blbits;\n#endif*/\n\n  /* Initialize the mapping length (0..255) -> length code (0..28) */\n  length = 0;\n  for (code = 0; code < LENGTH_CODES$1 - 1; code++) {\n    base_length[code] = length;\n    for (n = 0; n < (1 << extra_lbits[code]); n++) {\n      _length_code[length++] = code;\n    }\n  }\n  //Assert (length == 256, \"tr_static_init: length != 256\");\n  /* Note that the length 255 (match length 258) can be represented\n   * in two different ways: code 284 + 5 bits or code 285, so we\n   * overwrite length_code[255] to use the best encoding:\n   */\n  _length_code[length - 1] = code;\n\n  /* Initialize the mapping dist (0..32K) -> dist code (0..29) */\n  dist = 0;\n  for (code = 0; code < 16; code++) {\n    base_dist[code] = dist;\n    for (n = 0; n < (1 << extra_dbits[code]); n++) {\n      _dist_code[dist++] = code;\n    }\n  }\n  //Assert (dist == 256, \"tr_static_init: dist != 256\");\n  dist >>= 7; /* from now on, all distances are divided by 128 */\n  for (; code < D_CODES$1; code++) {\n    base_dist[code] = dist << 7;\n    for (n = 0; n < (1 << (extra_dbits[code] - 7)); n++) {\n      _dist_code[256 + dist++] = code;\n    }\n  }\n  //Assert (dist == 256, \"tr_static_init: 256+dist != 512\");\n\n  /* Construct the codes of the static literal tree */\n  for (bits = 0; bits <= MAX_BITS$1; bits++) {\n    bl_count[bits] = 0;\n  }\n\n  n = 0;\n  while (n <= 143) {\n    static_ltree[n * 2 + 1]/*.Len*/ = 8;\n    n++;\n    bl_count[8]++;\n  }\n  while (n <= 255) {\n    static_ltree[n * 2 + 1]/*.Len*/ = 9;\n    n++;\n    bl_count[9]++;\n  }\n  while (n <= 279) {\n    static_ltree[n * 2 + 1]/*.Len*/ = 7;\n    n++;\n    bl_count[7]++;\n  }\n  while (n <= 287) {\n    static_ltree[n * 2 + 1]/*.Len*/ = 8;\n    n++;\n    bl_count[8]++;\n  }\n  /* Codes 286 and 287 do not exist, but we must include them in the\n   * tree construction to get a canonical Huffman tree (longest code\n   * all ones)\n   */\n  gen_codes(static_ltree, L_CODES$1 + 1, bl_count);\n\n  /* The static distance tree is trivial: */\n  for (n = 0; n < D_CODES$1; n++) {\n    static_dtree[n * 2 + 1]/*.Len*/ = 5;\n    static_dtree[n * 2]/*.Code*/ = bi_reverse(n, 5);\n  }\n\n  // Now data ready and we can init static trees\n  static_l_desc = new StaticTreeDesc(static_ltree, extra_lbits, LITERALS$1 + 1, L_CODES$1, MAX_BITS$1);\n  static_d_desc = new StaticTreeDesc(static_dtree, extra_dbits, 0,          D_CODES$1, MAX_BITS$1);\n  static_bl_desc = new StaticTreeDesc(new Array(0), extra_blbits, 0,         BL_CODES$1, MAX_BL_BITS);\n\n  //static_init_done = true;\n};\n\n\n/* ===========================================================================\n * Initialize a new block.\n */\nconst init_block = (s) => {\n\n  let n; /* iterates over tree elements */\n\n  /* Initialize the trees. */\n  for (n = 0; n < L_CODES$1;  n++) { s.dyn_ltree[n * 2]/*.Freq*/ = 0; }\n  for (n = 0; n < D_CODES$1;  n++) { s.dyn_dtree[n * 2]/*.Freq*/ = 0; }\n  for (n = 0; n < BL_CODES$1; n++) { s.bl_tree[n * 2]/*.Freq*/ = 0; }\n\n  s.dyn_ltree[END_BLOCK * 2]/*.Freq*/ = 1;\n  s.opt_len = s.static_len = 0;\n  s.sym_next = s.matches = 0;\n};\n\n\n/* ===========================================================================\n * Flush the bit buffer and align the output on a byte boundary\n */\nconst bi_windup = (s) =>\n{\n  if (s.bi_valid > 8) {\n    put_short(s, s.bi_buf);\n  } else if (s.bi_valid > 0) {\n    //put_byte(s, (Byte)s->bi_buf);\n    s.pending_buf[s.pending++] = s.bi_buf;\n  }\n  s.bi_buf = 0;\n  s.bi_valid = 0;\n};\n\n/* ===========================================================================\n * Compares to subtrees, using the tree depth as tie breaker when\n * the subtrees have equal frequency. This minimizes the worst case length.\n */\nconst smaller = (tree, n, m, depth) => {\n\n  const _n2 = n * 2;\n  const _m2 = m * 2;\n  return (tree[_n2]/*.Freq*/ < tree[_m2]/*.Freq*/ ||\n         (tree[_n2]/*.Freq*/ === tree[_m2]/*.Freq*/ && depth[n] <= depth[m]));\n};\n\n/* ===========================================================================\n * Restore the heap property by moving down the tree starting at node k,\n * exchanging a node with the smallest of its two sons if necessary, stopping\n * when the heap property is re-established (each father smaller than its\n * two sons).\n */\nconst pqdownheap = (s, tree, k) => {\n//    deflate_state *s;\n//    ct_data *tree;  /* the tree to restore */\n//    int k;               /* node to move down */\n\n  const v = s.heap[k];\n  let j = k << 1;  /* left son of k */\n  while (j <= s.heap_len) {\n    /* Set j to the smallest of the two sons: */\n    if (j < s.heap_len &&\n      smaller(tree, s.heap[j + 1], s.heap[j], s.depth)) {\n      j++;\n    }\n    /* Exit if v is smaller than both sons */\n    if (smaller(tree, v, s.heap[j], s.depth)) { break; }\n\n    /* Exchange v with the smallest son */\n    s.heap[k] = s.heap[j];\n    k = j;\n\n    /* And continue down the tree, setting j to the left son of k */\n    j <<= 1;\n  }\n  s.heap[k] = v;\n};\n\n\n// inlined manually\n// const SMALLEST = 1;\n\n/* ===========================================================================\n * Send the block data compressed using the given Huffman trees\n */\nconst compress_block = (s, ltree, dtree) => {\n//    deflate_state *s;\n//    const ct_data *ltree; /* literal tree */\n//    const ct_data *dtree; /* distance tree */\n\n  let dist;           /* distance of matched string */\n  let lc;             /* match length or unmatched char (if dist == 0) */\n  let sx = 0;         /* running index in sym_buf */\n  let code;           /* the code to send */\n  let extra;          /* number of extra bits to send */\n\n  if (s.sym_next !== 0) {\n    do {\n      dist = s.pending_buf[s.sym_buf + sx++] & 0xff;\n      dist += (s.pending_buf[s.sym_buf + sx++] & 0xff) << 8;\n      lc = s.pending_buf[s.sym_buf + sx++];\n      if (dist === 0) {\n        send_code(s, lc, ltree); /* send a literal byte */\n        //Tracecv(isgraph(lc), (stderr,\" '%c' \", lc));\n      } else {\n        /* Here, lc is the match length - MIN_MATCH */\n        code = _length_code[lc];\n        send_code(s, code + LITERALS$1 + 1, ltree); /* send the length code */\n        extra = extra_lbits[code];\n        if (extra !== 0) {\n          lc -= base_length[code];\n          send_bits(s, lc, extra);       /* send the extra length bits */\n        }\n        dist--; /* dist is now the match distance - 1 */\n        code = d_code(dist);\n        //Assert (code < D_CODES, \"bad d_code\");\n\n        send_code(s, code, dtree);       /* send the distance code */\n        extra = extra_dbits[code];\n        if (extra !== 0) {\n          dist -= base_dist[code];\n          send_bits(s, dist, extra);   /* send the extra distance bits */\n        }\n      } /* literal or match pair ? */\n\n      /* Check that the overlay between pending_buf and sym_buf is ok: */\n      //Assert(s->pending < s->lit_bufsize + sx, \"pendingBuf overflow\");\n\n    } while (sx < s.sym_next);\n  }\n\n  send_code(s, END_BLOCK, ltree);\n};\n\n\n/* ===========================================================================\n * Construct one Huffman tree and assigns the code bit strings and lengths.\n * Update the total bit length for the current block.\n * IN assertion: the field freq is set for all tree elements.\n * OUT assertions: the fields len and code are set to the optimal bit length\n *     and corresponding code. The length opt_len is updated; static_len is\n *     also updated if stree is not null. The field max_code is set.\n */\nconst build_tree = (s, desc) => {\n//    deflate_state *s;\n//    tree_desc *desc; /* the tree descriptor */\n\n  const tree     = desc.dyn_tree;\n  const stree    = desc.stat_desc.static_tree;\n  const has_stree = desc.stat_desc.has_stree;\n  const elems    = desc.stat_desc.elems;\n  let n, m;          /* iterate over heap elements */\n  let max_code = -1; /* largest code with non zero frequency */\n  let node;          /* new node being created */\n\n  /* Construct the initial heap, with least frequent element in\n   * heap[SMALLEST]. The sons of heap[n] are heap[2*n] and heap[2*n+1].\n   * heap[0] is not used.\n   */\n  s.heap_len = 0;\n  s.heap_max = HEAP_SIZE$1;\n\n  for (n = 0; n < elems; n++) {\n    if (tree[n * 2]/*.Freq*/ !== 0) {\n      s.heap[++s.heap_len] = max_code = n;\n      s.depth[n] = 0;\n\n    } else {\n      tree[n * 2 + 1]/*.Len*/ = 0;\n    }\n  }\n\n  /* The pkzip format requires that at least one distance code exists,\n   * and that at least one bit should be sent even if there is only one\n   * possible code. So to avoid special checks later on we force at least\n   * two codes of non zero frequency.\n   */\n  while (s.heap_len < 2) {\n    node = s.heap[++s.heap_len] = (max_code < 2 ? ++max_code : 0);\n    tree[node * 2]/*.Freq*/ = 1;\n    s.depth[node] = 0;\n    s.opt_len--;\n\n    if (has_stree) {\n      s.static_len -= stree[node * 2 + 1]/*.Len*/;\n    }\n    /* node is 0 or 1 so it does not have extra bits */\n  }\n  desc.max_code = max_code;\n\n  /* The elements heap[heap_len/2+1 .. heap_len] are leaves of the tree,\n   * establish sub-heaps of increasing lengths:\n   */\n  for (n = (s.heap_len >> 1/*int /2*/); n >= 1; n--) { pqdownheap(s, tree, n); }\n\n  /* Construct the Huffman tree by repeatedly combining the least two\n   * frequent nodes.\n   */\n  node = elems;              /* next internal node of the tree */\n  do {\n    //pqremove(s, tree, n);  /* n = node of least frequency */\n    /*** pqremove ***/\n    n = s.heap[1/*SMALLEST*/];\n    s.heap[1/*SMALLEST*/] = s.heap[s.heap_len--];\n    pqdownheap(s, tree, 1/*SMALLEST*/);\n    /***/\n\n    m = s.heap[1/*SMALLEST*/]; /* m = node of next least frequency */\n\n    s.heap[--s.heap_max] = n; /* keep the nodes sorted by frequency */\n    s.heap[--s.heap_max] = m;\n\n    /* Create a new node father of n and m */\n    tree[node * 2]/*.Freq*/ = tree[n * 2]/*.Freq*/ + tree[m * 2]/*.Freq*/;\n    s.depth[node] = (s.depth[n] >= s.depth[m] ? s.depth[n] : s.depth[m]) + 1;\n    tree[n * 2 + 1]/*.Dad*/ = tree[m * 2 + 1]/*.Dad*/ = node;\n\n    /* and insert the new node in the heap */\n    s.heap[1/*SMALLEST*/] = node++;\n    pqdownheap(s, tree, 1/*SMALLEST*/);\n\n  } while (s.heap_len >= 2);\n\n  s.heap[--s.heap_max] = s.heap[1/*SMALLEST*/];\n\n  /* At this point, the fields freq and dad are set. We can now\n   * generate the bit lengths.\n   */\n  gen_bitlen(s, desc);\n\n  /* The field len is now set, we can generate the bit codes */\n  gen_codes(tree, max_code, s.bl_count);\n};\n\n\n/* ===========================================================================\n * Scan a literal or distance tree to determine the frequencies of the codes\n * in the bit length tree.\n */\nconst scan_tree = (s, tree, max_code) => {\n//    deflate_state *s;\n//    ct_data *tree;   /* the tree to be scanned */\n//    int max_code;    /* and its largest code of non zero frequency */\n\n  let n;                     /* iterates over all tree elements */\n  let prevlen = -1;          /* last emitted length */\n  let curlen;                /* length of current code */\n\n  let nextlen = tree[0 * 2 + 1]/*.Len*/; /* length of next code */\n\n  let count = 0;             /* repeat count of the current code */\n  let max_count = 7;         /* max repeat count */\n  let min_count = 4;         /* min repeat count */\n\n  if (nextlen === 0) {\n    max_count = 138;\n    min_count = 3;\n  }\n  tree[(max_code + 1) * 2 + 1]/*.Len*/ = 0xffff; /* guard */\n\n  for (n = 0; n <= max_code; n++) {\n    curlen = nextlen;\n    nextlen = tree[(n + 1) * 2 + 1]/*.Len*/;\n\n    if (++count < max_count && curlen === nextlen) {\n      continue;\n\n    } else if (count < min_count) {\n      s.bl_tree[curlen * 2]/*.Freq*/ += count;\n\n    } else if (curlen !== 0) {\n\n      if (curlen !== prevlen) { s.bl_tree[curlen * 2]/*.Freq*/++; }\n      s.bl_tree[REP_3_6 * 2]/*.Freq*/++;\n\n    } else if (count <= 10) {\n      s.bl_tree[REPZ_3_10 * 2]/*.Freq*/++;\n\n    } else {\n      s.bl_tree[REPZ_11_138 * 2]/*.Freq*/++;\n    }\n\n    count = 0;\n    prevlen = curlen;\n\n    if (nextlen === 0) {\n      max_count = 138;\n      min_count = 3;\n\n    } else if (curlen === nextlen) {\n      max_count = 6;\n      min_count = 3;\n\n    } else {\n      max_count = 7;\n      min_count = 4;\n    }\n  }\n};\n\n\n/* ===========================================================================\n * Send a literal or distance tree in compressed form, using the codes in\n * bl_tree.\n */\nconst send_tree = (s, tree, max_code) => {\n//    deflate_state *s;\n//    ct_data *tree; /* the tree to be scanned */\n//    int max_code;       /* and its largest code of non zero frequency */\n\n  let n;                     /* iterates over all tree elements */\n  let prevlen = -1;          /* last emitted length */\n  let curlen;                /* length of current code */\n\n  let nextlen = tree[0 * 2 + 1]/*.Len*/; /* length of next code */\n\n  let count = 0;             /* repeat count of the current code */\n  let max_count = 7;         /* max repeat count */\n  let min_count = 4;         /* min repeat count */\n\n  /* tree[max_code+1].Len = -1; */  /* guard already set */\n  if (nextlen === 0) {\n    max_count = 138;\n    min_count = 3;\n  }\n\n  for (n = 0; n <= max_code; n++) {\n    curlen = nextlen;\n    nextlen = tree[(n + 1) * 2 + 1]/*.Len*/;\n\n    if (++count < max_count && curlen === nextlen) {\n      continue;\n\n    } else if (count < min_count) {\n      do { send_code(s, curlen, s.bl_tree); } while (--count !== 0);\n\n    } else if (curlen !== 0) {\n      if (curlen !== prevlen) {\n        send_code(s, curlen, s.bl_tree);\n        count--;\n      }\n      //Assert(count >= 3 && count <= 6, \" 3_6?\");\n      send_code(s, REP_3_6, s.bl_tree);\n      send_bits(s, count - 3, 2);\n\n    } else if (count <= 10) {\n      send_code(s, REPZ_3_10, s.bl_tree);\n      send_bits(s, count - 3, 3);\n\n    } else {\n      send_code(s, REPZ_11_138, s.bl_tree);\n      send_bits(s, count - 11, 7);\n    }\n\n    count = 0;\n    prevlen = curlen;\n    if (nextlen === 0) {\n      max_count = 138;\n      min_count = 3;\n\n    } else if (curlen === nextlen) {\n      max_count = 6;\n      min_count = 3;\n\n    } else {\n      max_count = 7;\n      min_count = 4;\n    }\n  }\n};\n\n\n/* ===========================================================================\n * Construct the Huffman tree for the bit lengths and return the index in\n * bl_order of the last bit length code to send.\n */\nconst build_bl_tree = (s) => {\n\n  let max_blindex;  /* index of last bit length code of non zero freq */\n\n  /* Determine the bit length frequencies for literal and distance trees */\n  scan_tree(s, s.dyn_ltree, s.l_desc.max_code);\n  scan_tree(s, s.dyn_dtree, s.d_desc.max_code);\n\n  /* Build the bit length tree: */\n  build_tree(s, s.bl_desc);\n  /* opt_len now includes the length of the tree representations, except\n   * the lengths of the bit lengths codes and the 5+5+4 bits for the counts.\n   */\n\n  /* Determine the number of bit length codes to send. The pkzip format\n   * requires that at least 4 bit length codes be sent. (appnote.txt says\n   * 3 but the actual value used is 4.)\n   */\n  for (max_blindex = BL_CODES$1 - 1; max_blindex >= 3; max_blindex--) {\n    if (s.bl_tree[bl_order[max_blindex] * 2 + 1]/*.Len*/ !== 0) {\n      break;\n    }\n  }\n  /* Update opt_len to include the bit length tree and counts */\n  s.opt_len += 3 * (max_blindex + 1) + 5 + 5 + 4;\n  //Tracev((stderr, \"\\ndyn trees: dyn %ld, stat %ld\",\n  //        s->opt_len, s->static_len));\n\n  return max_blindex;\n};\n\n\n/* ===========================================================================\n * Send the header for a block using dynamic Huffman trees: the counts, the\n * lengths of the bit length codes, the literal tree and the distance tree.\n * IN assertion: lcodes >= 257, dcodes >= 1, blcodes >= 4.\n */\nconst send_all_trees = (s, lcodes, dcodes, blcodes) => {\n//    deflate_state *s;\n//    int lcodes, dcodes, blcodes; /* number of codes for each tree */\n\n  let rank;                    /* index in bl_order */\n\n  //Assert (lcodes >= 257 && dcodes >= 1 && blcodes >= 4, \"not enough codes\");\n  //Assert (lcodes <= L_CODES && dcodes <= D_CODES && blcodes <= BL_CODES,\n  //        \"too many codes\");\n  //Tracev((stderr, \"\\nbl counts: \"));\n  send_bits(s, lcodes - 257, 5); /* not +255 as stated in appnote.txt */\n  send_bits(s, dcodes - 1,   5);\n  send_bits(s, blcodes - 4,  4); /* not -3 as stated in appnote.txt */\n  for (rank = 0; rank < blcodes; rank++) {\n    //Tracev((stderr, \"\\nbl code %2d \", bl_order[rank]));\n    send_bits(s, s.bl_tree[bl_order[rank] * 2 + 1]/*.Len*/, 3);\n  }\n  //Tracev((stderr, \"\\nbl tree: sent %ld\", s->bits_sent));\n\n  send_tree(s, s.dyn_ltree, lcodes - 1); /* literal tree */\n  //Tracev((stderr, \"\\nlit tree: sent %ld\", s->bits_sent));\n\n  send_tree(s, s.dyn_dtree, dcodes - 1); /* distance tree */\n  //Tracev((stderr, \"\\ndist tree: sent %ld\", s->bits_sent));\n};\n\n\n/* ===========================================================================\n * Check if the data type is TEXT or BINARY, using the following algorithm:\n * - TEXT if the two conditions below are satisfied:\n *    a) There are no non-portable control characters belonging to the\n *       \"block list\" (0..6, 14..25, 28..31).\n *    b) There is at least one printable character belonging to the\n *       \"allow list\" (9 {TAB}, 10 {LF}, 13 {CR}, 32..255).\n * - BINARY otherwise.\n * - The following partially-portable control characters form a\n *   \"gray list\" that is ignored in this detection algorithm:\n *   (7 {BEL}, 8 {BS}, 11 {VT}, 12 {FF}, 26 {SUB}, 27 {ESC}).\n * IN assertion: the fields Freq of dyn_ltree are set.\n */\nconst detect_data_type = (s) => {\n  /* block_mask is the bit mask of block-listed bytes\n   * set bits 0..6, 14..25, and 28..31\n   * 0xf3ffc07f = binary 11110011111111111100000001111111\n   */\n  let block_mask = 0xf3ffc07f;\n  let n;\n\n  /* Check for non-textual (\"block-listed\") bytes. */\n  for (n = 0; n <= 31; n++, block_mask >>>= 1) {\n    if ((block_mask & 1) && (s.dyn_ltree[n * 2]/*.Freq*/ !== 0)) {\n      return Z_BINARY;\n    }\n  }\n\n  /* Check for textual (\"allow-listed\") bytes. */\n  if (s.dyn_ltree[9 * 2]/*.Freq*/ !== 0 || s.dyn_ltree[10 * 2]/*.Freq*/ !== 0 ||\n      s.dyn_ltree[13 * 2]/*.Freq*/ !== 0) {\n    return Z_TEXT;\n  }\n  for (n = 32; n < LITERALS$1; n++) {\n    if (s.dyn_ltree[n * 2]/*.Freq*/ !== 0) {\n      return Z_TEXT;\n    }\n  }\n\n  /* There are no \"block-listed\" or \"allow-listed\" bytes:\n   * this stream either is empty or has tolerated (\"gray-listed\") bytes only.\n   */\n  return Z_BINARY;\n};\n\n\nlet static_init_done = false;\n\n/* ===========================================================================\n * Initialize the tree data structures for a new zlib stream.\n */\nconst _tr_init$1 = (s) =>\n{\n\n  if (!static_init_done) {\n    tr_static_init();\n    static_init_done = true;\n  }\n\n  s.l_desc  = new TreeDesc(s.dyn_ltree, static_l_desc);\n  s.d_desc  = new TreeDesc(s.dyn_dtree, static_d_desc);\n  s.bl_desc = new TreeDesc(s.bl_tree, static_bl_desc);\n\n  s.bi_buf = 0;\n  s.bi_valid = 0;\n\n  /* Initialize the first block of the first file: */\n  init_block(s);\n};\n\n\n/* ===========================================================================\n * Send a stored block\n */\nconst _tr_stored_block$1 = (s, buf, stored_len, last) => {\n//DeflateState *s;\n//charf *buf;       /* input block */\n//ulg stored_len;   /* length of input block */\n//int last;         /* one if this is the last block for a file */\n\n  send_bits(s, (STORED_BLOCK << 1) + (last ? 1 : 0), 3);    /* send block type */\n  bi_windup(s);        /* align on byte boundary */\n  put_short(s, stored_len);\n  put_short(s, ~stored_len);\n  if (stored_len) {\n    s.pending_buf.set(s.window.subarray(buf, buf + stored_len), s.pending);\n  }\n  s.pending += stored_len;\n};\n\n\n/* ===========================================================================\n * Send one empty static block to give enough lookahead for inflate.\n * This takes 10 bits, of which 7 may remain in the bit buffer.\n */\nconst _tr_align$1 = (s) => {\n  send_bits(s, STATIC_TREES << 1, 3);\n  send_code(s, END_BLOCK, static_ltree);\n  bi_flush(s);\n};\n\n\n/* ===========================================================================\n * Determine the best encoding for the current block: dynamic trees, static\n * trees or store, and write out the encoded block.\n */\nconst _tr_flush_block$1 = (s, buf, stored_len, last) => {\n//DeflateState *s;\n//charf *buf;       /* input block, or NULL if too old */\n//ulg stored_len;   /* length of input block */\n//int last;         /* one if this is the last block for a file */\n\n  let opt_lenb, static_lenb;  /* opt_len and static_len in bytes */\n  let max_blindex = 0;        /* index of last bit length code of non zero freq */\n\n  /* Build the Huffman trees unless a stored block is forced */\n  if (s.level > 0) {\n\n    /* Check if the file is binary or text */\n    if (s.strm.data_type === Z_UNKNOWN$1) {\n      s.strm.data_type = detect_data_type(s);\n    }\n\n    /* Construct the literal and distance trees */\n    build_tree(s, s.l_desc);\n    // Tracev((stderr, \"\\nlit data: dyn %ld, stat %ld\", s->opt_len,\n    //        s->static_len));\n\n    build_tree(s, s.d_desc);\n    // Tracev((stderr, \"\\ndist data: dyn %ld, stat %ld\", s->opt_len,\n    //        s->static_len));\n    /* At this point, opt_len and static_len are the total bit lengths of\n     * the compressed block data, excluding the tree representations.\n     */\n\n    /* Build the bit length tree for the above two trees, and get the index\n     * in bl_order of the last bit length code to send.\n     */\n    max_blindex = build_bl_tree(s);\n\n    /* Determine the best encoding. Compute the block lengths in bytes. */\n    opt_lenb = (s.opt_len + 3 + 7) >>> 3;\n    static_lenb = (s.static_len + 3 + 7) >>> 3;\n\n    // Tracev((stderr, \"\\nopt %lu(%lu) stat %lu(%lu) stored %lu lit %u \",\n    //        opt_lenb, s->opt_len, static_lenb, s->static_len, stored_len,\n    //        s->sym_next / 3));\n\n    if (static_lenb <= opt_lenb) { opt_lenb = static_lenb; }\n\n  } else {\n    // Assert(buf != (char*)0, \"lost buf\");\n    opt_lenb = static_lenb = stored_len + 5; /* force a stored block */\n  }\n\n  if ((stored_len + 4 <= opt_lenb) && (buf !== -1)) {\n    /* 4: two words for the lengths */\n\n    /* The test buf != NULL is only necessary if LIT_BUFSIZE > WSIZE.\n     * Otherwise we can't have processed more than WSIZE input bytes since\n     * the last block flush, because compression would have been\n     * successful. If LIT_BUFSIZE <= WSIZE, it is never too late to\n     * transform a block into a stored block.\n     */\n    _tr_stored_block$1(s, buf, stored_len, last);\n\n  } else if (s.strategy === Z_FIXED$1 || static_lenb === opt_lenb) {\n\n    send_bits(s, (STATIC_TREES << 1) + (last ? 1 : 0), 3);\n    compress_block(s, static_ltree, static_dtree);\n\n  } else {\n    send_bits(s, (DYN_TREES << 1) + (last ? 1 : 0), 3);\n    send_all_trees(s, s.l_desc.max_code + 1, s.d_desc.max_code + 1, max_blindex + 1);\n    compress_block(s, s.dyn_ltree, s.dyn_dtree);\n  }\n  // Assert (s->compressed_len == s->bits_sent, \"bad compressed size\");\n  /* The above check is made mod 2^32, for files larger than 512 MB\n   * and uLong implemented on 32 bits.\n   */\n  init_block(s);\n\n  if (last) {\n    bi_windup(s);\n  }\n  // Tracev((stderr,\"\\ncomprlen %lu(%lu) \", s->compressed_len>>3,\n  //       s->compressed_len-7*last));\n};\n\n/* ===========================================================================\n * Save the match info and tally the frequency counts. Return true if\n * the current block must be flushed.\n */\nconst _tr_tally$1 = (s, dist, lc) => {\n//    deflate_state *s;\n//    unsigned dist;  /* distance of matched string */\n//    unsigned lc;    /* match length-MIN_MATCH or unmatched char (if dist==0) */\n\n  s.pending_buf[s.sym_buf + s.sym_next++] = dist;\n  s.pending_buf[s.sym_buf + s.sym_next++] = dist >> 8;\n  s.pending_buf[s.sym_buf + s.sym_next++] = lc;\n  if (dist === 0) {\n    /* lc is the unmatched char */\n    s.dyn_ltree[lc * 2]/*.Freq*/++;\n  } else {\n    s.matches++;\n    /* Here, lc is the match length - MIN_MATCH */\n    dist--;             /* dist = match distance - 1 */\n    //Assert((ush)dist < (ush)MAX_DIST(s) &&\n    //       (ush)lc <= (ush)(MAX_MATCH-MIN_MATCH) &&\n    //       (ush)d_code(dist) < (ush)D_CODES,  \"_tr_tally: bad match\");\n\n    s.dyn_ltree[(_length_code[lc] + LITERALS$1 + 1) * 2]/*.Freq*/++;\n    s.dyn_dtree[d_code(dist) * 2]/*.Freq*/++;\n  }\n\n  return (s.sym_next === s.sym_end);\n};\n\nvar _tr_init_1  = _tr_init$1;\nvar _tr_stored_block_1 = _tr_stored_block$1;\nvar _tr_flush_block_1  = _tr_flush_block$1;\nvar _tr_tally_1 = _tr_tally$1;\nvar _tr_align_1 = _tr_align$1;\n\nvar trees = {\n\t_tr_init: _tr_init_1,\n\t_tr_stored_block: _tr_stored_block_1,\n\t_tr_flush_block: _tr_flush_block_1,\n\t_tr_tally: _tr_tally_1,\n\t_tr_align: _tr_align_1\n};\n\n// Note: adler32 takes 12% for level 0 and 2% for level 6.\n// It isn't worth it to make additional optimizations as in original.\n// Small size is preferable.\n\n// (C) 1995-2013 Jean-loup Gailly and Mark Adler\n// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin\n//\n// This software is provided 'as-is', without any express or implied\n// warranty. In no event will the authors be held liable for any damages\n// arising from the use of this software.\n//\n// Permission is granted to anyone to use this software for any purpose,\n// including commercial applications, and to alter it and redistribute it\n// freely, subject to the following restrictions:\n//\n// 1. The origin of this software must not be misrepresented; you must not\n//   claim that you wrote the original software. If you use this software\n//   in a product, an acknowledgment in the product documentation would be\n//   appreciated but is not required.\n// 2. Altered source versions must be plainly marked as such, and must not be\n//   misrepresented as being the original software.\n// 3. This notice may not be removed or altered from any source distribution.\n\nconst adler32 = (adler, buf, len, pos) => {\n  let s1 = (adler & 0xffff) |0,\n      s2 = ((adler >>> 16) & 0xffff) |0,\n      n = 0;\n\n  while (len !== 0) {\n    // Set limit ~ twice less than 5552, to keep\n    // s2 in 31-bits, because we force signed ints.\n    // in other case %= will fail.\n    n = len > 2000 ? 2000 : len;\n    len -= n;\n\n    do {\n      s1 = (s1 + buf[pos++]) |0;\n      s2 = (s2 + s1) |0;\n    } while (--n);\n\n    s1 %= 65521;\n    s2 %= 65521;\n  }\n\n  return (s1 | (s2 << 16)) |0;\n};\n\n\nvar adler32_1 = adler32;\n\n// Note: we can't get significant speed boost here.\n// So write code to minimize size - no pregenerated tables\n// and array tools dependencies.\n\n// (C) 1995-2013 Jean-loup Gailly and Mark Adler\n// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin\n//\n// This software is provided 'as-is', without any express or implied\n// warranty. In no event will the authors be held liable for any damages\n// arising from the use of this software.\n//\n// Permission is granted to anyone to use this software for any purpose,\n// including commercial applications, and to alter it and redistribute it\n// freely, subject to the following restrictions:\n//\n// 1. The origin of this software must not be misrepresented; you must not\n//   claim that you wrote the original software. If you use this software\n//   in a product, an acknowledgment in the product documentation would be\n//   appreciated but is not required.\n// 2. Altered source versions must be plainly marked as such, and must not be\n//   misrepresented as being the original software.\n// 3. This notice may not be removed or altered from any source distribution.\n\n// Use ordinary array, since untyped makes no boost here\nconst makeTable = () => {\n  let c, table = [];\n\n  for (var n = 0; n < 256; n++) {\n    c = n;\n    for (var k = 0; k < 8; k++) {\n      c = ((c & 1) ? (0xEDB88320 ^ (c >>> 1)) : (c >>> 1));\n    }\n    table[n] = c;\n  }\n\n  return table;\n};\n\n// Create table on load. Just 255 signed longs. Not a problem.\nconst crcTable = new Uint32Array(makeTable());\n\n\nconst crc32 = (crc, buf, len, pos) => {\n  const t = crcTable;\n  const end = pos + len;\n\n  crc ^= -1;\n\n  for (let i = pos; i < end; i++) {\n    crc = (crc >>> 8) ^ t[(crc ^ buf[i]) & 0xFF];\n  }\n\n  return (crc ^ (-1)); // >>> 0;\n};\n\n\nvar crc32_1 = crc32;\n\n// (C) 1995-2013 Jean-loup Gailly and Mark Adler\n// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin\n//\n// This software is provided 'as-is', without any express or implied\n// warranty. In no event will the authors be held liable for any damages\n// arising from the use of this software.\n//\n// Permission is granted to anyone to use this software for any purpose,\n// including commercial applications, and to alter it and redistribute it\n// freely, subject to the following restrictions:\n//\n// 1. The origin of this software must not be misrepresented; you must not\n//   claim that you wrote the original software. If you use this software\n//   in a product, an acknowledgment in the product documentation would be\n//   appreciated but is not required.\n// 2. Altered source versions must be plainly marked as such, and must not be\n//   misrepresented as being the original software.\n// 3. This notice may not be removed or altered from any source distribution.\n\nvar messages = {\n  2:      'need dictionary',     /* Z_NEED_DICT       2  */\n  1:      'stream end',          /* Z_STREAM_END      1  */\n  0:      '',                    /* Z_OK              0  */\n  '-1':   'file error',          /* Z_ERRNO         (-1) */\n  '-2':   'stream error',        /* Z_STREAM_ERROR  (-2) */\n  '-3':   'data error',          /* Z_DATA_ERROR    (-3) */\n  '-4':   'insufficient memory', /* Z_MEM_ERROR     (-4) */\n  '-5':   'buffer error',        /* Z_BUF_ERROR     (-5) */\n  '-6':   'incompatible version' /* Z_VERSION_ERROR (-6) */\n};\n\n// (C) 1995-2013 Jean-loup Gailly and Mark Adler\n// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin\n//\n// This software is provided 'as-is', without any express or implied\n// warranty. In no event will the authors be held liable for any damages\n// arising from the use of this software.\n//\n// Permission is granted to anyone to use this software for any purpose,\n// including commercial applications, and to alter it and redistribute it\n// freely, subject to the following restrictions:\n//\n// 1. The origin of this software must not be misrepresented; you must not\n//   claim that you wrote the original software. If you use this software\n//   in a product, an acknowledgment in the product documentation would be\n//   appreciated but is not required.\n// 2. Altered source versions must be plainly marked as such, and must not be\n//   misrepresented as being the original software.\n// 3. This notice may not be removed or altered from any source distribution.\n\nvar constants$2 = {\n\n  /* Allowed flush values; see deflate() and inflate() below for details */\n  Z_NO_FLUSH:         0,\n  Z_PARTIAL_FLUSH:    1,\n  Z_SYNC_FLUSH:       2,\n  Z_FULL_FLUSH:       3,\n  Z_FINISH:           4,\n  Z_BLOCK:            5,\n  Z_TREES:            6,\n\n  /* Return codes for the compression/decompression functions. Negative values\n  * are errors, positive values are used for special but normal events.\n  */\n  Z_OK:               0,\n  Z_STREAM_END:       1,\n  Z_NEED_DICT:        2,\n  Z_ERRNO:           -1,\n  Z_STREAM_ERROR:    -2,\n  Z_DATA_ERROR:      -3,\n  Z_MEM_ERROR:       -4,\n  Z_BUF_ERROR:       -5,\n  //Z_VERSION_ERROR: -6,\n\n  /* compression levels */\n  Z_NO_COMPRESSION:         0,\n  Z_BEST_SPEED:             1,\n  Z_BEST_COMPRESSION:       9,\n  Z_DEFAULT_COMPRESSION:   -1,\n\n\n  Z_FILTERED:               1,\n  Z_HUFFMAN_ONLY:           2,\n  Z_RLE:                    3,\n  Z_FIXED:                  4,\n  Z_DEFAULT_STRATEGY:       0,\n\n  /* Possible values of the data_type field (though see inflate()) */\n  Z_BINARY:                 0,\n  Z_TEXT:                   1,\n  //Z_ASCII:                1, // = Z_TEXT (deprecated)\n  Z_UNKNOWN:                2,\n\n  /* The deflate compression method */\n  Z_DEFLATED:               8\n  //Z_NULL:                 null // Use -1 or null inline, depending on var type\n};\n\n// (C) 1995-2013 Jean-loup Gailly and Mark Adler\n// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin\n//\n// This software is provided 'as-is', without any express or implied\n// warranty. In no event will the authors be held liable for any damages\n// arising from the use of this software.\n//\n// Permission is granted to anyone to use this software for any purpose,\n// including commercial applications, and to alter it and redistribute it\n// freely, subject to the following restrictions:\n//\n// 1. The origin of this software must not be misrepresented; you must not\n//   claim that you wrote the original software. If you use this software\n//   in a product, an acknowledgment in the product documentation would be\n//   appreciated but is not required.\n// 2. Altered source versions must be plainly marked as such, and must not be\n//   misrepresented as being the original software.\n// 3. This notice may not be removed or altered from any source distribution.\n\nconst { _tr_init, _tr_stored_block, _tr_flush_block, _tr_tally, _tr_align } = trees;\n\n\n\n\n/* Public constants ==========================================================*/\n/* ===========================================================================*/\n\nconst {\n  Z_NO_FLUSH: Z_NO_FLUSH$2, Z_PARTIAL_FLUSH, Z_FULL_FLUSH: Z_FULL_FLUSH$1, Z_FINISH: Z_FINISH$3, Z_BLOCK: Z_BLOCK$1,\n  Z_OK: Z_OK$3, Z_STREAM_END: Z_STREAM_END$3, Z_STREAM_ERROR: Z_STREAM_ERROR$2, Z_DATA_ERROR: Z_DATA_ERROR$2, Z_BUF_ERROR: Z_BUF_ERROR$1,\n  Z_DEFAULT_COMPRESSION: Z_DEFAULT_COMPRESSION$1,\n  Z_FILTERED, Z_HUFFMAN_ONLY, Z_RLE, Z_FIXED, Z_DEFAULT_STRATEGY: Z_DEFAULT_STRATEGY$1,\n  Z_UNKNOWN,\n  Z_DEFLATED: Z_DEFLATED$2\n} = constants$2;\n\n/*============================================================================*/\n\n\nconst MAX_MEM_LEVEL = 9;\n/* Maximum value for memLevel in deflateInit2 */\nconst MAX_WBITS$1 = 15;\n/* 32K LZ77 window */\nconst DEF_MEM_LEVEL = 8;\n\n\nconst LENGTH_CODES  = 29;\n/* number of length codes, not counting the special END_BLOCK code */\nconst LITERALS      = 256;\n/* number of literal bytes 0..255 */\nconst L_CODES       = LITERALS + 1 + LENGTH_CODES;\n/* number of Literal or Length codes, including the END_BLOCK code */\nconst D_CODES       = 30;\n/* number of distance codes */\nconst BL_CODES      = 19;\n/* number of codes used to transfer the bit lengths */\nconst HEAP_SIZE     = 2 * L_CODES + 1;\n/* maximum heap size */\nconst MAX_BITS  = 15;\n/* All codes must not exceed MAX_BITS bits */\n\nconst MIN_MATCH = 3;\nconst MAX_MATCH = 258;\nconst MIN_LOOKAHEAD = (MAX_MATCH + MIN_MATCH + 1);\n\nconst PRESET_DICT = 0x20;\n\nconst INIT_STATE    =  42;    /* zlib header -> BUSY_STATE */\n//#ifdef GZIP\nconst GZIP_STATE    =  57;    /* gzip header -> BUSY_STATE | EXTRA_STATE */\n//#endif\nconst EXTRA_STATE   =  69;    /* gzip extra block -> NAME_STATE */\nconst NAME_STATE    =  73;    /* gzip file name -> COMMENT_STATE */\nconst COMMENT_STATE =  91;    /* gzip comment -> HCRC_STATE */\nconst HCRC_STATE    = 103;    /* gzip header CRC -> BUSY_STATE */\nconst BUSY_STATE    = 113;    /* deflate -> FINISH_STATE */\nconst FINISH_STATE  = 666;    /* stream complete */\n\nconst BS_NEED_MORE      = 1; /* block not completed, need more input or more output */\nconst BS_BLOCK_DONE     = 2; /* block flush performed */\nconst BS_FINISH_STARTED = 3; /* finish started, need only more output at next deflate */\nconst BS_FINISH_DONE    = 4; /* finish done, accept no more input or output */\n\nconst OS_CODE = 0x03; // Unix :) . Don't detect, use this default.\n\nconst err = (strm, errorCode) => {\n  strm.msg = messages[errorCode];\n  return errorCode;\n};\n\nconst rank = (f) => {\n  return ((f) * 2) - ((f) > 4 ? 9 : 0);\n};\n\nconst zero = (buf) => {\n  let len = buf.length; while (--len >= 0) { buf[len] = 0; }\n};\n\n/* ===========================================================================\n * Slide the hash table when sliding the window down (could be avoided with 32\n * bit values at the expense of memory usage). We slide even when level == 0 to\n * keep the hash table consistent if we switch back to level > 0 later.\n */\nconst slide_hash = (s) => {\n  let n, m;\n  let p;\n  let wsize = s.w_size;\n\n  n = s.hash_size;\n  p = n;\n  do {\n    m = s.head[--p];\n    s.head[p] = (m >= wsize ? m - wsize : 0);\n  } while (--n);\n  n = wsize;\n//#ifndef FASTEST\n  p = n;\n  do {\n    m = s.prev[--p];\n    s.prev[p] = (m >= wsize ? m - wsize : 0);\n    /* If n is not on any hash chain, prev[n] is garbage but\n     * its value will never be used.\n     */\n  } while (--n);\n//#endif\n};\n\n/* eslint-disable new-cap */\nlet HASH_ZLIB = (s, prev, data) => ((prev << s.hash_shift) ^ data) & s.hash_mask;\n// This hash causes less collisions, https://github.com/nodeca/pako/issues/135\n// But breaks binary compatibility\n//let HASH_FAST = (s, prev, data) => ((prev << 8) + (prev >> 8) + (data << 4)) & s.hash_mask;\nlet HASH = HASH_ZLIB;\n\n\n/* =========================================================================\n * Flush as much pending output as possible. All deflate() output, except for\n * some deflate_stored() output, goes through this function so some\n * applications may wish to modify it to avoid allocating a large\n * strm->next_out buffer and copying into it. (See also read_buf()).\n */\nconst flush_pending = (strm) => {\n  const s = strm.state;\n\n  //_tr_flush_bits(s);\n  let len = s.pending;\n  if (len > strm.avail_out) {\n    len = strm.avail_out;\n  }\n  if (len === 0) { return; }\n\n  strm.output.set(s.pending_buf.subarray(s.pending_out, s.pending_out + len), strm.next_out);\n  strm.next_out  += len;\n  s.pending_out  += len;\n  strm.total_out += len;\n  strm.avail_out -= len;\n  s.pending      -= len;\n  if (s.pending === 0) {\n    s.pending_out = 0;\n  }\n};\n\n\nconst flush_block_only = (s, last) => {\n  _tr_flush_block(s, (s.block_start >= 0 ? s.block_start : -1), s.strstart - s.block_start, last);\n  s.block_start = s.strstart;\n  flush_pending(s.strm);\n};\n\n\nconst put_byte = (s, b) => {\n  s.pending_buf[s.pending++] = b;\n};\n\n\n/* =========================================================================\n * Put a short in the pending buffer. The 16-bit value is put in MSB order.\n * IN assertion: the stream state is correct and there is enough room in\n * pending_buf.\n */\nconst putShortMSB = (s, b) => {\n\n  //  put_byte(s, (Byte)(b >> 8));\n//  put_byte(s, (Byte)(b & 0xff));\n  s.pending_buf[s.pending++] = (b >>> 8) & 0xff;\n  s.pending_buf[s.pending++] = b & 0xff;\n};\n\n\n/* ===========================================================================\n * Read a new buffer from the current input stream, update the adler32\n * and total number of bytes read.  All deflate() input goes through\n * this function so some applications may wish to modify it to avoid\n * allocating a large strm->input buffer and copying from it.\n * (See also flush_pending()).\n */\nconst read_buf = (strm, buf, start, size) => {\n\n  let len = strm.avail_in;\n\n  if (len > size) { len = size; }\n  if (len === 0) { return 0; }\n\n  strm.avail_in -= len;\n\n  // zmemcpy(buf, strm->next_in, len);\n  buf.set(strm.input.subarray(strm.next_in, strm.next_in + len), start);\n  if (strm.state.wrap === 1) {\n    strm.adler = adler32_1(strm.adler, buf, len, start);\n  }\n\n  else if (strm.state.wrap === 2) {\n    strm.adler = crc32_1(strm.adler, buf, len, start);\n  }\n\n  strm.next_in += len;\n  strm.total_in += len;\n\n  return len;\n};\n\n\n/* ===========================================================================\n * Set match_start to the longest match starting at the given string and\n * return its length. Matches shorter or equal to prev_length are discarded,\n * in which case the result is equal to prev_length and match_start is\n * garbage.\n * IN assertions: cur_match is the head of the hash chain for the current\n *   string (strstart) and its distance is <= MAX_DIST, and prev_length >= 1\n * OUT assertion: the match length is not greater than s->lookahead.\n */\nconst longest_match = (s, cur_match) => {\n\n  let chain_length = s.max_chain_length;      /* max hash chain length */\n  let scan = s.strstart; /* current string */\n  let match;                       /* matched string */\n  let len;                           /* length of current match */\n  let best_len = s.prev_length;              /* best match length so far */\n  let nice_match = s.nice_match;             /* stop if match long enough */\n  const limit = (s.strstart > (s.w_size - MIN_LOOKAHEAD)) ?\n      s.strstart - (s.w_size - MIN_LOOKAHEAD) : 0/*NIL*/;\n\n  const _win = s.window; // shortcut\n\n  const wmask = s.w_mask;\n  const prev  = s.prev;\n\n  /* Stop when cur_match becomes <= limit. To simplify the code,\n   * we prevent matches with the string of window index 0.\n   */\n\n  const strend = s.strstart + MAX_MATCH;\n  let scan_end1  = _win[scan + best_len - 1];\n  let scan_end   = _win[scan + best_len];\n\n  /* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16.\n   * It is easy to get rid of this optimization if necessary.\n   */\n  // Assert(s->hash_bits >= 8 && MAX_MATCH == 258, \"Code too clever\");\n\n  /* Do not waste too much time if we already have a good match: */\n  if (s.prev_length >= s.good_match) {\n    chain_length >>= 2;\n  }\n  /* Do not look for matches beyond the end of the input. This is necessary\n   * to make deflate deterministic.\n   */\n  if (nice_match > s.lookahead) { nice_match = s.lookahead; }\n\n  // Assert((ulg)s->strstart <= s->window_size-MIN_LOOKAHEAD, \"need lookahead\");\n\n  do {\n    // Assert(cur_match < s->strstart, \"no future\");\n    match = cur_match;\n\n    /* Skip to next match if the match length cannot increase\n     * or if the match length is less than 2.  Note that the checks below\n     * for insufficient lookahead only occur occasionally for performance\n     * reasons.  Therefore uninitialized memory will be accessed, and\n     * conditional jumps will be made that depend on those values.\n     * However the length of the match is limited to the lookahead, so\n     * the output of deflate is not affected by the uninitialized values.\n     */\n\n    if (_win[match + best_len]     !== scan_end  ||\n        _win[match + best_len - 1] !== scan_end1 ||\n        _win[match]                !== _win[scan] ||\n        _win[++match]              !== _win[scan + 1]) {\n      continue;\n    }\n\n    /* The check at best_len-1 can be removed because it will be made\n     * again later. (This heuristic is not always a win.)\n     * It is not necessary to compare scan[2] and match[2] since they\n     * are always equal when the other bytes match, given that\n     * the hash keys are equal and that HASH_BITS >= 8.\n     */\n    scan += 2;\n    match++;\n    // Assert(*scan == *match, \"match[2]?\");\n\n    /* We check for insufficient lookahead only every 8th comparison;\n     * the 256th check will be made at strstart+258.\n     */\n    do {\n      /*jshint noempty:false*/\n    } while (_win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&\n             _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&\n             _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&\n             _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&\n             scan < strend);\n\n    // Assert(scan <= s->window+(unsigned)(s->window_size-1), \"wild scan\");\n\n    len = MAX_MATCH - (strend - scan);\n    scan = strend - MAX_MATCH;\n\n    if (len > best_len) {\n      s.match_start = cur_match;\n      best_len = len;\n      if (len >= nice_match) {\n        break;\n      }\n      scan_end1  = _win[scan + best_len - 1];\n      scan_end   = _win[scan + best_len];\n    }\n  } while ((cur_match = prev[cur_match & wmask]) > limit && --chain_length !== 0);\n\n  if (best_len <= s.lookahead) {\n    return best_len;\n  }\n  return s.lookahead;\n};\n\n\n/* ===========================================================================\n * Fill the window when the lookahead becomes insufficient.\n * Updates strstart and lookahead.\n *\n * IN assertion: lookahead < MIN_LOOKAHEAD\n * OUT assertions: strstart <= window_size-MIN_LOOKAHEAD\n *    At least one byte has been read, or avail_in == 0; reads are\n *    performed for at least two bytes (required for the zip translate_eol\n *    option -- not supported here).\n */\nconst fill_window = (s) => {\n\n  const _w_size = s.w_size;\n  let n, more, str;\n\n  //Assert(s->lookahead < MIN_LOOKAHEAD, \"already enough lookahead\");\n\n  do {\n    more = s.window_size - s.lookahead - s.strstart;\n\n    // JS ints have 32 bit, block below not needed\n    /* Deal with !@#$% 64K limit: */\n    //if (sizeof(int) <= 2) {\n    //    if (more == 0 && s->strstart == 0 && s->lookahead == 0) {\n    //        more = wsize;\n    //\n    //  } else if (more == (unsigned)(-1)) {\n    //        /* Very unlikely, but possible on 16 bit machine if\n    //         * strstart == 0 && lookahead == 1 (input done a byte at time)\n    //         */\n    //        more--;\n    //    }\n    //}\n\n\n    /* If the window is almost full and there is insufficient lookahead,\n     * move the upper half to the lower one to make room in the upper half.\n     */\n    if (s.strstart >= _w_size + (_w_size - MIN_LOOKAHEAD)) {\n\n      s.window.set(s.window.subarray(_w_size, _w_size + _w_size - more), 0);\n      s.match_start -= _w_size;\n      s.strstart -= _w_size;\n      /* we now have strstart >= MAX_DIST */\n      s.block_start -= _w_size;\n      if (s.insert > s.strstart) {\n        s.insert = s.strstart;\n      }\n      slide_hash(s);\n      more += _w_size;\n    }\n    if (s.strm.avail_in === 0) {\n      break;\n    }\n\n    /* If there was no sliding:\n     *    strstart <= WSIZE+MAX_DIST-1 && lookahead <= MIN_LOOKAHEAD - 1 &&\n     *    more == window_size - lookahead - strstart\n     * => more >= window_size - (MIN_LOOKAHEAD-1 + WSIZE + MAX_DIST-1)\n     * => more >= window_size - 2*WSIZE + 2\n     * In the BIG_MEM or MMAP case (not yet supported),\n     *   window_size == input_size + MIN_LOOKAHEAD  &&\n     *   strstart + s->lookahead <= input_size => more >= MIN_LOOKAHEAD.\n     * Otherwise, window_size == 2*WSIZE so more >= 2.\n     * If there was sliding, more >= WSIZE. So in all cases, more >= 2.\n     */\n    //Assert(more >= 2, \"more < 2\");\n    n = read_buf(s.strm, s.window, s.strstart + s.lookahead, more);\n    s.lookahead += n;\n\n    /* Initialize the hash value now that we have some input: */\n    if (s.lookahead + s.insert >= MIN_MATCH) {\n      str = s.strstart - s.insert;\n      s.ins_h = s.window[str];\n\n      /* UPDATE_HASH(s, s->ins_h, s->window[str + 1]); */\n      s.ins_h = HASH(s, s.ins_h, s.window[str + 1]);\n//#if MIN_MATCH != 3\n//        Call update_hash() MIN_MATCH-3 more times\n//#endif\n      while (s.insert) {\n        /* UPDATE_HASH(s, s->ins_h, s->window[str + MIN_MATCH-1]); */\n        s.ins_h = HASH(s, s.ins_h, s.window[str + MIN_MATCH - 1]);\n\n        s.prev[str & s.w_mask] = s.head[s.ins_h];\n        s.head[s.ins_h] = str;\n        str++;\n        s.insert--;\n        if (s.lookahead + s.insert < MIN_MATCH) {\n          break;\n        }\n      }\n    }\n    /* If the whole input has less than MIN_MATCH bytes, ins_h is garbage,\n     * but this is not important since only literal bytes will be emitted.\n     */\n\n  } while (s.lookahead < MIN_LOOKAHEAD && s.strm.avail_in !== 0);\n\n  /* If the WIN_INIT bytes after the end of the current data have never been\n   * written, then zero those bytes in order to avoid memory check reports of\n   * the use of uninitialized (or uninitialised as Julian writes) bytes by\n   * the longest match routines.  Update the high water mark for the next\n   * time through here.  WIN_INIT is set to MAX_MATCH since the longest match\n   * routines allow scanning to strstart + MAX_MATCH, ignoring lookahead.\n   */\n//  if (s.high_water < s.window_size) {\n//    const curr = s.strstart + s.lookahead;\n//    let init = 0;\n//\n//    if (s.high_water < curr) {\n//      /* Previous high water mark below current data -- zero WIN_INIT\n//       * bytes or up to end of window, whichever is less.\n//       */\n//      init = s.window_size - curr;\n//      if (init > WIN_INIT)\n//        init = WIN_INIT;\n//      zmemzero(s->window + curr, (unsigned)init);\n//      s->high_water = curr + init;\n//    }\n//    else if (s->high_water < (ulg)curr + WIN_INIT) {\n//      /* High water mark at or above current data, but below current data\n//       * plus WIN_INIT -- zero out to current data plus WIN_INIT, or up\n//       * to end of window, whichever is less.\n//       */\n//      init = (ulg)curr + WIN_INIT - s->high_water;\n//      if (init > s->window_size - s->high_water)\n//        init = s->window_size - s->high_water;\n//      zmemzero(s->window + s->high_water, (unsigned)init);\n//      s->high_water += init;\n//    }\n//  }\n//\n//  Assert((ulg)s->strstart <= s->window_size - MIN_LOOKAHEAD,\n//    \"not enough room for search\");\n};\n\n/* ===========================================================================\n * Copy without compression as much as possible from the input stream, return\n * the current block state.\n *\n * In case deflateParams() is used to later switch to a non-zero compression\n * level, s->matches (otherwise unused when storing) keeps track of the number\n * of hash table slides to perform. If s->matches is 1, then one hash table\n * slide will be done when switching. If s->matches is 2, the maximum value\n * allowed here, then the hash table will be cleared, since two or more slides\n * is the same as a clear.\n *\n * deflate_stored() is written to minimize the number of times an input byte is\n * copied. It is most efficient with large input and output buffers, which\n * maximizes the opportunites to have a single copy from next_in to next_out.\n */\nconst deflate_stored = (s, flush) => {\n\n  /* Smallest worthy block size when not flushing or finishing. By default\n   * this is 32K. This can be as small as 507 bytes for memLevel == 1. For\n   * large input and output buffers, the stored block size will be larger.\n   */\n  let min_block = s.pending_buf_size - 5 > s.w_size ? s.w_size : s.pending_buf_size - 5;\n\n  /* Copy as many min_block or larger stored blocks directly to next_out as\n   * possible. If flushing, copy the remaining available input to next_out as\n   * stored blocks, if there is enough space.\n   */\n  let len, left, have, last = 0;\n  let used = s.strm.avail_in;\n  do {\n    /* Set len to the maximum size block that we can copy directly with the\n     * available input data and output space. Set left to how much of that\n     * would be copied from what's left in the window.\n     */\n    len = 65535/* MAX_STORED */;     /* maximum deflate stored block length */\n    have = (s.bi_valid + 42) >> 3;     /* number of header bytes */\n    if (s.strm.avail_out < have) {         /* need room for header */\n      break;\n    }\n      /* maximum stored block length that will fit in avail_out: */\n    have = s.strm.avail_out - have;\n    left = s.strstart - s.block_start;  /* bytes left in window */\n    if (len > left + s.strm.avail_in) {\n      len = left + s.strm.avail_in;   /* limit len to the input */\n    }\n    if (len > have) {\n      len = have;             /* limit len to the output */\n    }\n\n    /* If the stored block would be less than min_block in length, or if\n     * unable to copy all of the available input when flushing, then try\n     * copying to the window and the pending buffer instead. Also don't\n     * write an empty block when flushing -- deflate() does that.\n     */\n    if (len < min_block && ((len === 0 && flush !== Z_FINISH$3) ||\n                        flush === Z_NO_FLUSH$2 ||\n                        len !== left + s.strm.avail_in)) {\n      break;\n    }\n\n    /* Make a dummy stored block in pending to get the header bytes,\n     * including any pending bits. This also updates the debugging counts.\n     */\n    last = flush === Z_FINISH$3 && len === left + s.strm.avail_in ? 1 : 0;\n    _tr_stored_block(s, 0, 0, last);\n\n    /* Replace the lengths in the dummy stored block with len. */\n    s.pending_buf[s.pending - 4] = len;\n    s.pending_buf[s.pending - 3] = len >> 8;\n    s.pending_buf[s.pending - 2] = ~len;\n    s.pending_buf[s.pending - 1] = ~len >> 8;\n\n    /* Write the stored block header bytes. */\n    flush_pending(s.strm);\n\n//#ifdef ZLIB_DEBUG\n//    /* Update debugging counts for the data about to be copied. */\n//    s->compressed_len += len << 3;\n//    s->bits_sent += len << 3;\n//#endif\n\n    /* Copy uncompressed bytes from the window to next_out. */\n    if (left) {\n      if (left > len) {\n        left = len;\n      }\n      //zmemcpy(s->strm->next_out, s->window + s->block_start, left);\n      s.strm.output.set(s.window.subarray(s.block_start, s.block_start + left), s.strm.next_out);\n      s.strm.next_out += left;\n      s.strm.avail_out -= left;\n      s.strm.total_out += left;\n      s.block_start += left;\n      len -= left;\n    }\n\n    /* Copy uncompressed bytes directly from next_in to next_out, updating\n     * the check value.\n     */\n    if (len) {\n      read_buf(s.strm, s.strm.output, s.strm.next_out, len);\n      s.strm.next_out += len;\n      s.strm.avail_out -= len;\n      s.strm.total_out += len;\n    }\n  } while (last === 0);\n\n  /* Update the sliding window with the last s->w_size bytes of the copied\n   * data, or append all of the copied data to the existing window if less\n   * than s->w_size bytes were copied. Also update the number of bytes to\n   * insert in the hash tables, in the event that deflateParams() switches to\n   * a non-zero compression level.\n   */\n  used -= s.strm.avail_in;    /* number of input bytes directly copied */\n  if (used) {\n    /* If any input was used, then no unused input remains in the window,\n     * therefore s->block_start == s->strstart.\n     */\n    if (used >= s.w_size) {  /* supplant the previous history */\n      s.matches = 2;     /* clear hash */\n      //zmemcpy(s->window, s->strm->next_in - s->w_size, s->w_size);\n      s.window.set(s.strm.input.subarray(s.strm.next_in - s.w_size, s.strm.next_in), 0);\n      s.strstart = s.w_size;\n      s.insert = s.strstart;\n    }\n    else {\n      if (s.window_size - s.strstart <= used) {\n        /* Slide the window down. */\n        s.strstart -= s.w_size;\n        //zmemcpy(s->window, s->window + s->w_size, s->strstart);\n        s.window.set(s.window.subarray(s.w_size, s.w_size + s.strstart), 0);\n        if (s.matches < 2) {\n          s.matches++;   /* add a pending slide_hash() */\n        }\n        if (s.insert > s.strstart) {\n          s.insert = s.strstart;\n        }\n      }\n      //zmemcpy(s->window + s->strstart, s->strm->next_in - used, used);\n      s.window.set(s.strm.input.subarray(s.strm.next_in - used, s.strm.next_in), s.strstart);\n      s.strstart += used;\n      s.insert += used > s.w_size - s.insert ? s.w_size - s.insert : used;\n    }\n    s.block_start = s.strstart;\n  }\n  if (s.high_water < s.strstart) {\n    s.high_water = s.strstart;\n  }\n\n  /* If the last block was written to next_out, then done. */\n  if (last) {\n    return BS_FINISH_DONE;\n  }\n\n  /* If flushing and all input has been consumed, then done. */\n  if (flush !== Z_NO_FLUSH$2 && flush !== Z_FINISH$3 &&\n    s.strm.avail_in === 0 && s.strstart === s.block_start) {\n    return BS_BLOCK_DONE;\n  }\n\n  /* Fill the window with any remaining input. */\n  have = s.window_size - s.strstart;\n  if (s.strm.avail_in > have && s.block_start >= s.w_size) {\n    /* Slide the window down. */\n    s.block_start -= s.w_size;\n    s.strstart -= s.w_size;\n    //zmemcpy(s->window, s->window + s->w_size, s->strstart);\n    s.window.set(s.window.subarray(s.w_size, s.w_size + s.strstart), 0);\n    if (s.matches < 2) {\n      s.matches++;       /* add a pending slide_hash() */\n    }\n    have += s.w_size;      /* more space now */\n    if (s.insert > s.strstart) {\n      s.insert = s.strstart;\n    }\n  }\n  if (have > s.strm.avail_in) {\n    have = s.strm.avail_in;\n  }\n  if (have) {\n    read_buf(s.strm, s.window, s.strstart, have);\n    s.strstart += have;\n    s.insert += have > s.w_size - s.insert ? s.w_size - s.insert : have;\n  }\n  if (s.high_water < s.strstart) {\n    s.high_water = s.strstart;\n  }\n\n  /* There was not enough avail_out to write a complete worthy or flushed\n   * stored block to next_out. Write a stored block to pending instead, if we\n   * have enough input for a worthy block, or if flushing and there is enough\n   * room for the remaining input as a stored block in the pending buffer.\n   */\n  have = (s.bi_valid + 42) >> 3;     /* number of header bytes */\n    /* maximum stored block length that will fit in pending: */\n  have = s.pending_buf_size - have > 65535/* MAX_STORED */ ? 65535/* MAX_STORED */ : s.pending_buf_size - have;\n  min_block = have > s.w_size ? s.w_size : have;\n  left = s.strstart - s.block_start;\n  if (left >= min_block ||\n     ((left || flush === Z_FINISH$3) && flush !== Z_NO_FLUSH$2 &&\n     s.strm.avail_in === 0 && left <= have)) {\n    len = left > have ? have : left;\n    last = flush === Z_FINISH$3 && s.strm.avail_in === 0 &&\n         len === left ? 1 : 0;\n    _tr_stored_block(s, s.block_start, len, last);\n    s.block_start += len;\n    flush_pending(s.strm);\n  }\n\n  /* We've done all we can with the available input and output. */\n  return last ? BS_FINISH_STARTED : BS_NEED_MORE;\n};\n\n\n/* ===========================================================================\n * Compress as much as possible from the input stream, return the current\n * block state.\n * This function does not perform lazy evaluation of matches and inserts\n * new strings in the dictionary only for unmatched strings or for short\n * matches. It is used only for the fast compression options.\n */\nconst deflate_fast = (s, flush) => {\n\n  let hash_head;        /* head of the hash chain */\n  let bflush;           /* set if current block must be flushed */\n\n  for (;;) {\n    /* Make sure that we always have enough lookahead, except\n     * at the end of the input file. We need MAX_MATCH bytes\n     * for the next match, plus MIN_MATCH bytes to insert the\n     * string following the next match.\n     */\n    if (s.lookahead < MIN_LOOKAHEAD) {\n      fill_window(s);\n      if (s.lookahead < MIN_LOOKAHEAD && flush === Z_NO_FLUSH$2) {\n        return BS_NEED_MORE;\n      }\n      if (s.lookahead === 0) {\n        break; /* flush the current block */\n      }\n    }\n\n    /* Insert the string window[strstart .. strstart+2] in the\n     * dictionary, and set hash_head to the head of the hash chain:\n     */\n    hash_head = 0/*NIL*/;\n    if (s.lookahead >= MIN_MATCH) {\n      /*** INSERT_STRING(s, s.strstart, hash_head); ***/\n      s.ins_h = HASH(s, s.ins_h, s.window[s.strstart + MIN_MATCH - 1]);\n      hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];\n      s.head[s.ins_h] = s.strstart;\n      /***/\n    }\n\n    /* Find the longest match, discarding those <= prev_length.\n     * At this point we have always match_length < MIN_MATCH\n     */\n    if (hash_head !== 0/*NIL*/ && ((s.strstart - hash_head) <= (s.w_size - MIN_LOOKAHEAD))) {\n      /* To simplify the code, we prevent matches with the string\n       * of window index 0 (in particular we have to avoid a match\n       * of the string with itself at the start of the input file).\n       */\n      s.match_length = longest_match(s, hash_head);\n      /* longest_match() sets match_start */\n    }\n    if (s.match_length >= MIN_MATCH) {\n      // check_match(s, s.strstart, s.match_start, s.match_length); // for debug only\n\n      /*** _tr_tally_dist(s, s.strstart - s.match_start,\n                     s.match_length - MIN_MATCH, bflush); ***/\n      bflush = _tr_tally(s, s.strstart - s.match_start, s.match_length - MIN_MATCH);\n\n      s.lookahead -= s.match_length;\n\n      /* Insert new strings in the hash table only if the match length\n       * is not too large. This saves time but degrades compression.\n       */\n      if (s.match_length <= s.max_lazy_match/*max_insert_length*/ && s.lookahead >= MIN_MATCH) {\n        s.match_length--; /* string at strstart already in table */\n        do {\n          s.strstart++;\n          /*** INSERT_STRING(s, s.strstart, hash_head); ***/\n          s.ins_h = HASH(s, s.ins_h, s.window[s.strstart + MIN_MATCH - 1]);\n          hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];\n          s.head[s.ins_h] = s.strstart;\n          /***/\n          /* strstart never exceeds WSIZE-MAX_MATCH, so there are\n           * always MIN_MATCH bytes ahead.\n           */\n        } while (--s.match_length !== 0);\n        s.strstart++;\n      } else\n      {\n        s.strstart += s.match_length;\n        s.match_length = 0;\n        s.ins_h = s.window[s.strstart];\n        /* UPDATE_HASH(s, s.ins_h, s.window[s.strstart+1]); */\n        s.ins_h = HASH(s, s.ins_h, s.window[s.strstart + 1]);\n\n//#if MIN_MATCH != 3\n//                Call UPDATE_HASH() MIN_MATCH-3 more times\n//#endif\n        /* If lookahead < MIN_MATCH, ins_h is garbage, but it does not\n         * matter since it will be recomputed at next deflate call.\n         */\n      }\n    } else {\n      /* No match, output a literal byte */\n      //Tracevv((stderr,\"%c\", s.window[s.strstart]));\n      /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/\n      bflush = _tr_tally(s, 0, s.window[s.strstart]);\n\n      s.lookahead--;\n      s.strstart++;\n    }\n    if (bflush) {\n      /*** FLUSH_BLOCK(s, 0); ***/\n      flush_block_only(s, false);\n      if (s.strm.avail_out === 0) {\n        return BS_NEED_MORE;\n      }\n      /***/\n    }\n  }\n  s.insert = ((s.strstart < (MIN_MATCH - 1)) ? s.strstart : MIN_MATCH - 1);\n  if (flush === Z_FINISH$3) {\n    /*** FLUSH_BLOCK(s, 1); ***/\n    flush_block_only(s, true);\n    if (s.strm.avail_out === 0) {\n      return BS_FINISH_STARTED;\n    }\n    /***/\n    return BS_FINISH_DONE;\n  }\n  if (s.sym_next) {\n    /*** FLUSH_BLOCK(s, 0); ***/\n    flush_block_only(s, false);\n    if (s.strm.avail_out === 0) {\n      return BS_NEED_MORE;\n    }\n    /***/\n  }\n  return BS_BLOCK_DONE;\n};\n\n/* ===========================================================================\n * Same as above, but achieves better compression. We use a lazy\n * evaluation for matches: a match is finally adopted only if there is\n * no better match at the next window position.\n */\nconst deflate_slow = (s, flush) => {\n\n  let hash_head;          /* head of hash chain */\n  let bflush;              /* set if current block must be flushed */\n\n  let max_insert;\n\n  /* Process the input block. */\n  for (;;) {\n    /* Make sure that we always have enough lookahead, except\n     * at the end of the input file. We need MAX_MATCH bytes\n     * for the next match, plus MIN_MATCH bytes to insert the\n     * string following the next match.\n     */\n    if (s.lookahead < MIN_LOOKAHEAD) {\n      fill_window(s);\n      if (s.lookahead < MIN_LOOKAHEAD && flush === Z_NO_FLUSH$2) {\n        return BS_NEED_MORE;\n      }\n      if (s.lookahead === 0) { break; } /* flush the current block */\n    }\n\n    /* Insert the string window[strstart .. strstart+2] in the\n     * dictionary, and set hash_head to the head of the hash chain:\n     */\n    hash_head = 0/*NIL*/;\n    if (s.lookahead >= MIN_MATCH) {\n      /*** INSERT_STRING(s, s.strstart, hash_head); ***/\n      s.ins_h = HASH(s, s.ins_h, s.window[s.strstart + MIN_MATCH - 1]);\n      hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];\n      s.head[s.ins_h] = s.strstart;\n      /***/\n    }\n\n    /* Find the longest match, discarding those <= prev_length.\n     */\n    s.prev_length = s.match_length;\n    s.prev_match = s.match_start;\n    s.match_length = MIN_MATCH - 1;\n\n    if (hash_head !== 0/*NIL*/ && s.prev_length < s.max_lazy_match &&\n        s.strstart - hash_head <= (s.w_size - MIN_LOOKAHEAD)/*MAX_DIST(s)*/) {\n      /* To simplify the code, we prevent matches with the string\n       * of window index 0 (in particular we have to avoid a match\n       * of the string with itself at the start of the input file).\n       */\n      s.match_length = longest_match(s, hash_head);\n      /* longest_match() sets match_start */\n\n      if (s.match_length <= 5 &&\n         (s.strategy === Z_FILTERED || (s.match_length === MIN_MATCH && s.strstart - s.match_start > 4096/*TOO_FAR*/))) {\n\n        /* If prev_match is also MIN_MATCH, match_start is garbage\n         * but we will ignore the current match anyway.\n         */\n        s.match_length = MIN_MATCH - 1;\n      }\n    }\n    /* If there was a match at the previous step and the current\n     * match is not better, output the previous match:\n     */\n    if (s.prev_length >= MIN_MATCH && s.match_length <= s.prev_length) {\n      max_insert = s.strstart + s.lookahead - MIN_MATCH;\n      /* Do not insert strings in hash table beyond this. */\n\n      //check_match(s, s.strstart-1, s.prev_match, s.prev_length);\n\n      /***_tr_tally_dist(s, s.strstart - 1 - s.prev_match,\n                     s.prev_length - MIN_MATCH, bflush);***/\n      bflush = _tr_tally(s, s.strstart - 1 - s.prev_match, s.prev_length - MIN_MATCH);\n      /* Insert in hash table all strings up to the end of the match.\n       * strstart-1 and strstart are already inserted. If there is not\n       * enough lookahead, the last two strings are not inserted in\n       * the hash table.\n       */\n      s.lookahead -= s.prev_length - 1;\n      s.prev_length -= 2;\n      do {\n        if (++s.strstart <= max_insert) {\n          /*** INSERT_STRING(s, s.strstart, hash_head); ***/\n          s.ins_h = HASH(s, s.ins_h, s.window[s.strstart + MIN_MATCH - 1]);\n          hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];\n          s.head[s.ins_h] = s.strstart;\n          /***/\n        }\n      } while (--s.prev_length !== 0);\n      s.match_available = 0;\n      s.match_length = MIN_MATCH - 1;\n      s.strstart++;\n\n      if (bflush) {\n        /*** FLUSH_BLOCK(s, 0); ***/\n        flush_block_only(s, false);\n        if (s.strm.avail_out === 0) {\n          return BS_NEED_MORE;\n        }\n        /***/\n      }\n\n    } else if (s.match_available) {\n      /* If there was no match at the previous position, output a\n       * single literal. If there was a match but the current match\n       * is longer, truncate the previous match to a single literal.\n       */\n      //Tracevv((stderr,\"%c\", s->window[s->strstart-1]));\n      /*** _tr_tally_lit(s, s.window[s.strstart-1], bflush); ***/\n      bflush = _tr_tally(s, 0, s.window[s.strstart - 1]);\n\n      if (bflush) {\n        /*** FLUSH_BLOCK_ONLY(s, 0) ***/\n        flush_block_only(s, false);\n        /***/\n      }\n      s.strstart++;\n      s.lookahead--;\n      if (s.strm.avail_out === 0) {\n        return BS_NEED_MORE;\n      }\n    } else {\n      /* There is no previous match to compare with, wait for\n       * the next step to decide.\n       */\n      s.match_available = 1;\n      s.strstart++;\n      s.lookahead--;\n    }\n  }\n  //Assert (flush != Z_NO_FLUSH, \"no flush?\");\n  if (s.match_available) {\n    //Tracevv((stderr,\"%c\", s->window[s->strstart-1]));\n    /*** _tr_tally_lit(s, s.window[s.strstart-1], bflush); ***/\n    bflush = _tr_tally(s, 0, s.window[s.strstart - 1]);\n\n    s.match_available = 0;\n  }\n  s.insert = s.strstart < MIN_MATCH - 1 ? s.strstart : MIN_MATCH - 1;\n  if (flush === Z_FINISH$3) {\n    /*** FLUSH_BLOCK(s, 1); ***/\n    flush_block_only(s, true);\n    if (s.strm.avail_out === 0) {\n      return BS_FINISH_STARTED;\n    }\n    /***/\n    return BS_FINISH_DONE;\n  }\n  if (s.sym_next) {\n    /*** FLUSH_BLOCK(s, 0); ***/\n    flush_block_only(s, false);\n    if (s.strm.avail_out === 0) {\n      return BS_NEED_MORE;\n    }\n    /***/\n  }\n\n  return BS_BLOCK_DONE;\n};\n\n\n/* ===========================================================================\n * For Z_RLE, simply look for runs of bytes, generate matches only of distance\n * one.  Do not maintain a hash table.  (It will be regenerated if this run of\n * deflate switches away from Z_RLE.)\n */\nconst deflate_rle = (s, flush) => {\n\n  let bflush;            /* set if current block must be flushed */\n  let prev;              /* byte at distance one to match */\n  let scan, strend;      /* scan goes up to strend for length of run */\n\n  const _win = s.window;\n\n  for (;;) {\n    /* Make sure that we always have enough lookahead, except\n     * at the end of the input file. We need MAX_MATCH bytes\n     * for the longest run, plus one for the unrolled loop.\n     */\n    if (s.lookahead <= MAX_MATCH) {\n      fill_window(s);\n      if (s.lookahead <= MAX_MATCH && flush === Z_NO_FLUSH$2) {\n        return BS_NEED_MORE;\n      }\n      if (s.lookahead === 0) { break; } /* flush the current block */\n    }\n\n    /* See how many times the previous byte repeats */\n    s.match_length = 0;\n    if (s.lookahead >= MIN_MATCH && s.strstart > 0) {\n      scan = s.strstart - 1;\n      prev = _win[scan];\n      if (prev === _win[++scan] && prev === _win[++scan] && prev === _win[++scan]) {\n        strend = s.strstart + MAX_MATCH;\n        do {\n          /*jshint noempty:false*/\n        } while (prev === _win[++scan] && prev === _win[++scan] &&\n                 prev === _win[++scan] && prev === _win[++scan] &&\n                 prev === _win[++scan] && prev === _win[++scan] &&\n                 prev === _win[++scan] && prev === _win[++scan] &&\n                 scan < strend);\n        s.match_length = MAX_MATCH - (strend - scan);\n        if (s.match_length > s.lookahead) {\n          s.match_length = s.lookahead;\n        }\n      }\n      //Assert(scan <= s->window+(uInt)(s->window_size-1), \"wild scan\");\n    }\n\n    /* Emit match if have run of MIN_MATCH or longer, else emit literal */\n    if (s.match_length >= MIN_MATCH) {\n      //check_match(s, s.strstart, s.strstart - 1, s.match_length);\n\n      /*** _tr_tally_dist(s, 1, s.match_length - MIN_MATCH, bflush); ***/\n      bflush = _tr_tally(s, 1, s.match_length - MIN_MATCH);\n\n      s.lookahead -= s.match_length;\n      s.strstart += s.match_length;\n      s.match_length = 0;\n    } else {\n      /* No match, output a literal byte */\n      //Tracevv((stderr,\"%c\", s->window[s->strstart]));\n      /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/\n      bflush = _tr_tally(s, 0, s.window[s.strstart]);\n\n      s.lookahead--;\n      s.strstart++;\n    }\n    if (bflush) {\n      /*** FLUSH_BLOCK(s, 0); ***/\n      flush_block_only(s, false);\n      if (s.strm.avail_out === 0) {\n        return BS_NEED_MORE;\n      }\n      /***/\n    }\n  }\n  s.insert = 0;\n  if (flush === Z_FINISH$3) {\n    /*** FLUSH_BLOCK(s, 1); ***/\n    flush_block_only(s, true);\n    if (s.strm.avail_out === 0) {\n      return BS_FINISH_STARTED;\n    }\n    /***/\n    return BS_FINISH_DONE;\n  }\n  if (s.sym_next) {\n    /*** FLUSH_BLOCK(s, 0); ***/\n    flush_block_only(s, false);\n    if (s.strm.avail_out === 0) {\n      return BS_NEED_MORE;\n    }\n    /***/\n  }\n  return BS_BLOCK_DONE;\n};\n\n/* ===========================================================================\n * For Z_HUFFMAN_ONLY, do not look for matches.  Do not maintain a hash table.\n * (It will be regenerated if this run of deflate switches away from Huffman.)\n */\nconst deflate_huff = (s, flush) => {\n\n  let bflush;             /* set if current block must be flushed */\n\n  for (;;) {\n    /* Make sure that we have a literal to write. */\n    if (s.lookahead === 0) {\n      fill_window(s);\n      if (s.lookahead === 0) {\n        if (flush === Z_NO_FLUSH$2) {\n          return BS_NEED_MORE;\n        }\n        break;      /* flush the current block */\n      }\n    }\n\n    /* Output a literal byte */\n    s.match_length = 0;\n    //Tracevv((stderr,\"%c\", s->window[s->strstart]));\n    /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/\n    bflush = _tr_tally(s, 0, s.window[s.strstart]);\n    s.lookahead--;\n    s.strstart++;\n    if (bflush) {\n      /*** FLUSH_BLOCK(s, 0); ***/\n      flush_block_only(s, false);\n      if (s.strm.avail_out === 0) {\n        return BS_NEED_MORE;\n      }\n      /***/\n    }\n  }\n  s.insert = 0;\n  if (flush === Z_FINISH$3) {\n    /*** FLUSH_BLOCK(s, 1); ***/\n    flush_block_only(s, true);\n    if (s.strm.avail_out === 0) {\n      return BS_FINISH_STARTED;\n    }\n    /***/\n    return BS_FINISH_DONE;\n  }\n  if (s.sym_next) {\n    /*** FLUSH_BLOCK(s, 0); ***/\n    flush_block_only(s, false);\n    if (s.strm.avail_out === 0) {\n      return BS_NEED_MORE;\n    }\n    /***/\n  }\n  return BS_BLOCK_DONE;\n};\n\n/* Values for max_lazy_match, good_match and max_chain_length, depending on\n * the desired pack level (0..9). The values given below have been tuned to\n * exclude worst case performance for pathological files. Better values may be\n * found for specific files.\n */\nfunction Config(good_length, max_lazy, nice_length, max_chain, func) {\n\n  this.good_length = good_length;\n  this.max_lazy = max_lazy;\n  this.nice_length = nice_length;\n  this.max_chain = max_chain;\n  this.func = func;\n}\n\nconst configuration_table = [\n  /*      good lazy nice chain */\n  new Config(0, 0, 0, 0, deflate_stored),          /* 0 store only */\n  new Config(4, 4, 8, 4, deflate_fast),            /* 1 max speed, no lazy matches */\n  new Config(4, 5, 16, 8, deflate_fast),           /* 2 */\n  new Config(4, 6, 32, 32, deflate_fast),          /* 3 */\n\n  new Config(4, 4, 16, 16, deflate_slow),          /* 4 lazy matches */\n  new Config(8, 16, 32, 32, deflate_slow),         /* 5 */\n  new Config(8, 16, 128, 128, deflate_slow),       /* 6 */\n  new Config(8, 32, 128, 256, deflate_slow),       /* 7 */\n  new Config(32, 128, 258, 1024, deflate_slow),    /* 8 */\n  new Config(32, 258, 258, 4096, deflate_slow)     /* 9 max compression */\n];\n\n\n/* ===========================================================================\n * Initialize the \"longest match\" routines for a new zlib stream\n */\nconst lm_init = (s) => {\n\n  s.window_size = 2 * s.w_size;\n\n  /*** CLEAR_HASH(s); ***/\n  zero(s.head); // Fill with NIL (= 0);\n\n  /* Set the default configuration parameters:\n   */\n  s.max_lazy_match = configuration_table[s.level].max_lazy;\n  s.good_match = configuration_table[s.level].good_length;\n  s.nice_match = configuration_table[s.level].nice_length;\n  s.max_chain_length = configuration_table[s.level].max_chain;\n\n  s.strstart = 0;\n  s.block_start = 0;\n  s.lookahead = 0;\n  s.insert = 0;\n  s.match_length = s.prev_length = MIN_MATCH - 1;\n  s.match_available = 0;\n  s.ins_h = 0;\n};\n\n\nfunction DeflateState() {\n  this.strm = null;            /* pointer back to this zlib stream */\n  this.status = 0;            /* as the name implies */\n  this.pending_buf = null;      /* output still pending */\n  this.pending_buf_size = 0;  /* size of pending_buf */\n  this.pending_out = 0;       /* next pending byte to output to the stream */\n  this.pending = 0;           /* nb of bytes in the pending buffer */\n  this.wrap = 0;              /* bit 0 true for zlib, bit 1 true for gzip */\n  this.gzhead = null;         /* gzip header information to write */\n  this.gzindex = 0;           /* where in extra, name, or comment */\n  this.method = Z_DEFLATED$2; /* can only be DEFLATED */\n  this.last_flush = -1;   /* value of flush param for previous deflate call */\n\n  this.w_size = 0;  /* LZ77 window size (32K by default) */\n  this.w_bits = 0;  /* log2(w_size)  (8..16) */\n  this.w_mask = 0;  /* w_size - 1 */\n\n  this.window = null;\n  /* Sliding window. Input bytes are read into the second half of the window,\n   * and move to the first half later to keep a dictionary of at least wSize\n   * bytes. With this organization, matches are limited to a distance of\n   * wSize-MAX_MATCH bytes, but this ensures that IO is always\n   * performed with a length multiple of the block size.\n   */\n\n  this.window_size = 0;\n  /* Actual size of window: 2*wSize, except when the user input buffer\n   * is directly used as sliding window.\n   */\n\n  this.prev = null;\n  /* Link to older string with same hash index. To limit the size of this\n   * array to 64K, this link is maintained only for the last 32K strings.\n   * An index in this array is thus a window index modulo 32K.\n   */\n\n  this.head = null;   /* Heads of the hash chains or NIL. */\n\n  this.ins_h = 0;       /* hash index of string to be inserted */\n  this.hash_size = 0;   /* number of elements in hash table */\n  this.hash_bits = 0;   /* log2(hash_size) */\n  this.hash_mask = 0;   /* hash_size-1 */\n\n  this.hash_shift = 0;\n  /* Number of bits by which ins_h must be shifted at each input\n   * step. It must be such that after MIN_MATCH steps, the oldest\n   * byte no longer takes part in the hash key, that is:\n   *   hash_shift * MIN_MATCH >= hash_bits\n   */\n\n  this.block_start = 0;\n  /* Window position at the beginning of the current output block. Gets\n   * negative when the window is moved backwards.\n   */\n\n  this.match_length = 0;      /* length of best match */\n  this.prev_match = 0;        /* previous match */\n  this.match_available = 0;   /* set if previous match exists */\n  this.strstart = 0;          /* start of string to insert */\n  this.match_start = 0;       /* start of matching string */\n  this.lookahead = 0;         /* number of valid bytes ahead in window */\n\n  this.prev_length = 0;\n  /* Length of the best match at previous step. Matches not greater than this\n   * are discarded. This is used in the lazy match evaluation.\n   */\n\n  this.max_chain_length = 0;\n  /* To speed up deflation, hash chains are never searched beyond this\n   * length.  A higher limit improves compression ratio but degrades the\n   * speed.\n   */\n\n  this.max_lazy_match = 0;\n  /* Attempt to find a better match only when the current match is strictly\n   * smaller than this value. This mechanism is used only for compression\n   * levels >= 4.\n   */\n  // That's alias to max_lazy_match, don't use directly\n  //this.max_insert_length = 0;\n  /* Insert new strings in the hash table only if the match length is not\n   * greater than this length. This saves time but degrades compression.\n   * max_insert_length is used only for compression levels <= 3.\n   */\n\n  this.level = 0;     /* compression level (1..9) */\n  this.strategy = 0;  /* favor or force Huffman coding*/\n\n  this.good_match = 0;\n  /* Use a faster search when the previous match is longer than this */\n\n  this.nice_match = 0; /* Stop searching when current match exceeds this */\n\n              /* used by trees.c: */\n\n  /* Didn't use ct_data typedef below to suppress compiler warning */\n\n  // struct ct_data_s dyn_ltree[HEAP_SIZE];   /* literal and length tree */\n  // struct ct_data_s dyn_dtree[2*D_CODES+1]; /* distance tree */\n  // struct ct_data_s bl_tree[2*BL_CODES+1];  /* Huffman tree for bit lengths */\n\n  // Use flat array of DOUBLE size, with interleaved fata,\n  // because JS does not support effective\n  this.dyn_ltree  = new Uint16Array(HEAP_SIZE * 2);\n  this.dyn_dtree  = new Uint16Array((2 * D_CODES + 1) * 2);\n  this.bl_tree    = new Uint16Array((2 * BL_CODES + 1) * 2);\n  zero(this.dyn_ltree);\n  zero(this.dyn_dtree);\n  zero(this.bl_tree);\n\n  this.l_desc   = null;         /* desc. for literal tree */\n  this.d_desc   = null;         /* desc. for distance tree */\n  this.bl_desc  = null;         /* desc. for bit length tree */\n\n  //ush bl_count[MAX_BITS+1];\n  this.bl_count = new Uint16Array(MAX_BITS + 1);\n  /* number of codes at each bit length for an optimal tree */\n\n  //int heap[2*L_CODES+1];      /* heap used to build the Huffman trees */\n  this.heap = new Uint16Array(2 * L_CODES + 1);  /* heap used to build the Huffman trees */\n  zero(this.heap);\n\n  this.heap_len = 0;               /* number of elements in the heap */\n  this.heap_max = 0;               /* element of largest frequency */\n  /* The sons of heap[n] are heap[2*n] and heap[2*n+1]. heap[0] is not used.\n   * The same heap array is used to build all trees.\n   */\n\n  this.depth = new Uint16Array(2 * L_CODES + 1); //uch depth[2*L_CODES+1];\n  zero(this.depth);\n  /* Depth of each subtree used as tie breaker for trees of equal frequency\n   */\n\n  this.sym_buf = 0;        /* buffer for distances and literals/lengths */\n\n  this.lit_bufsize = 0;\n  /* Size of match buffer for literals/lengths.  There are 4 reasons for\n   * limiting lit_bufsize to 64K:\n   *   - frequencies can be kept in 16 bit counters\n   *   - if compression is not successful for the first block, all input\n   *     data is still in the window so we can still emit a stored block even\n   *     when input comes from standard input.  (This can also be done for\n   *     all blocks if lit_bufsize is not greater than 32K.)\n   *   - if compression is not successful for a file smaller than 64K, we can\n   *     even emit a stored file instead of a stored block (saving 5 bytes).\n   *     This is applicable only for zip (not gzip or zlib).\n   *   - creating new Huffman trees less frequently may not provide fast\n   *     adaptation to changes in the input data statistics. (Take for\n   *     example a binary file with poorly compressible code followed by\n   *     a highly compressible string table.) Smaller buffer sizes give\n   *     fast adaptation but have of course the overhead of transmitting\n   *     trees more frequently.\n   *   - I can't count above 4\n   */\n\n  this.sym_next = 0;      /* running index in sym_buf */\n  this.sym_end = 0;       /* symbol table full when sym_next reaches this */\n\n  this.opt_len = 0;       /* bit length of current block with optimal trees */\n  this.static_len = 0;    /* bit length of current block with static trees */\n  this.matches = 0;       /* number of string matches in current block */\n  this.insert = 0;        /* bytes at end of window left to insert */\n\n\n  this.bi_buf = 0;\n  /* Output buffer. bits are inserted starting at the bottom (least\n   * significant bits).\n   */\n  this.bi_valid = 0;\n  /* Number of valid bits in bi_buf.  All bits above the last valid bit\n   * are always zero.\n   */\n\n  // Used for window memory init. We safely ignore it for JS. That makes\n  // sense only for pointers and memory check tools.\n  //this.high_water = 0;\n  /* High water mark offset in window for initialized bytes -- bytes above\n   * this are set to zero in order to avoid memory check warnings when\n   * longest match routines access bytes past the input.  This is then\n   * updated to the new high water mark.\n   */\n}\n\n\n/* =========================================================================\n * Check for a valid deflate stream state. Return 0 if ok, 1 if not.\n */\nconst deflateStateCheck = (strm) => {\n\n  if (!strm) {\n    return 1;\n  }\n  const s = strm.state;\n  if (!s || s.strm !== strm || (s.status !== INIT_STATE &&\n//#ifdef GZIP\n                                s.status !== GZIP_STATE &&\n//#endif\n                                s.status !== EXTRA_STATE &&\n                                s.status !== NAME_STATE &&\n                                s.status !== COMMENT_STATE &&\n                                s.status !== HCRC_STATE &&\n                                s.status !== BUSY_STATE &&\n                                s.status !== FINISH_STATE)) {\n    return 1;\n  }\n  return 0;\n};\n\n\nconst deflateResetKeep = (strm) => {\n\n  if (deflateStateCheck(strm)) {\n    return err(strm, Z_STREAM_ERROR$2);\n  }\n\n  strm.total_in = strm.total_out = 0;\n  strm.data_type = Z_UNKNOWN;\n\n  const s = strm.state;\n  s.pending = 0;\n  s.pending_out = 0;\n\n  if (s.wrap < 0) {\n    s.wrap = -s.wrap;\n    /* was made negative by deflate(..., Z_FINISH); */\n  }\n  s.status =\n//#ifdef GZIP\n    s.wrap === 2 ? GZIP_STATE :\n//#endif\n    s.wrap ? INIT_STATE : BUSY_STATE;\n  strm.adler = (s.wrap === 2) ?\n    0  // crc32(0, Z_NULL, 0)\n  :\n    1; // adler32(0, Z_NULL, 0)\n  s.last_flush = -2;\n  _tr_init(s);\n  return Z_OK$3;\n};\n\n\nconst deflateReset = (strm) => {\n\n  const ret = deflateResetKeep(strm);\n  if (ret === Z_OK$3) {\n    lm_init(strm.state);\n  }\n  return ret;\n};\n\n\nconst deflateSetHeader = (strm, head) => {\n\n  if (deflateStateCheck(strm) || strm.state.wrap !== 2) {\n    return Z_STREAM_ERROR$2;\n  }\n  strm.state.gzhead = head;\n  return Z_OK$3;\n};\n\n\nconst deflateInit2 = (strm, level, method, windowBits, memLevel, strategy) => {\n\n  if (!strm) { // === Z_NULL\n    return Z_STREAM_ERROR$2;\n  }\n  let wrap = 1;\n\n  if (level === Z_DEFAULT_COMPRESSION$1) {\n    level = 6;\n  }\n\n  if (windowBits < 0) { /* suppress zlib wrapper */\n    wrap = 0;\n    windowBits = -windowBits;\n  }\n\n  else if (windowBits > 15) {\n    wrap = 2;           /* write gzip wrapper instead */\n    windowBits -= 16;\n  }\n\n\n  if (memLevel < 1 || memLevel > MAX_MEM_LEVEL || method !== Z_DEFLATED$2 ||\n    windowBits < 8 || windowBits > 15 || level < 0 || level > 9 ||\n    strategy < 0 || strategy > Z_FIXED || (windowBits === 8 && wrap !== 1)) {\n    return err(strm, Z_STREAM_ERROR$2);\n  }\n\n\n  if (windowBits === 8) {\n    windowBits = 9;\n  }\n  /* until 256-byte window bug fixed */\n\n  const s = new DeflateState();\n\n  strm.state = s;\n  s.strm = strm;\n  s.status = INIT_STATE;     /* to pass state test in deflateReset() */\n\n  s.wrap = wrap;\n  s.gzhead = null;\n  s.w_bits = windowBits;\n  s.w_size = 1 << s.w_bits;\n  s.w_mask = s.w_size - 1;\n\n  s.hash_bits = memLevel + 7;\n  s.hash_size = 1 << s.hash_bits;\n  s.hash_mask = s.hash_size - 1;\n  s.hash_shift = ~~((s.hash_bits + MIN_MATCH - 1) / MIN_MATCH);\n\n  s.window = new Uint8Array(s.w_size * 2);\n  s.head = new Uint16Array(s.hash_size);\n  s.prev = new Uint16Array(s.w_size);\n\n  // Don't need mem init magic for JS.\n  //s.high_water = 0;  /* nothing written to s->window yet */\n\n  s.lit_bufsize = 1 << (memLevel + 6); /* 16K elements by default */\n\n  /* We overlay pending_buf and sym_buf. This works since the average size\n   * for length/distance pairs over any compressed block is assured to be 31\n   * bits or less.\n   *\n   * Analysis: The longest fixed codes are a length code of 8 bits plus 5\n   * extra bits, for lengths 131 to 257. The longest fixed distance codes are\n   * 5 bits plus 13 extra bits, for distances 16385 to 32768. The longest\n   * possible fixed-codes length/distance pair is then 31 bits total.\n   *\n   * sym_buf starts one-fourth of the way into pending_buf. So there are\n   * three bytes in sym_buf for every four bytes in pending_buf. Each symbol\n   * in sym_buf is three bytes -- two for the distance and one for the\n   * literal/length. As each symbol is consumed, the pointer to the next\n   * sym_buf value to read moves forward three bytes. From that symbol, up to\n   * 31 bits are written to pending_buf. The closest the written pending_buf\n   * bits gets to the next sym_buf symbol to read is just before the last\n   * code is written. At that time, 31*(n-2) bits have been written, just\n   * after 24*(n-2) bits have been consumed from sym_buf. sym_buf starts at\n   * 8*n bits into pending_buf. (Note that the symbol buffer fills when n-1\n   * symbols are written.) The closest the writing gets to what is unread is\n   * then n+14 bits. Here n is lit_bufsize, which is 16384 by default, and\n   * can range from 128 to 32768.\n   *\n   * Therefore, at a minimum, there are 142 bits of space between what is\n   * written and what is read in the overlain buffers, so the symbols cannot\n   * be overwritten by the compressed data. That space is actually 139 bits,\n   * due to the three-bit fixed-code block header.\n   *\n   * That covers the case where either Z_FIXED is specified, forcing fixed\n   * codes, or when the use of fixed codes is chosen, because that choice\n   * results in a smaller compressed block than dynamic codes. That latter\n   * condition then assures that the above analysis also covers all dynamic\n   * blocks. A dynamic-code block will only be chosen to be emitted if it has\n   * fewer bits than a fixed-code block would for the same set of symbols.\n   * Therefore its average symbol length is assured to be less than 31. So\n   * the compressed data for a dynamic block also cannot overwrite the\n   * symbols from which it is being constructed.\n   */\n\n  s.pending_buf_size = s.lit_bufsize * 4;\n  s.pending_buf = new Uint8Array(s.pending_buf_size);\n\n  // It is offset from `s.pending_buf` (size is `s.lit_bufsize * 2`)\n  //s->sym_buf = s->pending_buf + s->lit_bufsize;\n  s.sym_buf = s.lit_bufsize;\n\n  //s->sym_end = (s->lit_bufsize - 1) * 3;\n  s.sym_end = (s.lit_bufsize - 1) * 3;\n  /* We avoid equality with lit_bufsize*3 because of wraparound at 64K\n   * on 16 bit machines and because stored blocks are restricted to\n   * 64K-1 bytes.\n   */\n\n  s.level = level;\n  s.strategy = strategy;\n  s.method = method;\n\n  return deflateReset(strm);\n};\n\nconst deflateInit = (strm, level) => {\n\n  return deflateInit2(strm, level, Z_DEFLATED$2, MAX_WBITS$1, DEF_MEM_LEVEL, Z_DEFAULT_STRATEGY$1);\n};\n\n\n/* ========================================================================= */\nconst deflate$2 = (strm, flush) => {\n\n  if (deflateStateCheck(strm) || flush > Z_BLOCK$1 || flush < 0) {\n    return strm ? err(strm, Z_STREAM_ERROR$2) : Z_STREAM_ERROR$2;\n  }\n\n  const s = strm.state;\n\n  if (!strm.output ||\n      (strm.avail_in !== 0 && !strm.input) ||\n      (s.status === FINISH_STATE && flush !== Z_FINISH$3)) {\n    return err(strm, (strm.avail_out === 0) ? Z_BUF_ERROR$1 : Z_STREAM_ERROR$2);\n  }\n\n  const old_flush = s.last_flush;\n  s.last_flush = flush;\n\n  /* Flush as much pending output as possible */\n  if (s.pending !== 0) {\n    flush_pending(strm);\n    if (strm.avail_out === 0) {\n      /* Since avail_out is 0, deflate will be called again with\n       * more output space, but possibly with both pending and\n       * avail_in equal to zero. There won't be anything to do,\n       * but this is not an error situation so make sure we\n       * return OK instead of BUF_ERROR at next call of deflate:\n       */\n      s.last_flush = -1;\n      return Z_OK$3;\n    }\n\n    /* Make sure there is something to do and avoid duplicate consecutive\n     * flushes. For repeated and useless calls with Z_FINISH, we keep\n     * returning Z_STREAM_END instead of Z_BUF_ERROR.\n     */\n  } else if (strm.avail_in === 0 && rank(flush) <= rank(old_flush) &&\n    flush !== Z_FINISH$3) {\n    return err(strm, Z_BUF_ERROR$1);\n  }\n\n  /* User must not provide more input after the first FINISH: */\n  if (s.status === FINISH_STATE && strm.avail_in !== 0) {\n    return err(strm, Z_BUF_ERROR$1);\n  }\n\n  /* Write the header */\n  if (s.status === INIT_STATE && s.wrap === 0) {\n    s.status = BUSY_STATE;\n  }\n  if (s.status === INIT_STATE) {\n    /* zlib header */\n    let header = (Z_DEFLATED$2 + ((s.w_bits - 8) << 4)) << 8;\n    let level_flags = -1;\n\n    if (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2) {\n      level_flags = 0;\n    } else if (s.level < 6) {\n      level_flags = 1;\n    } else if (s.level === 6) {\n      level_flags = 2;\n    } else {\n      level_flags = 3;\n    }\n    header |= (level_flags << 6);\n    if (s.strstart !== 0) { header |= PRESET_DICT; }\n    header += 31 - (header % 31);\n\n    putShortMSB(s, header);\n\n    /* Save the adler32 of the preset dictionary: */\n    if (s.strstart !== 0) {\n      putShortMSB(s, strm.adler >>> 16);\n      putShortMSB(s, strm.adler & 0xffff);\n    }\n    strm.adler = 1; // adler32(0L, Z_NULL, 0);\n    s.status = BUSY_STATE;\n\n    /* Compression must start with an empty pending buffer */\n    flush_pending(strm);\n    if (s.pending !== 0) {\n      s.last_flush = -1;\n      return Z_OK$3;\n    }\n  }\n//#ifdef GZIP\n  if (s.status === GZIP_STATE) {\n    /* gzip header */\n    strm.adler = 0;  //crc32(0L, Z_NULL, 0);\n    put_byte(s, 31);\n    put_byte(s, 139);\n    put_byte(s, 8);\n    if (!s.gzhead) { // s->gzhead == Z_NULL\n      put_byte(s, 0);\n      put_byte(s, 0);\n      put_byte(s, 0);\n      put_byte(s, 0);\n      put_byte(s, 0);\n      put_byte(s, s.level === 9 ? 2 :\n                  (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2 ?\n                   4 : 0));\n      put_byte(s, OS_CODE);\n      s.status = BUSY_STATE;\n\n      /* Compression must start with an empty pending buffer */\n      flush_pending(strm);\n      if (s.pending !== 0) {\n        s.last_flush = -1;\n        return Z_OK$3;\n      }\n    }\n    else {\n      put_byte(s, (s.gzhead.text ? 1 : 0) +\n                  (s.gzhead.hcrc ? 2 : 0) +\n                  (!s.gzhead.extra ? 0 : 4) +\n                  (!s.gzhead.name ? 0 : 8) +\n                  (!s.gzhead.comment ? 0 : 16)\n      );\n      put_byte(s, s.gzhead.time & 0xff);\n      put_byte(s, (s.gzhead.time >> 8) & 0xff);\n      put_byte(s, (s.gzhead.time >> 16) & 0xff);\n      put_byte(s, (s.gzhead.time >> 24) & 0xff);\n      put_byte(s, s.level === 9 ? 2 :\n                  (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2 ?\n                   4 : 0));\n      put_byte(s, s.gzhead.os & 0xff);\n      if (s.gzhead.extra && s.gzhead.extra.length) {\n        put_byte(s, s.gzhead.extra.length & 0xff);\n        put_byte(s, (s.gzhead.extra.length >> 8) & 0xff);\n      }\n      if (s.gzhead.hcrc) {\n        strm.adler = crc32_1(strm.adler, s.pending_buf, s.pending, 0);\n      }\n      s.gzindex = 0;\n      s.status = EXTRA_STATE;\n    }\n  }\n  if (s.status === EXTRA_STATE) {\n    if (s.gzhead.extra/* != Z_NULL*/) {\n      let beg = s.pending;   /* start of bytes to update crc */\n      let left = (s.gzhead.extra.length & 0xffff) - s.gzindex;\n      while (s.pending + left > s.pending_buf_size) {\n        let copy = s.pending_buf_size - s.pending;\n        // zmemcpy(s.pending_buf + s.pending,\n        //    s.gzhead.extra + s.gzindex, copy);\n        s.pending_buf.set(s.gzhead.extra.subarray(s.gzindex, s.gzindex + copy), s.pending);\n        s.pending = s.pending_buf_size;\n        //--- HCRC_UPDATE(beg) ---//\n        if (s.gzhead.hcrc && s.pending > beg) {\n          strm.adler = crc32_1(strm.adler, s.pending_buf, s.pending - beg, beg);\n        }\n        //---//\n        s.gzindex += copy;\n        flush_pending(strm);\n        if (s.pending !== 0) {\n          s.last_flush = -1;\n          return Z_OK$3;\n        }\n        beg = 0;\n        left -= copy;\n      }\n      // JS specific: s.gzhead.extra may be TypedArray or Array for backward compatibility\n      //              TypedArray.slice and TypedArray.from don't exist in IE10-IE11\n      let gzhead_extra = new Uint8Array(s.gzhead.extra);\n      // zmemcpy(s->pending_buf + s->pending,\n      //     s->gzhead->extra + s->gzindex, left);\n      s.pending_buf.set(gzhead_extra.subarray(s.gzindex, s.gzindex + left), s.pending);\n      s.pending += left;\n      //--- HCRC_UPDATE(beg) ---//\n      if (s.gzhead.hcrc && s.pending > beg) {\n        strm.adler = crc32_1(strm.adler, s.pending_buf, s.pending - beg, beg);\n      }\n      //---//\n      s.gzindex = 0;\n    }\n    s.status = NAME_STATE;\n  }\n  if (s.status === NAME_STATE) {\n    if (s.gzhead.name/* != Z_NULL*/) {\n      let beg = s.pending;   /* start of bytes to update crc */\n      let val;\n      do {\n        if (s.pending === s.pending_buf_size) {\n          //--- HCRC_UPDATE(beg) ---//\n          if (s.gzhead.hcrc && s.pending > beg) {\n            strm.adler = crc32_1(strm.adler, s.pending_buf, s.pending - beg, beg);\n          }\n          //---//\n          flush_pending(strm);\n          if (s.pending !== 0) {\n            s.last_flush = -1;\n            return Z_OK$3;\n          }\n          beg = 0;\n        }\n        // JS specific: little magic to add zero terminator to end of string\n        if (s.gzindex < s.gzhead.name.length) {\n          val = s.gzhead.name.charCodeAt(s.gzindex++) & 0xff;\n        } else {\n          val = 0;\n        }\n        put_byte(s, val);\n      } while (val !== 0);\n      //--- HCRC_UPDATE(beg) ---//\n      if (s.gzhead.hcrc && s.pending > beg) {\n        strm.adler = crc32_1(strm.adler, s.pending_buf, s.pending - beg, beg);\n      }\n      //---//\n      s.gzindex = 0;\n    }\n    s.status = COMMENT_STATE;\n  }\n  if (s.status === COMMENT_STATE) {\n    if (s.gzhead.comment/* != Z_NULL*/) {\n      let beg = s.pending;   /* start of bytes to update crc */\n      let val;\n      do {\n        if (s.pending === s.pending_buf_size) {\n          //--- HCRC_UPDATE(beg) ---//\n          if (s.gzhead.hcrc && s.pending > beg) {\n            strm.adler = crc32_1(strm.adler, s.pending_buf, s.pending - beg, beg);\n          }\n          //---//\n          flush_pending(strm);\n          if (s.pending !== 0) {\n            s.last_flush = -1;\n            return Z_OK$3;\n          }\n          beg = 0;\n        }\n        // JS specific: little magic to add zero terminator to end of string\n        if (s.gzindex < s.gzhead.comment.length) {\n          val = s.gzhead.comment.charCodeAt(s.gzindex++) & 0xff;\n        } else {\n          val = 0;\n        }\n        put_byte(s, val);\n      } while (val !== 0);\n      //--- HCRC_UPDATE(beg) ---//\n      if (s.gzhead.hcrc && s.pending > beg) {\n        strm.adler = crc32_1(strm.adler, s.pending_buf, s.pending - beg, beg);\n      }\n      //---//\n    }\n    s.status = HCRC_STATE;\n  }\n  if (s.status === HCRC_STATE) {\n    if (s.gzhead.hcrc) {\n      if (s.pending + 2 > s.pending_buf_size) {\n        flush_pending(strm);\n        if (s.pending !== 0) {\n          s.last_flush = -1;\n          return Z_OK$3;\n        }\n      }\n      put_byte(s, strm.adler & 0xff);\n      put_byte(s, (strm.adler >> 8) & 0xff);\n      strm.adler = 0; //crc32(0L, Z_NULL, 0);\n    }\n    s.status = BUSY_STATE;\n\n    /* Compression must start with an empty pending buffer */\n    flush_pending(strm);\n    if (s.pending !== 0) {\n      s.last_flush = -1;\n      return Z_OK$3;\n    }\n  }\n//#endif\n\n  /* Start a new block or continue the current one.\n   */\n  if (strm.avail_in !== 0 || s.lookahead !== 0 ||\n    (flush !== Z_NO_FLUSH$2 && s.status !== FINISH_STATE)) {\n    let bstate = s.level === 0 ? deflate_stored(s, flush) :\n                 s.strategy === Z_HUFFMAN_ONLY ? deflate_huff(s, flush) :\n                 s.strategy === Z_RLE ? deflate_rle(s, flush) :\n                 configuration_table[s.level].func(s, flush);\n\n    if (bstate === BS_FINISH_STARTED || bstate === BS_FINISH_DONE) {\n      s.status = FINISH_STATE;\n    }\n    if (bstate === BS_NEED_MORE || bstate === BS_FINISH_STARTED) {\n      if (strm.avail_out === 0) {\n        s.last_flush = -1;\n        /* avoid BUF_ERROR next call, see above */\n      }\n      return Z_OK$3;\n      /* If flush != Z_NO_FLUSH && avail_out == 0, the next call\n       * of deflate should use the same flush parameter to make sure\n       * that the flush is complete. So we don't have to output an\n       * empty block here, this will be done at next call. This also\n       * ensures that for a very small output buffer, we emit at most\n       * one empty block.\n       */\n    }\n    if (bstate === BS_BLOCK_DONE) {\n      if (flush === Z_PARTIAL_FLUSH) {\n        _tr_align(s);\n      }\n      else if (flush !== Z_BLOCK$1) { /* FULL_FLUSH or SYNC_FLUSH */\n\n        _tr_stored_block(s, 0, 0, false);\n        /* For a full flush, this empty block will be recognized\n         * as a special marker by inflate_sync().\n         */\n        if (flush === Z_FULL_FLUSH$1) {\n          /*** CLEAR_HASH(s); ***/             /* forget history */\n          zero(s.head); // Fill with NIL (= 0);\n\n          if (s.lookahead === 0) {\n            s.strstart = 0;\n            s.block_start = 0;\n            s.insert = 0;\n          }\n        }\n      }\n      flush_pending(strm);\n      if (strm.avail_out === 0) {\n        s.last_flush = -1; /* avoid BUF_ERROR at next call, see above */\n        return Z_OK$3;\n      }\n    }\n  }\n\n  if (flush !== Z_FINISH$3) { return Z_OK$3; }\n  if (s.wrap <= 0) { return Z_STREAM_END$3; }\n\n  /* Write the trailer */\n  if (s.wrap === 2) {\n    put_byte(s, strm.adler & 0xff);\n    put_byte(s, (strm.adler >> 8) & 0xff);\n    put_byte(s, (strm.adler >> 16) & 0xff);\n    put_byte(s, (strm.adler >> 24) & 0xff);\n    put_byte(s, strm.total_in & 0xff);\n    put_byte(s, (strm.total_in >> 8) & 0xff);\n    put_byte(s, (strm.total_in >> 16) & 0xff);\n    put_byte(s, (strm.total_in >> 24) & 0xff);\n  }\n  else\n  {\n    putShortMSB(s, strm.adler >>> 16);\n    putShortMSB(s, strm.adler & 0xffff);\n  }\n\n  flush_pending(strm);\n  /* If avail_out is zero, the application will call deflate again\n   * to flush the rest.\n   */\n  if (s.wrap > 0) { s.wrap = -s.wrap; }\n  /* write the trailer only once! */\n  return s.pending !== 0 ? Z_OK$3 : Z_STREAM_END$3;\n};\n\n\nconst deflateEnd = (strm) => {\n\n  if (deflateStateCheck(strm)) {\n    return Z_STREAM_ERROR$2;\n  }\n\n  const status = strm.state.status;\n\n  strm.state = null;\n\n  return status === BUSY_STATE ? err(strm, Z_DATA_ERROR$2) : Z_OK$3;\n};\n\n\n/* =========================================================================\n * Initializes the compression dictionary from the given byte\n * sequence without producing any compressed output.\n */\nconst deflateSetDictionary = (strm, dictionary) => {\n\n  let dictLength = dictionary.length;\n\n  if (deflateStateCheck(strm)) {\n    return Z_STREAM_ERROR$2;\n  }\n\n  const s = strm.state;\n  const wrap = s.wrap;\n\n  if (wrap === 2 || (wrap === 1 && s.status !== INIT_STATE) || s.lookahead) {\n    return Z_STREAM_ERROR$2;\n  }\n\n  /* when using zlib wrappers, compute Adler-32 for provided dictionary */\n  if (wrap === 1) {\n    /* adler32(strm->adler, dictionary, dictLength); */\n    strm.adler = adler32_1(strm.adler, dictionary, dictLength, 0);\n  }\n\n  s.wrap = 0;   /* avoid computing Adler-32 in read_buf */\n\n  /* if dictionary would fill window, just replace the history */\n  if (dictLength >= s.w_size) {\n    if (wrap === 0) {            /* already empty otherwise */\n      /*** CLEAR_HASH(s); ***/\n      zero(s.head); // Fill with NIL (= 0);\n      s.strstart = 0;\n      s.block_start = 0;\n      s.insert = 0;\n    }\n    /* use the tail */\n    // dictionary = dictionary.slice(dictLength - s.w_size);\n    let tmpDict = new Uint8Array(s.w_size);\n    tmpDict.set(dictionary.subarray(dictLength - s.w_size, dictLength), 0);\n    dictionary = tmpDict;\n    dictLength = s.w_size;\n  }\n  /* insert dictionary into window and hash */\n  const avail = strm.avail_in;\n  const next = strm.next_in;\n  const input = strm.input;\n  strm.avail_in = dictLength;\n  strm.next_in = 0;\n  strm.input = dictionary;\n  fill_window(s);\n  while (s.lookahead >= MIN_MATCH) {\n    let str = s.strstart;\n    let n = s.lookahead - (MIN_MATCH - 1);\n    do {\n      /* UPDATE_HASH(s, s->ins_h, s->window[str + MIN_MATCH-1]); */\n      s.ins_h = HASH(s, s.ins_h, s.window[str + MIN_MATCH - 1]);\n\n      s.prev[str & s.w_mask] = s.head[s.ins_h];\n\n      s.head[s.ins_h] = str;\n      str++;\n    } while (--n);\n    s.strstart = str;\n    s.lookahead = MIN_MATCH - 1;\n    fill_window(s);\n  }\n  s.strstart += s.lookahead;\n  s.block_start = s.strstart;\n  s.insert = s.lookahead;\n  s.lookahead = 0;\n  s.match_length = s.prev_length = MIN_MATCH - 1;\n  s.match_available = 0;\n  strm.next_in = next;\n  strm.input = input;\n  strm.avail_in = avail;\n  s.wrap = wrap;\n  return Z_OK$3;\n};\n\n\nvar deflateInit_1 = deflateInit;\nvar deflateInit2_1 = deflateInit2;\nvar deflateReset_1 = deflateReset;\nvar deflateResetKeep_1 = deflateResetKeep;\nvar deflateSetHeader_1 = deflateSetHeader;\nvar deflate_2$1 = deflate$2;\nvar deflateEnd_1 = deflateEnd;\nvar deflateSetDictionary_1 = deflateSetDictionary;\nvar deflateInfo = 'pako deflate (from Nodeca project)';\n\n/* Not implemented\nmodule.exports.deflateBound = deflateBound;\nmodule.exports.deflateCopy = deflateCopy;\nmodule.exports.deflateGetDictionary = deflateGetDictionary;\nmodule.exports.deflateParams = deflateParams;\nmodule.exports.deflatePending = deflatePending;\nmodule.exports.deflatePrime = deflatePrime;\nmodule.exports.deflateTune = deflateTune;\n*/\n\nvar deflate_1$2 = {\n\tdeflateInit: deflateInit_1,\n\tdeflateInit2: deflateInit2_1,\n\tdeflateReset: deflateReset_1,\n\tdeflateResetKeep: deflateResetKeep_1,\n\tdeflateSetHeader: deflateSetHeader_1,\n\tdeflate: deflate_2$1,\n\tdeflateEnd: deflateEnd_1,\n\tdeflateSetDictionary: deflateSetDictionary_1,\n\tdeflateInfo: deflateInfo\n};\n\nconst _has = (obj, key) => {\n  return Object.prototype.hasOwnProperty.call(obj, key);\n};\n\nvar assign = function (obj /*from1, from2, from3, ...*/) {\n  const sources = Array.prototype.slice.call(arguments, 1);\n  while (sources.length) {\n    const source = sources.shift();\n    if (!source) { continue; }\n\n    if (typeof source !== 'object') {\n      throw new TypeError(source + 'must be non-object');\n    }\n\n    for (const p in source) {\n      if (_has(source, p)) {\n        obj[p] = source[p];\n      }\n    }\n  }\n\n  return obj;\n};\n\n\n// Join array of chunks to single array.\nvar flattenChunks = (chunks) => {\n  // calculate data length\n  let len = 0;\n\n  for (let i = 0, l = chunks.length; i < l; i++) {\n    len += chunks[i].length;\n  }\n\n  // join chunks\n  const result = new Uint8Array(len);\n\n  for (let i = 0, pos = 0, l = chunks.length; i < l; i++) {\n    let chunk = chunks[i];\n    result.set(chunk, pos);\n    pos += chunk.length;\n  }\n\n  return result;\n};\n\nvar common = {\n\tassign: assign,\n\tflattenChunks: flattenChunks\n};\n\n// String encode/decode helpers\n\n\n// Quick check if we can use fast array to bin string conversion\n//\n// - apply(Array) can fail on Android 2.2\n// - apply(Uint8Array) can fail on iOS 5.1 Safari\n//\nlet STR_APPLY_UIA_OK = true;\n\ntry { String.fromCharCode.apply(null, new Uint8Array(1)); } catch (__) { STR_APPLY_UIA_OK = false; }\n\n\n// Table with utf8 lengths (calculated by first byte of sequence)\n// Note, that 5 & 6-byte values and some 4-byte values can not be represented in JS,\n// because max possible codepoint is 0x10ffff\nconst _utf8len = new Uint8Array(256);\nfor (let q = 0; q < 256; q++) {\n  _utf8len[q] = (q >= 252 ? 6 : q >= 248 ? 5 : q >= 240 ? 4 : q >= 224 ? 3 : q >= 192 ? 2 : 1);\n}\n_utf8len[254] = _utf8len[254] = 1; // Invalid sequence start\n\n\n// convert string to array (typed, when possible)\nvar string2buf = (str) => {\n  if (typeof TextEncoder === 'function' && TextEncoder.prototype.encode) {\n    return new TextEncoder().encode(str);\n  }\n\n  let buf, c, c2, m_pos, i, str_len = str.length, buf_len = 0;\n\n  // count binary size\n  for (m_pos = 0; m_pos < str_len; m_pos++) {\n    c = str.charCodeAt(m_pos);\n    if ((c & 0xfc00) === 0xd800 && (m_pos + 1 < str_len)) {\n      c2 = str.charCodeAt(m_pos + 1);\n      if ((c2 & 0xfc00) === 0xdc00) {\n        c = 0x10000 + ((c - 0xd800) << 10) + (c2 - 0xdc00);\n        m_pos++;\n      }\n    }\n    buf_len += c < 0x80 ? 1 : c < 0x800 ? 2 : c < 0x10000 ? 3 : 4;\n  }\n\n  // allocate buffer\n  buf = new Uint8Array(buf_len);\n\n  // convert\n  for (i = 0, m_pos = 0; i < buf_len; m_pos++) {\n    c = str.charCodeAt(m_pos);\n    if ((c & 0xfc00) === 0xd800 && (m_pos + 1 < str_len)) {\n      c2 = str.charCodeAt(m_pos + 1);\n      if ((c2 & 0xfc00) === 0xdc00) {\n        c = 0x10000 + ((c - 0xd800) << 10) + (c2 - 0xdc00);\n        m_pos++;\n      }\n    }\n    if (c < 0x80) {\n      /* one byte */\n      buf[i++] = c;\n    } else if (c < 0x800) {\n      /* two bytes */\n      buf[i++] = 0xC0 | (c >>> 6);\n      buf[i++] = 0x80 | (c & 0x3f);\n    } else if (c < 0x10000) {\n      /* three bytes */\n      buf[i++] = 0xE0 | (c >>> 12);\n      buf[i++] = 0x80 | (c >>> 6 & 0x3f);\n      buf[i++] = 0x80 | (c & 0x3f);\n    } else {\n      /* four bytes */\n      buf[i++] = 0xf0 | (c >>> 18);\n      buf[i++] = 0x80 | (c >>> 12 & 0x3f);\n      buf[i++] = 0x80 | (c >>> 6 & 0x3f);\n      buf[i++] = 0x80 | (c & 0x3f);\n    }\n  }\n\n  return buf;\n};\n\n// Helper\nconst buf2binstring = (buf, len) => {\n  // On Chrome, the arguments in a function call that are allowed is `65534`.\n  // If the length of the buffer is smaller than that, we can use this optimization,\n  // otherwise we will take a slower path.\n  if (len < 65534) {\n    if (buf.subarray && STR_APPLY_UIA_OK) {\n      return String.fromCharCode.apply(null, buf.length === len ? buf : buf.subarray(0, len));\n    }\n  }\n\n  let result = '';\n  for (let i = 0; i < len; i++) {\n    result += String.fromCharCode(buf[i]);\n  }\n  return result;\n};\n\n\n// convert array to string\nvar buf2string = (buf, max) => {\n  const len = max || buf.length;\n\n  if (typeof TextDecoder === 'function' && TextDecoder.prototype.decode) {\n    return new TextDecoder().decode(buf.subarray(0, max));\n  }\n\n  let i, out;\n\n  // Reserve max possible length (2 words per char)\n  // NB: by unknown reasons, Array is significantly faster for\n  //     String.fromCharCode.apply than Uint16Array.\n  const utf16buf = new Array(len * 2);\n\n  for (out = 0, i = 0; i < len;) {\n    let c = buf[i++];\n    // quick process ascii\n    if (c < 0x80) { utf16buf[out++] = c; continue; }\n\n    let c_len = _utf8len[c];\n    // skip 5 & 6 byte codes\n    if (c_len > 4) { utf16buf[out++] = 0xfffd; i += c_len - 1; continue; }\n\n    // apply mask on first byte\n    c &= c_len === 2 ? 0x1f : c_len === 3 ? 0x0f : 0x07;\n    // join the rest\n    while (c_len > 1 && i < len) {\n      c = (c << 6) | (buf[i++] & 0x3f);\n      c_len--;\n    }\n\n    // terminated by end of string?\n    if (c_len > 1) { utf16buf[out++] = 0xfffd; continue; }\n\n    if (c < 0x10000) {\n      utf16buf[out++] = c;\n    } else {\n      c -= 0x10000;\n      utf16buf[out++] = 0xd800 | ((c >> 10) & 0x3ff);\n      utf16buf[out++] = 0xdc00 | (c & 0x3ff);\n    }\n  }\n\n  return buf2binstring(utf16buf, out);\n};\n\n\n// Calculate max possible position in utf8 buffer,\n// that will not break sequence. If that's not possible\n// - (very small limits) return max size as is.\n//\n// buf[] - utf8 bytes array\n// max   - length limit (mandatory);\nvar utf8border = (buf, max) => {\n\n  max = max || buf.length;\n  if (max > buf.length) { max = buf.length; }\n\n  // go back from last position, until start of sequence found\n  let pos = max - 1;\n  while (pos >= 0 && (buf[pos] & 0xC0) === 0x80) { pos--; }\n\n  // Very small and broken sequence,\n  // return max, because we should return something anyway.\n  if (pos < 0) { return max; }\n\n  // If we came to start of buffer - that means buffer is too small,\n  // return max too.\n  if (pos === 0) { return max; }\n\n  return (pos + _utf8len[buf[pos]] > max) ? pos : max;\n};\n\nvar strings = {\n\tstring2buf: string2buf,\n\tbuf2string: buf2string,\n\tutf8border: utf8border\n};\n\n// (C) 1995-2013 Jean-loup Gailly and Mark Adler\n// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin\n//\n// This software is provided 'as-is', without any express or implied\n// warranty. In no event will the authors be held liable for any damages\n// arising from the use of this software.\n//\n// Permission is granted to anyone to use this software for any purpose,\n// including commercial applications, and to alter it and redistribute it\n// freely, subject to the following restrictions:\n//\n// 1. The origin of this software must not be misrepresented; you must not\n//   claim that you wrote the original software. If you use this software\n//   in a product, an acknowledgment in the product documentation would be\n//   appreciated but is not required.\n// 2. Altered source versions must be plainly marked as such, and must not be\n//   misrepresented as being the original software.\n// 3. This notice may not be removed or altered from any source distribution.\n\nfunction ZStream() {\n  /* next input byte */\n  this.input = null; // JS specific, because we have no pointers\n  this.next_in = 0;\n  /* number of bytes available at input */\n  this.avail_in = 0;\n  /* total number of input bytes read so far */\n  this.total_in = 0;\n  /* next output byte should be put there */\n  this.output = null; // JS specific, because we have no pointers\n  this.next_out = 0;\n  /* remaining free space at output */\n  this.avail_out = 0;\n  /* total number of bytes output so far */\n  this.total_out = 0;\n  /* last error message, NULL if no error */\n  this.msg = ''/*Z_NULL*/;\n  /* not visible by applications */\n  this.state = null;\n  /* best guess about the data type: binary or text */\n  this.data_type = 2/*Z_UNKNOWN*/;\n  /* adler32 value of the uncompressed data */\n  this.adler = 0;\n}\n\nvar zstream = ZStream;\n\nconst toString$1 = Object.prototype.toString;\n\n/* Public constants ==========================================================*/\n/* ===========================================================================*/\n\nconst {\n  Z_NO_FLUSH: Z_NO_FLUSH$1, Z_SYNC_FLUSH, Z_FULL_FLUSH, Z_FINISH: Z_FINISH$2,\n  Z_OK: Z_OK$2, Z_STREAM_END: Z_STREAM_END$2,\n  Z_DEFAULT_COMPRESSION,\n  Z_DEFAULT_STRATEGY,\n  Z_DEFLATED: Z_DEFLATED$1\n} = constants$2;\n\n/* ===========================================================================*/\n\n\n/**\n * class Deflate\n *\n * Generic JS-style wrapper for zlib calls. If you don't need\n * streaming behaviour - use more simple functions: [[deflate]],\n * [[deflateRaw]] and [[gzip]].\n **/\n\n/* internal\n * Deflate.chunks -> Array\n *\n * Chunks of output data, if [[Deflate#onData]] not overridden.\n **/\n\n/**\n * Deflate.result -> Uint8Array\n *\n * Compressed result, generated by default [[Deflate#onData]]\n * and [[Deflate#onEnd]] handlers. Filled after you push last chunk\n * (call [[Deflate#push]] with `Z_FINISH` / `true` param).\n **/\n\n/**\n * Deflate.err -> Number\n *\n * Error code after deflate finished. 0 (Z_OK) on success.\n * You will not need it in real life, because deflate errors\n * are possible only on wrong options or bad `onData` / `onEnd`\n * custom handlers.\n **/\n\n/**\n * Deflate.msg -> String\n *\n * Error message, if [[Deflate.err]] != 0\n **/\n\n\n/**\n * new Deflate(options)\n * - options (Object): zlib deflate options.\n *\n * Creates new deflator instance with specified params. Throws exception\n * on bad params. Supported options:\n *\n * - `level`\n * - `windowBits`\n * - `memLevel`\n * - `strategy`\n * - `dictionary`\n *\n * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)\n * for more information on these.\n *\n * Additional options, for internal needs:\n *\n * - `chunkSize` - size of generated data chunks (16K by default)\n * - `raw` (Boolean) - do raw deflate\n * - `gzip` (Boolean) - create gzip wrapper\n * - `header` (Object) - custom header for gzip\n *   - `text` (Boolean) - true if compressed data believed to be text\n *   - `time` (Number) - modification time, unix timestamp\n *   - `os` (Number) - operation system code\n *   - `extra` (Array) - array of bytes with extra data (max 65536)\n *   - `name` (String) - file name (binary string)\n *   - `comment` (String) - comment (binary string)\n *   - `hcrc` (Boolean) - true if header crc should be added\n *\n * ##### Example:\n *\n * ```javascript\n * const pako = require('pako')\n *   , chunk1 = new Uint8Array([1,2,3,4,5,6,7,8,9])\n *   , chunk2 = new Uint8Array([10,11,12,13,14,15,16,17,18,19]);\n *\n * const deflate = new pako.Deflate({ level: 3});\n *\n * deflate.push(chunk1, false);\n * deflate.push(chunk2, true);  // true -> last chunk\n *\n * if (deflate.err) { throw new Error(deflate.err); }\n *\n * console.log(deflate.result);\n * ```\n **/\nfunction Deflate$1(options) {\n  this.options = common.assign({\n    level: Z_DEFAULT_COMPRESSION,\n    method: Z_DEFLATED$1,\n    chunkSize: 16384,\n    windowBits: 15,\n    memLevel: 8,\n    strategy: Z_DEFAULT_STRATEGY\n  }, options || {});\n\n  let opt = this.options;\n\n  if (opt.raw && (opt.windowBits > 0)) {\n    opt.windowBits = -opt.windowBits;\n  }\n\n  else if (opt.gzip && (opt.windowBits > 0) && (opt.windowBits < 16)) {\n    opt.windowBits += 16;\n  }\n\n  this.err    = 0;      // error code, if happens (0 = Z_OK)\n  this.msg    = '';     // error message\n  this.ended  = false;  // used to avoid multiple onEnd() calls\n  this.chunks = [];     // chunks of compressed data\n\n  this.strm = new zstream();\n  this.strm.avail_out = 0;\n\n  let status = deflate_1$2.deflateInit2(\n    this.strm,\n    opt.level,\n    opt.method,\n    opt.windowBits,\n    opt.memLevel,\n    opt.strategy\n  );\n\n  if (status !== Z_OK$2) {\n    throw new Error(messages[status]);\n  }\n\n  if (opt.header) {\n    deflate_1$2.deflateSetHeader(this.strm, opt.header);\n  }\n\n  if (opt.dictionary) {\n    let dict;\n    // Convert data if needed\n    if (typeof opt.dictionary === 'string') {\n      // If we need to compress text, change encoding to utf8.\n      dict = strings.string2buf(opt.dictionary);\n    } else if (toString$1.call(opt.dictionary) === '[object ArrayBuffer]') {\n      dict = new Uint8Array(opt.dictionary);\n    } else {\n      dict = opt.dictionary;\n    }\n\n    status = deflate_1$2.deflateSetDictionary(this.strm, dict);\n\n    if (status !== Z_OK$2) {\n      throw new Error(messages[status]);\n    }\n\n    this._dict_set = true;\n  }\n}\n\n/**\n * Deflate#push(data[, flush_mode]) -> Boolean\n * - data (Uint8Array|ArrayBuffer|String): input data. Strings will be\n *   converted to utf8 byte sequence.\n * - flush_mode (Number|Boolean): 0..6 for corresponding Z_NO_FLUSH..Z_TREE modes.\n *   See constants. Skipped or `false` means Z_NO_FLUSH, `true` means Z_FINISH.\n *\n * Sends input data to deflate pipe, generating [[Deflate#onData]] calls with\n * new compressed chunks. Returns `true` on success. The last data block must\n * have `flush_mode` Z_FINISH (or `true`). That will flush internal pending\n * buffers and call [[Deflate#onEnd]].\n *\n * On fail call [[Deflate#onEnd]] with error code and return false.\n *\n * ##### Example\n *\n * ```javascript\n * push(chunk, false); // push one of data chunks\n * ...\n * push(chunk, true);  // push last chunk\n * ```\n **/\nDeflate$1.prototype.push = function (data, flush_mode) {\n  const strm = this.strm;\n  const chunkSize = this.options.chunkSize;\n  let status, _flush_mode;\n\n  if (this.ended) { return false; }\n\n  if (flush_mode === ~~flush_mode) _flush_mode = flush_mode;\n  else _flush_mode = flush_mode === true ? Z_FINISH$2 : Z_NO_FLUSH$1;\n\n  // Convert data if needed\n  if (typeof data === 'string') {\n    // If we need to compress text, change encoding to utf8.\n    strm.input = strings.string2buf(data);\n  } else if (toString$1.call(data) === '[object ArrayBuffer]') {\n    strm.input = new Uint8Array(data);\n  } else {\n    strm.input = data;\n  }\n\n  strm.next_in = 0;\n  strm.avail_in = strm.input.length;\n\n  for (;;) {\n    if (strm.avail_out === 0) {\n      strm.output = new Uint8Array(chunkSize);\n      strm.next_out = 0;\n      strm.avail_out = chunkSize;\n    }\n\n    // Make sure avail_out > 6 to avoid repeating markers\n    if ((_flush_mode === Z_SYNC_FLUSH || _flush_mode === Z_FULL_FLUSH) && strm.avail_out <= 6) {\n      this.onData(strm.output.subarray(0, strm.next_out));\n      strm.avail_out = 0;\n      continue;\n    }\n\n    status = deflate_1$2.deflate(strm, _flush_mode);\n\n    // Ended => flush and finish\n    if (status === Z_STREAM_END$2) {\n      if (strm.next_out > 0) {\n        this.onData(strm.output.subarray(0, strm.next_out));\n      }\n      status = deflate_1$2.deflateEnd(this.strm);\n      this.onEnd(status);\n      this.ended = true;\n      return status === Z_OK$2;\n    }\n\n    // Flush if out buffer full\n    if (strm.avail_out === 0) {\n      this.onData(strm.output);\n      continue;\n    }\n\n    // Flush if requested and has data\n    if (_flush_mode > 0 && strm.next_out > 0) {\n      this.onData(strm.output.subarray(0, strm.next_out));\n      strm.avail_out = 0;\n      continue;\n    }\n\n    if (strm.avail_in === 0) break;\n  }\n\n  return true;\n};\n\n\n/**\n * Deflate#onData(chunk) -> Void\n * - chunk (Uint8Array): output data.\n *\n * By default, stores data blocks in `chunks[]` property and glue\n * those in `onEnd`. Override this handler, if you need another behaviour.\n **/\nDeflate$1.prototype.onData = function (chunk) {\n  this.chunks.push(chunk);\n};\n\n\n/**\n * Deflate#onEnd(status) -> Void\n * - status (Number): deflate status. 0 (Z_OK) on success,\n *   other if not.\n *\n * Called once after you tell deflate that the input stream is\n * complete (Z_FINISH). By default - join collected chunks,\n * free memory and fill `results` / `err` properties.\n **/\nDeflate$1.prototype.onEnd = function (status) {\n  // On success - join\n  if (status === Z_OK$2) {\n    this.result = common.flattenChunks(this.chunks);\n  }\n  this.chunks = [];\n  this.err = status;\n  this.msg = this.strm.msg;\n};\n\n\n/**\n * deflate(data[, options]) -> Uint8Array\n * - data (Uint8Array|ArrayBuffer|String): input data to compress.\n * - options (Object): zlib deflate options.\n *\n * Compress `data` with deflate algorithm and `options`.\n *\n * Supported options are:\n *\n * - level\n * - windowBits\n * - memLevel\n * - strategy\n * - dictionary\n *\n * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)\n * for more information on these.\n *\n * Sugar (options):\n *\n * - `raw` (Boolean) - say that we work with raw stream, if you don't wish to specify\n *   negative windowBits implicitly.\n *\n * ##### Example:\n *\n * ```javascript\n * const pako = require('pako')\n * const data = new Uint8Array([1,2,3,4,5,6,7,8,9]);\n *\n * console.log(pako.deflate(data));\n * ```\n **/\nfunction deflate$1(input, options) {\n  const deflator = new Deflate$1(options);\n\n  deflator.push(input, true);\n\n  // That will never happens, if you don't cheat with options :)\n  if (deflator.err) { throw deflator.msg || messages[deflator.err]; }\n\n  return deflator.result;\n}\n\n\n/**\n * deflateRaw(data[, options]) -> Uint8Array\n * - data (Uint8Array|ArrayBuffer|String): input data to compress.\n * - options (Object): zlib deflate options.\n *\n * The same as [[deflate]], but creates raw data, without wrapper\n * (header and adler32 crc).\n **/\nfunction deflateRaw$1(input, options) {\n  options = options || {};\n  options.raw = true;\n  return deflate$1(input, options);\n}\n\n\n/**\n * gzip(data[, options]) -> Uint8Array\n * - data (Uint8Array|ArrayBuffer|String): input data to compress.\n * - options (Object): zlib deflate options.\n *\n * The same as [[deflate]], but create gzip wrapper instead of\n * deflate one.\n **/\nfunction gzip$1(input, options) {\n  options = options || {};\n  options.gzip = true;\n  return deflate$1(input, options);\n}\n\n\nvar Deflate_1$1 = Deflate$1;\nvar deflate_2 = deflate$1;\nvar deflateRaw_1$1 = deflateRaw$1;\nvar gzip_1$1 = gzip$1;\nvar constants$1 = constants$2;\n\nvar deflate_1$1 = {\n\tDeflate: Deflate_1$1,\n\tdeflate: deflate_2,\n\tdeflateRaw: deflateRaw_1$1,\n\tgzip: gzip_1$1,\n\tconstants: constants$1\n};\n\n// (C) 1995-2013 Jean-loup Gailly and Mark Adler\n// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin\n//\n// This software is provided 'as-is', without any express or implied\n// warranty. In no event will the authors be held liable for any damages\n// arising from the use of this software.\n//\n// Permission is granted to anyone to use this software for any purpose,\n// including commercial applications, and to alter it and redistribute it\n// freely, subject to the following restrictions:\n//\n// 1. The origin of this software must not be misrepresented; you must not\n//   claim that you wrote the original software. If you use this software\n//   in a product, an acknowledgment in the product documentation would be\n//   appreciated but is not required.\n// 2. Altered source versions must be plainly marked as such, and must not be\n//   misrepresented as being the original software.\n// 3. This notice may not be removed or altered from any source distribution.\n\n// See state defs from inflate.js\nconst BAD$1 = 16209;       /* got a data error -- remain here until reset */\nconst TYPE$1 = 16191;      /* i: waiting for type bits, including last-flag bit */\n\n/*\n   Decode literal, length, and distance codes and write out the resulting\n   literal and match bytes until either not enough input or output is\n   available, an end-of-block is encountered, or a data error is encountered.\n   When large enough input and output buffers are supplied to inflate(), for\n   example, a 16K input buffer and a 64K output buffer, more than 95% of the\n   inflate execution time is spent in this routine.\n\n   Entry assumptions:\n\n        state.mode === LEN\n        strm.avail_in >= 6\n        strm.avail_out >= 258\n        start >= strm.avail_out\n        state.bits < 8\n\n   On return, state.mode is one of:\n\n        LEN -- ran out of enough output space or enough available input\n        TYPE -- reached end of block code, inflate() to interpret next block\n        BAD -- error in block data\n\n   Notes:\n\n    - The maximum input bits used by a length/distance pair is 15 bits for the\n      length code, 5 bits for the length extra, 15 bits for the distance code,\n      and 13 bits for the distance extra.  This totals 48 bits, or six bytes.\n      Therefore if strm.avail_in >= 6, then there is enough input to avoid\n      checking for available input while decoding.\n\n    - The maximum bytes that a single length/distance pair can output is 258\n      bytes, which is the maximum length that can be coded.  inflate_fast()\n      requires strm.avail_out >= 258 for each loop to avoid checking for\n      output space.\n */\nvar inffast = function inflate_fast(strm, start) {\n  let _in;                    /* local strm.input */\n  let last;                   /* have enough input while in < last */\n  let _out;                   /* local strm.output */\n  let beg;                    /* inflate()'s initial strm.output */\n  let end;                    /* while out < end, enough space available */\n//#ifdef INFLATE_STRICT\n  let dmax;                   /* maximum distance from zlib header */\n//#endif\n  let wsize;                  /* window size or zero if not using window */\n  let whave;                  /* valid bytes in the window */\n  let wnext;                  /* window write index */\n  // Use `s_window` instead `window`, avoid conflict with instrumentation tools\n  let s_window;               /* allocated sliding window, if wsize != 0 */\n  let hold;                   /* local strm.hold */\n  let bits;                   /* local strm.bits */\n  let lcode;                  /* local strm.lencode */\n  let dcode;                  /* local strm.distcode */\n  let lmask;                  /* mask for first level of length codes */\n  let dmask;                  /* mask for first level of distance codes */\n  let here;                   /* retrieved table entry */\n  let op;                     /* code bits, operation, extra bits, or */\n                              /*  window position, window bytes to copy */\n  let len;                    /* match length, unused bytes */\n  let dist;                   /* match distance */\n  let from;                   /* where to copy match from */\n  let from_source;\n\n\n  let input, output; // JS specific, because we have no pointers\n\n  /* copy state to local variables */\n  const state = strm.state;\n  //here = state.here;\n  _in = strm.next_in;\n  input = strm.input;\n  last = _in + (strm.avail_in - 5);\n  _out = strm.next_out;\n  output = strm.output;\n  beg = _out - (start - strm.avail_out);\n  end = _out + (strm.avail_out - 257);\n//#ifdef INFLATE_STRICT\n  dmax = state.dmax;\n//#endif\n  wsize = state.wsize;\n  whave = state.whave;\n  wnext = state.wnext;\n  s_window = state.window;\n  hold = state.hold;\n  bits = state.bits;\n  lcode = state.lencode;\n  dcode = state.distcode;\n  lmask = (1 << state.lenbits) - 1;\n  dmask = (1 << state.distbits) - 1;\n\n\n  /* decode literals and length/distances until end-of-block or not enough\n     input data or output space */\n\n  top:\n  do {\n    if (bits < 15) {\n      hold += input[_in++] << bits;\n      bits += 8;\n      hold += input[_in++] << bits;\n      bits += 8;\n    }\n\n    here = lcode[hold & lmask];\n\n    dolen:\n    for (;;) { // Goto emulation\n      op = here >>> 24/*here.bits*/;\n      hold >>>= op;\n      bits -= op;\n      op = (here >>> 16) & 0xff/*here.op*/;\n      if (op === 0) {                          /* literal */\n        //Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ?\n        //        \"inflate:         literal '%c'\\n\" :\n        //        \"inflate:         literal 0x%02x\\n\", here.val));\n        output[_out++] = here & 0xffff/*here.val*/;\n      }\n      else if (op & 16) {                     /* length base */\n        len = here & 0xffff/*here.val*/;\n        op &= 15;                           /* number of extra bits */\n        if (op) {\n          if (bits < op) {\n            hold += input[_in++] << bits;\n            bits += 8;\n          }\n          len += hold & ((1 << op) - 1);\n          hold >>>= op;\n          bits -= op;\n        }\n        //Tracevv((stderr, \"inflate:         length %u\\n\", len));\n        if (bits < 15) {\n          hold += input[_in++] << bits;\n          bits += 8;\n          hold += input[_in++] << bits;\n          bits += 8;\n        }\n        here = dcode[hold & dmask];\n\n        dodist:\n        for (;;) { // goto emulation\n          op = here >>> 24/*here.bits*/;\n          hold >>>= op;\n          bits -= op;\n          op = (here >>> 16) & 0xff/*here.op*/;\n\n          if (op & 16) {                      /* distance base */\n            dist = here & 0xffff/*here.val*/;\n            op &= 15;                       /* number of extra bits */\n            if (bits < op) {\n              hold += input[_in++] << bits;\n              bits += 8;\n              if (bits < op) {\n                hold += input[_in++] << bits;\n                bits += 8;\n              }\n            }\n            dist += hold & ((1 << op) - 1);\n//#ifdef INFLATE_STRICT\n            if (dist > dmax) {\n              strm.msg = 'invalid distance too far back';\n              state.mode = BAD$1;\n              break top;\n            }\n//#endif\n            hold >>>= op;\n            bits -= op;\n            //Tracevv((stderr, \"inflate:         distance %u\\n\", dist));\n            op = _out - beg;                /* max distance in output */\n            if (dist > op) {                /* see if copy from window */\n              op = dist - op;               /* distance back in window */\n              if (op > whave) {\n                if (state.sane) {\n                  strm.msg = 'invalid distance too far back';\n                  state.mode = BAD$1;\n                  break top;\n                }\n\n// (!) This block is disabled in zlib defaults,\n// don't enable it for binary compatibility\n//#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR\n//                if (len <= op - whave) {\n//                  do {\n//                    output[_out++] = 0;\n//                  } while (--len);\n//                  continue top;\n//                }\n//                len -= op - whave;\n//                do {\n//                  output[_out++] = 0;\n//                } while (--op > whave);\n//                if (op === 0) {\n//                  from = _out - dist;\n//                  do {\n//                    output[_out++] = output[from++];\n//                  } while (--len);\n//                  continue top;\n//                }\n//#endif\n              }\n              from = 0; // window index\n              from_source = s_window;\n              if (wnext === 0) {           /* very common case */\n                from += wsize - op;\n                if (op < len) {         /* some from window */\n                  len -= op;\n                  do {\n                    output[_out++] = s_window[from++];\n                  } while (--op);\n                  from = _out - dist;  /* rest from output */\n                  from_source = output;\n                }\n              }\n              else if (wnext < op) {      /* wrap around window */\n                from += wsize + wnext - op;\n                op -= wnext;\n                if (op < len) {         /* some from end of window */\n                  len -= op;\n                  do {\n                    output[_out++] = s_window[from++];\n                  } while (--op);\n                  from = 0;\n                  if (wnext < len) {  /* some from start of window */\n                    op = wnext;\n                    len -= op;\n                    do {\n                      output[_out++] = s_window[from++];\n                    } while (--op);\n                    from = _out - dist;      /* rest from output */\n                    from_source = output;\n                  }\n                }\n              }\n              else {                      /* contiguous in window */\n                from += wnext - op;\n                if (op < len) {         /* some from window */\n                  len -= op;\n                  do {\n                    output[_out++] = s_window[from++];\n                  } while (--op);\n                  from = _out - dist;  /* rest from output */\n                  from_source = output;\n                }\n              }\n              while (len > 2) {\n                output[_out++] = from_source[from++];\n                output[_out++] = from_source[from++];\n                output[_out++] = from_source[from++];\n                len -= 3;\n              }\n              if (len) {\n                output[_out++] = from_source[from++];\n                if (len > 1) {\n                  output[_out++] = from_source[from++];\n                }\n              }\n            }\n            else {\n              from = _out - dist;          /* copy direct from output */\n              do {                        /* minimum length is three */\n                output[_out++] = output[from++];\n                output[_out++] = output[from++];\n                output[_out++] = output[from++];\n                len -= 3;\n              } while (len > 2);\n              if (len) {\n                output[_out++] = output[from++];\n                if (len > 1) {\n                  output[_out++] = output[from++];\n                }\n              }\n            }\n          }\n          else if ((op & 64) === 0) {          /* 2nd level distance code */\n            here = dcode[(here & 0xffff)/*here.val*/ + (hold & ((1 << op) - 1))];\n            continue dodist;\n          }\n          else {\n            strm.msg = 'invalid distance code';\n            state.mode = BAD$1;\n            break top;\n          }\n\n          break; // need to emulate goto via \"continue\"\n        }\n      }\n      else if ((op & 64) === 0) {              /* 2nd level length code */\n        here = lcode[(here & 0xffff)/*here.val*/ + (hold & ((1 << op) - 1))];\n        continue dolen;\n      }\n      else if (op & 32) {                     /* end-of-block */\n        //Tracevv((stderr, \"inflate:         end of block\\n\"));\n        state.mode = TYPE$1;\n        break top;\n      }\n      else {\n        strm.msg = 'invalid literal/length code';\n        state.mode = BAD$1;\n        break top;\n      }\n\n      break; // need to emulate goto via \"continue\"\n    }\n  } while (_in < last && _out < end);\n\n  /* return unused bytes (on entry, bits < 8, so in won't go too far back) */\n  len = bits >> 3;\n  _in -= len;\n  bits -= len << 3;\n  hold &= (1 << bits) - 1;\n\n  /* update state and return */\n  strm.next_in = _in;\n  strm.next_out = _out;\n  strm.avail_in = (_in < last ? 5 + (last - _in) : 5 - (_in - last));\n  strm.avail_out = (_out < end ? 257 + (end - _out) : 257 - (_out - end));\n  state.hold = hold;\n  state.bits = bits;\n  return;\n};\n\n// (C) 1995-2013 Jean-loup Gailly and Mark Adler\n// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin\n//\n// This software is provided 'as-is', without any express or implied\n// warranty. In no event will the authors be held liable for any damages\n// arising from the use of this software.\n//\n// Permission is granted to anyone to use this software for any purpose,\n// including commercial applications, and to alter it and redistribute it\n// freely, subject to the following restrictions:\n//\n// 1. The origin of this software must not be misrepresented; you must not\n//   claim that you wrote the original software. If you use this software\n//   in a product, an acknowledgment in the product documentation would be\n//   appreciated but is not required.\n// 2. Altered source versions must be plainly marked as such, and must not be\n//   misrepresented as being the original software.\n// 3. This notice may not be removed or altered from any source distribution.\n\nconst MAXBITS = 15;\nconst ENOUGH_LENS$1 = 852;\nconst ENOUGH_DISTS$1 = 592;\n//const ENOUGH = (ENOUGH_LENS+ENOUGH_DISTS);\n\nconst CODES$1 = 0;\nconst LENS$1 = 1;\nconst DISTS$1 = 2;\n\nconst lbase = new Uint16Array([ /* Length codes 257..285 base */\n  3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31,\n  35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 0, 0\n]);\n\nconst lext = new Uint8Array([ /* Length codes 257..285 extra */\n  16, 16, 16, 16, 16, 16, 16, 16, 17, 17, 17, 17, 18, 18, 18, 18,\n  19, 19, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 16, 72, 78\n]);\n\nconst dbase = new Uint16Array([ /* Distance codes 0..29 base */\n  1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193,\n  257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145,\n  8193, 12289, 16385, 24577, 0, 0\n]);\n\nconst dext = new Uint8Array([ /* Distance codes 0..29 extra */\n  16, 16, 16, 16, 17, 17, 18, 18, 19, 19, 20, 20, 21, 21, 22, 22,\n  23, 23, 24, 24, 25, 25, 26, 26, 27, 27,\n  28, 28, 29, 29, 64, 64\n]);\n\nconst inflate_table = (type, lens, lens_index, codes, table, table_index, work, opts) =>\n{\n  const bits = opts.bits;\n      //here = opts.here; /* table entry for duplication */\n\n  let len = 0;               /* a code's length in bits */\n  let sym = 0;               /* index of code symbols */\n  let min = 0, max = 0;          /* minimum and maximum code lengths */\n  let root = 0;              /* number of index bits for root table */\n  let curr = 0;              /* number of index bits for current table */\n  let drop = 0;              /* code bits to drop for sub-table */\n  let left = 0;                   /* number of prefix codes available */\n  let used = 0;              /* code entries in table used */\n  let huff = 0;              /* Huffman code */\n  let incr;              /* for incrementing code, index */\n  let fill;              /* index for replicating entries */\n  let low;               /* low bits for current root entry */\n  let mask;              /* mask for low root bits */\n  let next;             /* next available space in table */\n  let base = null;     /* base value table to use */\n//  let shoextra;    /* extra bits table to use */\n  let match;                  /* use base and extra for symbol >= match */\n  const count = new Uint16Array(MAXBITS + 1); //[MAXBITS+1];    /* number of codes of each length */\n  const offs = new Uint16Array(MAXBITS + 1); //[MAXBITS+1];     /* offsets in table for each length */\n  let extra = null;\n\n  let here_bits, here_op, here_val;\n\n  /*\n   Process a set of code lengths to create a canonical Huffman code.  The\n   code lengths are lens[0..codes-1].  Each length corresponds to the\n   symbols 0..codes-1.  The Huffman code is generated by first sorting the\n   symbols by length from short to long, and retaining the symbol order\n   for codes with equal lengths.  Then the code starts with all zero bits\n   for the first code of the shortest length, and the codes are integer\n   increments for the same length, and zeros are appended as the length\n   increases.  For the deflate format, these bits are stored backwards\n   from their more natural integer increment ordering, and so when the\n   decoding tables are built in the large loop below, the integer codes\n   are incremented backwards.\n\n   This routine assumes, but does not check, that all of the entries in\n   lens[] are in the range 0..MAXBITS.  The caller must assure this.\n   1..MAXBITS is interpreted as that code length.  zero means that that\n   symbol does not occur in this code.\n\n   The codes are sorted by computing a count of codes for each length,\n   creating from that a table of starting indices for each length in the\n   sorted table, and then entering the symbols in order in the sorted\n   table.  The sorted table is work[], with that space being provided by\n   the caller.\n\n   The length counts are used for other purposes as well, i.e. finding\n   the minimum and maximum length codes, determining if there are any\n   codes at all, checking for a valid set of lengths, and looking ahead\n   at length counts to determine sub-table sizes when building the\n   decoding tables.\n   */\n\n  /* accumulate lengths for codes (assumes lens[] all in 0..MAXBITS) */\n  for (len = 0; len <= MAXBITS; len++) {\n    count[len] = 0;\n  }\n  for (sym = 0; sym < codes; sym++) {\n    count[lens[lens_index + sym]]++;\n  }\n\n  /* bound code lengths, force root to be within code lengths */\n  root = bits;\n  for (max = MAXBITS; max >= 1; max--) {\n    if (count[max] !== 0) { break; }\n  }\n  if (root > max) {\n    root = max;\n  }\n  if (max === 0) {                     /* no symbols to code at all */\n    //table.op[opts.table_index] = 64;  //here.op = (var char)64;    /* invalid code marker */\n    //table.bits[opts.table_index] = 1;   //here.bits = (var char)1;\n    //table.val[opts.table_index++] = 0;   //here.val = (var short)0;\n    table[table_index++] = (1 << 24) | (64 << 16) | 0;\n\n\n    //table.op[opts.table_index] = 64;\n    //table.bits[opts.table_index] = 1;\n    //table.val[opts.table_index++] = 0;\n    table[table_index++] = (1 << 24) | (64 << 16) | 0;\n\n    opts.bits = 1;\n    return 0;     /* no symbols, but wait for decoding to report error */\n  }\n  for (min = 1; min < max; min++) {\n    if (count[min] !== 0) { break; }\n  }\n  if (root < min) {\n    root = min;\n  }\n\n  /* check for an over-subscribed or incomplete set of lengths */\n  left = 1;\n  for (len = 1; len <= MAXBITS; len++) {\n    left <<= 1;\n    left -= count[len];\n    if (left < 0) {\n      return -1;\n    }        /* over-subscribed */\n  }\n  if (left > 0 && (type === CODES$1 || max !== 1)) {\n    return -1;                      /* incomplete set */\n  }\n\n  /* generate offsets into symbol table for each length for sorting */\n  offs[1] = 0;\n  for (len = 1; len < MAXBITS; len++) {\n    offs[len + 1] = offs[len] + count[len];\n  }\n\n  /* sort symbols by length, by symbol order within each length */\n  for (sym = 0; sym < codes; sym++) {\n    if (lens[lens_index + sym] !== 0) {\n      work[offs[lens[lens_index + sym]]++] = sym;\n    }\n  }\n\n  /*\n   Create and fill in decoding tables.  In this loop, the table being\n   filled is at next and has curr index bits.  The code being used is huff\n   with length len.  That code is converted to an index by dropping drop\n   bits off of the bottom.  For codes where len is less than drop + curr,\n   those top drop + curr - len bits are incremented through all values to\n   fill the table with replicated entries.\n\n   root is the number of index bits for the root table.  When len exceeds\n   root, sub-tables are created pointed to by the root entry with an index\n   of the low root bits of huff.  This is saved in low to check for when a\n   new sub-table should be started.  drop is zero when the root table is\n   being filled, and drop is root when sub-tables are being filled.\n\n   When a new sub-table is needed, it is necessary to look ahead in the\n   code lengths to determine what size sub-table is needed.  The length\n   counts are used for this, and so count[] is decremented as codes are\n   entered in the tables.\n\n   used keeps track of how many table entries have been allocated from the\n   provided *table space.  It is checked for LENS and DIST tables against\n   the constants ENOUGH_LENS and ENOUGH_DISTS to guard against changes in\n   the initial root table size constants.  See the comments in inftrees.h\n   for more information.\n\n   sym increments through all symbols, and the loop terminates when\n   all codes of length max, i.e. all codes, have been processed.  This\n   routine permits incomplete codes, so another loop after this one fills\n   in the rest of the decoding tables with invalid code markers.\n   */\n\n  /* set up for code type */\n  // poor man optimization - use if-else instead of switch,\n  // to avoid deopts in old v8\n  if (type === CODES$1) {\n    base = extra = work;    /* dummy value--not used */\n    match = 20;\n\n  } else if (type === LENS$1) {\n    base = lbase;\n    extra = lext;\n    match = 257;\n\n  } else {                    /* DISTS */\n    base = dbase;\n    extra = dext;\n    match = 0;\n  }\n\n  /* initialize opts for loop */\n  huff = 0;                   /* starting code */\n  sym = 0;                    /* starting code symbol */\n  len = min;                  /* starting code length */\n  next = table_index;              /* current table to fill in */\n  curr = root;                /* current table index bits */\n  drop = 0;                   /* current bits to drop from code for index */\n  low = -1;                   /* trigger new sub-table when len > root */\n  used = 1 << root;          /* use root table entries */\n  mask = used - 1;            /* mask for comparing low */\n\n  /* check available table space */\n  if ((type === LENS$1 && used > ENOUGH_LENS$1) ||\n    (type === DISTS$1 && used > ENOUGH_DISTS$1)) {\n    return 1;\n  }\n\n  /* process all codes and make table entries */\n  for (;;) {\n    /* create table entry */\n    here_bits = len - drop;\n    if (work[sym] + 1 < match) {\n      here_op = 0;\n      here_val = work[sym];\n    }\n    else if (work[sym] >= match) {\n      here_op = extra[work[sym] - match];\n      here_val = base[work[sym] - match];\n    }\n    else {\n      here_op = 32 + 64;         /* end of block */\n      here_val = 0;\n    }\n\n    /* replicate for those indices with low len bits equal to huff */\n    incr = 1 << (len - drop);\n    fill = 1 << curr;\n    min = fill;                 /* save offset to next table */\n    do {\n      fill -= incr;\n      table[next + (huff >> drop) + fill] = (here_bits << 24) | (here_op << 16) | here_val |0;\n    } while (fill !== 0);\n\n    /* backwards increment the len-bit code huff */\n    incr = 1 << (len - 1);\n    while (huff & incr) {\n      incr >>= 1;\n    }\n    if (incr !== 0) {\n      huff &= incr - 1;\n      huff += incr;\n    } else {\n      huff = 0;\n    }\n\n    /* go to next symbol, update count, len */\n    sym++;\n    if (--count[len] === 0) {\n      if (len === max) { break; }\n      len = lens[lens_index + work[sym]];\n    }\n\n    /* create new sub-table if needed */\n    if (len > root && (huff & mask) !== low) {\n      /* if first time, transition to sub-tables */\n      if (drop === 0) {\n        drop = root;\n      }\n\n      /* increment past last table */\n      next += min;            /* here min is 1 << curr */\n\n      /* determine length of next table */\n      curr = len - drop;\n      left = 1 << curr;\n      while (curr + drop < max) {\n        left -= count[curr + drop];\n        if (left <= 0) { break; }\n        curr++;\n        left <<= 1;\n      }\n\n      /* check for enough space */\n      used += 1 << curr;\n      if ((type === LENS$1 && used > ENOUGH_LENS$1) ||\n        (type === DISTS$1 && used > ENOUGH_DISTS$1)) {\n        return 1;\n      }\n\n      /* point entry in root table to sub-table */\n      low = huff & mask;\n      /*table.op[low] = curr;\n      table.bits[low] = root;\n      table.val[low] = next - opts.table_index;*/\n      table[low] = (root << 24) | (curr << 16) | (next - table_index) |0;\n    }\n  }\n\n  /* fill in remaining table entry if code is incomplete (guaranteed to have\n   at most one remaining entry, since if the code is incomplete, the\n   maximum code length that was allowed to get this far is one bit) */\n  if (huff !== 0) {\n    //table.op[next + huff] = 64;            /* invalid code marker */\n    //table.bits[next + huff] = len - drop;\n    //table.val[next + huff] = 0;\n    table[next + huff] = ((len - drop) << 24) | (64 << 16) |0;\n  }\n\n  /* set return parameters */\n  //opts.table_index += used;\n  opts.bits = root;\n  return 0;\n};\n\n\nvar inftrees = inflate_table;\n\n// (C) 1995-2013 Jean-loup Gailly and Mark Adler\n// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin\n//\n// This software is provided 'as-is', without any express or implied\n// warranty. In no event will the authors be held liable for any damages\n// arising from the use of this software.\n//\n// Permission is granted to anyone to use this software for any purpose,\n// including commercial applications, and to alter it and redistribute it\n// freely, subject to the following restrictions:\n//\n// 1. The origin of this software must not be misrepresented; you must not\n//   claim that you wrote the original software. If you use this software\n//   in a product, an acknowledgment in the product documentation would be\n//   appreciated but is not required.\n// 2. Altered source versions must be plainly marked as such, and must not be\n//   misrepresented as being the original software.\n// 3. This notice may not be removed or altered from any source distribution.\n\n\n\n\n\n\nconst CODES = 0;\nconst LENS = 1;\nconst DISTS = 2;\n\n/* Public constants ==========================================================*/\n/* ===========================================================================*/\n\nconst {\n  Z_FINISH: Z_FINISH$1, Z_BLOCK, Z_TREES,\n  Z_OK: Z_OK$1, Z_STREAM_END: Z_STREAM_END$1, Z_NEED_DICT: Z_NEED_DICT$1, Z_STREAM_ERROR: Z_STREAM_ERROR$1, Z_DATA_ERROR: Z_DATA_ERROR$1, Z_MEM_ERROR: Z_MEM_ERROR$1, Z_BUF_ERROR,\n  Z_DEFLATED\n} = constants$2;\n\n\n/* STATES ====================================================================*/\n/* ===========================================================================*/\n\n\nconst    HEAD = 16180;       /* i: waiting for magic header */\nconst    FLAGS = 16181;      /* i: waiting for method and flags (gzip) */\nconst    TIME = 16182;       /* i: waiting for modification time (gzip) */\nconst    OS = 16183;         /* i: waiting for extra flags and operating system (gzip) */\nconst    EXLEN = 16184;      /* i: waiting for extra length (gzip) */\nconst    EXTRA = 16185;      /* i: waiting for extra bytes (gzip) */\nconst    NAME = 16186;       /* i: waiting for end of file name (gzip) */\nconst    COMMENT = 16187;    /* i: waiting for end of comment (gzip) */\nconst    HCRC = 16188;       /* i: waiting for header crc (gzip) */\nconst    DICTID = 16189;    /* i: waiting for dictionary check value */\nconst    DICT = 16190;      /* waiting for inflateSetDictionary() call */\nconst        TYPE = 16191;      /* i: waiting for type bits, including last-flag bit */\nconst        TYPEDO = 16192;    /* i: same, but skip check to exit inflate on new block */\nconst        STORED = 16193;    /* i: waiting for stored size (length and complement) */\nconst        COPY_ = 16194;     /* i/o: same as COPY below, but only first time in */\nconst        COPY = 16195;      /* i/o: waiting for input or output to copy stored block */\nconst        TABLE = 16196;     /* i: waiting for dynamic block table lengths */\nconst        LENLENS = 16197;   /* i: waiting for code length code lengths */\nconst        CODELENS = 16198;  /* i: waiting for length/lit and distance code lengths */\nconst            LEN_ = 16199;      /* i: same as LEN below, but only first time in */\nconst            LEN = 16200;       /* i: waiting for length/lit/eob code */\nconst            LENEXT = 16201;    /* i: waiting for length extra bits */\nconst            DIST = 16202;      /* i: waiting for distance code */\nconst            DISTEXT = 16203;   /* i: waiting for distance extra bits */\nconst            MATCH = 16204;     /* o: waiting for output space to copy string */\nconst            LIT = 16205;       /* o: waiting for output space to write literal */\nconst    CHECK = 16206;     /* i: waiting for 32-bit check value */\nconst    LENGTH = 16207;    /* i: waiting for 32-bit length (gzip) */\nconst    DONE = 16208;      /* finished check, done -- remain here until reset */\nconst    BAD = 16209;       /* got a data error -- remain here until reset */\nconst    MEM = 16210;       /* got an inflate() memory error -- remain here until reset */\nconst    SYNC = 16211;      /* looking for synchronization bytes to restart inflate() */\n\n/* ===========================================================================*/\n\n\n\nconst ENOUGH_LENS = 852;\nconst ENOUGH_DISTS = 592;\n//const ENOUGH =  (ENOUGH_LENS+ENOUGH_DISTS);\n\nconst MAX_WBITS = 15;\n/* 32K LZ77 window */\nconst DEF_WBITS = MAX_WBITS;\n\n\nconst zswap32 = (q) => {\n\n  return  (((q >>> 24) & 0xff) +\n          ((q >>> 8) & 0xff00) +\n          ((q & 0xff00) << 8) +\n          ((q & 0xff) << 24));\n};\n\n\nfunction InflateState() {\n  this.strm = null;           /* pointer back to this zlib stream */\n  this.mode = 0;              /* current inflate mode */\n  this.last = false;          /* true if processing last block */\n  this.wrap = 0;              /* bit 0 true for zlib, bit 1 true for gzip,\n                                 bit 2 true to validate check value */\n  this.havedict = false;      /* true if dictionary provided */\n  this.flags = 0;             /* gzip header method and flags (0 if zlib), or\n                                 -1 if raw or no header yet */\n  this.dmax = 0;              /* zlib header max distance (INFLATE_STRICT) */\n  this.check = 0;             /* protected copy of check value */\n  this.total = 0;             /* protected copy of output count */\n  // TODO: may be {}\n  this.head = null;           /* where to save gzip header information */\n\n  /* sliding window */\n  this.wbits = 0;             /* log base 2 of requested window size */\n  this.wsize = 0;             /* window size or zero if not using window */\n  this.whave = 0;             /* valid bytes in the window */\n  this.wnext = 0;             /* window write index */\n  this.window = null;         /* allocated sliding window, if needed */\n\n  /* bit accumulator */\n  this.hold = 0;              /* input bit accumulator */\n  this.bits = 0;              /* number of bits in \"in\" */\n\n  /* for string and stored block copying */\n  this.length = 0;            /* literal or length of data to copy */\n  this.offset = 0;            /* distance back to copy string from */\n\n  /* for table and code decoding */\n  this.extra = 0;             /* extra bits needed */\n\n  /* fixed and dynamic code tables */\n  this.lencode = null;          /* starting table for length/literal codes */\n  this.distcode = null;         /* starting table for distance codes */\n  this.lenbits = 0;           /* index bits for lencode */\n  this.distbits = 0;          /* index bits for distcode */\n\n  /* dynamic table building */\n  this.ncode = 0;             /* number of code length code lengths */\n  this.nlen = 0;              /* number of length code lengths */\n  this.ndist = 0;             /* number of distance code lengths */\n  this.have = 0;              /* number of code lengths in lens[] */\n  this.next = null;              /* next available space in codes[] */\n\n  this.lens = new Uint16Array(320); /* temporary storage for code lengths */\n  this.work = new Uint16Array(288); /* work area for code table building */\n\n  /*\n   because we don't have pointers in js, we use lencode and distcode directly\n   as buffers so we don't need codes\n  */\n  //this.codes = new Int32Array(ENOUGH);       /* space for code tables */\n  this.lendyn = null;              /* dynamic table for length/literal codes (JS specific) */\n  this.distdyn = null;             /* dynamic table for distance codes (JS specific) */\n  this.sane = 0;                   /* if false, allow invalid distance too far */\n  this.back = 0;                   /* bits back of last unprocessed length/lit */\n  this.was = 0;                    /* initial length of match */\n}\n\n\nconst inflateStateCheck = (strm) => {\n\n  if (!strm) {\n    return 1;\n  }\n  const state = strm.state;\n  if (!state || state.strm !== strm ||\n    state.mode < HEAD || state.mode > SYNC) {\n    return 1;\n  }\n  return 0;\n};\n\n\nconst inflateResetKeep = (strm) => {\n\n  if (inflateStateCheck(strm)) { return Z_STREAM_ERROR$1; }\n  const state = strm.state;\n  strm.total_in = strm.total_out = state.total = 0;\n  strm.msg = ''; /*Z_NULL*/\n  if (state.wrap) {       /* to support ill-conceived Java test suite */\n    strm.adler = state.wrap & 1;\n  }\n  state.mode = HEAD;\n  state.last = 0;\n  state.havedict = 0;\n  state.flags = -1;\n  state.dmax = 32768;\n  state.head = null/*Z_NULL*/;\n  state.hold = 0;\n  state.bits = 0;\n  //state.lencode = state.distcode = state.next = state.codes;\n  state.lencode = state.lendyn = new Int32Array(ENOUGH_LENS);\n  state.distcode = state.distdyn = new Int32Array(ENOUGH_DISTS);\n\n  state.sane = 1;\n  state.back = -1;\n  //Tracev((stderr, \"inflate: reset\\n\"));\n  return Z_OK$1;\n};\n\n\nconst inflateReset = (strm) => {\n\n  if (inflateStateCheck(strm)) { return Z_STREAM_ERROR$1; }\n  const state = strm.state;\n  state.wsize = 0;\n  state.whave = 0;\n  state.wnext = 0;\n  return inflateResetKeep(strm);\n\n};\n\n\nconst inflateReset2 = (strm, windowBits) => {\n  let wrap;\n\n  /* get the state */\n  if (inflateStateCheck(strm)) { return Z_STREAM_ERROR$1; }\n  const state = strm.state;\n\n  /* extract wrap request from windowBits parameter */\n  if (windowBits < 0) {\n    wrap = 0;\n    windowBits = -windowBits;\n  }\n  else {\n    wrap = (windowBits >> 4) + 5;\n    if (windowBits < 48) {\n      windowBits &= 15;\n    }\n  }\n\n  /* set number of window bits, free window if different */\n  if (windowBits && (windowBits < 8 || windowBits > 15)) {\n    return Z_STREAM_ERROR$1;\n  }\n  if (state.window !== null && state.wbits !== windowBits) {\n    state.window = null;\n  }\n\n  /* update state and reset the rest of it */\n  state.wrap = wrap;\n  state.wbits = windowBits;\n  return inflateReset(strm);\n};\n\n\nconst inflateInit2 = (strm, windowBits) => {\n\n  if (!strm) { return Z_STREAM_ERROR$1; }\n  //strm.msg = Z_NULL;                 /* in case we return an error */\n\n  const state = new InflateState();\n\n  //if (state === Z_NULL) return Z_MEM_ERROR;\n  //Tracev((stderr, \"inflate: allocated\\n\"));\n  strm.state = state;\n  state.strm = strm;\n  state.window = null/*Z_NULL*/;\n  state.mode = HEAD;     /* to pass state test in inflateReset2() */\n  const ret = inflateReset2(strm, windowBits);\n  if (ret !== Z_OK$1) {\n    strm.state = null/*Z_NULL*/;\n  }\n  return ret;\n};\n\n\nconst inflateInit = (strm) => {\n\n  return inflateInit2(strm, DEF_WBITS);\n};\n\n\n/*\n Return state with length and distance decoding tables and index sizes set to\n fixed code decoding.  Normally this returns fixed tables from inffixed.h.\n If BUILDFIXED is defined, then instead this routine builds the tables the\n first time it's called, and returns those tables the first time and\n thereafter.  This reduces the size of the code by about 2K bytes, in\n exchange for a little execution time.  However, BUILDFIXED should not be\n used for threaded applications, since the rewriting of the tables and virgin\n may not be thread-safe.\n */\nlet virgin = true;\n\nlet lenfix, distfix; // We have no pointers in JS, so keep tables separate\n\n\nconst fixedtables = (state) => {\n\n  /* build fixed huffman tables if first call (may not be thread safe) */\n  if (virgin) {\n    lenfix = new Int32Array(512);\n    distfix = new Int32Array(32);\n\n    /* literal/length table */\n    let sym = 0;\n    while (sym < 144) { state.lens[sym++] = 8; }\n    while (sym < 256) { state.lens[sym++] = 9; }\n    while (sym < 280) { state.lens[sym++] = 7; }\n    while (sym < 288) { state.lens[sym++] = 8; }\n\n    inftrees(LENS,  state.lens, 0, 288, lenfix,   0, state.work, { bits: 9 });\n\n    /* distance table */\n    sym = 0;\n    while (sym < 32) { state.lens[sym++] = 5; }\n\n    inftrees(DISTS, state.lens, 0, 32,   distfix, 0, state.work, { bits: 5 });\n\n    /* do this just once */\n    virgin = false;\n  }\n\n  state.lencode = lenfix;\n  state.lenbits = 9;\n  state.distcode = distfix;\n  state.distbits = 5;\n};\n\n\n/*\n Update the window with the last wsize (normally 32K) bytes written before\n returning.  If window does not exist yet, create it.  This is only called\n when a window is already in use, or when output has been written during this\n inflate call, but the end of the deflate stream has not been reached yet.\n It is also called to create a window for dictionary data when a dictionary\n is loaded.\n\n Providing output buffers larger than 32K to inflate() should provide a speed\n advantage, since only the last 32K of output is copied to the sliding window\n upon return from inflate(), and since all distances after the first 32K of\n output will fall in the output data, making match copies simpler and faster.\n The advantage may be dependent on the size of the processor's data caches.\n */\nconst updatewindow = (strm, src, end, copy) => {\n\n  let dist;\n  const state = strm.state;\n\n  /* if it hasn't been done already, allocate space for the window */\n  if (state.window === null) {\n    state.wsize = 1 << state.wbits;\n    state.wnext = 0;\n    state.whave = 0;\n\n    state.window = new Uint8Array(state.wsize);\n  }\n\n  /* copy state->wsize or less output bytes into the circular window */\n  if (copy >= state.wsize) {\n    state.window.set(src.subarray(end - state.wsize, end), 0);\n    state.wnext = 0;\n    state.whave = state.wsize;\n  }\n  else {\n    dist = state.wsize - state.wnext;\n    if (dist > copy) {\n      dist = copy;\n    }\n    //zmemcpy(state->window + state->wnext, end - copy, dist);\n    state.window.set(src.subarray(end - copy, end - copy + dist), state.wnext);\n    copy -= dist;\n    if (copy) {\n      //zmemcpy(state->window, end - copy, copy);\n      state.window.set(src.subarray(end - copy, end), 0);\n      state.wnext = copy;\n      state.whave = state.wsize;\n    }\n    else {\n      state.wnext += dist;\n      if (state.wnext === state.wsize) { state.wnext = 0; }\n      if (state.whave < state.wsize) { state.whave += dist; }\n    }\n  }\n  return 0;\n};\n\n\nconst inflate$2 = (strm, flush) => {\n\n  let state;\n  let input, output;          // input/output buffers\n  let next;                   /* next input INDEX */\n  let put;                    /* next output INDEX */\n  let have, left;             /* available input and output */\n  let hold;                   /* bit buffer */\n  let bits;                   /* bits in bit buffer */\n  let _in, _out;              /* save starting available input and output */\n  let copy;                   /* number of stored or match bytes to copy */\n  let from;                   /* where to copy match bytes from */\n  let from_source;\n  let here = 0;               /* current decoding table entry */\n  let here_bits, here_op, here_val; // paked \"here\" denormalized (JS specific)\n  //let last;                   /* parent table entry */\n  let last_bits, last_op, last_val; // paked \"last\" denormalized (JS specific)\n  let len;                    /* length to copy for repeats, bits to drop */\n  let ret;                    /* return code */\n  const hbuf = new Uint8Array(4);    /* buffer for gzip header crc calculation */\n  let opts;\n\n  let n; // temporary variable for NEED_BITS\n\n  const order = /* permutation of code lengths */\n    new Uint8Array([ 16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15 ]);\n\n\n  if (inflateStateCheck(strm) || !strm.output ||\n      (!strm.input && strm.avail_in !== 0)) {\n    return Z_STREAM_ERROR$1;\n  }\n\n  state = strm.state;\n  if (state.mode === TYPE) { state.mode = TYPEDO; }    /* skip check */\n\n\n  //--- LOAD() ---\n  put = strm.next_out;\n  output = strm.output;\n  left = strm.avail_out;\n  next = strm.next_in;\n  input = strm.input;\n  have = strm.avail_in;\n  hold = state.hold;\n  bits = state.bits;\n  //---\n\n  _in = have;\n  _out = left;\n  ret = Z_OK$1;\n\n  inf_leave: // goto emulation\n  for (;;) {\n    switch (state.mode) {\n      case HEAD:\n        if (state.wrap === 0) {\n          state.mode = TYPEDO;\n          break;\n        }\n        //=== NEEDBITS(16);\n        while (bits < 16) {\n          if (have === 0) { break inf_leave; }\n          have--;\n          hold += input[next++] << bits;\n          bits += 8;\n        }\n        //===//\n        if ((state.wrap & 2) && hold === 0x8b1f) {  /* gzip header */\n          if (state.wbits === 0) {\n            state.wbits = 15;\n          }\n          state.check = 0/*crc32(0L, Z_NULL, 0)*/;\n          //=== CRC2(state.check, hold);\n          hbuf[0] = hold & 0xff;\n          hbuf[1] = (hold >>> 8) & 0xff;\n          state.check = crc32_1(state.check, hbuf, 2, 0);\n          //===//\n\n          //=== INITBITS();\n          hold = 0;\n          bits = 0;\n          //===//\n          state.mode = FLAGS;\n          break;\n        }\n        if (state.head) {\n          state.head.done = false;\n        }\n        if (!(state.wrap & 1) ||   /* check if zlib header allowed */\n          (((hold & 0xff)/*BITS(8)*/ << 8) + (hold >> 8)) % 31) {\n          strm.msg = 'incorrect header check';\n          state.mode = BAD;\n          break;\n        }\n        if ((hold & 0x0f)/*BITS(4)*/ !== Z_DEFLATED) {\n          strm.msg = 'unknown compression method';\n          state.mode = BAD;\n          break;\n        }\n        //--- DROPBITS(4) ---//\n        hold >>>= 4;\n        bits -= 4;\n        //---//\n        len = (hold & 0x0f)/*BITS(4)*/ + 8;\n        if (state.wbits === 0) {\n          state.wbits = len;\n        }\n        if (len > 15 || len > state.wbits) {\n          strm.msg = 'invalid window size';\n          state.mode = BAD;\n          break;\n        }\n\n        // !!! pako patch. Force use `options.windowBits` if passed.\n        // Required to always use max window size by default.\n        state.dmax = 1 << state.wbits;\n        //state.dmax = 1 << len;\n\n        state.flags = 0;               /* indicate zlib header */\n        //Tracev((stderr, \"inflate:   zlib header ok\\n\"));\n        strm.adler = state.check = 1/*adler32(0L, Z_NULL, 0)*/;\n        state.mode = hold & 0x200 ? DICTID : TYPE;\n        //=== INITBITS();\n        hold = 0;\n        bits = 0;\n        //===//\n        break;\n      case FLAGS:\n        //=== NEEDBITS(16); */\n        while (bits < 16) {\n          if (have === 0) { break inf_leave; }\n          have--;\n          hold += input[next++] << bits;\n          bits += 8;\n        }\n        //===//\n        state.flags = hold;\n        if ((state.flags & 0xff) !== Z_DEFLATED) {\n          strm.msg = 'unknown compression method';\n          state.mode = BAD;\n          break;\n        }\n        if (state.flags & 0xe000) {\n          strm.msg = 'unknown header flags set';\n          state.mode = BAD;\n          break;\n        }\n        if (state.head) {\n          state.head.text = ((hold >> 8) & 1);\n        }\n        if ((state.flags & 0x0200) && (state.wrap & 4)) {\n          //=== CRC2(state.check, hold);\n          hbuf[0] = hold & 0xff;\n          hbuf[1] = (hold >>> 8) & 0xff;\n          state.check = crc32_1(state.check, hbuf, 2, 0);\n          //===//\n        }\n        //=== INITBITS();\n        hold = 0;\n        bits = 0;\n        //===//\n        state.mode = TIME;\n        /* falls through */\n      case TIME:\n        //=== NEEDBITS(32); */\n        while (bits < 32) {\n          if (have === 0) { break inf_leave; }\n          have--;\n          hold += input[next++] << bits;\n          bits += 8;\n        }\n        //===//\n        if (state.head) {\n          state.head.time = hold;\n        }\n        if ((state.flags & 0x0200) && (state.wrap & 4)) {\n          //=== CRC4(state.check, hold)\n          hbuf[0] = hold & 0xff;\n          hbuf[1] = (hold >>> 8) & 0xff;\n          hbuf[2] = (hold >>> 16) & 0xff;\n          hbuf[3] = (hold >>> 24) & 0xff;\n          state.check = crc32_1(state.check, hbuf, 4, 0);\n          //===\n        }\n        //=== INITBITS();\n        hold = 0;\n        bits = 0;\n        //===//\n        state.mode = OS;\n        /* falls through */\n      case OS:\n        //=== NEEDBITS(16); */\n        while (bits < 16) {\n          if (have === 0) { break inf_leave; }\n          have--;\n          hold += input[next++] << bits;\n          bits += 8;\n        }\n        //===//\n        if (state.head) {\n          state.head.xflags = (hold & 0xff);\n          state.head.os = (hold >> 8);\n        }\n        if ((state.flags & 0x0200) && (state.wrap & 4)) {\n          //=== CRC2(state.check, hold);\n          hbuf[0] = hold & 0xff;\n          hbuf[1] = (hold >>> 8) & 0xff;\n          state.check = crc32_1(state.check, hbuf, 2, 0);\n          //===//\n        }\n        //=== INITBITS();\n        hold = 0;\n        bits = 0;\n        //===//\n        state.mode = EXLEN;\n        /* falls through */\n      case EXLEN:\n        if (state.flags & 0x0400) {\n          //=== NEEDBITS(16); */\n          while (bits < 16) {\n            if (have === 0) { break inf_leave; }\n            have--;\n            hold += input[next++] << bits;\n            bits += 8;\n          }\n          //===//\n          state.length = hold;\n          if (state.head) {\n            state.head.extra_len = hold;\n          }\n          if ((state.flags & 0x0200) && (state.wrap & 4)) {\n            //=== CRC2(state.check, hold);\n            hbuf[0] = hold & 0xff;\n            hbuf[1] = (hold >>> 8) & 0xff;\n            state.check = crc32_1(state.check, hbuf, 2, 0);\n            //===//\n          }\n          //=== INITBITS();\n          hold = 0;\n          bits = 0;\n          //===//\n        }\n        else if (state.head) {\n          state.head.extra = null/*Z_NULL*/;\n        }\n        state.mode = EXTRA;\n        /* falls through */\n      case EXTRA:\n        if (state.flags & 0x0400) {\n          copy = state.length;\n          if (copy > have) { copy = have; }\n          if (copy) {\n            if (state.head) {\n              len = state.head.extra_len - state.length;\n              if (!state.head.extra) {\n                // Use untyped array for more convenient processing later\n                state.head.extra = new Uint8Array(state.head.extra_len);\n              }\n              state.head.extra.set(\n                input.subarray(\n                  next,\n                  // extra field is limited to 65536 bytes\n                  // - no need for additional size check\n                  next + copy\n                ),\n                /*len + copy > state.head.extra_max - len ? state.head.extra_max : copy,*/\n                len\n              );\n              //zmemcpy(state.head.extra + len, next,\n              //        len + copy > state.head.extra_max ?\n              //        state.head.extra_max - len : copy);\n            }\n            if ((state.flags & 0x0200) && (state.wrap & 4)) {\n              state.check = crc32_1(state.check, input, copy, next);\n            }\n            have -= copy;\n            next += copy;\n            state.length -= copy;\n          }\n          if (state.length) { break inf_leave; }\n        }\n        state.length = 0;\n        state.mode = NAME;\n        /* falls through */\n      case NAME:\n        if (state.flags & 0x0800) {\n          if (have === 0) { break inf_leave; }\n          copy = 0;\n          do {\n            // TODO: 2 or 1 bytes?\n            len = input[next + copy++];\n            /* use constant limit because in js we should not preallocate memory */\n            if (state.head && len &&\n                (state.length < 65536 /*state.head.name_max*/)) {\n              state.head.name += String.fromCharCode(len);\n            }\n          } while (len && copy < have);\n\n          if ((state.flags & 0x0200) && (state.wrap & 4)) {\n            state.check = crc32_1(state.check, input, copy, next);\n          }\n          have -= copy;\n          next += copy;\n          if (len) { break inf_leave; }\n        }\n        else if (state.head) {\n          state.head.name = null;\n        }\n        state.length = 0;\n        state.mode = COMMENT;\n        /* falls through */\n      case COMMENT:\n        if (state.flags & 0x1000) {\n          if (have === 0) { break inf_leave; }\n          copy = 0;\n          do {\n            len = input[next + copy++];\n            /* use constant limit because in js we should not preallocate memory */\n            if (state.head && len &&\n                (state.length < 65536 /*state.head.comm_max*/)) {\n              state.head.comment += String.fromCharCode(len);\n            }\n          } while (len && copy < have);\n          if ((state.flags & 0x0200) && (state.wrap & 4)) {\n            state.check = crc32_1(state.check, input, copy, next);\n          }\n          have -= copy;\n          next += copy;\n          if (len) { break inf_leave; }\n        }\n        else if (state.head) {\n          state.head.comment = null;\n        }\n        state.mode = HCRC;\n        /* falls through */\n      case HCRC:\n        if (state.flags & 0x0200) {\n          //=== NEEDBITS(16); */\n          while (bits < 16) {\n            if (have === 0) { break inf_leave; }\n            have--;\n            hold += input[next++] << bits;\n            bits += 8;\n          }\n          //===//\n          if ((state.wrap & 4) && hold !== (state.check & 0xffff)) {\n            strm.msg = 'header crc mismatch';\n            state.mode = BAD;\n            break;\n          }\n          //=== INITBITS();\n          hold = 0;\n          bits = 0;\n          //===//\n        }\n        if (state.head) {\n          state.head.hcrc = ((state.flags >> 9) & 1);\n          state.head.done = true;\n        }\n        strm.adler = state.check = 0;\n        state.mode = TYPE;\n        break;\n      case DICTID:\n        //=== NEEDBITS(32); */\n        while (bits < 32) {\n          if (have === 0) { break inf_leave; }\n          have--;\n          hold += input[next++] << bits;\n          bits += 8;\n        }\n        //===//\n        strm.adler = state.check = zswap32(hold);\n        //=== INITBITS();\n        hold = 0;\n        bits = 0;\n        //===//\n        state.mode = DICT;\n        /* falls through */\n      case DICT:\n        if (state.havedict === 0) {\n          //--- RESTORE() ---\n          strm.next_out = put;\n          strm.avail_out = left;\n          strm.next_in = next;\n          strm.avail_in = have;\n          state.hold = hold;\n          state.bits = bits;\n          //---\n          return Z_NEED_DICT$1;\n        }\n        strm.adler = state.check = 1/*adler32(0L, Z_NULL, 0)*/;\n        state.mode = TYPE;\n        /* falls through */\n      case TYPE:\n        if (flush === Z_BLOCK || flush === Z_TREES) { break inf_leave; }\n        /* falls through */\n      case TYPEDO:\n        if (state.last) {\n          //--- BYTEBITS() ---//\n          hold >>>= bits & 7;\n          bits -= bits & 7;\n          //---//\n          state.mode = CHECK;\n          break;\n        }\n        //=== NEEDBITS(3); */\n        while (bits < 3) {\n          if (have === 0) { break inf_leave; }\n          have--;\n          hold += input[next++] << bits;\n          bits += 8;\n        }\n        //===//\n        state.last = (hold & 0x01)/*BITS(1)*/;\n        //--- DROPBITS(1) ---//\n        hold >>>= 1;\n        bits -= 1;\n        //---//\n\n        switch ((hold & 0x03)/*BITS(2)*/) {\n          case 0:                             /* stored block */\n            //Tracev((stderr, \"inflate:     stored block%s\\n\",\n            //        state.last ? \" (last)\" : \"\"));\n            state.mode = STORED;\n            break;\n          case 1:                             /* fixed block */\n            fixedtables(state);\n            //Tracev((stderr, \"inflate:     fixed codes block%s\\n\",\n            //        state.last ? \" (last)\" : \"\"));\n            state.mode = LEN_;             /* decode codes */\n            if (flush === Z_TREES) {\n              //--- DROPBITS(2) ---//\n              hold >>>= 2;\n              bits -= 2;\n              //---//\n              break inf_leave;\n            }\n            break;\n          case 2:                             /* dynamic block */\n            //Tracev((stderr, \"inflate:     dynamic codes block%s\\n\",\n            //        state.last ? \" (last)\" : \"\"));\n            state.mode = TABLE;\n            break;\n          case 3:\n            strm.msg = 'invalid block type';\n            state.mode = BAD;\n        }\n        //--- DROPBITS(2) ---//\n        hold >>>= 2;\n        bits -= 2;\n        //---//\n        break;\n      case STORED:\n        //--- BYTEBITS() ---// /* go to byte boundary */\n        hold >>>= bits & 7;\n        bits -= bits & 7;\n        //---//\n        //=== NEEDBITS(32); */\n        while (bits < 32) {\n          if (have === 0) { break inf_leave; }\n          have--;\n          hold += input[next++] << bits;\n          bits += 8;\n        }\n        //===//\n        if ((hold & 0xffff) !== ((hold >>> 16) ^ 0xffff)) {\n          strm.msg = 'invalid stored block lengths';\n          state.mode = BAD;\n          break;\n        }\n        state.length = hold & 0xffff;\n        //Tracev((stderr, \"inflate:       stored length %u\\n\",\n        //        state.length));\n        //=== INITBITS();\n        hold = 0;\n        bits = 0;\n        //===//\n        state.mode = COPY_;\n        if (flush === Z_TREES) { break inf_leave; }\n        /* falls through */\n      case COPY_:\n        state.mode = COPY;\n        /* falls through */\n      case COPY:\n        copy = state.length;\n        if (copy) {\n          if (copy > have) { copy = have; }\n          if (copy > left) { copy = left; }\n          if (copy === 0) { break inf_leave; }\n          //--- zmemcpy(put, next, copy); ---\n          output.set(input.subarray(next, next + copy), put);\n          //---//\n          have -= copy;\n          next += copy;\n          left -= copy;\n          put += copy;\n          state.length -= copy;\n          break;\n        }\n        //Tracev((stderr, \"inflate:       stored end\\n\"));\n        state.mode = TYPE;\n        break;\n      case TABLE:\n        //=== NEEDBITS(14); */\n        while (bits < 14) {\n          if (have === 0) { break inf_leave; }\n          have--;\n          hold += input[next++] << bits;\n          bits += 8;\n        }\n        //===//\n        state.nlen = (hold & 0x1f)/*BITS(5)*/ + 257;\n        //--- DROPBITS(5) ---//\n        hold >>>= 5;\n        bits -= 5;\n        //---//\n        state.ndist = (hold & 0x1f)/*BITS(5)*/ + 1;\n        //--- DROPBITS(5) ---//\n        hold >>>= 5;\n        bits -= 5;\n        //---//\n        state.ncode = (hold & 0x0f)/*BITS(4)*/ + 4;\n        //--- DROPBITS(4) ---//\n        hold >>>= 4;\n        bits -= 4;\n        //---//\n//#ifndef PKZIP_BUG_WORKAROUND\n        if (state.nlen > 286 || state.ndist > 30) {\n          strm.msg = 'too many length or distance symbols';\n          state.mode = BAD;\n          break;\n        }\n//#endif\n        //Tracev((stderr, \"inflate:       table sizes ok\\n\"));\n        state.have = 0;\n        state.mode = LENLENS;\n        /* falls through */\n      case LENLENS:\n        while (state.have < state.ncode) {\n          //=== NEEDBITS(3);\n          while (bits < 3) {\n            if (have === 0) { break inf_leave; }\n            have--;\n            hold += input[next++] << bits;\n            bits += 8;\n          }\n          //===//\n          state.lens[order[state.have++]] = (hold & 0x07);//BITS(3);\n          //--- DROPBITS(3) ---//\n          hold >>>= 3;\n          bits -= 3;\n          //---//\n        }\n        while (state.have < 19) {\n          state.lens[order[state.have++]] = 0;\n        }\n        // We have separate tables & no pointers. 2 commented lines below not needed.\n        //state.next = state.codes;\n        //state.lencode = state.next;\n        // Switch to use dynamic table\n        state.lencode = state.lendyn;\n        state.lenbits = 7;\n\n        opts = { bits: state.lenbits };\n        ret = inftrees(CODES, state.lens, 0, 19, state.lencode, 0, state.work, opts);\n        state.lenbits = opts.bits;\n\n        if (ret) {\n          strm.msg = 'invalid code lengths set';\n          state.mode = BAD;\n          break;\n        }\n        //Tracev((stderr, \"inflate:       code lengths ok\\n\"));\n        state.have = 0;\n        state.mode = CODELENS;\n        /* falls through */\n      case CODELENS:\n        while (state.have < state.nlen + state.ndist) {\n          for (;;) {\n            here = state.lencode[hold & ((1 << state.lenbits) - 1)];/*BITS(state.lenbits)*/\n            here_bits = here >>> 24;\n            here_op = (here >>> 16) & 0xff;\n            here_val = here & 0xffff;\n\n            if ((here_bits) <= bits) { break; }\n            //--- PULLBYTE() ---//\n            if (have === 0) { break inf_leave; }\n            have--;\n            hold += input[next++] << bits;\n            bits += 8;\n            //---//\n          }\n          if (here_val < 16) {\n            //--- DROPBITS(here.bits) ---//\n            hold >>>= here_bits;\n            bits -= here_bits;\n            //---//\n            state.lens[state.have++] = here_val;\n          }\n          else {\n            if (here_val === 16) {\n              //=== NEEDBITS(here.bits + 2);\n              n = here_bits + 2;\n              while (bits < n) {\n                if (have === 0) { break inf_leave; }\n                have--;\n                hold += input[next++] << bits;\n                bits += 8;\n              }\n              //===//\n              //--- DROPBITS(here.bits) ---//\n              hold >>>= here_bits;\n              bits -= here_bits;\n              //---//\n              if (state.have === 0) {\n                strm.msg = 'invalid bit length repeat';\n                state.mode = BAD;\n                break;\n              }\n              len = state.lens[state.have - 1];\n              copy = 3 + (hold & 0x03);//BITS(2);\n              //--- DROPBITS(2) ---//\n              hold >>>= 2;\n              bits -= 2;\n              //---//\n            }\n            else if (here_val === 17) {\n              //=== NEEDBITS(here.bits + 3);\n              n = here_bits + 3;\n              while (bits < n) {\n                if (have === 0) { break inf_leave; }\n                have--;\n                hold += input[next++] << bits;\n                bits += 8;\n              }\n              //===//\n              //--- DROPBITS(here.bits) ---//\n              hold >>>= here_bits;\n              bits -= here_bits;\n              //---//\n              len = 0;\n              copy = 3 + (hold & 0x07);//BITS(3);\n              //--- DROPBITS(3) ---//\n              hold >>>= 3;\n              bits -= 3;\n              //---//\n            }\n            else {\n              //=== NEEDBITS(here.bits + 7);\n              n = here_bits + 7;\n              while (bits < n) {\n                if (have === 0) { break inf_leave; }\n                have--;\n                hold += input[next++] << bits;\n                bits += 8;\n              }\n              //===//\n              //--- DROPBITS(here.bits) ---//\n              hold >>>= here_bits;\n              bits -= here_bits;\n              //---//\n              len = 0;\n              copy = 11 + (hold & 0x7f);//BITS(7);\n              //--- DROPBITS(7) ---//\n              hold >>>= 7;\n              bits -= 7;\n              //---//\n            }\n            if (state.have + copy > state.nlen + state.ndist) {\n              strm.msg = 'invalid bit length repeat';\n              state.mode = BAD;\n              break;\n            }\n            while (copy--) {\n              state.lens[state.have++] = len;\n            }\n          }\n        }\n\n        /* handle error breaks in while */\n        if (state.mode === BAD) { break; }\n\n        /* check for end-of-block code (better have one) */\n        if (state.lens[256] === 0) {\n          strm.msg = 'invalid code -- missing end-of-block';\n          state.mode = BAD;\n          break;\n        }\n\n        /* build code tables -- note: do not change the lenbits or distbits\n           values here (9 and 6) without reading the comments in inftrees.h\n           concerning the ENOUGH constants, which depend on those values */\n        state.lenbits = 9;\n\n        opts = { bits: state.lenbits };\n        ret = inftrees(LENS, state.lens, 0, state.nlen, state.lencode, 0, state.work, opts);\n        // We have separate tables & no pointers. 2 commented lines below not needed.\n        // state.next_index = opts.table_index;\n        state.lenbits = opts.bits;\n        // state.lencode = state.next;\n\n        if (ret) {\n          strm.msg = 'invalid literal/lengths set';\n          state.mode = BAD;\n          break;\n        }\n\n        state.distbits = 6;\n        //state.distcode.copy(state.codes);\n        // Switch to use dynamic table\n        state.distcode = state.distdyn;\n        opts = { bits: state.distbits };\n        ret = inftrees(DISTS, state.lens, state.nlen, state.ndist, state.distcode, 0, state.work, opts);\n        // We have separate tables & no pointers. 2 commented lines below not needed.\n        // state.next_index = opts.table_index;\n        state.distbits = opts.bits;\n        // state.distcode = state.next;\n\n        if (ret) {\n          strm.msg = 'invalid distances set';\n          state.mode = BAD;\n          break;\n        }\n        //Tracev((stderr, 'inflate:       codes ok\\n'));\n        state.mode = LEN_;\n        if (flush === Z_TREES) { break inf_leave; }\n        /* falls through */\n      case LEN_:\n        state.mode = LEN;\n        /* falls through */\n      case LEN:\n        if (have >= 6 && left >= 258) {\n          //--- RESTORE() ---\n          strm.next_out = put;\n          strm.avail_out = left;\n          strm.next_in = next;\n          strm.avail_in = have;\n          state.hold = hold;\n          state.bits = bits;\n          //---\n          inffast(strm, _out);\n          //--- LOAD() ---\n          put = strm.next_out;\n          output = strm.output;\n          left = strm.avail_out;\n          next = strm.next_in;\n          input = strm.input;\n          have = strm.avail_in;\n          hold = state.hold;\n          bits = state.bits;\n          //---\n\n          if (state.mode === TYPE) {\n            state.back = -1;\n          }\n          break;\n        }\n        state.back = 0;\n        for (;;) {\n          here = state.lencode[hold & ((1 << state.lenbits) - 1)];  /*BITS(state.lenbits)*/\n          here_bits = here >>> 24;\n          here_op = (here >>> 16) & 0xff;\n          here_val = here & 0xffff;\n\n          if (here_bits <= bits) { break; }\n          //--- PULLBYTE() ---//\n          if (have === 0) { break inf_leave; }\n          have--;\n          hold += input[next++] << bits;\n          bits += 8;\n          //---//\n        }\n        if (here_op && (here_op & 0xf0) === 0) {\n          last_bits = here_bits;\n          last_op = here_op;\n          last_val = here_val;\n          for (;;) {\n            here = state.lencode[last_val +\n                    ((hold & ((1 << (last_bits + last_op)) - 1))/*BITS(last.bits + last.op)*/ >> last_bits)];\n            here_bits = here >>> 24;\n            here_op = (here >>> 16) & 0xff;\n            here_val = here & 0xffff;\n\n            if ((last_bits + here_bits) <= bits) { break; }\n            //--- PULLBYTE() ---//\n            if (have === 0) { break inf_leave; }\n            have--;\n            hold += input[next++] << bits;\n            bits += 8;\n            //---//\n          }\n          //--- DROPBITS(last.bits) ---//\n          hold >>>= last_bits;\n          bits -= last_bits;\n          //---//\n          state.back += last_bits;\n        }\n        //--- DROPBITS(here.bits) ---//\n        hold >>>= here_bits;\n        bits -= here_bits;\n        //---//\n        state.back += here_bits;\n        state.length = here_val;\n        if (here_op === 0) {\n          //Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ?\n          //        \"inflate:         literal '%c'\\n\" :\n          //        \"inflate:         literal 0x%02x\\n\", here.val));\n          state.mode = LIT;\n          break;\n        }\n        if (here_op & 32) {\n          //Tracevv((stderr, \"inflate:         end of block\\n\"));\n          state.back = -1;\n          state.mode = TYPE;\n          break;\n        }\n        if (here_op & 64) {\n          strm.msg = 'invalid literal/length code';\n          state.mode = BAD;\n          break;\n        }\n        state.extra = here_op & 15;\n        state.mode = LENEXT;\n        /* falls through */\n      case LENEXT:\n        if (state.extra) {\n          //=== NEEDBITS(state.extra);\n          n = state.extra;\n          while (bits < n) {\n            if (have === 0) { break inf_leave; }\n            have--;\n            hold += input[next++] << bits;\n            bits += 8;\n          }\n          //===//\n          state.length += hold & ((1 << state.extra) - 1)/*BITS(state.extra)*/;\n          //--- DROPBITS(state.extra) ---//\n          hold >>>= state.extra;\n          bits -= state.extra;\n          //---//\n          state.back += state.extra;\n        }\n        //Tracevv((stderr, \"inflate:         length %u\\n\", state.length));\n        state.was = state.length;\n        state.mode = DIST;\n        /* falls through */\n      case DIST:\n        for (;;) {\n          here = state.distcode[hold & ((1 << state.distbits) - 1)];/*BITS(state.distbits)*/\n          here_bits = here >>> 24;\n          here_op = (here >>> 16) & 0xff;\n          here_val = here & 0xffff;\n\n          if ((here_bits) <= bits) { break; }\n          //--- PULLBYTE() ---//\n          if (have === 0) { break inf_leave; }\n          have--;\n          hold += input[next++] << bits;\n          bits += 8;\n          //---//\n        }\n        if ((here_op & 0xf0) === 0) {\n          last_bits = here_bits;\n          last_op = here_op;\n          last_val = here_val;\n          for (;;) {\n            here = state.distcode[last_val +\n                    ((hold & ((1 << (last_bits + last_op)) - 1))/*BITS(last.bits + last.op)*/ >> last_bits)];\n            here_bits = here >>> 24;\n            here_op = (here >>> 16) & 0xff;\n            here_val = here & 0xffff;\n\n            if ((last_bits + here_bits) <= bits) { break; }\n            //--- PULLBYTE() ---//\n            if (have === 0) { break inf_leave; }\n            have--;\n            hold += input[next++] << bits;\n            bits += 8;\n            //---//\n          }\n          //--- DROPBITS(last.bits) ---//\n          hold >>>= last_bits;\n          bits -= last_bits;\n          //---//\n          state.back += last_bits;\n        }\n        //--- DROPBITS(here.bits) ---//\n        hold >>>= here_bits;\n        bits -= here_bits;\n        //---//\n        state.back += here_bits;\n        if (here_op & 64) {\n          strm.msg = 'invalid distance code';\n          state.mode = BAD;\n          break;\n        }\n        state.offset = here_val;\n        state.extra = (here_op) & 15;\n        state.mode = DISTEXT;\n        /* falls through */\n      case DISTEXT:\n        if (state.extra) {\n          //=== NEEDBITS(state.extra);\n          n = state.extra;\n          while (bits < n) {\n            if (have === 0) { break inf_leave; }\n            have--;\n            hold += input[next++] << bits;\n            bits += 8;\n          }\n          //===//\n          state.offset += hold & ((1 << state.extra) - 1)/*BITS(state.extra)*/;\n          //--- DROPBITS(state.extra) ---//\n          hold >>>= state.extra;\n          bits -= state.extra;\n          //---//\n          state.back += state.extra;\n        }\n//#ifdef INFLATE_STRICT\n        if (state.offset > state.dmax) {\n          strm.msg = 'invalid distance too far back';\n          state.mode = BAD;\n          break;\n        }\n//#endif\n        //Tracevv((stderr, \"inflate:         distance %u\\n\", state.offset));\n        state.mode = MATCH;\n        /* falls through */\n      case MATCH:\n        if (left === 0) { break inf_leave; }\n        copy = _out - left;\n        if (state.offset > copy) {         /* copy from window */\n          copy = state.offset - copy;\n          if (copy > state.whave) {\n            if (state.sane) {\n              strm.msg = 'invalid distance too far back';\n              state.mode = BAD;\n              break;\n            }\n// (!) This block is disabled in zlib defaults,\n// don't enable it for binary compatibility\n//#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR\n//          Trace((stderr, \"inflate.c too far\\n\"));\n//          copy -= state.whave;\n//          if (copy > state.length) { copy = state.length; }\n//          if (copy > left) { copy = left; }\n//          left -= copy;\n//          state.length -= copy;\n//          do {\n//            output[put++] = 0;\n//          } while (--copy);\n//          if (state.length === 0) { state.mode = LEN; }\n//          break;\n//#endif\n          }\n          if (copy > state.wnext) {\n            copy -= state.wnext;\n            from = state.wsize - copy;\n          }\n          else {\n            from = state.wnext - copy;\n          }\n          if (copy > state.length) { copy = state.length; }\n          from_source = state.window;\n        }\n        else {                              /* copy from output */\n          from_source = output;\n          from = put - state.offset;\n          copy = state.length;\n        }\n        if (copy > left) { copy = left; }\n        left -= copy;\n        state.length -= copy;\n        do {\n          output[put++] = from_source[from++];\n        } while (--copy);\n        if (state.length === 0) { state.mode = LEN; }\n        break;\n      case LIT:\n        if (left === 0) { break inf_leave; }\n        output[put++] = state.length;\n        left--;\n        state.mode = LEN;\n        break;\n      case CHECK:\n        if (state.wrap) {\n          //=== NEEDBITS(32);\n          while (bits < 32) {\n            if (have === 0) { break inf_leave; }\n            have--;\n            // Use '|' instead of '+' to make sure that result is signed\n            hold |= input[next++] << bits;\n            bits += 8;\n          }\n          //===//\n          _out -= left;\n          strm.total_out += _out;\n          state.total += _out;\n          if ((state.wrap & 4) && _out) {\n            strm.adler = state.check =\n                /*UPDATE_CHECK(state.check, put - _out, _out);*/\n                (state.flags ? crc32_1(state.check, output, _out, put - _out) : adler32_1(state.check, output, _out, put - _out));\n\n          }\n          _out = left;\n          // NB: crc32 stored as signed 32-bit int, zswap32 returns signed too\n          if ((state.wrap & 4) && (state.flags ? hold : zswap32(hold)) !== state.check) {\n            strm.msg = 'incorrect data check';\n            state.mode = BAD;\n            break;\n          }\n          //=== INITBITS();\n          hold = 0;\n          bits = 0;\n          //===//\n          //Tracev((stderr, \"inflate:   check matches trailer\\n\"));\n        }\n        state.mode = LENGTH;\n        /* falls through */\n      case LENGTH:\n        if (state.wrap && state.flags) {\n          //=== NEEDBITS(32);\n          while (bits < 32) {\n            if (have === 0) { break inf_leave; }\n            have--;\n            hold += input[next++] << bits;\n            bits += 8;\n          }\n          //===//\n          if ((state.wrap & 4) && hold !== (state.total & 0xffffffff)) {\n            strm.msg = 'incorrect length check';\n            state.mode = BAD;\n            break;\n          }\n          //=== INITBITS();\n          hold = 0;\n          bits = 0;\n          //===//\n          //Tracev((stderr, \"inflate:   length matches trailer\\n\"));\n        }\n        state.mode = DONE;\n        /* falls through */\n      case DONE:\n        ret = Z_STREAM_END$1;\n        break inf_leave;\n      case BAD:\n        ret = Z_DATA_ERROR$1;\n        break inf_leave;\n      case MEM:\n        return Z_MEM_ERROR$1;\n      case SYNC:\n        /* falls through */\n      default:\n        return Z_STREAM_ERROR$1;\n    }\n  }\n\n  // inf_leave <- here is real place for \"goto inf_leave\", emulated via \"break inf_leave\"\n\n  /*\n     Return from inflate(), updating the total counts and the check value.\n     If there was no progress during the inflate() call, return a buffer\n     error.  Call updatewindow() to create and/or update the window state.\n     Note: a memory error from inflate() is non-recoverable.\n   */\n\n  //--- RESTORE() ---\n  strm.next_out = put;\n  strm.avail_out = left;\n  strm.next_in = next;\n  strm.avail_in = have;\n  state.hold = hold;\n  state.bits = bits;\n  //---\n\n  if (state.wsize || (_out !== strm.avail_out && state.mode < BAD &&\n                      (state.mode < CHECK || flush !== Z_FINISH$1))) {\n    if (updatewindow(strm, strm.output, strm.next_out, _out - strm.avail_out)) ;\n  }\n  _in -= strm.avail_in;\n  _out -= strm.avail_out;\n  strm.total_in += _in;\n  strm.total_out += _out;\n  state.total += _out;\n  if ((state.wrap & 4) && _out) {\n    strm.adler = state.check = /*UPDATE_CHECK(state.check, strm.next_out - _out, _out);*/\n      (state.flags ? crc32_1(state.check, output, _out, strm.next_out - _out) : adler32_1(state.check, output, _out, strm.next_out - _out));\n  }\n  strm.data_type = state.bits + (state.last ? 64 : 0) +\n                    (state.mode === TYPE ? 128 : 0) +\n                    (state.mode === LEN_ || state.mode === COPY_ ? 256 : 0);\n  if (((_in === 0 && _out === 0) || flush === Z_FINISH$1) && ret === Z_OK$1) {\n    ret = Z_BUF_ERROR;\n  }\n  return ret;\n};\n\n\nconst inflateEnd = (strm) => {\n\n  if (inflateStateCheck(strm)) {\n    return Z_STREAM_ERROR$1;\n  }\n\n  let state = strm.state;\n  if (state.window) {\n    state.window = null;\n  }\n  strm.state = null;\n  return Z_OK$1;\n};\n\n\nconst inflateGetHeader = (strm, head) => {\n\n  /* check state */\n  if (inflateStateCheck(strm)) { return Z_STREAM_ERROR$1; }\n  const state = strm.state;\n  if ((state.wrap & 2) === 0) { return Z_STREAM_ERROR$1; }\n\n  /* save header structure */\n  state.head = head;\n  head.done = false;\n  return Z_OK$1;\n};\n\n\nconst inflateSetDictionary = (strm, dictionary) => {\n  const dictLength = dictionary.length;\n\n  let state;\n  let dictid;\n  let ret;\n\n  /* check state */\n  if (inflateStateCheck(strm)) { return Z_STREAM_ERROR$1; }\n  state = strm.state;\n\n  if (state.wrap !== 0 && state.mode !== DICT) {\n    return Z_STREAM_ERROR$1;\n  }\n\n  /* check for correct dictionary identifier */\n  if (state.mode === DICT) {\n    dictid = 1; /* adler32(0, null, 0)*/\n    /* dictid = adler32(dictid, dictionary, dictLength); */\n    dictid = adler32_1(dictid, dictionary, dictLength, 0);\n    if (dictid !== state.check) {\n      return Z_DATA_ERROR$1;\n    }\n  }\n  /* copy dictionary to window using updatewindow(), which will amend the\n   existing dictionary if appropriate */\n  ret = updatewindow(strm, dictionary, dictLength, dictLength);\n  if (ret) {\n    state.mode = MEM;\n    return Z_MEM_ERROR$1;\n  }\n  state.havedict = 1;\n  // Tracev((stderr, \"inflate:   dictionary set\\n\"));\n  return Z_OK$1;\n};\n\n\nvar inflateReset_1 = inflateReset;\nvar inflateReset2_1 = inflateReset2;\nvar inflateResetKeep_1 = inflateResetKeep;\nvar inflateInit_1 = inflateInit;\nvar inflateInit2_1 = inflateInit2;\nvar inflate_2$1 = inflate$2;\nvar inflateEnd_1 = inflateEnd;\nvar inflateGetHeader_1 = inflateGetHeader;\nvar inflateSetDictionary_1 = inflateSetDictionary;\nvar inflateInfo = 'pako inflate (from Nodeca project)';\n\n/* Not implemented\nmodule.exports.inflateCodesUsed = inflateCodesUsed;\nmodule.exports.inflateCopy = inflateCopy;\nmodule.exports.inflateGetDictionary = inflateGetDictionary;\nmodule.exports.inflateMark = inflateMark;\nmodule.exports.inflatePrime = inflatePrime;\nmodule.exports.inflateSync = inflateSync;\nmodule.exports.inflateSyncPoint = inflateSyncPoint;\nmodule.exports.inflateUndermine = inflateUndermine;\nmodule.exports.inflateValidate = inflateValidate;\n*/\n\nvar inflate_1$2 = {\n\tinflateReset: inflateReset_1,\n\tinflateReset2: inflateReset2_1,\n\tinflateResetKeep: inflateResetKeep_1,\n\tinflateInit: inflateInit_1,\n\tinflateInit2: inflateInit2_1,\n\tinflate: inflate_2$1,\n\tinflateEnd: inflateEnd_1,\n\tinflateGetHeader: inflateGetHeader_1,\n\tinflateSetDictionary: inflateSetDictionary_1,\n\tinflateInfo: inflateInfo\n};\n\n// (C) 1995-2013 Jean-loup Gailly and Mark Adler\n// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin\n//\n// This software is provided 'as-is', without any express or implied\n// warranty. In no event will the authors be held liable for any damages\n// arising from the use of this software.\n//\n// Permission is granted to anyone to use this software for any purpose,\n// including commercial applications, and to alter it and redistribute it\n// freely, subject to the following restrictions:\n//\n// 1. The origin of this software must not be misrepresented; you must not\n//   claim that you wrote the original software. If you use this software\n//   in a product, an acknowledgment in the product documentation would be\n//   appreciated but is not required.\n// 2. Altered source versions must be plainly marked as such, and must not be\n//   misrepresented as being the original software.\n// 3. This notice may not be removed or altered from any source distribution.\n\nfunction GZheader() {\n  /* true if compressed data believed to be text */\n  this.text       = 0;\n  /* modification time */\n  this.time       = 0;\n  /* extra flags (not used when writing a gzip file) */\n  this.xflags     = 0;\n  /* operating system */\n  this.os         = 0;\n  /* pointer to extra field or Z_NULL if none */\n  this.extra      = null;\n  /* extra field length (valid if extra != Z_NULL) */\n  this.extra_len  = 0; // Actually, we don't need it in JS,\n                       // but leave for few code modifications\n\n  //\n  // Setup limits is not necessary because in js we should not preallocate memory\n  // for inflate use constant limit in 65536 bytes\n  //\n\n  /* space at extra (only when reading header) */\n  // this.extra_max  = 0;\n  /* pointer to zero-terminated file name or Z_NULL */\n  this.name       = '';\n  /* space at name (only when reading header) */\n  // this.name_max   = 0;\n  /* pointer to zero-terminated comment or Z_NULL */\n  this.comment    = '';\n  /* space at comment (only when reading header) */\n  // this.comm_max   = 0;\n  /* true if there was or will be a header crc */\n  this.hcrc       = 0;\n  /* true when done reading gzip header (not used when writing a gzip file) */\n  this.done       = false;\n}\n\nvar gzheader = GZheader;\n\nconst toString = Object.prototype.toString;\n\n/* Public constants ==========================================================*/\n/* ===========================================================================*/\n\nconst {\n  Z_NO_FLUSH, Z_FINISH,\n  Z_OK, Z_STREAM_END, Z_NEED_DICT, Z_STREAM_ERROR, Z_DATA_ERROR, Z_MEM_ERROR\n} = constants$2;\n\n/* ===========================================================================*/\n\n\n/**\n * class Inflate\n *\n * Generic JS-style wrapper for zlib calls. If you don't need\n * streaming behaviour - use more simple functions: [[inflate]]\n * and [[inflateRaw]].\n **/\n\n/* internal\n * inflate.chunks -> Array\n *\n * Chunks of output data, if [[Inflate#onData]] not overridden.\n **/\n\n/**\n * Inflate.result -> Uint8Array|String\n *\n * Uncompressed result, generated by default [[Inflate#onData]]\n * and [[Inflate#onEnd]] handlers. Filled after you push last chunk\n * (call [[Inflate#push]] with `Z_FINISH` / `true` param).\n **/\n\n/**\n * Inflate.err -> Number\n *\n * Error code after inflate finished. 0 (Z_OK) on success.\n * Should be checked if broken data possible.\n **/\n\n/**\n * Inflate.msg -> String\n *\n * Error message, if [[Inflate.err]] != 0\n **/\n\n\n/**\n * new Inflate(options)\n * - options (Object): zlib inflate options.\n *\n * Creates new inflator instance with specified params. Throws exception\n * on bad params. Supported options:\n *\n * - `windowBits`\n * - `dictionary`\n *\n * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)\n * for more information on these.\n *\n * Additional options, for internal needs:\n *\n * - `chunkSize` - size of generated data chunks (16K by default)\n * - `raw` (Boolean) - do raw inflate\n * - `to` (String) - if equal to 'string', then result will be converted\n *   from utf8 to utf16 (javascript) string. When string output requested,\n *   chunk length can differ from `chunkSize`, depending on content.\n *\n * By default, when no options set, autodetect deflate/gzip data format via\n * wrapper header.\n *\n * ##### Example:\n *\n * ```javascript\n * const pako = require('pako')\n * const chunk1 = new Uint8Array([1,2,3,4,5,6,7,8,9])\n * const chunk2 = new Uint8Array([10,11,12,13,14,15,16,17,18,19]);\n *\n * const inflate = new pako.Inflate({ level: 3});\n *\n * inflate.push(chunk1, false);\n * inflate.push(chunk2, true);  // true -> last chunk\n *\n * if (inflate.err) { throw new Error(inflate.err); }\n *\n * console.log(inflate.result);\n * ```\n **/\nfunction Inflate$1(options) {\n  this.options = common.assign({\n    chunkSize: 1024 * 64,\n    windowBits: 15,\n    to: ''\n  }, options || {});\n\n  const opt = this.options;\n\n  // Force window size for `raw` data, if not set directly,\n  // because we have no header for autodetect.\n  if (opt.raw && (opt.windowBits >= 0) && (opt.windowBits < 16)) {\n    opt.windowBits = -opt.windowBits;\n    if (opt.windowBits === 0) { opt.windowBits = -15; }\n  }\n\n  // If `windowBits` not defined (and mode not raw) - set autodetect flag for gzip/deflate\n  if ((opt.windowBits >= 0) && (opt.windowBits < 16) &&\n      !(options && options.windowBits)) {\n    opt.windowBits += 32;\n  }\n\n  // Gzip header has no info about windows size, we can do autodetect only\n  // for deflate. So, if window size not set, force it to max when gzip possible\n  if ((opt.windowBits > 15) && (opt.windowBits < 48)) {\n    // bit 3 (16) -> gzipped data\n    // bit 4 (32) -> autodetect gzip/deflate\n    if ((opt.windowBits & 15) === 0) {\n      opt.windowBits |= 15;\n    }\n  }\n\n  this.err    = 0;      // error code, if happens (0 = Z_OK)\n  this.msg    = '';     // error message\n  this.ended  = false;  // used to avoid multiple onEnd() calls\n  this.chunks = [];     // chunks of compressed data\n\n  this.strm   = new zstream();\n  this.strm.avail_out = 0;\n\n  let status  = inflate_1$2.inflateInit2(\n    this.strm,\n    opt.windowBits\n  );\n\n  if (status !== Z_OK) {\n    throw new Error(messages[status]);\n  }\n\n  this.header = new gzheader();\n\n  inflate_1$2.inflateGetHeader(this.strm, this.header);\n\n  // Setup dictionary\n  if (opt.dictionary) {\n    // Convert data if needed\n    if (typeof opt.dictionary === 'string') {\n      opt.dictionary = strings.string2buf(opt.dictionary);\n    } else if (toString.call(opt.dictionary) === '[object ArrayBuffer]') {\n      opt.dictionary = new Uint8Array(opt.dictionary);\n    }\n    if (opt.raw) { //In raw mode we need to set the dictionary early\n      status = inflate_1$2.inflateSetDictionary(this.strm, opt.dictionary);\n      if (status !== Z_OK) {\n        throw new Error(messages[status]);\n      }\n    }\n  }\n}\n\n/**\n * Inflate#push(data[, flush_mode]) -> Boolean\n * - data (Uint8Array|ArrayBuffer): input data\n * - flush_mode (Number|Boolean): 0..6 for corresponding Z_NO_FLUSH..Z_TREE\n *   flush modes. See constants. Skipped or `false` means Z_NO_FLUSH,\n *   `true` means Z_FINISH.\n *\n * Sends input data to inflate pipe, generating [[Inflate#onData]] calls with\n * new output chunks. Returns `true` on success. If end of stream detected,\n * [[Inflate#onEnd]] will be called.\n *\n * `flush_mode` is not needed for normal operation, because end of stream\n * detected automatically. You may try to use it for advanced things, but\n * this functionality was not tested.\n *\n * On fail call [[Inflate#onEnd]] with error code and return false.\n *\n * ##### Example\n *\n * ```javascript\n * push(chunk, false); // push one of data chunks\n * ...\n * push(chunk, true);  // push last chunk\n * ```\n **/\nInflate$1.prototype.push = function (data, flush_mode) {\n  const strm = this.strm;\n  const chunkSize = this.options.chunkSize;\n  const dictionary = this.options.dictionary;\n  let status, _flush_mode, last_avail_out;\n\n  if (this.ended) return false;\n\n  if (flush_mode === ~~flush_mode) _flush_mode = flush_mode;\n  else _flush_mode = flush_mode === true ? Z_FINISH : Z_NO_FLUSH;\n\n  // Convert data if needed\n  if (toString.call(data) === '[object ArrayBuffer]') {\n    strm.input = new Uint8Array(data);\n  } else {\n    strm.input = data;\n  }\n\n  strm.next_in = 0;\n  strm.avail_in = strm.input.length;\n\n  for (;;) {\n    if (strm.avail_out === 0) {\n      strm.output = new Uint8Array(chunkSize);\n      strm.next_out = 0;\n      strm.avail_out = chunkSize;\n    }\n\n    status = inflate_1$2.inflate(strm, _flush_mode);\n\n    if (status === Z_NEED_DICT && dictionary) {\n      status = inflate_1$2.inflateSetDictionary(strm, dictionary);\n\n      if (status === Z_OK) {\n        status = inflate_1$2.inflate(strm, _flush_mode);\n      } else if (status === Z_DATA_ERROR) {\n        // Replace code with more verbose\n        status = Z_NEED_DICT;\n      }\n    }\n\n    // Skip snyc markers if more data follows and not raw mode\n    while (strm.avail_in > 0 &&\n           status === Z_STREAM_END &&\n           strm.state.wrap > 0 &&\n           data[strm.next_in] !== 0)\n    {\n      inflate_1$2.inflateReset(strm);\n      status = inflate_1$2.inflate(strm, _flush_mode);\n    }\n\n    switch (status) {\n      case Z_STREAM_ERROR:\n      case Z_DATA_ERROR:\n      case Z_NEED_DICT:\n      case Z_MEM_ERROR:\n        this.onEnd(status);\n        this.ended = true;\n        return false;\n    }\n\n    // Remember real `avail_out` value, because we may patch out buffer content\n    // to align utf8 strings boundaries.\n    last_avail_out = strm.avail_out;\n\n    if (strm.next_out) {\n      if (strm.avail_out === 0 || status === Z_STREAM_END) {\n\n        if (this.options.to === 'string') {\n\n          let next_out_utf8 = strings.utf8border(strm.output, strm.next_out);\n\n          let tail = strm.next_out - next_out_utf8;\n          let utf8str = strings.buf2string(strm.output, next_out_utf8);\n\n          // move tail & realign counters\n          strm.next_out = tail;\n          strm.avail_out = chunkSize - tail;\n          if (tail) strm.output.set(strm.output.subarray(next_out_utf8, next_out_utf8 + tail), 0);\n\n          this.onData(utf8str);\n\n        } else {\n          this.onData(strm.output.length === strm.next_out ? strm.output : strm.output.subarray(0, strm.next_out));\n        }\n      }\n    }\n\n    // Must repeat iteration if out buffer is full\n    if (status === Z_OK && last_avail_out === 0) continue;\n\n    // Finalize if end of stream reached.\n    if (status === Z_STREAM_END) {\n      status = inflate_1$2.inflateEnd(this.strm);\n      this.onEnd(status);\n      this.ended = true;\n      return true;\n    }\n\n    if (strm.avail_in === 0) break;\n  }\n\n  return true;\n};\n\n\n/**\n * Inflate#onData(chunk) -> Void\n * - chunk (Uint8Array|String): output data. When string output requested,\n *   each chunk will be string.\n *\n * By default, stores data blocks in `chunks[]` property and glue\n * those in `onEnd`. Override this handler, if you need another behaviour.\n **/\nInflate$1.prototype.onData = function (chunk) {\n  this.chunks.push(chunk);\n};\n\n\n/**\n * Inflate#onEnd(status) -> Void\n * - status (Number): inflate status. 0 (Z_OK) on success,\n *   other if not.\n *\n * Called either after you tell inflate that the input stream is\n * complete (Z_FINISH). By default - join collected chunks,\n * free memory and fill `results` / `err` properties.\n **/\nInflate$1.prototype.onEnd = function (status) {\n  // On success - join\n  if (status === Z_OK) {\n    if (this.options.to === 'string') {\n      this.result = this.chunks.join('');\n    } else {\n      this.result = common.flattenChunks(this.chunks);\n    }\n  }\n  this.chunks = [];\n  this.err = status;\n  this.msg = this.strm.msg;\n};\n\n\n/**\n * inflate(data[, options]) -> Uint8Array|String\n * - data (Uint8Array|ArrayBuffer): input data to decompress.\n * - options (Object): zlib inflate options.\n *\n * Decompress `data` with inflate/ungzip and `options`. Autodetect\n * format via wrapper header by default. That's why we don't provide\n * separate `ungzip` method.\n *\n * Supported options are:\n *\n * - windowBits\n *\n * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)\n * for more information.\n *\n * Sugar (options):\n *\n * - `raw` (Boolean) - say that we work with raw stream, if you don't wish to specify\n *   negative windowBits implicitly.\n * - `to` (String) - if equal to 'string', then result will be converted\n *   from utf8 to utf16 (javascript) string. When string output requested,\n *   chunk length can differ from `chunkSize`, depending on content.\n *\n *\n * ##### Example:\n *\n * ```javascript\n * const pako = require('pako');\n * const input = pako.deflate(new Uint8Array([1,2,3,4,5,6,7,8,9]));\n * let output;\n *\n * try {\n *   output = pako.inflate(input);\n * } catch (err) {\n *   console.log(err);\n * }\n * ```\n **/\nfunction inflate$1(input, options) {\n  const inflator = new Inflate$1(options);\n\n  inflator.push(input);\n\n  // That will never happens, if you don't cheat with options :)\n  if (inflator.err) throw inflator.msg || messages[inflator.err];\n\n  return inflator.result;\n}\n\n\n/**\n * inflateRaw(data[, options]) -> Uint8Array|String\n * - data (Uint8Array|ArrayBuffer): input data to decompress.\n * - options (Object): zlib inflate options.\n *\n * The same as [[inflate]], but creates raw data, without wrapper\n * (header and adler32 crc).\n **/\nfunction inflateRaw$1(input, options) {\n  options = options || {};\n  options.raw = true;\n  return inflate$1(input, options);\n}\n\n\n/**\n * ungzip(data[, options]) -> Uint8Array|String\n * - data (Uint8Array|ArrayBuffer): input data to decompress.\n * - options (Object): zlib inflate options.\n *\n * Just shortcut to [[inflate]], because it autodetects format\n * by header.content. Done for convenience.\n **/\n\n\nvar Inflate_1$1 = Inflate$1;\nvar inflate_2 = inflate$1;\nvar inflateRaw_1$1 = inflateRaw$1;\nvar ungzip$1 = inflate$1;\nvar constants = constants$2;\n\nvar inflate_1$1 = {\n\tInflate: Inflate_1$1,\n\tinflate: inflate_2,\n\tinflateRaw: inflateRaw_1$1,\n\tungzip: ungzip$1,\n\tconstants: constants\n};\n\nconst { Deflate, deflate, deflateRaw, gzip } = deflate_1$1;\n\nconst { Inflate, inflate, inflateRaw, ungzip } = inflate_1$1;\n\n\n\nvar Deflate_1 = Deflate;\nvar deflate_1 = deflate;\nvar deflateRaw_1 = deflateRaw;\nvar gzip_1 = gzip;\nvar Inflate_1 = Inflate;\nvar inflate_1 = inflate;\nvar inflateRaw_1 = inflateRaw;\nvar ungzip_1 = ungzip;\nvar constants_1 = constants$2;\n\nvar pako = {\n\tDeflate: Deflate_1,\n\tdeflate: deflate_1,\n\tdeflateRaw: deflateRaw_1,\n\tgzip: gzip_1,\n\tInflate: Inflate_1,\n\tinflate: inflate_1,\n\tinflateRaw: inflateRaw_1,\n\tungzip: ungzip_1,\n\tconstants: constants_1\n};\n\nexport { Deflate_1 as Deflate, Inflate_1 as Inflate, constants_1 as constants, pako as default, deflate_1 as deflate, deflateRaw_1 as deflateRaw, gzip_1 as gzip, inflate_1 as inflate, inflateRaw_1 as inflateRaw, ungzip_1 as ungzip };\n","import { fire, mapToObject } from '@slideslive/fuse-kit/utils';\nimport base45 from 'base45';\nimport { Decoder } from 'cbor-x';\nimport jsQR from 'jsqr-es6';\nimport ApplicationController from 'modules/application_controller';\nimport pako from 'pako';\n\nexport default class extends ApplicationController {\n  static get targets() {\n    return ['dataLineTemplate', 'inputData', 'inputInfo', 'jsonData', 'uploadedCertificate'];\n  }\n\n  connect() {\n    this.parseUploadedCovidCertificates();\n  }\n\n  decodeQr(event) {\n    const qrImage = event.target.files[0];\n\n    if (!qrImage) {\n      this.inputDataTarget.value = '';\n      this.jsonDataTarget.value = '';\n      this.inputInfoTarget.innerHTML = '';\n\n      return;\n    }\n\n    const reader = new FileReader();\n    const img = document.createElement('img');\n    const canvas = document.createElement('canvas');\n    // const canvas = document.getElementById('canvas');\n\n    reader.onload = (e) => {\n      img.src = e.target.result;\n    };\n\n    img.onload = () => {\n      canvas.width = img.width;\n      canvas.height = img.height;\n\n      const ctx = canvas.getContext('2d');\n      ctx.drawImage(img, 0, 0);\n\n      const imageData = ctx.getImageData(0, 0, img.width, img.height);\n      const decodedQR = jsQR(imageData.data, imageData.width, imageData.height);\n\n      this.inputDataTarget.value = decodedQR.data;\n\n      const decodedBody = decodedQR.data.substr(4);\n      const decodedData = base45.decode(decodedBody);\n      const inflatedData = pako.inflate(decodedData);\n      const cborResults = new Decoder().decode(inflatedData);\n\n      const cborData = cborResults.value[2];\n\n      const data = new Decoder().decode(cborData);\n      const jsonData = JSON.stringify(mapToObject(data.get(-260).get(1)), null, 2);\n\n      this.jsonDataTarget.value = jsonData;\n      fire(this.jsonDataTarget, 'change');\n\n      this.parseCovidCertificateInfoFromJSON(jsonData, this.inputInfoTarget);\n    };\n\n    reader.readAsDataURL(qrImage);\n  }\n\n  parseUploadedCovidCertificates() {\n    for (const element of this.uploadedCertificateTargets) {\n      this.parseCovidCertificateInfoFromJSON(element.dataset.certificateJson, element);\n    }\n  }\n\n  parseCovidCertificateInfoFromJSON(jsonString, element) {\n    const json = JSON.parse(jsonString);\n\n    const info = [];\n\n    if (json.v) {\n      info.push(['Certificate type', 'vaccination']);\n    } else if (json.r) {\n      info.push(['Certificate type', 'recovery']);\n    } else if (json.t) {\n      info.push(['Certificate type', 'test']);\n    }\n\n    info.push(['Date of birth', json.dob]);\n    info.push(['First name', json.nam.gn]);\n    info.push(['Last name', json.nam.fn]);\n\n    if (json.v) {\n      const v = json.v[0];\n\n      info.push(['Vaccine', v.mp]);\n      info.push(['Current dose number', v.dn]);\n      info.push(['Total dose number', v.sd]);\n      info.push(['Date of vaccination', v.dt]);\n      info.push(['Place of vaccination', v.co]);\n      info.push(['Certificate issuer', v.is]);\n    } else if (json.r) {\n      const r = json.r[0];\n\n      info.push(['Date of positive test', r.fr]);\n      info.push(['Place of positive test', r.co]);\n      info.push(['Certificate issuer', r.is]);\n      info.push(['Certificate valid from', r.df]);\n      info.push(['Certificate valid until', r.cu]);\n    } else if (json.t) {\n      const t = json.t[0];\n\n      info.push(['Test type', t.tt]);\n      info.push(['Test name', t.tn]);\n      info.push(['Test device ID', t.ma]);\n      info.push(['Date and time of sample collection', t.sc]);\n      info.push(['Test result', t.tr]);\n      info.push(['Testing centre', t.tc]);\n      info.push(['Testing country', t.co]);\n      info.push(['Certificate issuer', t.is]);\n    }\n\n    element.innerHTML = info\n      .map((pair) => this.dataLineTemplateTarget.innerHTML.replace('{content}', `${pair[0]}: ${pair[1]}`))\n      .join('');\n    element.hidden = false;\n  }\n}\n","import ApplicationController from 'modules/application_controller';\n\nexport default class extends ApplicationController {\n  static get targets() {\n    return ['hourlyRateCurrency'];\n  }\n\n  updateHourlyRateCurrency(event) {\n    const currency = event.target.value;\n\n    for (const hourlyRateCurrencyTarget of this.hourlyRateCurrencyTargets) {\n      hourlyRateCurrencyTarget.value = currency;\n    }\n  }\n}\n","import ApplicationController from 'modules/application_controller';\n\nexport default class extends ApplicationController {\n  static get targets() {\n    return ['payoutMethodData', 'payoutMethodSelect', 'payoutMethod'];\n  }\n\n  updatePayoutMethodData() {\n    const data = {};\n\n    for (const el of this.payoutMethodTargets) {\n      const method = el.dataset.dependValue;\n      const paramEls = el.querySelectorAll('[data-payout-method-param]');\n\n      data[method] = {};\n\n      for (const paramEl of paramEls) {\n        data[method][paramEl.dataset.payoutMethodParam] = paramEl.value;\n      }\n    }\n\n    this.payoutMethodDataTarget.value = JSON.stringify(data);\n  }\n}\n","import ApplicationController from 'modules/application_controller';\n\nexport default class extends ApplicationController {\n  static get targets() {\n    return [\n      'recordingRadiusUserInput',\n      'searchInput',\n      'map',\n      'recordingRadius',\n      'recordingRadiusLat',\n      'recordingRadiusLng',\n    ];\n  }\n\n  connect() {\n    this.initializeMap();\n  }\n\n  initializeMap() {\n    if (!window.isMapApiInitialized(this.initializeMap.bind(this))) {\n      return;\n    }\n\n    const defaultLatLng = {\n      lat: this.lat,\n      lng: this.lng,\n    };\n\n    const mapOptions = {\n      mapId: 'recordingRadius',\n      mapTypeId: 'roadmap',\n      center: defaultLatLng,\n      zoom: 5,\n      mapTypeControl: false,\n      streetViewControl: false,\n      rotateControl: false,\n      fullscreenControl: false,\n    };\n\n    this.map = new google.maps.Map(this.mapTarget, mapOptions);\n\n    const markerOptions = {\n      position: defaultLatLng,\n      map: this.map,\n      gmpDraggable: !this.readonly,\n    };\n\n    this.marker = new google.maps.marker.AdvancedMarkerElement(markerOptions);\n\n    const circleOptions = {\n      strokeColor: '#FF0000',\n      strokeOpacity: 0.8,\n      strokeWeight: 2,\n      fillColor: '#FF0000',\n      fillOpacity: 0.35,\n      map: this.marker.map,\n      center: this.marker.position,\n      editable: !this.readonly,\n      radius: this.radius,\n    };\n\n    this.circle = new google.maps.Circle(circleOptions);\n\n    if (!this.readonly) {\n      this.marker.addListener('drag', (event) => this.circle.setCenter(event.latLng));\n      this.marker.addListener('dragend', (event) => this.setPositionFromMap(event.latLng));\n\n      this.circle.addListener('radius_changed', () => this.setRadiusFromMap(Math.round(this.circle.getRadius())));\n\n      this.searchBox = new google.maps.places.Autocomplete(this.searchInputTarget, { fields: ['geometry'] });\n\n      this.searchBox.bindTo('bounds', this.map);\n      this.searchBox.addListener('place_changed', () => {\n        const place = this.searchBox.getPlace();\n        if (place?.geometry) {\n          this.map.setCenter(place.geometry.location);\n          this.marker.position = place.geometry.location;\n          this.circle.setCenter(place.geometry.location);\n\n          this.setPositionFromMap(place.geometry.location);\n        }\n      });\n    }\n  }\n\n  setPositionFromMap(position) {\n    this.lat = position.lat();\n    this.lng = position.lng();\n  }\n\n  setRadiusFromMap(radius) {\n    this.recordingRadiusTarget.value = radius;\n    this.recordingRadiusUserInputTarget.value = Math.round(radius / 1000);\n  }\n\n  setRecordingRadiusFromUserInput(event) {\n    const radius = parseFloat(event.target.value) * 1000;\n\n    this.circle.setRadius(radius);\n    this.recordingRadiusTarget.value = radius;\n    this.recordingRadiusUserInputTarget.value = Math.round(radius / 1000);\n  }\n\n  get readonly() {\n    return this.element.dataset.readonly === 'true';\n  }\n\n  set lat(value) {\n    this.recordingRadiusLatTarget.value = value;\n  }\n\n  set lng(value) {\n    this.recordingRadiusLngTarget.value = value;\n  }\n\n  get lat() {\n    return parseFloat(this.recordingRadiusLatTarget.value);\n  }\n\n  get lng() {\n    return parseFloat(this.recordingRadiusLngTarget.value);\n  }\n\n  get radius() {\n    return parseInt(this.recordingRadiusTarget.value, 10);\n  }\n}\n","import colors from '@slideslive/fuse-kit/colors';\nimport ApplicationController from 'modules/application_controller';\n\nexport default class extends ApplicationController {\n  static get targets() {\n    return ['firstColor', 'secondColor'];\n  }\n\n  resetFirstColor() {\n    this.resetColor(this.firstColorTarget, colors.gradient.from);\n  }\n\n  resetSecondColor() {\n    this.resetColor(this.secondColorTarget, colors.gradient.to);\n  }\n\n  resetColor(input, color) {\n    input.value = color;\n  }\n}\n","import ApplicationController from 'modules/application_controller';\n\nexport default class extends ApplicationController {\n  static get targets() {\n    return ['currentPasswordInput', 'passwordInput', 'passwordConfirmationInput'];\n  }\n\n  clearForm(event) {\n    if (!event.detail.fetchResponse?.response?.ok) {\n      return;\n    }\n\n    this.currentPasswordInputTarget.value = '';\n    this.passwordInputTarget.value = '';\n    this.passwordConfirmationInputTarget.value = '';\n  }\n}\n","import ApplicationController from 'modules/application_controller';\n\nexport default class extends ApplicationController {\n  static get targets() {\n    return [\n      'accountUrl',\n      'editAccountUrl',\n      'recordingRadiusModalLink',\n      'recordingRadius',\n      'recordingRadiusLat',\n      'recordingRadiusLng',\n    ];\n  }\n\n  connect() {\n    this.updateUrl();\n  }\n\n  updateUrl() {\n    if (`${window.location.origin}${window.location.pathname}` === this.editAccountUrl) {\n      return;\n    }\n\n    this.element.setAttribute('action', this.accountUrl);\n    window.history.replaceState(window.history.state, document.title, this.editAccountUrl);\n  }\n\n  updateRecordingRadius({ detail: { radius, lat, lng } }) {\n    this.recordingRadiusTarget.value = radius;\n    this.recordingRadiusLatTarget.value = lat;\n    this.recordingRadiusLngTarget.value = lng;\n\n    const url = new URL(this.recordingRadiusModalLinkTarget.dataset.modalUrl);\n    url.searchParams.set('radius', radius);\n    url.searchParams.set('lat', lat);\n    url.searchParams.set('lng', lng);\n\n    this.recordingRadiusModalLinkTarget.dataset.modalUrl = url;\n  }\n\n  get accountUrl() {\n    return this.accountUrlTarget.value;\n  }\n\n  get editAccountUrl() {\n    return this.editAccountUrlTarget.value;\n  }\n}\n","import { remove } from '@slideslive/fuse-kit/utils';\nimport ApplicationController from 'modules/application_controller';\n\nexport default class extends ApplicationController {\n  loadAllPresentations({ target }) {\n    remove(target);\n    this.dispatch('loadAll', { target: window, detail: { feed: 'presentations' } });\n  }\n\n  loadAllFolders({ target }) {\n    remove(target);\n    this.dispatch('loadAll', { target: window, detail: { feed: 'folders' } });\n  }\n}\n","import { defer } from '@slideslive/fuse-kit/utils';\nimport ApplicationController from 'modules/application_controller';\nimport Sortable from 'sortablejs';\n\nexport default class extends ApplicationController {\n  initialize() {\n    this.props = {\n      sortable: null,\n    };\n\n    defer(this.initSortable.bind(this));\n  }\n\n  initSortable() {\n    if (!this.isSortable) {\n      return;\n    }\n\n    this.sortable = new Sortable(this.element, {\n      animation: 150,\n      group: 'super-acc',\n      sort: true,\n      dataIdAttr: 'data-item-id',\n      draggable: '[data-sortable-item=\"true\"]',\n      handle: '[data-sortable-handle=\"true\"]',\n      onSort: () => {\n        const data = {};\n\n        for (let i = 0; i < this.element.children.length; i++) {\n          const item = this.element.children[i];\n          const id = item.dataset.itemId;\n\n          data[id] = i;\n        }\n\n        fetch(this.sortableUrl, {\n          method: 'PATCH',\n          headers: {\n            'X-CSRF-Token': document.querySelector('meta[name=\"csrf-token\"]').content,\n            'Content-Type': 'application/json; charset=utf-8',\n          },\n          body: JSON.stringify(data),\n        }).catch((res) => console.warn(res));\n      },\n    });\n  }\n\n  get sortableUrl() {\n    return this.element.dataset.sortableUrl;\n  }\n\n  get isSortable() {\n    return this.element.dataset.sortable === 'true';\n  }\n\n  get sortable() {\n    return this.props.sortable;\n  }\n\n  set sortable(value) {\n    this.props.sortable = value;\n  }\n}\n","import ApplicationController from 'modules/application_controller';\nimport shave from 'shave';\n\nconst TITLE_LINES = 3;\n\nexport default class extends ApplicationController {\n  static get targets() {\n    return ['title'];\n  }\n\n  initialize() {\n    this.props = {\n      originalTitle: '',\n    };\n  }\n\n  connect() {\n    this.originalTitle = this.titleTarget.textContent;\n    this.shaveTitle();\n  }\n\n  shaveTitle() {\n    this.titleTarget.textContent = this.originalTitle;\n    shave(this.titleTarget, 19 * TITLE_LINES, { spaces: false });\n  }\n\n  get originalTitle() {\n    return this.props.originalTitle;\n  }\n\n  set originalTitle(value) {\n    this.props.originalTitle = value;\n  }\n}\n","import ApplicationController from 'modules/application_controller';\nimport VimeoPlayerApiLoader from 'vimeo-player-api-loader';\n\nimport './images/background,h_568.avif';\nimport './images/background,h_568.jpeg';\nimport './images/background,h_568.webp';\nimport './images/background,h_768.avif';\nimport './images/background,h_768.jpeg';\nimport './images/background,h_768.webp';\nimport './images/background,h_1024.avif';\nimport './images/background,h_1024.jpeg';\nimport './images/background,h_1024.webp';\nimport './images/background,h_1080.avif';\nimport './images/background,h_1080.jpeg';\nimport './images/background,h_1080.webp';\n\nexport default class extends ApplicationController {\n  static get targets() {\n    return ['video'];\n  }\n\n  initialize() {\n    this.player = null;\n    this.observer = new ResizeObserver(this.handleResize.bind(this));\n  }\n\n  connect() {\n    if (this.isTurboPreview) return;\n\n    this.loadVideo();\n    this.observer.observe(this.element);\n  }\n\n  disconnect() {\n    this.destroyVideo();\n    this.observer.disconnect();\n  }\n\n  loadVideo() {\n    if (this.player) return;\n\n    VimeoPlayerApiLoader.load((Vimeo) => {\n      this.player = new Vimeo.Player(this.videoTarget);\n\n      this.player.on('error', this.handleVideoError.bind(this));\n      this.player.on('play', this.handleVideoPlay.bind(this));\n    });\n  }\n\n  async destroyVideo() {\n    if (!this.player) return;\n\n    await this.player.unload();\n\n    this.player = null;\n  }\n\n  handleVideoError() {\n    this.videoTarget.hidden = true;\n  }\n\n  handleVideoPlay() {\n    this.videoTarget.hidden = false;\n  }\n\n  handleResize(entries) {\n    for (const {\n      contentRect: { width, height },\n    } of entries) {\n      this.updateSize(width, height);\n    }\n  }\n\n  updateSize(width, height) {\n    if (height === (width / 16) * 9) {\n      return;\n    }\n\n    if (height < (width / 16) * 9) {\n      height = (width / 16) * 9;\n    } else {\n      width = (height / 9) * 16;\n    }\n\n    Object.assign(this.videoTarget.style, {\n      height: `${height}px`,\n      width: `${width}px`,\n    });\n  }\n}\n","import { addListener, fire, removeListener } from '@slideslive/fuse-kit/utils';\nimport ApplicationController from 'modules/application_controller';\n\nexport default class extends ApplicationController {\n  connect() {\n    this.messageListenerId = addListener(window, 'message onmessage', this.handleMessage.bind(this));\n  }\n\n  disconnect() {\n    removeListener(window, { id: this.messageListenerId });\n  }\n\n  sendMessage(message) {\n    message.slideslive = true;\n    message.targetId = this.embedContainerId;\n\n    if (window.ActiveXObject) {\n      message = JSON.stringify(message);\n    }\n\n    window.parent.postMessage(message, this.embedOrigin);\n  }\n\n  handleMessage(event) {\n    if (event.origin !== this.embedOrigin && event.origin !== window.origin) {\n      return true;\n    }\n\n    let { data } = event;\n\n    try {\n      if (typeof data === 'string') {\n        data = JSON.parse(data.replace('/*framebus*/', ''));\n      }\n    } catch {\n      return true;\n    }\n\n    if (typeof data !== 'object' || !data.slideslive) {\n      return true;\n    }\n\n    fire(window, 'embed:message', { detail: { message: data } });\n    return true;\n  }\n\n  sendSetSize({ width = '100%', height }) {\n    if (!this.embedOrigin || !this.embedContainerId) {\n      return;\n    }\n\n    this.sendMessage({\n      method: 'setSize',\n      width,\n      height,\n    });\n  }\n\n  sendUpdateSizeRequest() {\n    if (!this.embedOrigin || !this.embedContainerId) {\n      return;\n    }\n\n    this.sendMessage({ method: 'updateSizeRequest' });\n  }\n\n  get embedOrigin() {\n    return this.element.dataset.embedOrigin;\n  }\n\n  get embedContainerId() {\n    return this.element.dataset.embedContainerId;\n  }\n}\n","/**\r\n * A collection of shims that provide minimal functionality of the ES6 collections.\r\n *\r\n * These implementations are not meant to be used outside of the ResizeObserver\r\n * modules as they cover only a limited range of use cases.\r\n */\r\n/* eslint-disable require-jsdoc, valid-jsdoc */\r\nvar MapShim = (function () {\r\n    if (typeof Map !== 'undefined') {\r\n        return Map;\r\n    }\r\n    /**\r\n     * Returns index in provided array that matches the specified key.\r\n     *\r\n     * @param {Array<Array>} arr\r\n     * @param {*} key\r\n     * @returns {number}\r\n     */\r\n    function getIndex(arr, key) {\r\n        var result = -1;\r\n        arr.some(function (entry, index) {\r\n            if (entry[0] === key) {\r\n                result = index;\r\n                return true;\r\n            }\r\n            return false;\r\n        });\r\n        return result;\r\n    }\r\n    return /** @class */ (function () {\r\n        function class_1() {\r\n            this.__entries__ = [];\r\n        }\r\n        Object.defineProperty(class_1.prototype, \"size\", {\r\n            /**\r\n             * @returns {boolean}\r\n             */\r\n            get: function () {\r\n                return this.__entries__.length;\r\n            },\r\n            enumerable: true,\r\n            configurable: true\r\n        });\r\n        /**\r\n         * @param {*} key\r\n         * @returns {*}\r\n         */\r\n        class_1.prototype.get = function (key) {\r\n            var index = getIndex(this.__entries__, key);\r\n            var entry = this.__entries__[index];\r\n            return entry && entry[1];\r\n        };\r\n        /**\r\n         * @param {*} key\r\n         * @param {*} value\r\n         * @returns {void}\r\n         */\r\n        class_1.prototype.set = function (key, value) {\r\n            var index = getIndex(this.__entries__, key);\r\n            if (~index) {\r\n                this.__entries__[index][1] = value;\r\n            }\r\n            else {\r\n                this.__entries__.push([key, value]);\r\n            }\r\n        };\r\n        /**\r\n         * @param {*} key\r\n         * @returns {void}\r\n         */\r\n        class_1.prototype.delete = function (key) {\r\n            var entries = this.__entries__;\r\n            var index = getIndex(entries, key);\r\n            if (~index) {\r\n                entries.splice(index, 1);\r\n            }\r\n        };\r\n        /**\r\n         * @param {*} key\r\n         * @returns {void}\r\n         */\r\n        class_1.prototype.has = function (key) {\r\n            return !!~getIndex(this.__entries__, key);\r\n        };\r\n        /**\r\n         * @returns {void}\r\n         */\r\n        class_1.prototype.clear = function () {\r\n            this.__entries__.splice(0);\r\n        };\r\n        /**\r\n         * @param {Function} callback\r\n         * @param {*} [ctx=null]\r\n         * @returns {void}\r\n         */\r\n        class_1.prototype.forEach = function (callback, ctx) {\r\n            if (ctx === void 0) { ctx = null; }\r\n            for (var _i = 0, _a = this.__entries__; _i < _a.length; _i++) {\r\n                var entry = _a[_i];\r\n                callback.call(ctx, entry[1], entry[0]);\r\n            }\r\n        };\r\n        return class_1;\r\n    }());\r\n})();\n\n/**\r\n * Detects whether window and document objects are available in current environment.\r\n */\r\nvar isBrowser = typeof window !== 'undefined' && typeof document !== 'undefined' && window.document === document;\n\n// Returns global object of a current environment.\r\nvar global$1 = (function () {\r\n    if (typeof global !== 'undefined' && global.Math === Math) {\r\n        return global;\r\n    }\r\n    if (typeof self !== 'undefined' && self.Math === Math) {\r\n        return self;\r\n    }\r\n    if (typeof window !== 'undefined' && window.Math === Math) {\r\n        return window;\r\n    }\r\n    // eslint-disable-next-line no-new-func\r\n    return Function('return this')();\r\n})();\n\n/**\r\n * A shim for the requestAnimationFrame which falls back to the setTimeout if\r\n * first one is not supported.\r\n *\r\n * @returns {number} Requests' identifier.\r\n */\r\nvar requestAnimationFrame$1 = (function () {\r\n    if (typeof requestAnimationFrame === 'function') {\r\n        // It's required to use a bounded function because IE sometimes throws\r\n        // an \"Invalid calling object\" error if rAF is invoked without the global\r\n        // object on the left hand side.\r\n        return requestAnimationFrame.bind(global$1);\r\n    }\r\n    return function (callback) { return setTimeout(function () { return callback(Date.now()); }, 1000 / 60); };\r\n})();\n\n// Defines minimum timeout before adding a trailing call.\r\nvar trailingTimeout = 2;\r\n/**\r\n * Creates a wrapper function which ensures that provided callback will be\r\n * invoked only once during the specified delay period.\r\n *\r\n * @param {Function} callback - Function to be invoked after the delay period.\r\n * @param {number} delay - Delay after which to invoke callback.\r\n * @returns {Function}\r\n */\r\nfunction throttle (callback, delay) {\r\n    var leadingCall = false, trailingCall = false, lastCallTime = 0;\r\n    /**\r\n     * Invokes the original callback function and schedules new invocation if\r\n     * the \"proxy\" was called during current request.\r\n     *\r\n     * @returns {void}\r\n     */\r\n    function resolvePending() {\r\n        if (leadingCall) {\r\n            leadingCall = false;\r\n            callback();\r\n        }\r\n        if (trailingCall) {\r\n            proxy();\r\n        }\r\n    }\r\n    /**\r\n     * Callback invoked after the specified delay. It will further postpone\r\n     * invocation of the original function delegating it to the\r\n     * requestAnimationFrame.\r\n     *\r\n     * @returns {void}\r\n     */\r\n    function timeoutCallback() {\r\n        requestAnimationFrame$1(resolvePending);\r\n    }\r\n    /**\r\n     * Schedules invocation of the original function.\r\n     *\r\n     * @returns {void}\r\n     */\r\n    function proxy() {\r\n        var timeStamp = Date.now();\r\n        if (leadingCall) {\r\n            // Reject immediately following calls.\r\n            if (timeStamp - lastCallTime < trailingTimeout) {\r\n                return;\r\n            }\r\n            // Schedule new call to be in invoked when the pending one is resolved.\r\n            // This is important for \"transitions\" which never actually start\r\n            // immediately so there is a chance that we might miss one if change\r\n            // happens amids the pending invocation.\r\n            trailingCall = true;\r\n        }\r\n        else {\r\n            leadingCall = true;\r\n            trailingCall = false;\r\n            setTimeout(timeoutCallback, delay);\r\n        }\r\n        lastCallTime = timeStamp;\r\n    }\r\n    return proxy;\r\n}\n\n// Minimum delay before invoking the update of observers.\r\nvar REFRESH_DELAY = 20;\r\n// A list of substrings of CSS properties used to find transition events that\r\n// might affect dimensions of observed elements.\r\nvar transitionKeys = ['top', 'right', 'bottom', 'left', 'width', 'height', 'size', 'weight'];\r\n// Check if MutationObserver is available.\r\nvar mutationObserverSupported = typeof MutationObserver !== 'undefined';\r\n/**\r\n * Singleton controller class which handles updates of ResizeObserver instances.\r\n */\r\nvar ResizeObserverController = /** @class */ (function () {\r\n    /**\r\n     * Creates a new instance of ResizeObserverController.\r\n     *\r\n     * @private\r\n     */\r\n    function ResizeObserverController() {\r\n        /**\r\n         * Indicates whether DOM listeners have been added.\r\n         *\r\n         * @private {boolean}\r\n         */\r\n        this.connected_ = false;\r\n        /**\r\n         * Tells that controller has subscribed for Mutation Events.\r\n         *\r\n         * @private {boolean}\r\n         */\r\n        this.mutationEventsAdded_ = false;\r\n        /**\r\n         * Keeps reference to the instance of MutationObserver.\r\n         *\r\n         * @private {MutationObserver}\r\n         */\r\n        this.mutationsObserver_ = null;\r\n        /**\r\n         * A list of connected observers.\r\n         *\r\n         * @private {Array<ResizeObserverSPI>}\r\n         */\r\n        this.observers_ = [];\r\n        this.onTransitionEnd_ = this.onTransitionEnd_.bind(this);\r\n        this.refresh = throttle(this.refresh.bind(this), REFRESH_DELAY);\r\n    }\r\n    /**\r\n     * Adds observer to observers list.\r\n     *\r\n     * @param {ResizeObserverSPI} observer - Observer to be added.\r\n     * @returns {void}\r\n     */\r\n    ResizeObserverController.prototype.addObserver = function (observer) {\r\n        if (!~this.observers_.indexOf(observer)) {\r\n            this.observers_.push(observer);\r\n        }\r\n        // Add listeners if they haven't been added yet.\r\n        if (!this.connected_) {\r\n            this.connect_();\r\n        }\r\n    };\r\n    /**\r\n     * Removes observer from observers list.\r\n     *\r\n     * @param {ResizeObserverSPI} observer - Observer to be removed.\r\n     * @returns {void}\r\n     */\r\n    ResizeObserverController.prototype.removeObserver = function (observer) {\r\n        var observers = this.observers_;\r\n        var index = observers.indexOf(observer);\r\n        // Remove observer if it's present in registry.\r\n        if (~index) {\r\n            observers.splice(index, 1);\r\n        }\r\n        // Remove listeners if controller has no connected observers.\r\n        if (!observers.length && this.connected_) {\r\n            this.disconnect_();\r\n        }\r\n    };\r\n    /**\r\n     * Invokes the update of observers. It will continue running updates insofar\r\n     * it detects changes.\r\n     *\r\n     * @returns {void}\r\n     */\r\n    ResizeObserverController.prototype.refresh = function () {\r\n        var changesDetected = this.updateObservers_();\r\n        // Continue running updates if changes have been detected as there might\r\n        // be future ones caused by CSS transitions.\r\n        if (changesDetected) {\r\n            this.refresh();\r\n        }\r\n    };\r\n    /**\r\n     * Updates every observer from observers list and notifies them of queued\r\n     * entries.\r\n     *\r\n     * @private\r\n     * @returns {boolean} Returns \"true\" if any observer has detected changes in\r\n     *      dimensions of it's elements.\r\n     */\r\n    ResizeObserverController.prototype.updateObservers_ = function () {\r\n        // Collect observers that have active observations.\r\n        var activeObservers = this.observers_.filter(function (observer) {\r\n            return observer.gatherActive(), observer.hasActive();\r\n        });\r\n        // Deliver notifications in a separate cycle in order to avoid any\r\n        // collisions between observers, e.g. when multiple instances of\r\n        // ResizeObserver are tracking the same element and the callback of one\r\n        // of them changes content dimensions of the observed target. Sometimes\r\n        // this may result in notifications being blocked for the rest of observers.\r\n        activeObservers.forEach(function (observer) { return observer.broadcastActive(); });\r\n        return activeObservers.length > 0;\r\n    };\r\n    /**\r\n     * Initializes DOM listeners.\r\n     *\r\n     * @private\r\n     * @returns {void}\r\n     */\r\n    ResizeObserverController.prototype.connect_ = function () {\r\n        // Do nothing if running in a non-browser environment or if listeners\r\n        // have been already added.\r\n        if (!isBrowser || this.connected_) {\r\n            return;\r\n        }\r\n        // Subscription to the \"Transitionend\" event is used as a workaround for\r\n        // delayed transitions. This way it's possible to capture at least the\r\n        // final state of an element.\r\n        document.addEventListener('transitionend', this.onTransitionEnd_);\r\n        window.addEventListener('resize', this.refresh);\r\n        if (mutationObserverSupported) {\r\n            this.mutationsObserver_ = new MutationObserver(this.refresh);\r\n            this.mutationsObserver_.observe(document, {\r\n                attributes: true,\r\n                childList: true,\r\n                characterData: true,\r\n                subtree: true\r\n            });\r\n        }\r\n        else {\r\n            document.addEventListener('DOMSubtreeModified', this.refresh);\r\n            this.mutationEventsAdded_ = true;\r\n        }\r\n        this.connected_ = true;\r\n    };\r\n    /**\r\n     * Removes DOM listeners.\r\n     *\r\n     * @private\r\n     * @returns {void}\r\n     */\r\n    ResizeObserverController.prototype.disconnect_ = function () {\r\n        // Do nothing if running in a non-browser environment or if listeners\r\n        // have been already removed.\r\n        if (!isBrowser || !this.connected_) {\r\n            return;\r\n        }\r\n        document.removeEventListener('transitionend', this.onTransitionEnd_);\r\n        window.removeEventListener('resize', this.refresh);\r\n        if (this.mutationsObserver_) {\r\n            this.mutationsObserver_.disconnect();\r\n        }\r\n        if (this.mutationEventsAdded_) {\r\n            document.removeEventListener('DOMSubtreeModified', this.refresh);\r\n        }\r\n        this.mutationsObserver_ = null;\r\n        this.mutationEventsAdded_ = false;\r\n        this.connected_ = false;\r\n    };\r\n    /**\r\n     * \"Transitionend\" event handler.\r\n     *\r\n     * @private\r\n     * @param {TransitionEvent} event\r\n     * @returns {void}\r\n     */\r\n    ResizeObserverController.prototype.onTransitionEnd_ = function (_a) {\r\n        var _b = _a.propertyName, propertyName = _b === void 0 ? '' : _b;\r\n        // Detect whether transition may affect dimensions of an element.\r\n        var isReflowProperty = transitionKeys.some(function (key) {\r\n            return !!~propertyName.indexOf(key);\r\n        });\r\n        if (isReflowProperty) {\r\n            this.refresh();\r\n        }\r\n    };\r\n    /**\r\n     * Returns instance of the ResizeObserverController.\r\n     *\r\n     * @returns {ResizeObserverController}\r\n     */\r\n    ResizeObserverController.getInstance = function () {\r\n        if (!this.instance_) {\r\n            this.instance_ = new ResizeObserverController();\r\n        }\r\n        return this.instance_;\r\n    };\r\n    /**\r\n     * Holds reference to the controller's instance.\r\n     *\r\n     * @private {ResizeObserverController}\r\n     */\r\n    ResizeObserverController.instance_ = null;\r\n    return ResizeObserverController;\r\n}());\n\n/**\r\n * Defines non-writable/enumerable properties of the provided target object.\r\n *\r\n * @param {Object} target - Object for which to define properties.\r\n * @param {Object} props - Properties to be defined.\r\n * @returns {Object} Target object.\r\n */\r\nvar defineConfigurable = (function (target, props) {\r\n    for (var _i = 0, _a = Object.keys(props); _i < _a.length; _i++) {\r\n        var key = _a[_i];\r\n        Object.defineProperty(target, key, {\r\n            value: props[key],\r\n            enumerable: false,\r\n            writable: false,\r\n            configurable: true\r\n        });\r\n    }\r\n    return target;\r\n});\n\n/**\r\n * Returns the global object associated with provided element.\r\n *\r\n * @param {Object} target\r\n * @returns {Object}\r\n */\r\nvar getWindowOf = (function (target) {\r\n    // Assume that the element is an instance of Node, which means that it\r\n    // has the \"ownerDocument\" property from which we can retrieve a\r\n    // corresponding global object.\r\n    var ownerGlobal = target && target.ownerDocument && target.ownerDocument.defaultView;\r\n    // Return the local global object if it's not possible extract one from\r\n    // provided element.\r\n    return ownerGlobal || global$1;\r\n});\n\n// Placeholder of an empty content rectangle.\r\nvar emptyRect = createRectInit(0, 0, 0, 0);\r\n/**\r\n * Converts provided string to a number.\r\n *\r\n * @param {number|string} value\r\n * @returns {number}\r\n */\r\nfunction toFloat(value) {\r\n    return parseFloat(value) || 0;\r\n}\r\n/**\r\n * Extracts borders size from provided styles.\r\n *\r\n * @param {CSSStyleDeclaration} styles\r\n * @param {...string} positions - Borders positions (top, right, ...)\r\n * @returns {number}\r\n */\r\nfunction getBordersSize(styles) {\r\n    var positions = [];\r\n    for (var _i = 1; _i < arguments.length; _i++) {\r\n        positions[_i - 1] = arguments[_i];\r\n    }\r\n    return positions.reduce(function (size, position) {\r\n        var value = styles['border-' + position + '-width'];\r\n        return size + toFloat(value);\r\n    }, 0);\r\n}\r\n/**\r\n * Extracts paddings sizes from provided styles.\r\n *\r\n * @param {CSSStyleDeclaration} styles\r\n * @returns {Object} Paddings box.\r\n */\r\nfunction getPaddings(styles) {\r\n    var positions = ['top', 'right', 'bottom', 'left'];\r\n    var paddings = {};\r\n    for (var _i = 0, positions_1 = positions; _i < positions_1.length; _i++) {\r\n        var position = positions_1[_i];\r\n        var value = styles['padding-' + position];\r\n        paddings[position] = toFloat(value);\r\n    }\r\n    return paddings;\r\n}\r\n/**\r\n * Calculates content rectangle of provided SVG element.\r\n *\r\n * @param {SVGGraphicsElement} target - Element content rectangle of which needs\r\n *      to be calculated.\r\n * @returns {DOMRectInit}\r\n */\r\nfunction getSVGContentRect(target) {\r\n    var bbox = target.getBBox();\r\n    return createRectInit(0, 0, bbox.width, bbox.height);\r\n}\r\n/**\r\n * Calculates content rectangle of provided HTMLElement.\r\n *\r\n * @param {HTMLElement} target - Element for which to calculate the content rectangle.\r\n * @returns {DOMRectInit}\r\n */\r\nfunction getHTMLElementContentRect(target) {\r\n    // Client width & height properties can't be\r\n    // used exclusively as they provide rounded values.\r\n    var clientWidth = target.clientWidth, clientHeight = target.clientHeight;\r\n    // By this condition we can catch all non-replaced inline, hidden and\r\n    // detached elements. Though elements with width & height properties less\r\n    // than 0.5 will be discarded as well.\r\n    //\r\n    // Without it we would need to implement separate methods for each of\r\n    // those cases and it's not possible to perform a precise and performance\r\n    // effective test for hidden elements. E.g. even jQuery's ':visible' filter\r\n    // gives wrong results for elements with width & height less than 0.5.\r\n    if (!clientWidth && !clientHeight) {\r\n        return emptyRect;\r\n    }\r\n    var styles = getWindowOf(target).getComputedStyle(target);\r\n    var paddings = getPaddings(styles);\r\n    var horizPad = paddings.left + paddings.right;\r\n    var vertPad = paddings.top + paddings.bottom;\r\n    // Computed styles of width & height are being used because they are the\r\n    // only dimensions available to JS that contain non-rounded values. It could\r\n    // be possible to utilize the getBoundingClientRect if only it's data wasn't\r\n    // affected by CSS transformations let alone paddings, borders and scroll bars.\r\n    var width = toFloat(styles.width), height = toFloat(styles.height);\r\n    // Width & height include paddings and borders when the 'border-box' box\r\n    // model is applied (except for IE).\r\n    if (styles.boxSizing === 'border-box') {\r\n        // Following conditions are required to handle Internet Explorer which\r\n        // doesn't include paddings and borders to computed CSS dimensions.\r\n        //\r\n        // We can say that if CSS dimensions + paddings are equal to the \"client\"\r\n        // properties then it's either IE, and thus we don't need to subtract\r\n        // anything, or an element merely doesn't have paddings/borders styles.\r\n        if (Math.round(width + horizPad) !== clientWidth) {\r\n            width -= getBordersSize(styles, 'left', 'right') + horizPad;\r\n        }\r\n        if (Math.round(height + vertPad) !== clientHeight) {\r\n            height -= getBordersSize(styles, 'top', 'bottom') + vertPad;\r\n        }\r\n    }\r\n    // Following steps can't be applied to the document's root element as its\r\n    // client[Width/Height] properties represent viewport area of the window.\r\n    // Besides, it's as well not necessary as the <html> itself neither has\r\n    // rendered scroll bars nor it can be clipped.\r\n    if (!isDocumentElement(target)) {\r\n        // In some browsers (only in Firefox, actually) CSS width & height\r\n        // include scroll bars size which can be removed at this step as scroll\r\n        // bars are the only difference between rounded dimensions + paddings\r\n        // and \"client\" properties, though that is not always true in Chrome.\r\n        var vertScrollbar = Math.round(width + horizPad) - clientWidth;\r\n        var horizScrollbar = Math.round(height + vertPad) - clientHeight;\r\n        // Chrome has a rather weird rounding of \"client\" properties.\r\n        // E.g. for an element with content width of 314.2px it sometimes gives\r\n        // the client width of 315px and for the width of 314.7px it may give\r\n        // 314px. And it doesn't happen all the time. So just ignore this delta\r\n        // as a non-relevant.\r\n        if (Math.abs(vertScrollbar) !== 1) {\r\n            width -= vertScrollbar;\r\n        }\r\n        if (Math.abs(horizScrollbar) !== 1) {\r\n            height -= horizScrollbar;\r\n        }\r\n    }\r\n    return createRectInit(paddings.left, paddings.top, width, height);\r\n}\r\n/**\r\n * Checks whether provided element is an instance of the SVGGraphicsElement.\r\n *\r\n * @param {Element} target - Element to be checked.\r\n * @returns {boolean}\r\n */\r\nvar isSVGGraphicsElement = (function () {\r\n    // Some browsers, namely IE and Edge, don't have the SVGGraphicsElement\r\n    // interface.\r\n    if (typeof SVGGraphicsElement !== 'undefined') {\r\n        return function (target) { return target instanceof getWindowOf(target).SVGGraphicsElement; };\r\n    }\r\n    // If it's so, then check that element is at least an instance of the\r\n    // SVGElement and that it has the \"getBBox\" method.\r\n    // eslint-disable-next-line no-extra-parens\r\n    return function (target) { return (target instanceof getWindowOf(target).SVGElement &&\r\n        typeof target.getBBox === 'function'); };\r\n})();\r\n/**\r\n * Checks whether provided element is a document element (<html>).\r\n *\r\n * @param {Element} target - Element to be checked.\r\n * @returns {boolean}\r\n */\r\nfunction isDocumentElement(target) {\r\n    return target === getWindowOf(target).document.documentElement;\r\n}\r\n/**\r\n * Calculates an appropriate content rectangle for provided html or svg element.\r\n *\r\n * @param {Element} target - Element content rectangle of which needs to be calculated.\r\n * @returns {DOMRectInit}\r\n */\r\nfunction getContentRect(target) {\r\n    if (!isBrowser) {\r\n        return emptyRect;\r\n    }\r\n    if (isSVGGraphicsElement(target)) {\r\n        return getSVGContentRect(target);\r\n    }\r\n    return getHTMLElementContentRect(target);\r\n}\r\n/**\r\n * Creates rectangle with an interface of the DOMRectReadOnly.\r\n * Spec: https://drafts.fxtf.org/geometry/#domrectreadonly\r\n *\r\n * @param {DOMRectInit} rectInit - Object with rectangle's x/y coordinates and dimensions.\r\n * @returns {DOMRectReadOnly}\r\n */\r\nfunction createReadOnlyRect(_a) {\r\n    var x = _a.x, y = _a.y, width = _a.width, height = _a.height;\r\n    // If DOMRectReadOnly is available use it as a prototype for the rectangle.\r\n    var Constr = typeof DOMRectReadOnly !== 'undefined' ? DOMRectReadOnly : Object;\r\n    var rect = Object.create(Constr.prototype);\r\n    // Rectangle's properties are not writable and non-enumerable.\r\n    defineConfigurable(rect, {\r\n        x: x, y: y, width: width, height: height,\r\n        top: y,\r\n        right: x + width,\r\n        bottom: height + y,\r\n        left: x\r\n    });\r\n    return rect;\r\n}\r\n/**\r\n * Creates DOMRectInit object based on the provided dimensions and the x/y coordinates.\r\n * Spec: https://drafts.fxtf.org/geometry/#dictdef-domrectinit\r\n *\r\n * @param {number} x - X coordinate.\r\n * @param {number} y - Y coordinate.\r\n * @param {number} width - Rectangle's width.\r\n * @param {number} height - Rectangle's height.\r\n * @returns {DOMRectInit}\r\n */\r\nfunction createRectInit(x, y, width, height) {\r\n    return { x: x, y: y, width: width, height: height };\r\n}\n\n/**\r\n * Class that is responsible for computations of the content rectangle of\r\n * provided DOM element and for keeping track of it's changes.\r\n */\r\nvar ResizeObservation = /** @class */ (function () {\r\n    /**\r\n     * Creates an instance of ResizeObservation.\r\n     *\r\n     * @param {Element} target - Element to be observed.\r\n     */\r\n    function ResizeObservation(target) {\r\n        /**\r\n         * Broadcasted width of content rectangle.\r\n         *\r\n         * @type {number}\r\n         */\r\n        this.broadcastWidth = 0;\r\n        /**\r\n         * Broadcasted height of content rectangle.\r\n         *\r\n         * @type {number}\r\n         */\r\n        this.broadcastHeight = 0;\r\n        /**\r\n         * Reference to the last observed content rectangle.\r\n         *\r\n         * @private {DOMRectInit}\r\n         */\r\n        this.contentRect_ = createRectInit(0, 0, 0, 0);\r\n        this.target = target;\r\n    }\r\n    /**\r\n     * Updates content rectangle and tells whether it's width or height properties\r\n     * have changed since the last broadcast.\r\n     *\r\n     * @returns {boolean}\r\n     */\r\n    ResizeObservation.prototype.isActive = function () {\r\n        var rect = getContentRect(this.target);\r\n        this.contentRect_ = rect;\r\n        return (rect.width !== this.broadcastWidth ||\r\n            rect.height !== this.broadcastHeight);\r\n    };\r\n    /**\r\n     * Updates 'broadcastWidth' and 'broadcastHeight' properties with a data\r\n     * from the corresponding properties of the last observed content rectangle.\r\n     *\r\n     * @returns {DOMRectInit} Last observed content rectangle.\r\n     */\r\n    ResizeObservation.prototype.broadcastRect = function () {\r\n        var rect = this.contentRect_;\r\n        this.broadcastWidth = rect.width;\r\n        this.broadcastHeight = rect.height;\r\n        return rect;\r\n    };\r\n    return ResizeObservation;\r\n}());\n\nvar ResizeObserverEntry = /** @class */ (function () {\r\n    /**\r\n     * Creates an instance of ResizeObserverEntry.\r\n     *\r\n     * @param {Element} target - Element that is being observed.\r\n     * @param {DOMRectInit} rectInit - Data of the element's content rectangle.\r\n     */\r\n    function ResizeObserverEntry(target, rectInit) {\r\n        var contentRect = createReadOnlyRect(rectInit);\r\n        // According to the specification following properties are not writable\r\n        // and are also not enumerable in the native implementation.\r\n        //\r\n        // Property accessors are not being used as they'd require to define a\r\n        // private WeakMap storage which may cause memory leaks in browsers that\r\n        // don't support this type of collections.\r\n        defineConfigurable(this, { target: target, contentRect: contentRect });\r\n    }\r\n    return ResizeObserverEntry;\r\n}());\n\nvar ResizeObserverSPI = /** @class */ (function () {\r\n    /**\r\n     * Creates a new instance of ResizeObserver.\r\n     *\r\n     * @param {ResizeObserverCallback} callback - Callback function that is invoked\r\n     *      when one of the observed elements changes it's content dimensions.\r\n     * @param {ResizeObserverController} controller - Controller instance which\r\n     *      is responsible for the updates of observer.\r\n     * @param {ResizeObserver} callbackCtx - Reference to the public\r\n     *      ResizeObserver instance which will be passed to callback function.\r\n     */\r\n    function ResizeObserverSPI(callback, controller, callbackCtx) {\r\n        /**\r\n         * Collection of resize observations that have detected changes in dimensions\r\n         * of elements.\r\n         *\r\n         * @private {Array<ResizeObservation>}\r\n         */\r\n        this.activeObservations_ = [];\r\n        /**\r\n         * Registry of the ResizeObservation instances.\r\n         *\r\n         * @private {Map<Element, ResizeObservation>}\r\n         */\r\n        this.observations_ = new MapShim();\r\n        if (typeof callback !== 'function') {\r\n            throw new TypeError('The callback provided as parameter 1 is not a function.');\r\n        }\r\n        this.callback_ = callback;\r\n        this.controller_ = controller;\r\n        this.callbackCtx_ = callbackCtx;\r\n    }\r\n    /**\r\n     * Starts observing provided element.\r\n     *\r\n     * @param {Element} target - Element to be observed.\r\n     * @returns {void}\r\n     */\r\n    ResizeObserverSPI.prototype.observe = function (target) {\r\n        if (!arguments.length) {\r\n            throw new TypeError('1 argument required, but only 0 present.');\r\n        }\r\n        // Do nothing if current environment doesn't have the Element interface.\r\n        if (typeof Element === 'undefined' || !(Element instanceof Object)) {\r\n            return;\r\n        }\r\n        if (!(target instanceof getWindowOf(target).Element)) {\r\n            throw new TypeError('parameter 1 is not of type \"Element\".');\r\n        }\r\n        var observations = this.observations_;\r\n        // Do nothing if element is already being observed.\r\n        if (observations.has(target)) {\r\n            return;\r\n        }\r\n        observations.set(target, new ResizeObservation(target));\r\n        this.controller_.addObserver(this);\r\n        // Force the update of observations.\r\n        this.controller_.refresh();\r\n    };\r\n    /**\r\n     * Stops observing provided element.\r\n     *\r\n     * @param {Element} target - Element to stop observing.\r\n     * @returns {void}\r\n     */\r\n    ResizeObserverSPI.prototype.unobserve = function (target) {\r\n        if (!arguments.length) {\r\n            throw new TypeError('1 argument required, but only 0 present.');\r\n        }\r\n        // Do nothing if current environment doesn't have the Element interface.\r\n        if (typeof Element === 'undefined' || !(Element instanceof Object)) {\r\n            return;\r\n        }\r\n        if (!(target instanceof getWindowOf(target).Element)) {\r\n            throw new TypeError('parameter 1 is not of type \"Element\".');\r\n        }\r\n        var observations = this.observations_;\r\n        // Do nothing if element is not being observed.\r\n        if (!observations.has(target)) {\r\n            return;\r\n        }\r\n        observations.delete(target);\r\n        if (!observations.size) {\r\n            this.controller_.removeObserver(this);\r\n        }\r\n    };\r\n    /**\r\n     * Stops observing all elements.\r\n     *\r\n     * @returns {void}\r\n     */\r\n    ResizeObserverSPI.prototype.disconnect = function () {\r\n        this.clearActive();\r\n        this.observations_.clear();\r\n        this.controller_.removeObserver(this);\r\n    };\r\n    /**\r\n     * Collects observation instances the associated element of which has changed\r\n     * it's content rectangle.\r\n     *\r\n     * @returns {void}\r\n     */\r\n    ResizeObserverSPI.prototype.gatherActive = function () {\r\n        var _this = this;\r\n        this.clearActive();\r\n        this.observations_.forEach(function (observation) {\r\n            if (observation.isActive()) {\r\n                _this.activeObservations_.push(observation);\r\n            }\r\n        });\r\n    };\r\n    /**\r\n     * Invokes initial callback function with a list of ResizeObserverEntry\r\n     * instances collected from active resize observations.\r\n     *\r\n     * @returns {void}\r\n     */\r\n    ResizeObserverSPI.prototype.broadcastActive = function () {\r\n        // Do nothing if observer doesn't have active observations.\r\n        if (!this.hasActive()) {\r\n            return;\r\n        }\r\n        var ctx = this.callbackCtx_;\r\n        // Create ResizeObserverEntry instance for every active observation.\r\n        var entries = this.activeObservations_.map(function (observation) {\r\n            return new ResizeObserverEntry(observation.target, observation.broadcastRect());\r\n        });\r\n        this.callback_.call(ctx, entries, ctx);\r\n        this.clearActive();\r\n    };\r\n    /**\r\n     * Clears the collection of active observations.\r\n     *\r\n     * @returns {void}\r\n     */\r\n    ResizeObserverSPI.prototype.clearActive = function () {\r\n        this.activeObservations_.splice(0);\r\n    };\r\n    /**\r\n     * Tells whether observer has active observations.\r\n     *\r\n     * @returns {boolean}\r\n     */\r\n    ResizeObserverSPI.prototype.hasActive = function () {\r\n        return this.activeObservations_.length > 0;\r\n    };\r\n    return ResizeObserverSPI;\r\n}());\n\n// Registry of internal observers. If WeakMap is not available use current shim\r\n// for the Map collection as it has all required methods and because WeakMap\r\n// can't be fully polyfilled anyway.\r\nvar observers = typeof WeakMap !== 'undefined' ? new WeakMap() : new MapShim();\r\n/**\r\n * ResizeObserver API. Encapsulates the ResizeObserver SPI implementation\r\n * exposing only those methods and properties that are defined in the spec.\r\n */\r\nvar ResizeObserver = /** @class */ (function () {\r\n    /**\r\n     * Creates a new instance of ResizeObserver.\r\n     *\r\n     * @param {ResizeObserverCallback} callback - Callback that is invoked when\r\n     *      dimensions of the observed elements change.\r\n     */\r\n    function ResizeObserver(callback) {\r\n        if (!(this instanceof ResizeObserver)) {\r\n            throw new TypeError('Cannot call a class as a function.');\r\n        }\r\n        if (!arguments.length) {\r\n            throw new TypeError('1 argument required, but only 0 present.');\r\n        }\r\n        var controller = ResizeObserverController.getInstance();\r\n        var observer = new ResizeObserverSPI(callback, controller, this);\r\n        observers.set(this, observer);\r\n    }\r\n    return ResizeObserver;\r\n}());\r\n// Expose public methods of ResizeObserver.\r\n[\r\n    'observe',\r\n    'unobserve',\r\n    'disconnect'\r\n].forEach(function (method) {\r\n    ResizeObserver.prototype[method] = function () {\r\n        var _a;\r\n        return (_a = observers.get(this))[method].apply(_a, arguments);\r\n    };\r\n});\n\nvar index = (function () {\r\n    // Export existing implementation if available.\r\n    if (typeof global$1.ResizeObserver !== 'undefined') {\r\n        return global$1.ResizeObserver;\r\n    }\r\n    return ResizeObserver;\r\n})();\n\nexport default index;\n","import ApplicationController from 'modules/application_controller';\nimport ResizeObserver from 'resize-observer-polyfill';\n\nexport default class extends ApplicationController {\n  connect() {\n    this.resizeObserver = new ResizeObserver(() => {\n      this.sendSetSize();\n    });\n\n    this.resizeObserver.observe(this.element);\n\n    this.embedController.sendUpdateSizeRequest();\n    this.sendSetSize();\n  }\n\n  disconnect() {\n    this.resizeObserver.disconnect();\n    this.resizeObserver = null;\n  }\n\n  sendSetSize() {\n    this.embedController.sendSetSize({ height: this.element.offsetHeight });\n  }\n\n  get embedController() {\n    return this.findParentControllerByName('library--embed--body', { hideWarning: true });\n  }\n}\n","import { addListener, removeListener } from '@slideslive/fuse-kit/utils';\nimport ApplicationController from 'modules/application_controller';\nimport Player from 'modules/player/player';\n\nexport default class extends ApplicationController {\n  initialize() {\n    this.player = null;\n\n    this.initPlayer();\n    this.embedController.sendUpdateSizeRequest();\n  }\n\n  connect() {\n    this.messageListenerId = addListener(window, 'embed:message', this.handleMessage.bind(this));\n  }\n\n  disconnect() {\n    removeListener(window, { id: this.messageListenerId });\n  }\n\n  initPlayer() {\n    this.player = new Player('player');\n  }\n\n  handleMessage(event) {\n    const {\n      detail: { message },\n    } = event;\n\n    switch (message.method) {\n      case 'play':\n        this.player.play();\n        break;\n\n      case 'pause':\n        this.player.pause();\n        break;\n\n      case 'toggle':\n        this.player.toggle();\n        break;\n\n      case 'seekTo':\n        this.player.seekTo(message.time);\n        break;\n\n      case 'seekToLivePosition':\n        this.player.seekToLivePosition();\n        break;\n\n      case 'seekToSlide':\n        this.player.seekToSlide(message.slide);\n        break;\n\n      case 'prevSlide':\n        this.player.prevSlide();\n        break;\n\n      case 'nextSlide':\n        this.player.nextSlide();\n        break;\n\n      case 'syncVideoToSlide':\n        this.player.syncVideoToSlides();\n        break;\n\n      case 'syncSlideToVideo':\n        this.player.syncSlidesToVideo();\n        break;\n\n      case 'setVolume':\n        this.player.volume = message.volume;\n        break;\n\n      case 'setMuted':\n        this.player.muted = message.muted;\n        break;\n\n      case 'setPlaybackRate':\n        this.player.playbackRate = message.rate;\n        break;\n\n      case 'setZoomRatio':\n        this.player.zoomRatio = message.ratio;\n        break;\n\n      // private api\n\n      case 'setAvailableSize':\n        if (this.player.setAvailableSize != null) {\n          this.player.setAvailableSize(message.height);\n        }\n        break;\n\n      case 'getSlideUrl':\n        this.player.getSlideUrlFromEmbed(message.slide);\n        break;\n\n      default:\n    }\n\n    return true;\n  }\n\n  get embedController() {\n    return this.findParentControllerByName('library--embed--body', { hideWarning: true });\n  }\n}\n","import ApplicationController from 'modules/application_controller';\n\nexport default class extends ApplicationController {\n  connect() {\n    this.dispatch('initialize');\n  }\n}\n","import { getData, setData } from '@slideslive/fuse-kit/utils';\nimport ApplicationController from 'modules/application_controller';\n\nexport default class extends ApplicationController {\n  static get targets() {\n    return ['content'];\n  }\n\n  initialize() {\n    this.props = {\n      hidden: false,\n    };\n  }\n\n  handleRender() {\n    if (this.isTurboPreview) {\n      this.handleRenderPreview();\n\n      return;\n    }\n\n    this.handleRenderNew();\n  }\n\n  handleRenderPreview() {\n    if (!this.element.hidden) {\n      return;\n    }\n\n    setData(window, this.windowCachedDataKey, { hidden: true });\n  }\n\n  handleRenderNew() {\n    const cachedData = getData(window, this.windowCachedDataKey);\n\n    if (!cachedData) {\n      return;\n    }\n\n    setData(window, this.windowCachedDataKey, undefined);\n    this.element.hidden = cachedData.hidden;\n  }\n\n  contentRendered() {\n    if (this.hidden) {\n      return;\n    }\n\n    this.element.hidden = false;\n  }\n\n  hide() {\n    this.hidden = true;\n    this.element.hidden = true;\n  }\n\n  get hidden() {\n    return this.props.hidden;\n  }\n\n  set hidden(value) {\n    this.props.hidden = value;\n  }\n\n  get windowCachedDataKey() {\n    return `fireEmptyCache:${window.location.pathname}#${this.contentTarget.id}`;\n  }\n}\n","import { pushDataLayer } from '@slideslive/fuse-kit/utils';\nimport ApplicationController from 'modules/application_controller';\n\nexport default class extends ApplicationController {\n  track() {\n    pushDataLayer({ event: this.action, follow_target: this.followId });\n  }\n\n  get action() {\n    if (this.follow) {\n      return 'sl_library_follow';\n    }\n\n    return 'sl_library_unfollow';\n  }\n\n  get follow() {\n    return this.element.dataset.follow === 'true';\n  }\n\n  get followId() {\n    return this.element.dataset.followId;\n  }\n}\n","import ApplicationController from 'modules/application_controller';\n\nexport default class extends ApplicationController {\n  static get targets() {\n    return ['form'];\n  }\n\n  initialize() {\n    this.props = {\n      done: false,\n    };\n  }\n\n  followChanged(event) {\n    if (this.done || event.srcElement.action.includes('unfollow')) {\n      return;\n    }\n\n    this.done = true;\n    this.formTarget.requestSubmit();\n  }\n\n  get done() {\n    return this.props.done;\n  }\n\n  set done(value) {\n    this.props.done = value;\n  }\n}\n","import ApplicationController from 'modules/application_controller';\n\nexport default class extends ApplicationController {\n  static get targets() {\n    return ['thirdParty', 'emailForm'];\n  }\n\n  showEmailForm() {\n    this.thirdPartyTarget.hidden = true;\n    this.emailFormTarget.hidden = false;\n  }\n}\n","import ApplicationController from 'modules/application_controller';\n\nexport default class extends ApplicationController {\n  static get targets() {\n    return ['cloudflareJson', 'submitButton'];\n  }\n\n  static get outlets() {\n    return ['fuse--button'];\n  }\n\n  connect() {\n    this.loading = true;\n\n    this._fetchCloudflareJson();\n  }\n\n  fuseButtonOutletConnected(outlet) {\n    this._syncFuseButtonOutletLoading(outlet);\n  }\n\n  _fetchCloudflareJson() {\n    if (!this.hasCloudflareJsonTarget) {\n      this.loading = false;\n\n      return;\n    }\n\n    fetch('https://checkme.slideslive.com/api/v1/ping', {\n      credentials: 'omit',\n      referrerPolicy: 'no-referrer',\n    })\n      .then((response) => response.json())\n      .then((json) => {\n        this.cloudflareJsonTarget.value = JSON.stringify(json);\n\n        this.loading = false;\n      })\n      .catch((error) => {\n        console.warn(error);\n\n        this.loading = false;\n      });\n  }\n\n  get loading() {\n    return this._loading;\n  }\n\n  set loading(value) {\n    this._loading = value;\n    this._syncFuseButtonOutletLoading();\n  }\n\n  _syncFuseButtonOutletLoading(outlet) {\n    if (!outlet) {\n      if (!this.hasFuseButtonOutlet) return;\n\n      outlet = this.fuseButtonOutlet;\n    }\n\n    if (this.loading) {\n      outlet.loading();\n    } else {\n      outlet.done();\n    }\n  }\n}\n","import ApplicationController from 'modules/application_controller';\n\nexport default class extends ApplicationController {\n  static get targets() {\n    return ['thirdParty', 'email'];\n  }\n\n  showEmail() {\n    this.thirdPartyTarget.hidden = true;\n    this.emailTarget.hidden = false;\n  }\n\n  hideEmail() {\n    this.emailTarget.hidden = true;\n    this.thirdPartyTarget.hidden = false;\n  }\n}\n","import ApplicationController from 'modules/application_controller';\n\nexport default class extends ApplicationController {}\n","import { fire, getData, setData } from '@slideslive/fuse-kit/utils';\n\nfunction permanentPlayerKey() {\n  return 'permanentPlayer';\n}\n\nfunction save({ presentationId, playerElement }) {\n  setData(window, permanentPlayerKey(), { presentationId, playerElement });\n}\n\nfunction clear() {\n  setData(window, permanentPlayerKey(), undefined);\n}\n\nfunction permanentPlayerData() {\n  return getData(window, permanentPlayerKey());\n}\n\nfunction currentPresentationId() {\n  return permanentPlayerData()?.presentationId;\n}\n\nfunction currentPlayerElement() {\n  return permanentPlayerData()?.playerElement;\n}\n\nfunction exist() {\n  return !!permanentPlayerData();\n}\n\nfunction open({ presentationId, playerElement, url, title }) {\n  return fire(document, `${permanentPlayerKey()}:open`, {\n    detail: {\n      presentationId,\n      playerElement,\n      url,\n      title,\n    },\n    bubbles: true,\n    cancelable: true,\n  });\n}\n\nfunction close() {\n  return fire(document, `${permanentPlayerKey()}:close`, {\n    bubbles: true,\n    cancelable: true,\n  });\n}\n\nexport {\n  clear,\n  close,\n  currentPlayerElement,\n  currentPresentationId,\n  exist,\n  open,\n  permanentPlayerData,\n  permanentPlayerKey,\n  save,\n};\n","import ApplicationController from 'modules/application_controller';\nimport * as PermanentPlayer from 'modules/permanent_player';\n\nexport default class extends ApplicationController {\n  static get targets() {\n    return ['playerWrapper', 'title', 'maximize'];\n  }\n\n  open({ detail: { presentationId, playerElement, title, url } }) {\n    if (PermanentPlayer.exist()) {\n      PermanentPlayer.close();\n    }\n\n    this.playerWrapperTarget.insertAdjacentElement('afterbegin', playerElement);\n\n    this.maximizeTarget.href = url;\n    this.titleTarget.href = url;\n    this.titleTarget.textContent = title;\n\n    this.element.hidden = false;\n\n    PermanentPlayer.save({ presentationId, playerElement });\n  }\n\n  close() {\n    this.element.hidden = true;\n\n    if (this.playerController) {\n      this.playerController.isPermanent = false;\n    }\n\n    this.playerWrapperTarget.innerHTML = '';\n    this.maximizeTarget.href = '#';\n    this.titleTarget.href = '#';\n    this.titleTarget.textContent = '';\n\n    PermanentPlayer.clear();\n  }\n\n  get playerController() {\n    if (!this.playerWrapperTarget.firstElementChild) {\n      return null;\n    }\n\n    return this.findControllerOnElement(this.playerWrapperTarget.firstElementChild);\n  }\n}\n","import ApplicationController from 'modules/application_controller';\nimport * as PermanentPlayer from 'modules/permanent_player';\nimport Player from 'modules/player/player';\n\nexport default class extends ApplicationController {\n  initialize() {\n    this.props = {\n      player: null,\n      benUrlInitialized: false,\n      isPermanent: false,\n    };\n  }\n\n  connect() {\n    this.initBenUrl();\n    this.initPlayer();\n  }\n\n  disconnect() {\n    if (this.player && !this.isPermanent) {\n      this.destroy();\n      this.player = null;\n    }\n  }\n\n  initBenUrl() {\n    if (this.benUrlInitialized) {\n      return;\n    }\n\n    this.benUrlInitialized = true;\n\n    if (gon.env !== 'development') {\n      return;\n    }\n\n    const host = window.location.host.split('.');\n\n    while (host.length > 2) {\n      host.shift();\n    }\n\n    const meta = document.createElement('meta');\n    meta.name = 'ben-base-url';\n    meta.content = `${window.location.protocol}//${host.join('.')}`;\n\n    document.head.insertAdjacentElement('beforeend', meta);\n  }\n\n  initPlayer() {\n    if (this.isTurboPreview || this.player) {\n      if (this.player) {\n        this.player.updateSize();\n      }\n\n      return false;\n    }\n\n    this.player = new Player(this.element.id, this.playerOptions);\n    this.player.on('play', () => {\n      if (this.player.firstPlay && PermanentPlayer.exist()) {\n        PermanentPlayer.close();\n      }\n    });\n\n    return true;\n  }\n\n  play() {\n    this.player.play();\n  }\n\n  pause() {\n    this.player.pause();\n  }\n\n  seekTo(seconds) {\n    this.player.seekTo(seconds * 1000);\n  }\n\n  seekSlide(slide) {\n    this.player.seekToSlide(slide);\n  }\n\n  updateSize() {\n    this.player.updateSize();\n  }\n\n  destroy() {\n    this.player.destroy();\n  }\n\n  get playerOptions() {\n    return {};\n  }\n\n  get player() {\n    return this.props.player;\n  }\n\n  set player(value) {\n    this.props.player = value;\n  }\n\n  get benUrlInitialized() {\n    return this.props.benUrlInitialized;\n  }\n\n  set benUrlInitialized(value) {\n    this.props.benUrlInitialized = value;\n  }\n\n  get isPermanent() {\n    return this.props.isPermanent;\n  }\n\n  set isPermanent(value) {\n    this.props.isPermanent = value;\n  }\n}\n","import ApplicationController from 'modules/application_controller';\n\nexport default class extends ApplicationController {\n  static get targets() {\n    return ['thumbnail'];\n  }\n\n  updatePublished(published) {\n    this.thumbnailController.setPublished(published);\n  }\n\n  updatePrivacy({ detail: { privacy } }) {\n    this.thumbnailController.setPrivacy(privacy);\n  }\n\n  updatePrice({ detail: { priceCents, priceCurrency } }) {\n    this.thumbnailController.setPrice(priceCents, priceCurrency);\n  }\n\n  publishedChanged({ target }) {\n    this.updatePublished(target.checked);\n  }\n\n  get thumbnailController() {\n    return this.application.getControllerForElementAndIdentifier(\n      this.thumbnailTarget,\n      'library--presentation-edit--thumbnail',\n    );\n  }\n}\n","import PlayerBaseController from 'library/player_base_component/player_base_component';\n\nexport default class extends PlayerBaseController {\n  load() {\n    this.player.loadWhenVisible();\n  }\n\n  get playerOptions() {\n    return {\n      autoPlay: false,\n      disableTracking: false,\n      disableGoogleAnalytics: true,\n      showThumbnail: false,\n    };\n  }\n}\n","import ApplicationController from 'modules/application_controller';\n\nexport default class extends ApplicationController {\n  static get targets() {\n    return ['priceCents', 'priceCurrency'];\n  }\n\n  privacyChanged(event) {\n    const detail = { privacy: event.target.value };\n    this.dispatch('privacyChanged', { detail });\n  }\n\n  priceChanged() {\n    const detail = {\n      priceCents: parseFloat(this.priceCentsTarget.value) * 100,\n      priceCurrency: this.priceCurrencyTarget.value,\n    };\n    this.dispatch('priceChanged', { detail });\n  }\n}\n","import ApplicationController from 'modules/application_controller';\n\nexport default class extends ApplicationController {\n  static get targets() {\n    return ['name'];\n  }\n\n  setName(event) {\n    this.nameTarget.value = event.detail.label;\n  }\n}\n","import ApplicationController from 'modules/application_controller';\n\nexport default class extends ApplicationController {\n  initialize() {\n    this.props = {\n      reloadTimeout: null,\n    };\n  }\n\n  connect() {\n    this.scheduleReload();\n  }\n\n  disconnect() {\n    if (this.reloadTimeout) {\n      clearTimeout(this.reloadTimeout);\n    }\n  }\n\n  scheduleReload() {\n    this.reloadTimeout = setTimeout(() => {\n      this.dispatch('reload');\n    }, this.checkInterval);\n  }\n\n  get reloadTimeout() {\n    return this.props.reloadTimeout;\n  }\n\n  set reloadTimeout(value) {\n    this.props.reloadTimeout = value;\n  }\n\n  get checkInterval() {\n    return 10000;\n  }\n}\n","import ApplicationController from 'modules/application_controller';\nimport Money from 'modules/money';\n\nexport default class extends ApplicationController {\n  static get targets() {\n    return ['private', 'unlisted', 'unpublished', 'price', 'thumbnail'];\n  }\n\n  setTitle(title) {\n    this.thumbnailTarget.setAttribute('alt', title);\n  }\n\n  setPublished(published) {\n    this.unpublishedTarget.hidden = published;\n  }\n\n  setPrivacy(privacy) {\n    this.unlistedTarget.hidden = privacy !== '2';\n    this.privateTarget.hidden = privacy !== '3';\n  }\n\n  setPrice(cents, currency) {\n    const price = new Money(cents, currency);\n\n    this.priceTarget.hidden = cents <= 0;\n    this.priceTarget.textContent = price.format();\n  }\n}\n","import { remove } from '@slideslive/fuse-kit/utils';\nimport ApplicationController from 'modules/application_controller';\n\nexport default class extends ApplicationController {\n  static get targets() {\n    return ['player'];\n  }\n\n  loadPlayer(event) {\n    remove(event.target);\n\n    this.playerTarget.hidden = false;\n    this.playerController.load();\n  }\n\n  get playerController() {\n    return this.findControllerByName('library--presentation-edit--player', {\n      useQuerySelector: false,\n      element: this.playerTarget,\n    });\n  }\n}\n","import ApplicationController from 'modules/application_controller';\nimport shave from 'shave';\n\nconst TITLE_LINES = 3;\n\nexport default class extends ApplicationController {\n  static get targets() {\n    return ['title'];\n  }\n\n  initialize() {\n    this.props = {\n      originalTitle: '',\n    };\n  }\n\n  connect() {\n    this.originalTitle = this.titleTarget.textContent;\n    this.shaveTitle();\n  }\n\n  shaveTitle() {\n    this.titleTarget.textContent = this.originalTitle;\n    shave(this.titleTarget, 19 * TITLE_LINES, { spaces: false });\n  }\n\n  get originalTitle() {\n    return this.props.originalTitle;\n  }\n\n  set originalTitle(value) {\n    this.props.originalTitle = value;\n  }\n}\n","import ApplicationController from 'modules/application_controller';\n\nexport default class extends ApplicationController {\n  initialize() {\n    this.props = {\n      alreadyLoading: false,\n    };\n  }\n\n  connect() {\n    this.submitForm();\n  }\n\n  handleLoading(event) {\n    if (event.detail.url !== this.submitUrl) {\n      return;\n    }\n\n    this.alreadyLoading = true;\n  }\n\n  submitForm() {\n    if (this.alreadyLoading) {\n      return;\n    }\n\n    this.alreadyLoading = true;\n\n    this.dispatch('loading', { target: document, detail: { url: this.submitUrl } });\n    this.element.requestSubmit();\n  }\n\n  get submitUrl() {\n    return this.element.action;\n  }\n\n  get alreadyLoading() {\n    return this.props.alreadyLoading;\n  }\n\n  set alreadyLoading(value) {\n    this.props.alreadyLoading = value;\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 * @fileoverview Firebase constants.  Some of these (@defines) can be overridden at compile-time.\n */\nconst CONSTANTS = {\n    /**\n     * @define {boolean} Whether this is the client Node.js SDK.\n     */\n    NODE_CLIENT: false,\n    /**\n     * @define {boolean} Whether this is the Admin Node.js SDK.\n     */\n    NODE_ADMIN: false,\n    /**\n     * Firebase SDK Version\n     */\n    SDK_VERSION: '${JSCORE_VERSION}'\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 * Throws an error if the provided assertion is falsy\n */\nconst assert = function (assertion, message) {\n    if (!assertion) {\n        throw assertionError(message);\n    }\n};\n/**\n * Returns an Error object suitable for throwing.\n */\nconst assertionError = function (message) {\n    return new Error('Firebase Database (' +\n        CONSTANTS.SDK_VERSION +\n        ') INTERNAL ASSERT FAILED: ' +\n        message);\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 */\nconst stringToByteArray$1 = function (str) {\n    // TODO(user): Use native implementations if/when available\n    const out = [];\n    let p = 0;\n    for (let i = 0; i < str.length; i++) {\n        let c = str.charCodeAt(i);\n        if (c < 128) {\n            out[p++] = c;\n        }\n        else if (c < 2048) {\n            out[p++] = (c >> 6) | 192;\n            out[p++] = (c & 63) | 128;\n        }\n        else if ((c & 0xfc00) === 0xd800 &&\n            i + 1 < str.length &&\n            (str.charCodeAt(i + 1) & 0xfc00) === 0xdc00) {\n            // Surrogate Pair\n            c = 0x10000 + ((c & 0x03ff) << 10) + (str.charCodeAt(++i) & 0x03ff);\n            out[p++] = (c >> 18) | 240;\n            out[p++] = ((c >> 12) & 63) | 128;\n            out[p++] = ((c >> 6) & 63) | 128;\n            out[p++] = (c & 63) | 128;\n        }\n        else {\n            out[p++] = (c >> 12) | 224;\n            out[p++] = ((c >> 6) & 63) | 128;\n            out[p++] = (c & 63) | 128;\n        }\n    }\n    return out;\n};\n/**\n * Turns an array of numbers into the string given by the concatenation of the\n * characters to which the numbers correspond.\n * @param bytes Array of numbers representing characters.\n * @return Stringification of the array.\n */\nconst byteArrayToString = function (bytes) {\n    // TODO(user): Use native implementations if/when available\n    const out = [];\n    let pos = 0, c = 0;\n    while (pos < bytes.length) {\n        const c1 = bytes[pos++];\n        if (c1 < 128) {\n            out[c++] = String.fromCharCode(c1);\n        }\n        else if (c1 > 191 && c1 < 224) {\n            const c2 = bytes[pos++];\n            out[c++] = String.fromCharCode(((c1 & 31) << 6) | (c2 & 63));\n        }\n        else if (c1 > 239 && c1 < 365) {\n            // Surrogate Pair\n            const c2 = bytes[pos++];\n            const c3 = bytes[pos++];\n            const c4 = bytes[pos++];\n            const u = (((c1 & 7) << 18) | ((c2 & 63) << 12) | ((c3 & 63) << 6) | (c4 & 63)) -\n                0x10000;\n            out[c++] = String.fromCharCode(0xd800 + (u >> 10));\n            out[c++] = String.fromCharCode(0xdc00 + (u & 1023));\n        }\n        else {\n            const c2 = bytes[pos++];\n            const c3 = bytes[pos++];\n            out[c++] = String.fromCharCode(((c1 & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));\n        }\n    }\n    return out.join('');\n};\n// We define it as an object literal instead of a class because a class compiled down to es5 can't\n// be treeshaked. https://github.com/rollup/rollup/issues/1691\n// Static lookup maps, lazily populated by init_()\n// TODO(dlarocque): Define this as a class, since we no longer target ES5.\nconst base64 = {\n    /**\n     * Maps bytes to characters.\n     */\n    byteToCharMap_: null,\n    /**\n     * Maps characters to bytes.\n     */\n    charToByteMap_: null,\n    /**\n     * Maps bytes to websafe characters.\n     * @private\n     */\n    byteToCharMapWebSafe_: null,\n    /**\n     * Maps websafe characters to bytes.\n     * @private\n     */\n    charToByteMapWebSafe_: null,\n    /**\n     * Our default alphabet, shared between\n     * ENCODED_VALS and ENCODED_VALS_WEBSAFE\n     */\n    ENCODED_VALS_BASE: 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' + 'abcdefghijklmnopqrstuvwxyz' + '0123456789',\n    /**\n     * Our default alphabet. Value 64 (=) is special; it means \"nothing.\"\n     */\n    get ENCODED_VALS() {\n        return this.ENCODED_VALS_BASE + '+/=';\n    },\n    /**\n     * Our websafe alphabet.\n     */\n    get ENCODED_VALS_WEBSAFE() {\n        return this.ENCODED_VALS_BASE + '-_.';\n    },\n    /**\n     * Whether this browser supports the atob and btoa functions. This extension\n     * started at Mozilla but is now implemented by many browsers. We use the\n     * ASSUME_* variables to avoid pulling in the full useragent detection library\n     * but still allowing the standard per-browser compilations.\n     *\n     */\n    HAS_NATIVE_SUPPORT: typeof atob === 'function',\n    /**\n     * Base64-encode an array of bytes.\n     *\n     * @param input An array of bytes (numbers with\n     *     value in [0, 255]) to encode.\n     * @param webSafe Boolean indicating we should use the\n     *     alternative alphabet.\n     * @return The base64 encoded string.\n     */\n    encodeByteArray(input, webSafe) {\n        if (!Array.isArray(input)) {\n            throw Error('encodeByteArray takes an array as a parameter');\n        }\n        this.init_();\n        const byteToCharMap = webSafe\n            ? this.byteToCharMapWebSafe_\n            : this.byteToCharMap_;\n        const output = [];\n        for (let i = 0; i < input.length; i += 3) {\n            const byte1 = input[i];\n            const haveByte2 = i + 1 < input.length;\n            const byte2 = haveByte2 ? input[i + 1] : 0;\n            const haveByte3 = i + 2 < input.length;\n            const byte3 = haveByte3 ? input[i + 2] : 0;\n            const outByte1 = byte1 >> 2;\n            const outByte2 = ((byte1 & 0x03) << 4) | (byte2 >> 4);\n            let outByte3 = ((byte2 & 0x0f) << 2) | (byte3 >> 6);\n            let outByte4 = byte3 & 0x3f;\n            if (!haveByte3) {\n                outByte4 = 64;\n                if (!haveByte2) {\n                    outByte3 = 64;\n                }\n            }\n            output.push(byteToCharMap[outByte1], byteToCharMap[outByte2], byteToCharMap[outByte3], byteToCharMap[outByte4]);\n        }\n        return output.join('');\n    },\n    /**\n     * Base64-encode a string.\n     *\n     * @param input A string to encode.\n     * @param webSafe If true, we should use the\n     *     alternative alphabet.\n     * @return The base64 encoded string.\n     */\n    encodeString(input, webSafe) {\n        // Shortcut for Mozilla browsers that implement\n        // a native base64 encoder in the form of \"btoa/atob\"\n        if (this.HAS_NATIVE_SUPPORT && !webSafe) {\n            return btoa(input);\n        }\n        return this.encodeByteArray(stringToByteArray$1(input), webSafe);\n    },\n    /**\n     * Base64-decode a string.\n     *\n     * @param input to decode.\n     * @param webSafe True if we should use the\n     *     alternative alphabet.\n     * @return string representing the decoded value.\n     */\n    decodeString(input, webSafe) {\n        // Shortcut for Mozilla browsers that implement\n        // a native base64 encoder in the form of \"btoa/atob\"\n        if (this.HAS_NATIVE_SUPPORT && !webSafe) {\n            return atob(input);\n        }\n        return byteArrayToString(this.decodeStringToByteArray(input, webSafe));\n    },\n    /**\n     * Base64-decode a string.\n     *\n     * In base-64 decoding, groups of four characters are converted into three\n     * bytes.  If the encoder did not apply padding, the input length may not\n     * be a multiple of 4.\n     *\n     * In this case, the last group will have fewer than 4 characters, and\n     * padding will be inferred.  If the group has one or two characters, it decodes\n     * to one byte.  If the group has three characters, it decodes to two bytes.\n     *\n     * @param input Input to decode.\n     * @param webSafe True if we should use the web-safe alphabet.\n     * @return bytes representing the decoded value.\n     */\n    decodeStringToByteArray(input, webSafe) {\n        this.init_();\n        const charToByteMap = webSafe\n            ? this.charToByteMapWebSafe_\n            : this.charToByteMap_;\n        const output = [];\n        for (let i = 0; i < input.length;) {\n            const byte1 = charToByteMap[input.charAt(i++)];\n            const haveByte2 = i < input.length;\n            const byte2 = haveByte2 ? charToByteMap[input.charAt(i)] : 0;\n            ++i;\n            const haveByte3 = i < input.length;\n            const byte3 = haveByte3 ? charToByteMap[input.charAt(i)] : 64;\n            ++i;\n            const haveByte4 = i < input.length;\n            const byte4 = haveByte4 ? charToByteMap[input.charAt(i)] : 64;\n            ++i;\n            if (byte1 == null || byte2 == null || byte3 == null || byte4 == null) {\n                throw new DecodeBase64StringError();\n            }\n            const outByte1 = (byte1 << 2) | (byte2 >> 4);\n            output.push(outByte1);\n            if (byte3 !== 64) {\n                const outByte2 = ((byte2 << 4) & 0xf0) | (byte3 >> 2);\n                output.push(outByte2);\n                if (byte4 !== 64) {\n                    const outByte3 = ((byte3 << 6) & 0xc0) | byte4;\n                    output.push(outByte3);\n                }\n            }\n        }\n        return output;\n    },\n    /**\n     * Lazy static initialization function. Called before\n     * accessing any of the static map variables.\n     * @private\n     */\n    init_() {\n        if (!this.byteToCharMap_) {\n            this.byteToCharMap_ = {};\n            this.charToByteMap_ = {};\n            this.byteToCharMapWebSafe_ = {};\n            this.charToByteMapWebSafe_ = {};\n            // We want quick mappings back and forth, so we precompute two maps.\n            for (let i = 0; i < this.ENCODED_VALS.length; i++) {\n                this.byteToCharMap_[i] = this.ENCODED_VALS.charAt(i);\n                this.charToByteMap_[this.byteToCharMap_[i]] = i;\n                this.byteToCharMapWebSafe_[i] = this.ENCODED_VALS_WEBSAFE.charAt(i);\n                this.charToByteMapWebSafe_[this.byteToCharMapWebSafe_[i]] = i;\n                // Be forgiving when decoding and correctly decode both encodings.\n                if (i >= this.ENCODED_VALS_BASE.length) {\n                    this.charToByteMap_[this.ENCODED_VALS_WEBSAFE.charAt(i)] = i;\n                    this.charToByteMapWebSafe_[this.ENCODED_VALS.charAt(i)] = i;\n                }\n            }\n        }\n    }\n};\n/**\n * An error encountered while decoding base64 string.\n */\nclass DecodeBase64StringError extends Error {\n    constructor() {\n        super(...arguments);\n        this.name = 'DecodeBase64StringError';\n    }\n}\n/**\n * URL-safe base64 encoding\n */\nconst base64Encode = function (str) {\n    const utf8Bytes = stringToByteArray$1(str);\n    return base64.encodeByteArray(utf8Bytes, true);\n};\n/**\n * URL-safe base64 encoding (without \".\" padding in the end).\n * e.g. Used in JSON Web Token (JWT) parts.\n */\nconst base64urlEncodeWithoutPadding = function (str) {\n    // Use base64url encoding and remove padding in the end (dot characters).\n    return base64Encode(str).replace(/\\./g, '');\n};\n/**\n * URL-safe base64 decoding\n *\n * NOTE: DO NOT use the global atob() function - it does NOT support the\n * base64Url variant encoding.\n *\n * @param str To be decoded\n * @return Decoded result, if possible\n */\nconst base64Decode = function (str) {\n    try {\n        return base64.decodeString(str, true);\n    }\n    catch (e) {\n        console.error('base64Decode failed: ', e);\n    }\n    return null;\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 * Do a deep-copy of basic JavaScript Objects or Arrays.\n */\nfunction deepCopy(value) {\n    return deepExtend(undefined, value);\n}\n/**\n * Copy properties from source to target (recursively allows extension\n * of Objects and Arrays).  Scalar values in the target are over-written.\n * If target is undefined, an object of the appropriate type will be created\n * (and returned).\n *\n * We recursively copy all child properties of plain Objects in the source- so\n * that namespace- like dictionaries are merged.\n *\n * Note that the target can be a function, in which case the properties in\n * the source Object are copied onto it as static properties of the Function.\n *\n * Note: we don't merge __proto__ to prevent prototype pollution\n */\nfunction deepExtend(target, source) {\n    if (!(source instanceof Object)) {\n        return source;\n    }\n    switch (source.constructor) {\n        case Date:\n            // Treat Dates like scalars; if the target date object had any child\n            // properties - they will be lost!\n            const dateValue = source;\n            return new Date(dateValue.getTime());\n        case Object:\n            if (target === undefined) {\n                target = {};\n            }\n            break;\n        case Array:\n            // Always copy the array source and overwrite the target.\n            target = [];\n            break;\n        default:\n            // Not a plain Object - treat it as a scalar.\n            return source;\n    }\n    for (const prop in source) {\n        // use isValidKey to guard against prototype pollution. See https://snyk.io/vuln/SNYK-JS-LODASH-450202\n        if (!source.hasOwnProperty(prop) || !isValidKey(prop)) {\n            continue;\n        }\n        target[prop] = deepExtend(target[prop], source[prop]);\n    }\n    return target;\n}\nfunction isValidKey(key) {\n    return key !== '__proto__';\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 * Polyfill for `globalThis` object.\n * @returns the `globalThis` object for the given environment.\n * @public\n */\nfunction getGlobal() {\n    if (typeof self !== 'undefined') {\n        return self;\n    }\n    if (typeof window !== 'undefined') {\n        return window;\n    }\n    if (typeof global !== 'undefined') {\n        return global;\n    }\n    throw new Error('Unable to locate global object.');\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 */\nconst getDefaultsFromGlobal = () => getGlobal().__FIREBASE_DEFAULTS__;\n/**\n * Attempt to read defaults from a JSON string provided to\n * process(.)env(.)__FIREBASE_DEFAULTS__ or a JSON file whose path is in\n * process(.)env(.)__FIREBASE_DEFAULTS_PATH__\n * The dots are in parens because certain compilers (Vite?) cannot\n * handle seeing that variable in comments.\n * See https://github.com/firebase/firebase-js-sdk/issues/6838\n */\nconst getDefaultsFromEnvVariable = () => {\n    if (typeof process === 'undefined' || typeof process.env === 'undefined') {\n        return;\n    }\n    const defaultsJsonString = process.env.__FIREBASE_DEFAULTS__;\n    if (defaultsJsonString) {\n        return JSON.parse(defaultsJsonString);\n    }\n};\nconst getDefaultsFromCookie = () => {\n    if (typeof document === 'undefined') {\n        return;\n    }\n    let match;\n    try {\n        match = document.cookie.match(/__FIREBASE_DEFAULTS__=([^;]+)/);\n    }\n    catch (e) {\n        // Some environments such as Angular Universal SSR have a\n        // `document` object but error on accessing `document.cookie`.\n        return;\n    }\n    const decoded = match && base64Decode(match[1]);\n    return decoded && JSON.parse(decoded);\n};\n/**\n * Get the __FIREBASE_DEFAULTS__ object. It checks in order:\n * (1) if such an object exists as a property of `globalThis`\n * (2) if such an object was provided on a shell environment variable\n * (3) if such an object exists in a cookie\n * @public\n */\nconst getDefaults = () => {\n    try {\n        return (getDefaultsFromGlobal() ||\n            getDefaultsFromEnvVariable() ||\n            getDefaultsFromCookie());\n    }\n    catch (e) {\n        /**\n         * Catch-all for being unable to get __FIREBASE_DEFAULTS__ due\n         * to any environment case we have not accounted for. Log to\n         * info instead of swallowing so we can find these unknown cases\n         * and add paths for them if needed.\n         */\n        console.info(`Unable to get __FIREBASE_DEFAULTS__ due to: ${e}`);\n        return;\n    }\n};\n/**\n * Returns emulator host stored in the __FIREBASE_DEFAULTS__ object\n * for the given product.\n * @returns a URL host formatted like `127.0.0.1:9999` or `[::1]:4000` if available\n * @public\n */\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]; };\n/**\n * Returns emulator hostname and port stored in the __FIREBASE_DEFAULTS__ object\n * for the given product.\n * @returns a pair of hostname and port like `[\"::1\", 4000]` if available\n * @public\n */\nconst getDefaultEmulatorHostnameAndPort = (productName) => {\n    const host = getDefaultEmulatorHost(productName);\n    if (!host) {\n        return undefined;\n    }\n    const separatorIndex = host.lastIndexOf(':'); // Finding the last since IPv6 addr also has colons.\n    if (separatorIndex <= 0 || separatorIndex + 1 === host.length) {\n        throw new Error(`Invalid host ${host} with no separate hostname and port!`);\n    }\n    // eslint-disable-next-line no-restricted-globals\n    const port = parseInt(host.substring(separatorIndex + 1), 10);\n    if (host[0] === '[') {\n        // Bracket-quoted `[ipv6addr]:port` => return \"ipv6addr\" (without brackets).\n        return [host.substring(1, separatorIndex - 1), port];\n    }\n    else {\n        return [host.substring(0, separatorIndex), port];\n    }\n};\n/**\n * Returns Firebase app config stored in the __FIREBASE_DEFAULTS__ object.\n * @public\n */\nconst getDefaultAppConfig = () => { var _a; return (_a = getDefaults()) === null || _a === void 0 ? void 0 : _a.config; };\n/**\n * Returns an experimental setting on the __FIREBASE_DEFAULTS__ object (properties\n * prefixed by \"_\")\n * @public\n */\nconst getExperimentalSetting = (name) => { var _a; return (_a = getDefaults()) === null || _a === void 0 ? void 0 : _a[`_${name}`]; };\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 Deferred {\n    constructor() {\n        this.reject = () => { };\n        this.resolve = () => { };\n        this.promise = new Promise((resolve, reject) => {\n            this.resolve = resolve;\n            this.reject = reject;\n        });\n    }\n    /**\n     * Our API internals are not promisified and cannot because our callback APIs have subtle expectations around\n     * invoking promises inline, which Promises are forbidden to do. This method accepts an optional node-style callback\n     * and returns a node-style callback which will resolve or reject the Deferred's promise.\n     */\n    wrapCallback(callback) {\n        return (error, value) => {\n            if (error) {\n                this.reject(error);\n            }\n            else {\n                this.resolve(value);\n            }\n            if (typeof callback === 'function') {\n                // Attaching noop handler just in case developer wasn't expecting\n                // promises\n                this.promise.catch(() => { });\n                // Some of our callbacks don't expect a value and our own tests\n                // assert that the parameter length is 1\n                if (callback.length === 1) {\n                    callback(error);\n                }\n                else {\n                    callback(error, value);\n                }\n            }\n        };\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 */\nfunction createMockUserToken(token, projectId) {\n    if (token.uid) {\n        throw new Error('The \"uid\" field is no longer supported by mockUserToken. Please use \"sub\" instead for Firebase Auth User ID.');\n    }\n    // Unsecured JWTs use \"none\" as the algorithm.\n    const header = {\n        alg: 'none',\n        type: 'JWT'\n    };\n    const project = projectId || 'demo-project';\n    const iat = token.iat || 0;\n    const sub = token.sub || token.user_id;\n    if (!sub) {\n        throw new Error(\"mockUserToken must contain 'sub' or 'user_id' field!\");\n    }\n    const payload = Object.assign({ \n        // Set all required fields to decent defaults\n        iss: `https://securetoken.google.com/${project}`, aud: project, iat, exp: iat + 3600, auth_time: iat, sub, user_id: sub, firebase: {\n            sign_in_provider: 'custom',\n            identities: {}\n        } }, token);\n    // Unsecured JWTs use the empty string as a signature.\n    const signature = '';\n    return [\n        base64urlEncodeWithoutPadding(JSON.stringify(header)),\n        base64urlEncodeWithoutPadding(JSON.stringify(payload)),\n        signature\n    ].join('.');\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 * Returns navigator.userAgent string or '' if it's not defined.\n * @return user agent string\n */\nfunction getUA() {\n    if (typeof navigator !== 'undefined' &&\n        typeof navigator['userAgent'] === 'string') {\n        return navigator['userAgent'];\n    }\n    else {\n        return '';\n    }\n}\n/**\n * Detect Cordova / PhoneGap / Ionic frameworks on a mobile device.\n *\n * Deliberately does not rely on checking `file://` URLs (as this fails PhoneGap\n * in the Ripple emulator) nor Cordova `onDeviceReady`, which would normally\n * wait for a callback.\n */\nfunction isMobileCordova() {\n    return (typeof window !== 'undefined' &&\n        // @ts-ignore Setting up an broadly applicable index signature for Window\n        // just to deal with this case would probably be a bad idea.\n        !!(window['cordova'] || window['phonegap'] || window['PhoneGap']) &&\n        /ios|iphone|ipod|ipad|android|blackberry|iemobile/i.test(getUA()));\n}\n/**\n * Detect Node.js.\n *\n * @return true if Node.js environment is detected or specified.\n */\n// Node detection logic from: https://github.com/iliakan/detect-node/\nfunction isNode() {\n    var _a;\n    const forceEnvironment = (_a = getDefaults()) === null || _a === void 0 ? void 0 : _a.forceEnvironment;\n    if (forceEnvironment === 'node') {\n        return true;\n    }\n    else if (forceEnvironment === 'browser') {\n        return false;\n    }\n    try {\n        return (Object.prototype.toString.call(global.process) === '[object process]');\n    }\n    catch (e) {\n        return false;\n    }\n}\n/**\n * Detect Browser Environment.\n * Note: This will return true for certain test frameworks that are incompletely\n * mimicking a browser, and should not lead to assuming all browser APIs are\n * available.\n */\nfunction isBrowser() {\n    return typeof window !== 'undefined' || isWebWorker();\n}\n/**\n * Detect Web Worker context.\n */\nfunction isWebWorker() {\n    return (typeof WorkerGlobalScope !== 'undefined' &&\n        typeof self !== 'undefined' &&\n        self instanceof WorkerGlobalScope);\n}\n/**\n * Detect Cloudflare Worker context.\n */\nfunction isCloudflareWorker() {\n    return (typeof navigator !== 'undefined' &&\n        navigator.userAgent === 'Cloudflare-Workers');\n}\nfunction isBrowserExtension() {\n    const runtime = typeof chrome === 'object'\n        ? chrome.runtime\n        : typeof browser === 'object'\n            ? browser.runtime\n            : undefined;\n    return typeof runtime === 'object' && runtime.id !== undefined;\n}\n/**\n * Detect React Native.\n *\n * @return true if ReactNative environment is detected.\n */\nfunction isReactNative() {\n    return (typeof navigator === 'object' && navigator['product'] === 'ReactNative');\n}\n/** Detects Electron apps. */\nfunction isElectron() {\n    return getUA().indexOf('Electron/') >= 0;\n}\n/** Detects Internet Explorer. */\nfunction isIE() {\n    const ua = getUA();\n    return ua.indexOf('MSIE ') >= 0 || ua.indexOf('Trident/') >= 0;\n}\n/** Detects Universal Windows Platform apps. */\nfunction isUWP() {\n    return getUA().indexOf('MSAppHost/') >= 0;\n}\n/**\n * Detect whether the current SDK build is the Node version.\n *\n * @return true if it's the Node SDK build.\n */\nfunction isNodeSdk() {\n    return CONSTANTS.NODE_CLIENT === true || CONSTANTS.NODE_ADMIN === true;\n}\n/** Returns true if we are running in Safari. */\nfunction isSafari() {\n    return (!isNode() &&\n        !!navigator.userAgent &&\n        navigator.userAgent.includes('Safari') &&\n        !navigator.userAgent.includes('Chrome'));\n}\n/**\n * This method checks if indexedDB is supported by current browser/service worker context\n * @return true if indexedDB is supported by current browser/service worker context\n */\nfunction isIndexedDBAvailable() {\n    try {\n        return typeof indexedDB === 'object';\n    }\n    catch (e) {\n        return false;\n    }\n}\n/**\n * This method validates browser/sw context for indexedDB by opening a dummy indexedDB database and reject\n * if errors occur during the database open operation.\n *\n * @throws exception if current browser/sw context can't run idb.open (ex: Safari iframe, Firefox\n * private browsing)\n */\nfunction validateIndexedDBOpenable() {\n    return new Promise((resolve, reject) => {\n        try {\n            let preExist = true;\n            const DB_CHECK_NAME = 'validate-browser-context-for-indexeddb-analytics-module';\n            const request = self.indexedDB.open(DB_CHECK_NAME);\n            request.onsuccess = () => {\n                request.result.close();\n                // delete database only when it doesn't pre-exist\n                if (!preExist) {\n                    self.indexedDB.deleteDatabase(DB_CHECK_NAME);\n                }\n                resolve(true);\n            };\n            request.onupgradeneeded = () => {\n                preExist = false;\n            };\n            request.onerror = () => {\n                var _a;\n                reject(((_a = request.error) === null || _a === void 0 ? void 0 : _a.message) || '');\n            };\n        }\n        catch (error) {\n            reject(error);\n        }\n    });\n}\n/**\n *\n * This method checks whether cookie is enabled within current browser\n * @return true if cookie is enabled within current browser\n */\nfunction areCookiesEnabled() {\n    if (typeof navigator === 'undefined' || !navigator.cookieEnabled) {\n        return false;\n    }\n    return true;\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 * @fileoverview Standardized Firebase Error.\n *\n * Usage:\n *\n *   // TypeScript string literals for type-safe codes\n *   type Err =\n *     'unknown' |\n *     'object-not-found'\n *     ;\n *\n *   // Closure enum for type-safe error codes\n *   // at-enum {string}\n *   var Err = {\n *     UNKNOWN: 'unknown',\n *     OBJECT_NOT_FOUND: 'object-not-found',\n *   }\n *\n *   let errors: Map<Err, string> = {\n *     'generic-error': \"Unknown error\",\n *     'file-not-found': \"Could not find file: {$file}\",\n *   };\n *\n *   // Type-safe function - must pass a valid error code as param.\n *   let error = new ErrorFactory<Err>('service', 'Service', errors);\n *\n *   ...\n *   throw error.create(Err.GENERIC);\n *   ...\n *   throw error.create(Err.FILE_NOT_FOUND, {'file': fileName});\n *   ...\n *   // Service: Could not file file: foo.txt (service/file-not-found).\n *\n *   catch (e) {\n *     assert(e.message === \"Could not find file: foo.txt.\");\n *     if ((e as FirebaseError)?.code === 'service/file-not-found') {\n *       console.log(\"Could not read file: \" + e['file']);\n *     }\n *   }\n */\nconst ERROR_NAME = 'FirebaseError';\n// Based on code from:\n// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error#Custom_Error_Types\nclass FirebaseError extends Error {\n    constructor(\n    /** The error code for this error. */\n    code, message, \n    /** Custom data for this error. */\n    customData) {\n        super(message);\n        this.code = code;\n        this.customData = customData;\n        /** The custom name for all FirebaseErrors. */\n        this.name = ERROR_NAME;\n        // Fix For ES5\n        // https://github.com/Microsoft/TypeScript-wiki/blob/master/Breaking-Changes.md#extending-built-ins-like-error-array-and-map-may-no-longer-work\n        // TODO(dlarocque): Replace this with `new.target`: https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-2.html#support-for-newtarget\n        //                   which we can now use since we no longer target ES5.\n        Object.setPrototypeOf(this, FirebaseError.prototype);\n        // Maintains proper stack trace for where our error was thrown.\n        // Only available on V8.\n        if (Error.captureStackTrace) {\n            Error.captureStackTrace(this, ErrorFactory.prototype.create);\n        }\n    }\n}\nclass ErrorFactory {\n    constructor(service, serviceName, errors) {\n        this.service = service;\n        this.serviceName = serviceName;\n        this.errors = errors;\n    }\n    create(code, ...data) {\n        const customData = data[0] || {};\n        const fullCode = `${this.service}/${code}`;\n        const template = this.errors[code];\n        const message = template ? replaceTemplate(template, customData) : 'Error';\n        // Service Name: Error message (service/code).\n        const fullMessage = `${this.serviceName}: ${message} (${fullCode}).`;\n        const error = new FirebaseError(fullCode, fullMessage, customData);\n        return error;\n    }\n}\nfunction replaceTemplate(template, data) {\n    return template.replace(PATTERN, (_, key) => {\n        const value = data[key];\n        return value != null ? String(value) : `<${key}?>`;\n    });\n}\nconst PATTERN = /\\{\\$([^}]+)}/g;\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 * Evaluates a JSON string into a javascript object.\n *\n * @param {string} str A string containing JSON.\n * @return {*} The javascript object representing the specified JSON.\n */\nfunction jsonEval(str) {\n    return JSON.parse(str);\n}\n/**\n * Returns JSON representing a javascript object.\n * @param {*} data JavaScript object to be stringified.\n * @return {string} The JSON contents of the object.\n */\nfunction stringify(data) {\n    return JSON.stringify(data);\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 * Decodes a Firebase auth. token into constituent parts.\n *\n * Notes:\n * - May return with invalid / incomplete claims if there's no native base64 decoding support.\n * - Doesn't check if the token is actually valid.\n */\nconst decode = function (token) {\n    let header = {}, claims = {}, data = {}, signature = '';\n    try {\n        const parts = token.split('.');\n        header = jsonEval(base64Decode(parts[0]) || '');\n        claims = jsonEval(base64Decode(parts[1]) || '');\n        signature = parts[2];\n        data = claims['d'] || {};\n        delete claims['d'];\n    }\n    catch (e) { }\n    return {\n        header,\n        claims,\n        data,\n        signature\n    };\n};\n/**\n * Decodes a Firebase auth. token and checks the validity of its time-based claims. Will return true if the\n * token is within the time window authorized by the 'nbf' (not-before) and 'iat' (issued-at) claims.\n *\n * Notes:\n * - May return a false negative if there's no native base64 decoding support.\n * - Doesn't check if the token is actually valid.\n */\nconst isValidTimestamp = function (token) {\n    const claims = decode(token).claims;\n    const now = Math.floor(new Date().getTime() / 1000);\n    let validSince = 0, validUntil = 0;\n    if (typeof claims === 'object') {\n        if (claims.hasOwnProperty('nbf')) {\n            validSince = claims['nbf'];\n        }\n        else if (claims.hasOwnProperty('iat')) {\n            validSince = claims['iat'];\n        }\n        if (claims.hasOwnProperty('exp')) {\n            validUntil = claims['exp'];\n        }\n        else {\n            // token will expire after 24h by default\n            validUntil = validSince + 86400;\n        }\n    }\n    return (!!now &&\n        !!validSince &&\n        !!validUntil &&\n        now >= validSince &&\n        now <= validUntil);\n};\n/**\n * Decodes a Firebase auth. token and returns its issued at time if valid, null otherwise.\n *\n * Notes:\n * - May return null if there's no native base64 decoding support.\n * - Doesn't check if the token is actually valid.\n */\nconst issuedAtTime = function (token) {\n    const claims = decode(token).claims;\n    if (typeof claims === 'object' && claims.hasOwnProperty('iat')) {\n        return claims['iat'];\n    }\n    return null;\n};\n/**\n * Decodes a Firebase auth. token and checks the validity of its format. Expects a valid issued-at time.\n *\n * Notes:\n * - May return a false negative if there's no native base64 decoding support.\n * - Doesn't check if the token is actually valid.\n */\nconst isValidFormat = function (token) {\n    const decoded = decode(token), claims = decoded.claims;\n    return !!claims && typeof claims === 'object' && claims.hasOwnProperty('iat');\n};\n/**\n * Attempts to peer into an auth token and determine if it's an admin auth token by looking at the claims portion.\n *\n * Notes:\n * - May return a false negative if there's no native base64 decoding support.\n * - Doesn't check if the token is actually valid.\n */\nconst isAdmin = function (token) {\n    const claims = decode(token).claims;\n    return typeof claims === 'object' && claims['admin'] === true;\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 */\nfunction contains(obj, key) {\n    return Object.prototype.hasOwnProperty.call(obj, key);\n}\nfunction safeGet(obj, key) {\n    if (Object.prototype.hasOwnProperty.call(obj, key)) {\n        return obj[key];\n    }\n    else {\n        return undefined;\n    }\n}\nfunction isEmpty(obj) {\n    for (const key in obj) {\n        if (Object.prototype.hasOwnProperty.call(obj, key)) {\n            return false;\n        }\n    }\n    return true;\n}\nfunction map(obj, fn, contextObj) {\n    const res = {};\n    for (const key in obj) {\n        if (Object.prototype.hasOwnProperty.call(obj, key)) {\n            res[key] = fn.call(contextObj, obj[key], key, obj);\n        }\n    }\n    return res;\n}\n/**\n * Deep equal two objects. Support Arrays and Objects.\n */\nfunction deepEqual(a, b) {\n    if (a === b) {\n        return true;\n    }\n    const aKeys = Object.keys(a);\n    const bKeys = Object.keys(b);\n    for (const k of aKeys) {\n        if (!bKeys.includes(k)) {\n            return false;\n        }\n        const aProp = a[k];\n        const bProp = b[k];\n        if (isObject(aProp) && isObject(bProp)) {\n            if (!deepEqual(aProp, bProp)) {\n                return false;\n            }\n        }\n        else if (aProp !== bProp) {\n            return false;\n        }\n    }\n    for (const k of bKeys) {\n        if (!aKeys.includes(k)) {\n            return false;\n        }\n    }\n    return true;\n}\nfunction isObject(thing) {\n    return thing !== null && typeof thing === 'object';\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 * Rejects if the given promise doesn't resolve in timeInMS milliseconds.\n * @internal\n */\nfunction promiseWithTimeout(promise, timeInMS = 2000) {\n    const deferredPromise = new Deferred();\n    setTimeout(() => deferredPromise.reject('timeout!'), timeInMS);\n    promise.then(deferredPromise.resolve, deferredPromise.reject);\n    return deferredPromise.promise;\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 * Returns a querystring-formatted string (e.g. &arg=val&arg2=val2) from a\n * params object (e.g. {arg: 'val', arg2: 'val2'})\n * Note: You must prepend it with ? when adding it to a URL.\n */\nfunction querystring(querystringParams) {\n    const params = [];\n    for (const [key, value] of Object.entries(querystringParams)) {\n        if (Array.isArray(value)) {\n            value.forEach(arrayVal => {\n                params.push(encodeURIComponent(key) + '=' + encodeURIComponent(arrayVal));\n            });\n        }\n        else {\n            params.push(encodeURIComponent(key) + '=' + encodeURIComponent(value));\n        }\n    }\n    return params.length ? '&' + params.join('&') : '';\n}\n/**\n * Decodes a querystring (e.g. ?arg=val&arg2=val2) into a params object\n * (e.g. {arg: 'val', arg2: 'val2'})\n */\nfunction querystringDecode(querystring) {\n    const obj = {};\n    const tokens = querystring.replace(/^\\?/, '').split('&');\n    tokens.forEach(token => {\n        if (token) {\n            const [key, value] = token.split('=');\n            obj[decodeURIComponent(key)] = decodeURIComponent(value);\n        }\n    });\n    return obj;\n}\n/**\n * Extract the query string part of a URL, including the leading question mark (if present).\n */\nfunction extractQuerystring(url) {\n    const queryStart = url.indexOf('?');\n    if (!queryStart) {\n        return '';\n    }\n    const fragmentStart = url.indexOf('#', queryStart);\n    return url.substring(queryStart, fragmentStart > 0 ? fragmentStart : undefined);\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 * @fileoverview SHA-1 cryptographic hash.\n * Variable names follow the notation in FIPS PUB 180-3:\n * http://csrc.nist.gov/publications/fips/fips180-3/fips180-3_final.pdf.\n *\n * Usage:\n *   var sha1 = new sha1();\n *   sha1.update(bytes);\n *   var hash = sha1.digest();\n *\n * Performance:\n *   Chrome 23:   ~400 Mbit/s\n *   Firefox 16:  ~250 Mbit/s\n *\n */\n/**\n * SHA-1 cryptographic hash constructor.\n *\n * The properties declared here are discussed in the above algorithm document.\n * @constructor\n * @final\n * @struct\n */\nclass Sha1 {\n    constructor() {\n        /**\n         * Holds the previous values of accumulated variables a-e in the compress_\n         * function.\n         * @private\n         */\n        this.chain_ = [];\n        /**\n         * A buffer holding the partially computed hash result.\n         * @private\n         */\n        this.buf_ = [];\n        /**\n         * An array of 80 bytes, each a part of the message to be hashed.  Referred to\n         * as the message schedule in the docs.\n         * @private\n         */\n        this.W_ = [];\n        /**\n         * Contains data needed to pad messages less than 64 bytes.\n         * @private\n         */\n        this.pad_ = [];\n        /**\n         * @private {number}\n         */\n        this.inbuf_ = 0;\n        /**\n         * @private {number}\n         */\n        this.total_ = 0;\n        this.blockSize = 512 / 8;\n        this.pad_[0] = 128;\n        for (let i = 1; i < this.blockSize; ++i) {\n            this.pad_[i] = 0;\n        }\n        this.reset();\n    }\n    reset() {\n        this.chain_[0] = 0x67452301;\n        this.chain_[1] = 0xefcdab89;\n        this.chain_[2] = 0x98badcfe;\n        this.chain_[3] = 0x10325476;\n        this.chain_[4] = 0xc3d2e1f0;\n        this.inbuf_ = 0;\n        this.total_ = 0;\n    }\n    /**\n     * Internal compress helper function.\n     * @param buf Block to compress.\n     * @param offset Offset of the block in the buffer.\n     * @private\n     */\n    compress_(buf, offset) {\n        if (!offset) {\n            offset = 0;\n        }\n        const W = this.W_;\n        // get 16 big endian words\n        if (typeof buf === 'string') {\n            for (let i = 0; i < 16; i++) {\n                // TODO(user): [bug 8140122] Recent versions of Safari for Mac OS and iOS\n                // have a bug that turns the post-increment ++ operator into pre-increment\n                // during JIT compilation.  We have code that depends heavily on SHA-1 for\n                // correctness and which is affected by this bug, so I've removed all uses\n                // of post-increment ++ in which the result value is used.  We can revert\n                // this change once the Safari bug\n                // (https://bugs.webkit.org/show_bug.cgi?id=109036) has been fixed and\n                // most clients have been updated.\n                W[i] =\n                    (buf.charCodeAt(offset) << 24) |\n                        (buf.charCodeAt(offset + 1) << 16) |\n                        (buf.charCodeAt(offset + 2) << 8) |\n                        buf.charCodeAt(offset + 3);\n                offset += 4;\n            }\n        }\n        else {\n            for (let i = 0; i < 16; i++) {\n                W[i] =\n                    (buf[offset] << 24) |\n                        (buf[offset + 1] << 16) |\n                        (buf[offset + 2] << 8) |\n                        buf[offset + 3];\n                offset += 4;\n            }\n        }\n        // expand to 80 words\n        for (let i = 16; i < 80; i++) {\n            const t = W[i - 3] ^ W[i - 8] ^ W[i - 14] ^ W[i - 16];\n            W[i] = ((t << 1) | (t >>> 31)) & 0xffffffff;\n        }\n        let a = this.chain_[0];\n        let b = this.chain_[1];\n        let c = this.chain_[2];\n        let d = this.chain_[3];\n        let e = this.chain_[4];\n        let f, k;\n        // TODO(user): Try to unroll this loop to speed up the computation.\n        for (let i = 0; i < 80; i++) {\n            if (i < 40) {\n                if (i < 20) {\n                    f = d ^ (b & (c ^ d));\n                    k = 0x5a827999;\n                }\n                else {\n                    f = b ^ c ^ d;\n                    k = 0x6ed9eba1;\n                }\n            }\n            else {\n                if (i < 60) {\n                    f = (b & c) | (d & (b | c));\n                    k = 0x8f1bbcdc;\n                }\n                else {\n                    f = b ^ c ^ d;\n                    k = 0xca62c1d6;\n                }\n            }\n            const t = (((a << 5) | (a >>> 27)) + f + e + k + W[i]) & 0xffffffff;\n            e = d;\n            d = c;\n            c = ((b << 30) | (b >>> 2)) & 0xffffffff;\n            b = a;\n            a = t;\n        }\n        this.chain_[0] = (this.chain_[0] + a) & 0xffffffff;\n        this.chain_[1] = (this.chain_[1] + b) & 0xffffffff;\n        this.chain_[2] = (this.chain_[2] + c) & 0xffffffff;\n        this.chain_[3] = (this.chain_[3] + d) & 0xffffffff;\n        this.chain_[4] = (this.chain_[4] + e) & 0xffffffff;\n    }\n    update(bytes, length) {\n        // TODO(johnlenz): tighten the function signature and remove this check\n        if (bytes == null) {\n            return;\n        }\n        if (length === undefined) {\n            length = bytes.length;\n        }\n        const lengthMinusBlock = length - this.blockSize;\n        let n = 0;\n        // Using local instead of member variables gives ~5% speedup on Firefox 16.\n        const buf = this.buf_;\n        let inbuf = this.inbuf_;\n        // The outer while loop should execute at most twice.\n        while (n < length) {\n            // When we have no data in the block to top up, we can directly process the\n            // input buffer (assuming it contains sufficient data). This gives ~25%\n            // speedup on Chrome 23 and ~15% speedup on Firefox 16, but requires that\n            // the data is provided in large chunks (or in multiples of 64 bytes).\n            if (inbuf === 0) {\n                while (n <= lengthMinusBlock) {\n                    this.compress_(bytes, n);\n                    n += this.blockSize;\n                }\n            }\n            if (typeof bytes === 'string') {\n                while (n < length) {\n                    buf[inbuf] = bytes.charCodeAt(n);\n                    ++inbuf;\n                    ++n;\n                    if (inbuf === this.blockSize) {\n                        this.compress_(buf);\n                        inbuf = 0;\n                        // Jump to the outer loop so we use the full-block optimization.\n                        break;\n                    }\n                }\n            }\n            else {\n                while (n < length) {\n                    buf[inbuf] = bytes[n];\n                    ++inbuf;\n                    ++n;\n                    if (inbuf === this.blockSize) {\n                        this.compress_(buf);\n                        inbuf = 0;\n                        // Jump to the outer loop so we use the full-block optimization.\n                        break;\n                    }\n                }\n            }\n        }\n        this.inbuf_ = inbuf;\n        this.total_ += length;\n    }\n    /** @override */\n    digest() {\n        const digest = [];\n        let totalBits = this.total_ * 8;\n        // Add pad 0x80 0x00*.\n        if (this.inbuf_ < 56) {\n            this.update(this.pad_, 56 - this.inbuf_);\n        }\n        else {\n            this.update(this.pad_, this.blockSize - (this.inbuf_ - 56));\n        }\n        // Add # bits.\n        for (let i = this.blockSize - 1; i >= 56; i--) {\n            this.buf_[i] = totalBits & 255;\n            totalBits /= 256; // Don't use bit-shifting here!\n        }\n        this.compress_(this.buf_);\n        let n = 0;\n        for (let i = 0; i < 5; i++) {\n            for (let j = 24; j >= 0; j -= 8) {\n                digest[n] = (this.chain_[i] >> j) & 255;\n                ++n;\n            }\n        }\n        return digest;\n    }\n}\n\n/**\n * Helper to make a Subscribe function (just like Promise helps make a\n * Thenable).\n *\n * @param executor Function which can make calls to a single Observer\n *     as a proxy.\n * @param onNoObservers Callback when count of Observers goes to zero.\n */\nfunction createSubscribe(executor, onNoObservers) {\n    const proxy = new ObserverProxy(executor, onNoObservers);\n    return proxy.subscribe.bind(proxy);\n}\n/**\n * Implement fan-out for any number of Observers attached via a subscribe\n * function.\n */\nclass ObserverProxy {\n    /**\n     * @param executor Function which can make calls to a single Observer\n     *     as a proxy.\n     * @param onNoObservers Callback when count of Observers goes to zero.\n     */\n    constructor(executor, onNoObservers) {\n        this.observers = [];\n        this.unsubscribes = [];\n        this.observerCount = 0;\n        // Micro-task scheduling by calling task.then().\n        this.task = Promise.resolve();\n        this.finalized = false;\n        this.onNoObservers = onNoObservers;\n        // Call the executor asynchronously so subscribers that are called\n        // synchronously after the creation of the subscribe function\n        // can still receive the very first value generated in the executor.\n        this.task\n            .then(() => {\n            executor(this);\n        })\n            .catch(e => {\n            this.error(e);\n        });\n    }\n    next(value) {\n        this.forEachObserver((observer) => {\n            observer.next(value);\n        });\n    }\n    error(error) {\n        this.forEachObserver((observer) => {\n            observer.error(error);\n        });\n        this.close(error);\n    }\n    complete() {\n        this.forEachObserver((observer) => {\n            observer.complete();\n        });\n        this.close();\n    }\n    /**\n     * Subscribe function that can be used to add an Observer to the fan-out list.\n     *\n     * - We require that no event is sent to a subscriber synchronously to their\n     *   call to subscribe().\n     */\n    subscribe(nextOrObserver, error, complete) {\n        let observer;\n        if (nextOrObserver === undefined &&\n            error === undefined &&\n            complete === undefined) {\n            throw new Error('Missing Observer.');\n        }\n        // Assemble an Observer object when passed as callback functions.\n        if (implementsAnyMethods(nextOrObserver, [\n            'next',\n            'error',\n            'complete'\n        ])) {\n            observer = nextOrObserver;\n        }\n        else {\n            observer = {\n                next: nextOrObserver,\n                error,\n                complete\n            };\n        }\n        if (observer.next === undefined) {\n            observer.next = noop;\n        }\n        if (observer.error === undefined) {\n            observer.error = noop;\n        }\n        if (observer.complete === undefined) {\n            observer.complete = noop;\n        }\n        const unsub = this.unsubscribeOne.bind(this, this.observers.length);\n        // Attempt to subscribe to a terminated Observable - we\n        // just respond to the Observer with the final error or complete\n        // event.\n        if (this.finalized) {\n            // eslint-disable-next-line @typescript-eslint/no-floating-promises\n            this.task.then(() => {\n                try {\n                    if (this.finalError) {\n                        observer.error(this.finalError);\n                    }\n                    else {\n                        observer.complete();\n                    }\n                }\n                catch (e) {\n                    // nothing\n                }\n                return;\n            });\n        }\n        this.observers.push(observer);\n        return unsub;\n    }\n    // Unsubscribe is synchronous - we guarantee that no events are sent to\n    // any unsubscribed Observer.\n    unsubscribeOne(i) {\n        if (this.observers === undefined || this.observers[i] === undefined) {\n            return;\n        }\n        delete this.observers[i];\n        this.observerCount -= 1;\n        if (this.observerCount === 0 && this.onNoObservers !== undefined) {\n            this.onNoObservers(this);\n        }\n    }\n    forEachObserver(fn) {\n        if (this.finalized) {\n            // Already closed by previous event....just eat the additional values.\n            return;\n        }\n        // Since sendOne calls asynchronously - there is no chance that\n        // this.observers will become undefined.\n        for (let i = 0; i < this.observers.length; i++) {\n            this.sendOne(i, fn);\n        }\n    }\n    // Call the Observer via one of it's callback function. We are careful to\n    // confirm that the observe has not been unsubscribed since this asynchronous\n    // function had been queued.\n    sendOne(i, fn) {\n        // Execute the callback asynchronously\n        // eslint-disable-next-line @typescript-eslint/no-floating-promises\n        this.task.then(() => {\n            if (this.observers !== undefined && this.observers[i] !== undefined) {\n                try {\n                    fn(this.observers[i]);\n                }\n                catch (e) {\n                    // Ignore exceptions raised in Observers or missing methods of an\n                    // Observer.\n                    // Log error to console. b/31404806\n                    if (typeof console !== 'undefined' && console.error) {\n                        console.error(e);\n                    }\n                }\n            }\n        });\n    }\n    close(err) {\n        if (this.finalized) {\n            return;\n        }\n        this.finalized = true;\n        if (err !== undefined) {\n            this.finalError = err;\n        }\n        // Proxy is no longer needed - garbage collect references\n        // eslint-disable-next-line @typescript-eslint/no-floating-promises\n        this.task.then(() => {\n            this.observers = undefined;\n            this.onNoObservers = undefined;\n        });\n    }\n}\n/** Turn synchronous function into one called asynchronously. */\n// eslint-disable-next-line @typescript-eslint/ban-types\nfunction async(fn, onError) {\n    return (...args) => {\n        Promise.resolve(true)\n            .then(() => {\n            fn(...args);\n        })\n            .catch((error) => {\n            if (onError) {\n                onError(error);\n            }\n        });\n    };\n}\n/**\n * Return true if the object passed in implements any of the named methods.\n */\nfunction implementsAnyMethods(obj, methods) {\n    if (typeof obj !== 'object' || obj === null) {\n        return false;\n    }\n    for (const method of methods) {\n        if (method in obj && typeof obj[method] === 'function') {\n            return true;\n        }\n    }\n    return false;\n}\nfunction noop() {\n    // do nothing\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 * Check to make sure the appropriate number of arguments are provided for a public function.\n * Throws an error if it fails.\n *\n * @param fnName The function name\n * @param minCount The minimum number of arguments to allow for the function call\n * @param maxCount The maximum number of argument to allow for the function call\n * @param argCount The actual number of arguments provided.\n */\nconst validateArgCount = function (fnName, minCount, maxCount, argCount) {\n    let argError;\n    if (argCount < minCount) {\n        argError = 'at least ' + minCount;\n    }\n    else if (argCount > maxCount) {\n        argError = maxCount === 0 ? 'none' : 'no more than ' + maxCount;\n    }\n    if (argError) {\n        const error = fnName +\n            ' failed: Was called with ' +\n            argCount +\n            (argCount === 1 ? ' argument.' : ' arguments.') +\n            ' Expects ' +\n            argError +\n            '.';\n        throw new Error(error);\n    }\n};\n/**\n * Generates a string to prefix an error message about failed argument validation\n *\n * @param fnName The function name\n * @param argName The name of the argument\n * @return The prefix to add to the error thrown for validation.\n */\nfunction errorPrefix(fnName, argName) {\n    return `${fnName} failed: ${argName} argument `;\n}\n/**\n * @param fnName\n * @param argumentNumber\n * @param namespace\n * @param optional\n */\nfunction validateNamespace(fnName, namespace, optional) {\n    if (optional && !namespace) {\n        return;\n    }\n    if (typeof namespace !== 'string') {\n        //TODO: I should do more validation here. We only allow certain chars in namespaces.\n        throw new Error(errorPrefix(fnName, 'namespace') + 'must be a valid firebase namespace.');\n    }\n}\nfunction validateCallback(fnName, argumentName, \n// eslint-disable-next-line @typescript-eslint/ban-types\ncallback, optional) {\n    if (optional && !callback) {\n        return;\n    }\n    if (typeof callback !== 'function') {\n        throw new Error(errorPrefix(fnName, argumentName) + 'must be a valid function.');\n    }\n}\nfunction validateContextObject(fnName, argumentName, context, optional) {\n    if (optional && !context) {\n        return;\n    }\n    if (typeof context !== 'object' || context === null) {\n        throw new Error(errorPrefix(fnName, argumentName) + 'must be a valid context object.');\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// Code originally came from goog.crypt.stringToUtf8ByteArray, but for some reason they\n// automatically replaced '\\r\\n' with '\\n', and they didn't handle surrogate pairs,\n// so it's been modified.\n// Note that not all Unicode characters appear as single characters in JavaScript strings.\n// fromCharCode returns the UTF-16 encoding of a character - so some Unicode characters\n// use 2 characters in JavaScript.  All 4-byte UTF-8 characters begin with a first\n// character in the range 0xD800 - 0xDBFF (the first character of a so-called surrogate\n// pair).\n// See http://www.ecma-international.org/ecma-262/5.1/#sec-15.1.3\n/**\n * @param {string} str\n * @return {Array}\n */\nconst stringToByteArray = function (str) {\n    const out = [];\n    let p = 0;\n    for (let i = 0; i < str.length; i++) {\n        let c = str.charCodeAt(i);\n        // Is this the lead surrogate in a surrogate pair?\n        if (c >= 0xd800 && c <= 0xdbff) {\n            const high = c - 0xd800; // the high 10 bits.\n            i++;\n            assert(i < str.length, 'Surrogate pair missing trail surrogate.');\n            const low = str.charCodeAt(i) - 0xdc00; // the low 10 bits.\n            c = 0x10000 + (high << 10) + low;\n        }\n        if (c < 128) {\n            out[p++] = c;\n        }\n        else if (c < 2048) {\n            out[p++] = (c >> 6) | 192;\n            out[p++] = (c & 63) | 128;\n        }\n        else if (c < 65536) {\n            out[p++] = (c >> 12) | 224;\n            out[p++] = ((c >> 6) & 63) | 128;\n            out[p++] = (c & 63) | 128;\n        }\n        else {\n            out[p++] = (c >> 18) | 240;\n            out[p++] = ((c >> 12) & 63) | 128;\n            out[p++] = ((c >> 6) & 63) | 128;\n            out[p++] = (c & 63) | 128;\n        }\n    }\n    return out;\n};\n/**\n * Calculate length without actually converting; useful for doing cheaper validation.\n * @param {string} str\n * @return {number}\n */\nconst stringLength = function (str) {\n    let p = 0;\n    for (let i = 0; i < str.length; i++) {\n        const c = str.charCodeAt(i);\n        if (c < 128) {\n            p++;\n        }\n        else if (c < 2048) {\n            p += 2;\n        }\n        else if (c >= 0xd800 && c <= 0xdbff) {\n            // Lead surrogate of a surrogate pair.  The pair together will take 4 bytes to represent.\n            p += 4;\n            i++; // skip trail surrogate.\n        }\n        else {\n            p += 3;\n        }\n    }\n    return p;\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 * Copied from https://stackoverflow.com/a/2117523\n * Generates a new uuid.\n * @public\n */\nconst uuidv4 = function () {\n    return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, c => {\n        const r = (Math.random() * 16) | 0, v = c === 'x' ? r : (r & 0x3) | 0x8;\n        return v.toString(16);\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 amount of milliseconds to exponentially increase.\n */\nconst DEFAULT_INTERVAL_MILLIS = 1000;\n/**\n * The factor to backoff by.\n * Should be a number greater than 1.\n */\nconst DEFAULT_BACKOFF_FACTOR = 2;\n/**\n * The maximum milliseconds to increase to.\n *\n * <p>Visible for testing\n */\nconst MAX_VALUE_MILLIS = 4 * 60 * 60 * 1000; // Four hours, like iOS and Android.\n/**\n * The percentage of backoff time to randomize by.\n * See\n * http://go/safe-client-behavior#step-1-determine-the-appropriate-retry-interval-to-handle-spike-traffic\n * for context.\n *\n * <p>Visible for testing\n */\nconst RANDOM_FACTOR = 0.5;\n/**\n * Based on the backoff method from\n * https://github.com/google/closure-library/blob/master/closure/goog/math/exponentialbackoff.js.\n * Extracted here so we don't need to pass metadata and a stateful ExponentialBackoff object around.\n */\nfunction calculateBackoffMillis(backoffCount, intervalMillis = DEFAULT_INTERVAL_MILLIS, backoffFactor = DEFAULT_BACKOFF_FACTOR) {\n    // Calculates an exponentially increasing value.\n    // Deviation: calculates value from count and a constant interval, so we only need to save value\n    // and count to restore state.\n    const currBaseValue = intervalMillis * Math.pow(backoffFactor, backoffCount);\n    // A random \"fuzz\" to avoid waves of retries.\n    // Deviation: randomFactor is required.\n    const randomWait = Math.round(\n    // A fraction of the backoff value to add/subtract.\n    // Deviation: changes multiplication order to improve readability.\n    RANDOM_FACTOR *\n        currBaseValue *\n        // A random float (rounded to int by Math.round above) in the range [-1, 1]. Determines\n        // if we add or subtract.\n        (Math.random() - 0.5) *\n        2);\n    // Limits backoff to max to avoid effectively permanent backoff.\n    return Math.min(MAX_VALUE_MILLIS, currBaseValue + randomWait);\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 * Provide English ordinal letters after a number\n */\nfunction ordinal(i) {\n    if (!Number.isFinite(i)) {\n        return `${i}`;\n    }\n    return i + indicator(i);\n}\nfunction indicator(i) {\n    i = Math.abs(i);\n    const cent = i % 100;\n    if (cent >= 10 && cent <= 20) {\n        return 'th';\n    }\n    const dec = i % 10;\n    if (dec === 1) {\n        return 'st';\n    }\n    if (dec === 2) {\n        return 'nd';\n    }\n    if (dec === 3) {\n        return 'rd';\n    }\n    return 'th';\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 */\nfunction getModularInstance(service) {\n    if (service && service._delegate) {\n        return service._delegate;\n    }\n    else {\n        return service;\n    }\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, isCloudflareWorker, isElectron, isEmpty, isIE, isIndexedDBAvailable, isMobileCordova, isNode, isNodeSdk, isReactNative, isSafari, isUWP, isValidFormat, isValidTimestamp, isWebWorker, 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/**\n * Component for service name T, e.g. `auth`, `auth-internal`\n */\nclass Component {\n    /**\n     *\n     * @param name The public service name, e.g. app, auth, firestore, database\n     * @param instanceFactory Service factory responsible for creating the public interface\n     * @param type whether the service provided by the component is public or private\n     */\n    constructor(name, instanceFactory, type) {\n        this.name = name;\n        this.instanceFactory = instanceFactory;\n        this.type = type;\n        this.multipleInstances = false;\n        /**\n         * Properties to be added to the service namespace\n         */\n        this.serviceProps = {};\n        this.instantiationMode = \"LAZY\" /* InstantiationMode.LAZY */;\n        this.onInstanceCreated = null;\n    }\n    setInstantiationMode(mode) {\n        this.instantiationMode = mode;\n        return this;\n    }\n    setMultipleInstances(multipleInstances) {\n        this.multipleInstances = multipleInstances;\n        return this;\n    }\n    setServiceProps(props) {\n        this.serviceProps = props;\n        return this;\n    }\n    setInstanceCreatedCallback(callback) {\n        this.onInstanceCreated = callback;\n        return this;\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 */\nconst DEFAULT_ENTRY_NAME = '[DEFAULT]';\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 * Provider for instance for service name T, e.g. 'auth', 'auth-internal'\n * NameServiceMapping[T] is an alias for the type of the instance\n */\nclass Provider {\n    constructor(name, container) {\n        this.name = name;\n        this.container = container;\n        this.component = null;\n        this.instances = new Map();\n        this.instancesDeferred = new Map();\n        this.instancesOptions = new Map();\n        this.onInitCallbacks = new Map();\n    }\n    /**\n     * @param identifier A provider can provide multiple instances of a service\n     * if this.component.multipleInstances is true.\n     */\n    get(identifier) {\n        // if multipleInstances is not supported, use the default name\n        const normalizedIdentifier = this.normalizeInstanceIdentifier(identifier);\n        if (!this.instancesDeferred.has(normalizedIdentifier)) {\n            const deferred = new Deferred();\n            this.instancesDeferred.set(normalizedIdentifier, deferred);\n            if (this.isInitialized(normalizedIdentifier) ||\n                this.shouldAutoInitialize()) {\n                // initialize the service if it can be auto-initialized\n                try {\n                    const instance = this.getOrInitializeService({\n                        instanceIdentifier: normalizedIdentifier\n                    });\n                    if (instance) {\n                        deferred.resolve(instance);\n                    }\n                }\n                catch (e) {\n                    // when the instance factory throws an exception during get(), it should not cause\n                    // a fatal error. We just return the unresolved promise in this case.\n                }\n            }\n        }\n        return this.instancesDeferred.get(normalizedIdentifier).promise;\n    }\n    getImmediate(options) {\n        var _a;\n        // if multipleInstances is not supported, use the default name\n        const normalizedIdentifier = this.normalizeInstanceIdentifier(options === null || options === void 0 ? void 0 : options.identifier);\n        const optional = (_a = options === null || options === void 0 ? void 0 : options.optional) !== null && _a !== void 0 ? _a : false;\n        if (this.isInitialized(normalizedIdentifier) ||\n            this.shouldAutoInitialize()) {\n            try {\n                return this.getOrInitializeService({\n                    instanceIdentifier: normalizedIdentifier\n                });\n            }\n            catch (e) {\n                if (optional) {\n                    return null;\n                }\n                else {\n                    throw e;\n                }\n            }\n        }\n        else {\n            // In case a component is not initialized and should/cannot be auto-initialized at the moment, return null if the optional flag is set, or throw\n            if (optional) {\n                return null;\n            }\n            else {\n                throw Error(`Service ${this.name} is not available`);\n            }\n        }\n    }\n    getComponent() {\n        return this.component;\n    }\n    setComponent(component) {\n        if (component.name !== this.name) {\n            throw Error(`Mismatching Component ${component.name} for Provider ${this.name}.`);\n        }\n        if (this.component) {\n            throw Error(`Component for ${this.name} has already been provided`);\n        }\n        this.component = component;\n        // return early without attempting to initialize the component if the component requires explicit initialization (calling `Provider.initialize()`)\n        if (!this.shouldAutoInitialize()) {\n            return;\n        }\n        // if the service is eager, initialize the default instance\n        if (isComponentEager(component)) {\n            try {\n                this.getOrInitializeService({ instanceIdentifier: DEFAULT_ENTRY_NAME });\n            }\n            catch (e) {\n                // when the instance factory for an eager Component throws an exception during the eager\n                // initialization, it should not cause a fatal error.\n                // TODO: Investigate if we need to make it configurable, because some component may want to cause\n                // a fatal error in this case?\n            }\n        }\n        // Create service instances for the pending promises and resolve them\n        // NOTE: if this.multipleInstances is false, only the default instance will be created\n        // and all promises with resolve with it regardless of the identifier.\n        for (const [instanceIdentifier, instanceDeferred] of this.instancesDeferred.entries()) {\n            const normalizedIdentifier = this.normalizeInstanceIdentifier(instanceIdentifier);\n            try {\n                // `getOrInitializeService()` should always return a valid instance since a component is guaranteed. use ! to make typescript happy.\n                const instance = this.getOrInitializeService({\n                    instanceIdentifier: normalizedIdentifier\n                });\n                instanceDeferred.resolve(instance);\n            }\n            catch (e) {\n                // when the instance factory throws an exception, it should not cause\n                // a fatal error. We just leave the promise unresolved.\n            }\n        }\n    }\n    clearInstance(identifier = DEFAULT_ENTRY_NAME) {\n        this.instancesDeferred.delete(identifier);\n        this.instancesOptions.delete(identifier);\n        this.instances.delete(identifier);\n    }\n    // app.delete() will call this method on every provider to delete the services\n    // TODO: should we mark the provider as deleted?\n    async delete() {\n        const services = Array.from(this.instances.values());\n        await Promise.all([\n            ...services\n                .filter(service => 'INTERNAL' in service) // legacy services\n                // eslint-disable-next-line @typescript-eslint/no-explicit-any\n                .map(service => service.INTERNAL.delete()),\n            ...services\n                .filter(service => '_delete' in service) // modularized services\n                // eslint-disable-next-line @typescript-eslint/no-explicit-any\n                .map(service => service._delete())\n        ]);\n    }\n    isComponentSet() {\n        return this.component != null;\n    }\n    isInitialized(identifier = DEFAULT_ENTRY_NAME) {\n        return this.instances.has(identifier);\n    }\n    getOptions(identifier = DEFAULT_ENTRY_NAME) {\n        return this.instancesOptions.get(identifier) || {};\n    }\n    initialize(opts = {}) {\n        const { options = {} } = opts;\n        const normalizedIdentifier = this.normalizeInstanceIdentifier(opts.instanceIdentifier);\n        if (this.isInitialized(normalizedIdentifier)) {\n            throw Error(`${this.name}(${normalizedIdentifier}) has already been initialized`);\n        }\n        if (!this.isComponentSet()) {\n            throw Error(`Component ${this.name} has not been registered yet`);\n        }\n        const instance = this.getOrInitializeService({\n            instanceIdentifier: normalizedIdentifier,\n            options\n        });\n        // resolve any pending promise waiting for the service instance\n        for (const [instanceIdentifier, instanceDeferred] of this.instancesDeferred.entries()) {\n            const normalizedDeferredIdentifier = this.normalizeInstanceIdentifier(instanceIdentifier);\n            if (normalizedIdentifier === normalizedDeferredIdentifier) {\n                instanceDeferred.resolve(instance);\n            }\n        }\n        return instance;\n    }\n    /**\n     *\n     * @param callback - a function that will be invoked  after the provider has been initialized by calling provider.initialize().\n     * The function is invoked SYNCHRONOUSLY, so it should not execute any longrunning tasks in order to not block the program.\n     *\n     * @param identifier An optional instance identifier\n     * @returns a function to unregister the callback\n     */\n    onInit(callback, identifier) {\n        var _a;\n        const normalizedIdentifier = this.normalizeInstanceIdentifier(identifier);\n        const existingCallbacks = (_a = this.onInitCallbacks.get(normalizedIdentifier)) !== null && _a !== void 0 ? _a : new Set();\n        existingCallbacks.add(callback);\n        this.onInitCallbacks.set(normalizedIdentifier, existingCallbacks);\n        const existingInstance = this.instances.get(normalizedIdentifier);\n        if (existingInstance) {\n            callback(existingInstance, normalizedIdentifier);\n        }\n        return () => {\n            existingCallbacks.delete(callback);\n        };\n    }\n    /**\n     * Invoke onInit callbacks synchronously\n     * @param instance the service instance`\n     */\n    invokeOnInitCallbacks(instance, identifier) {\n        const callbacks = this.onInitCallbacks.get(identifier);\n        if (!callbacks) {\n            return;\n        }\n        for (const callback of callbacks) {\n            try {\n                callback(instance, identifier);\n            }\n            catch (_a) {\n                // ignore errors in the onInit callback\n            }\n        }\n    }\n    getOrInitializeService({ instanceIdentifier, options = {} }) {\n        let instance = this.instances.get(instanceIdentifier);\n        if (!instance && this.component) {\n            instance = this.component.instanceFactory(this.container, {\n                instanceIdentifier: normalizeIdentifierForFactory(instanceIdentifier),\n                options\n            });\n            this.instances.set(instanceIdentifier, instance);\n            this.instancesOptions.set(instanceIdentifier, options);\n            /**\n             * Invoke onInit listeners.\n             * Note this.component.onInstanceCreated is different, which is used by the component creator,\n             * while onInit listeners are registered by consumers of the provider.\n             */\n            this.invokeOnInitCallbacks(instance, instanceIdentifier);\n            /**\n             * Order is important\n             * onInstanceCreated() should be called after this.instances.set(instanceIdentifier, instance); which\n             * makes `isInitialized()` return true.\n             */\n            if (this.component.onInstanceCreated) {\n                try {\n                    this.component.onInstanceCreated(this.container, instanceIdentifier, instance);\n                }\n                catch (_a) {\n                    // ignore errors in the onInstanceCreatedCallback\n                }\n            }\n        }\n        return instance || null;\n    }\n    normalizeInstanceIdentifier(identifier = DEFAULT_ENTRY_NAME) {\n        if (this.component) {\n            return this.component.multipleInstances ? identifier : DEFAULT_ENTRY_NAME;\n        }\n        else {\n            return identifier; // assume multiple instances are supported before the component is provided.\n        }\n    }\n    shouldAutoInitialize() {\n        return (!!this.component &&\n            this.component.instantiationMode !== \"EXPLICIT\" /* InstantiationMode.EXPLICIT */);\n    }\n}\n// undefined should be passed to the service factory for the default instance\nfunction normalizeIdentifierForFactory(identifier) {\n    return identifier === DEFAULT_ENTRY_NAME ? undefined : identifier;\n}\nfunction isComponentEager(component) {\n    return component.instantiationMode === \"EAGER\" /* InstantiationMode.EAGER */;\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 * ComponentContainer that provides Providers for service name T, e.g. `auth`, `auth-internal`\n */\nclass ComponentContainer {\n    constructor(name) {\n        this.name = name;\n        this.providers = new Map();\n    }\n    /**\n     *\n     * @param component Component being added\n     * @param overwrite When a component with the same name has already been registered,\n     * if overwrite is true: overwrite the existing component with the new component and create a new\n     * provider with the new component. It can be useful in tests where you want to use different mocks\n     * for different tests.\n     * if overwrite is false: throw an exception\n     */\n    addComponent(component) {\n        const provider = this.getProvider(component.name);\n        if (provider.isComponentSet()) {\n            throw new Error(`Component ${component.name} has already been registered with ${this.name}`);\n        }\n        provider.setComponent(component);\n    }\n    addOrOverwriteComponent(component) {\n        const provider = this.getProvider(component.name);\n        if (provider.isComponentSet()) {\n            // delete the existing provider from the container, so we can register the new component\n            this.providers.delete(component.name);\n        }\n        this.addComponent(component);\n    }\n    /**\n     * getProvider provides a type safe interface where it can only be called with a field name\n     * present in NameServiceMapping interface.\n     *\n     * Firebase SDKs providing services should extend NameServiceMapping interface to register\n     * themselves.\n     */\n    getProvider(name) {\n        if (this.providers.has(name)) {\n            return this.providers.get(name);\n        }\n        // create a Provider for a service that hasn't registered with Firebase\n        const provider = new Provider(name, this);\n        this.providers.set(name, provider);\n        return provider;\n    }\n    getProviders() {\n        return Array.from(this.providers.values());\n    }\n}\n\nexport { Component, ComponentContainer, Provider };\n//# sourceMappingURL=index.esm2017.js.map\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 container for all of the Logger instances\n */\nconst instances = [];\n/**\n * The JS SDK supports 5 log levels and also allows a user the ability to\n * silence the logs altogether.\n *\n * The order is a follows:\n * DEBUG < VERBOSE < INFO < WARN < ERROR\n *\n * All of the log types above the current log level will be captured (i.e. if\n * you set the log level to `INFO`, errors will still be logged, but `DEBUG` and\n * `VERBOSE` logs will not)\n */\nvar LogLevel;\n(function (LogLevel) {\n    LogLevel[LogLevel[\"DEBUG\"] = 0] = \"DEBUG\";\n    LogLevel[LogLevel[\"VERBOSE\"] = 1] = \"VERBOSE\";\n    LogLevel[LogLevel[\"INFO\"] = 2] = \"INFO\";\n    LogLevel[LogLevel[\"WARN\"] = 3] = \"WARN\";\n    LogLevel[LogLevel[\"ERROR\"] = 4] = \"ERROR\";\n    LogLevel[LogLevel[\"SILENT\"] = 5] = \"SILENT\";\n})(LogLevel || (LogLevel = {}));\nconst levelStringToEnum = {\n    'debug': LogLevel.DEBUG,\n    'verbose': LogLevel.VERBOSE,\n    'info': LogLevel.INFO,\n    'warn': LogLevel.WARN,\n    'error': LogLevel.ERROR,\n    'silent': LogLevel.SILENT\n};\n/**\n * The default log level\n */\nconst defaultLogLevel = LogLevel.INFO;\n/**\n * By default, `console.debug` is not displayed in the developer console (in\n * chrome). To avoid forcing users to have to opt-in to these logs twice\n * (i.e. once for firebase, and once in the console), we are sending `DEBUG`\n * logs to the `console.log` function.\n */\nconst ConsoleMethod = {\n    [LogLevel.DEBUG]: 'log',\n    [LogLevel.VERBOSE]: 'log',\n    [LogLevel.INFO]: 'info',\n    [LogLevel.WARN]: 'warn',\n    [LogLevel.ERROR]: 'error'\n};\n/**\n * The default log handler will forward DEBUG, VERBOSE, INFO, WARN, and ERROR\n * messages on to their corresponding console counterparts (if the log method\n * is supported by the current log level)\n */\nconst defaultLogHandler = (instance, logType, ...args) => {\n    if (logType < instance.logLevel) {\n        return;\n    }\n    const now = new Date().toISOString();\n    const method = ConsoleMethod[logType];\n    if (method) {\n        console[method](`[${now}]  ${instance.name}:`, ...args);\n    }\n    else {\n        throw new Error(`Attempted to log a message with an invalid logType (value: ${logType})`);\n    }\n};\nclass Logger {\n    /**\n     * Gives you an instance of a Logger to capture messages according to\n     * Firebase's logging scheme.\n     *\n     * @param name The name that the logs will be associated with\n     */\n    constructor(name) {\n        this.name = name;\n        /**\n         * The log level of the given Logger instance.\n         */\n        this._logLevel = defaultLogLevel;\n        /**\n         * The main (internal) log handler for the Logger instance.\n         * Can be set to a new function in internal package code but not by user.\n         */\n        this._logHandler = defaultLogHandler;\n        /**\n         * The optional, additional, user-defined log handler for the Logger instance.\n         */\n        this._userLogHandler = null;\n        /**\n         * Capture the current instance for later use\n         */\n        instances.push(this);\n    }\n    get logLevel() {\n        return this._logLevel;\n    }\n    set logLevel(val) {\n        if (!(val in LogLevel)) {\n            throw new TypeError(`Invalid value \"${val}\" assigned to \\`logLevel\\``);\n        }\n        this._logLevel = val;\n    }\n    // Workaround for setter/getter having to be the same type.\n    setLogLevel(val) {\n        this._logLevel = typeof val === 'string' ? levelStringToEnum[val] : val;\n    }\n    get logHandler() {\n        return this._logHandler;\n    }\n    set logHandler(val) {\n        if (typeof val !== 'function') {\n            throw new TypeError('Value assigned to `logHandler` must be a function');\n        }\n        this._logHandler = val;\n    }\n    get userLogHandler() {\n        return this._userLogHandler;\n    }\n    set userLogHandler(val) {\n        this._userLogHandler = val;\n    }\n    /**\n     * The functions below are all based on the `console` interface\n     */\n    debug(...args) {\n        this._userLogHandler && this._userLogHandler(this, LogLevel.DEBUG, ...args);\n        this._logHandler(this, LogLevel.DEBUG, ...args);\n    }\n    log(...args) {\n        this._userLogHandler &&\n            this._userLogHandler(this, LogLevel.VERBOSE, ...args);\n        this._logHandler(this, LogLevel.VERBOSE, ...args);\n    }\n    info(...args) {\n        this._userLogHandler && this._userLogHandler(this, LogLevel.INFO, ...args);\n        this._logHandler(this, LogLevel.INFO, ...args);\n    }\n    warn(...args) {\n        this._userLogHandler && this._userLogHandler(this, LogLevel.WARN, ...args);\n        this._logHandler(this, LogLevel.WARN, ...args);\n    }\n    error(...args) {\n        this._userLogHandler && this._userLogHandler(this, LogLevel.ERROR, ...args);\n        this._logHandler(this, LogLevel.ERROR, ...args);\n    }\n}\nfunction setLogLevel(level) {\n    instances.forEach(inst => {\n        inst.setLogLevel(level);\n    });\n}\nfunction setUserLogHandler(logCallback, options) {\n    for (const instance of instances) {\n        let customLogLevel = null;\n        if (options && options.level) {\n            customLogLevel = levelStringToEnum[options.level];\n        }\n        if (logCallback === null) {\n            instance.userLogHandler = null;\n        }\n        else {\n            instance.userLogHandler = (instance, level, ...args) => {\n                const message = args\n                    .map(arg => {\n                    if (arg == null) {\n                        return null;\n                    }\n                    else if (typeof arg === 'string') {\n                        return arg;\n                    }\n                    else if (typeof arg === 'number' || typeof arg === 'boolean') {\n                        return arg.toString();\n                    }\n                    else if (arg instanceof Error) {\n                        return arg.message;\n                    }\n                    else {\n                        try {\n                            return JSON.stringify(arg);\n                        }\n                        catch (ignored) {\n                            return null;\n                        }\n                    }\n                })\n                    .filter(arg => arg)\n                    .join(' ');\n                if (level >= (customLogLevel !== null && customLogLevel !== void 0 ? customLogLevel : instance.logLevel)) {\n                    logCallback({\n                        level: LogLevel[level].toLowerCase(),\n                        message,\n                        args,\n                        type: instance.name\n                    });\n                }\n            };\n        }\n    }\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, isBrowser, isWebWorker, FirebaseError, base64urlEncodeWithoutPadding, isIndexedDBAvailable, validateIndexedDBOpenable } from '@firebase/util';\nexport { FirebaseError } from '@firebase/util';\nimport { openDB } from 'idb';\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 */\nclass PlatformLoggerServiceImpl {\n    constructor(container) {\n        this.container = container;\n    }\n    // In initial implementation, this will be called by installations on\n    // auth token refresh, and installations will send this string.\n    getPlatformInfoString() {\n        const providers = this.container.getProviders();\n        // Loop through providers and get library/version pairs from any that are\n        // version components.\n        return providers\n            .map(provider => {\n            if (isVersionServiceProvider(provider)) {\n                const service = provider.getImmediate();\n                return `${service.library}/${service.version}`;\n            }\n            else {\n                return null;\n            }\n        })\n            .filter(logString => logString)\n            .join(' ');\n    }\n}\n/**\n *\n * @param provider check if this provider provides a VersionService\n *\n * NOTE: Using Provider<'app-version'> is a hack to indicate that the provider\n * provides VersionService. The provider is not necessarily a 'app-version'\n * provider.\n */\nfunction isVersionServiceProvider(provider) {\n    const component = provider.getComponent();\n    return (component === null || component === void 0 ? void 0 : component.type) === \"VERSION\" /* ComponentType.VERSION */;\n}\n\nconst name$q = \"@firebase/app\";\nconst version$1 = \"0.10.17\";\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 */\nconst logger = new Logger('@firebase/app');\n\nconst name$p = \"@firebase/app-compat\";\n\nconst name$o = \"@firebase/analytics-compat\";\n\nconst name$n = \"@firebase/analytics\";\n\nconst name$m = \"@firebase/app-check-compat\";\n\nconst name$l = \"@firebase/app-check\";\n\nconst name$k = \"@firebase/auth\";\n\nconst name$j = \"@firebase/auth-compat\";\n\nconst name$i = \"@firebase/database\";\n\nconst name$h = \"@firebase/data-connect\";\n\nconst name$g = \"@firebase/database-compat\";\n\nconst name$f = \"@firebase/functions\";\n\nconst name$e = \"@firebase/functions-compat\";\n\nconst name$d = \"@firebase/installations\";\n\nconst name$c = \"@firebase/installations-compat\";\n\nconst name$b = \"@firebase/messaging\";\n\nconst name$a = \"@firebase/messaging-compat\";\n\nconst name$9 = \"@firebase/performance\";\n\nconst name$8 = \"@firebase/performance-compat\";\n\nconst name$7 = \"@firebase/remote-config\";\n\nconst name$6 = \"@firebase/remote-config-compat\";\n\nconst name$5 = \"@firebase/storage\";\n\nconst name$4 = \"@firebase/storage-compat\";\n\nconst name$3 = \"@firebase/firestore\";\n\nconst name$2 = \"@firebase/vertexai\";\n\nconst name$1 = \"@firebase/firestore-compat\";\n\nconst name = \"firebase\";\nconst version = \"11.1.0\";\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 default app name\n *\n * @internal\n */\nconst DEFAULT_ENTRY_NAME = '[DEFAULT]';\nconst PLATFORM_LOG_STRING = {\n    [name$q]: 'fire-core',\n    [name$p]: 'fire-core-compat',\n    [name$n]: 'fire-analytics',\n    [name$o]: 'fire-analytics-compat',\n    [name$l]: 'fire-app-check',\n    [name$m]: 'fire-app-check-compat',\n    [name$k]: 'fire-auth',\n    [name$j]: 'fire-auth-compat',\n    [name$i]: 'fire-rtdb',\n    [name$h]: 'fire-data-connect',\n    [name$g]: 'fire-rtdb-compat',\n    [name$f]: 'fire-fn',\n    [name$e]: 'fire-fn-compat',\n    [name$d]: 'fire-iid',\n    [name$c]: 'fire-iid-compat',\n    [name$b]: 'fire-fcm',\n    [name$a]: 'fire-fcm-compat',\n    [name$9]: 'fire-perf',\n    [name$8]: 'fire-perf-compat',\n    [name$7]: 'fire-rc',\n    [name$6]: 'fire-rc-compat',\n    [name$5]: 'fire-gcs',\n    [name$4]: 'fire-gcs-compat',\n    [name$3]: 'fire-fst',\n    [name$1]: 'fire-fst-compat',\n    [name$2]: 'fire-vertex',\n    'fire-js': 'fire-js', // Platform identifier for JS SDK.\n    [name]: 'fire-js-all'\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 * @internal\n */\nconst _apps = new Map();\n/**\n * @internal\n */\nconst _serverApps = new Map();\n/**\n * Registered components.\n *\n * @internal\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nconst _components = new Map();\n/**\n * @param component - the component being added to this app's container\n *\n * @internal\n */\nfunction _addComponent(app, component) {\n    try {\n        app.container.addComponent(component);\n    }\n    catch (e) {\n        logger.debug(`Component ${component.name} failed to register with FirebaseApp ${app.name}`, e);\n    }\n}\n/**\n *\n * @internal\n */\nfunction _addOrOverwriteComponent(app, component) {\n    app.container.addOrOverwriteComponent(component);\n}\n/**\n *\n * @param component - the component to register\n * @returns whether or not the component is registered successfully\n *\n * @internal\n */\nfunction _registerComponent(component) {\n    const componentName = component.name;\n    if (_components.has(componentName)) {\n        logger.debug(`There were multiple attempts to register component ${componentName}.`);\n        return false;\n    }\n    _components.set(componentName, component);\n    // add the component to existing app instances\n    for (const app of _apps.values()) {\n        _addComponent(app, component);\n    }\n    for (const serverApp of _serverApps.values()) {\n        _addComponent(serverApp, component);\n    }\n    return true;\n}\n/**\n *\n * @param app - FirebaseApp instance\n * @param name - service name\n *\n * @returns the provider for the service with the matching name\n *\n * @internal\n */\nfunction _getProvider(app, name) {\n    const heartbeatController = app.container\n        .getProvider('heartbeat')\n        .getImmediate({ optional: true });\n    if (heartbeatController) {\n        void heartbeatController.triggerHeartbeat();\n    }\n    return app.container.getProvider(name);\n}\n/**\n *\n * @param app - FirebaseApp instance\n * @param name - service name\n * @param instanceIdentifier - service instance identifier in case the service supports multiple instances\n *\n * @internal\n */\nfunction _removeServiceInstance(app, name, instanceIdentifier = DEFAULT_ENTRY_NAME) {\n    _getProvider(app, name).clearInstance(instanceIdentifier);\n}\n/**\n *\n * @param obj - an object of type FirebaseApp or FirebaseOptions.\n *\n * @returns true if the provide object is of type FirebaseApp.\n *\n * @internal\n */\nfunction _isFirebaseApp(obj) {\n    return obj.options !== undefined;\n}\n/**\n *\n * @param obj - an object of type FirebaseApp.\n *\n * @returns true if the provided object is of type FirebaseServerAppImpl.\n *\n * @internal\n */\nfunction _isFirebaseServerApp(obj) {\n    return obj.settings !== undefined;\n}\n/**\n * Test only\n *\n * @internal\n */\nfunction _clearComponents() {\n    _components.clear();\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 */\nconst ERRORS = {\n    [\"no-app\" /* AppError.NO_APP */]: \"No Firebase App '{$appName}' has been created - \" +\n        'call initializeApp() first',\n    [\"bad-app-name\" /* AppError.BAD_APP_NAME */]: \"Illegal App name: '{$appName}'\",\n    [\"duplicate-app\" /* AppError.DUPLICATE_APP */]: \"Firebase App named '{$appName}' already exists with different options or config\",\n    [\"app-deleted\" /* AppError.APP_DELETED */]: \"Firebase App named '{$appName}' already deleted\",\n    [\"server-app-deleted\" /* AppError.SERVER_APP_DELETED */]: 'Firebase Server App has been deleted',\n    [\"no-options\" /* AppError.NO_OPTIONS */]: 'Need to provide options, when not being deployed to hosting via source.',\n    [\"invalid-app-argument\" /* AppError.INVALID_APP_ARGUMENT */]: 'firebase.{$appName}() takes either no argument or a ' +\n        'Firebase App instance.',\n    [\"invalid-log-argument\" /* AppError.INVALID_LOG_ARGUMENT */]: 'First argument to `onLog` must be null or a function.',\n    [\"idb-open\" /* AppError.IDB_OPEN */]: 'Error thrown when opening IndexedDB. Original error: {$originalErrorMessage}.',\n    [\"idb-get\" /* AppError.IDB_GET */]: 'Error thrown when reading from IndexedDB. Original error: {$originalErrorMessage}.',\n    [\"idb-set\" /* AppError.IDB_WRITE */]: 'Error thrown when writing to IndexedDB. Original error: {$originalErrorMessage}.',\n    [\"idb-delete\" /* AppError.IDB_DELETE */]: 'Error thrown when deleting from IndexedDB. Original error: {$originalErrorMessage}.',\n    [\"finalization-registry-not-supported\" /* AppError.FINALIZATION_REGISTRY_NOT_SUPPORTED */]: 'FirebaseServerApp deleteOnDeref field defined but the JS runtime does not support FinalizationRegistry.',\n    [\"invalid-server-app-environment\" /* AppError.INVALID_SERVER_APP_ENVIRONMENT */]: 'FirebaseServerApp is not for use in browser environments.'\n};\nconst ERROR_FACTORY = new ErrorFactory('app', 'Firebase', ERRORS);\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 */\nclass FirebaseAppImpl {\n    constructor(options, config, container) {\n        this._isDeleted = false;\n        this._options = Object.assign({}, options);\n        this._config = Object.assign({}, config);\n        this._name = config.name;\n        this._automaticDataCollectionEnabled =\n            config.automaticDataCollectionEnabled;\n        this._container = container;\n        this.container.addComponent(new Component('app', () => this, \"PUBLIC\" /* ComponentType.PUBLIC */));\n    }\n    get automaticDataCollectionEnabled() {\n        this.checkDestroyed();\n        return this._automaticDataCollectionEnabled;\n    }\n    set automaticDataCollectionEnabled(val) {\n        this.checkDestroyed();\n        this._automaticDataCollectionEnabled = val;\n    }\n    get name() {\n        this.checkDestroyed();\n        return this._name;\n    }\n    get options() {\n        this.checkDestroyed();\n        return this._options;\n    }\n    get config() {\n        this.checkDestroyed();\n        return this._config;\n    }\n    get container() {\n        return this._container;\n    }\n    get isDeleted() {\n        return this._isDeleted;\n    }\n    set isDeleted(val) {\n        this._isDeleted = val;\n    }\n    /**\n     * This function will throw an Error if the App has already been deleted -\n     * use before performing API actions on the App.\n     */\n    checkDestroyed() {\n        if (this.isDeleted) {\n            throw ERROR_FACTORY.create(\"app-deleted\" /* AppError.APP_DELETED */, { appName: this._name });\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 */\nclass FirebaseServerAppImpl extends FirebaseAppImpl {\n    constructor(options, serverConfig, name, container) {\n        // Build configuration parameters for the FirebaseAppImpl base class.\n        const automaticDataCollectionEnabled = serverConfig.automaticDataCollectionEnabled !== undefined\n            ? serverConfig.automaticDataCollectionEnabled\n            : false;\n        // Create the FirebaseAppSettings object for the FirebaseAppImp constructor.\n        const config = {\n            name,\n            automaticDataCollectionEnabled\n        };\n        if (options.apiKey !== undefined) {\n            // Construct the parent FirebaseAppImp object.\n            super(options, config, container);\n        }\n        else {\n            const appImpl = options;\n            super(appImpl.options, config, container);\n        }\n        // Now construct the data for the FirebaseServerAppImpl.\n        this._serverConfig = Object.assign({ automaticDataCollectionEnabled }, serverConfig);\n        this._finalizationRegistry = null;\n        if (typeof FinalizationRegistry !== 'undefined') {\n            this._finalizationRegistry = new FinalizationRegistry(() => {\n                this.automaticCleanup();\n            });\n        }\n        this._refCount = 0;\n        this.incRefCount(this._serverConfig.releaseOnDeref);\n        // Do not retain a hard reference to the dref object, otherwise the FinalizationRegistry\n        // will never trigger.\n        this._serverConfig.releaseOnDeref = undefined;\n        serverConfig.releaseOnDeref = undefined;\n        registerVersion(name$q, version$1, 'serverapp');\n    }\n    toJSON() {\n        return undefined;\n    }\n    get refCount() {\n        return this._refCount;\n    }\n    // Increment the reference count of this server app. If an object is provided, register it\n    // with the finalization registry.\n    incRefCount(obj) {\n        if (this.isDeleted) {\n            return;\n        }\n        this._refCount++;\n        if (obj !== undefined && this._finalizationRegistry !== null) {\n            this._finalizationRegistry.register(obj, this);\n        }\n    }\n    // Decrement the reference count.\n    decRefCount() {\n        if (this.isDeleted) {\n            return 0;\n        }\n        return --this._refCount;\n    }\n    // Invoked by the FinalizationRegistry callback to note that this app should go through its\n    // reference counts and delete itself if no reference count remain. The coordinating logic that\n    // handles this is in deleteApp(...).\n    automaticCleanup() {\n        void deleteApp(this);\n    }\n    get settings() {\n        this.checkDestroyed();\n        return this._serverConfig;\n    }\n    /**\n     * This function will throw an Error if the App has already been deleted -\n     * use before performing API actions on the App.\n     */\n    checkDestroyed() {\n        if (this.isDeleted) {\n            throw ERROR_FACTORY.create(\"server-app-deleted\" /* AppError.SERVER_APP_DELETED */);\n        }\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 current SDK version.\n *\n * @public\n */\nconst SDK_VERSION = version;\nfunction initializeApp(_options, rawConfig = {}) {\n    let options = _options;\n    if (typeof rawConfig !== 'object') {\n        const name = rawConfig;\n        rawConfig = { name };\n    }\n    const config = Object.assign({ name: DEFAULT_ENTRY_NAME, automaticDataCollectionEnabled: false }, rawConfig);\n    const name = config.name;\n    if (typeof name !== 'string' || !name) {\n        throw ERROR_FACTORY.create(\"bad-app-name\" /* AppError.BAD_APP_NAME */, {\n            appName: String(name)\n        });\n    }\n    options || (options = getDefaultAppConfig());\n    if (!options) {\n        throw ERROR_FACTORY.create(\"no-options\" /* AppError.NO_OPTIONS */);\n    }\n    const existingApp = _apps.get(name);\n    if (existingApp) {\n        // return the existing app if options and config deep equal the ones in the existing app.\n        if (deepEqual(options, existingApp.options) &&\n            deepEqual(config, existingApp.config)) {\n            return existingApp;\n        }\n        else {\n            throw ERROR_FACTORY.create(\"duplicate-app\" /* AppError.DUPLICATE_APP */, { appName: name });\n        }\n    }\n    const container = new ComponentContainer(name);\n    for (const component of _components.values()) {\n        container.addComponent(component);\n    }\n    const newApp = new FirebaseAppImpl(options, config, container);\n    _apps.set(name, newApp);\n    return newApp;\n}\nfunction initializeServerApp(_options, _serverAppConfig) {\n    if (isBrowser() && !isWebWorker()) {\n        // FirebaseServerApp isn't designed to be run in browsers.\n        throw ERROR_FACTORY.create(\"invalid-server-app-environment\" /* AppError.INVALID_SERVER_APP_ENVIRONMENT */);\n    }\n    if (_serverAppConfig.automaticDataCollectionEnabled === undefined) {\n        _serverAppConfig.automaticDataCollectionEnabled = false;\n    }\n    let appOptions;\n    if (_isFirebaseApp(_options)) {\n        appOptions = _options.options;\n    }\n    else {\n        appOptions = _options;\n    }\n    // Build an app name based on a hash of the configuration options.\n    const nameObj = Object.assign(Object.assign({}, _serverAppConfig), appOptions);\n    // However, Do not mangle the name based on releaseOnDeref, since it will vary between the\n    // construction of FirebaseServerApp instances. For example, if the object is the request headers.\n    if (nameObj.releaseOnDeref !== undefined) {\n        delete nameObj.releaseOnDeref;\n    }\n    const hashCode = (s) => {\n        return [...s].reduce((hash, c) => (Math.imul(31, hash) + c.charCodeAt(0)) | 0, 0);\n    };\n    if (_serverAppConfig.releaseOnDeref !== undefined) {\n        if (typeof FinalizationRegistry === 'undefined') {\n            throw ERROR_FACTORY.create(\"finalization-registry-not-supported\" /* AppError.FINALIZATION_REGISTRY_NOT_SUPPORTED */, {});\n        }\n    }\n    const nameString = '' + hashCode(JSON.stringify(nameObj));\n    const existingApp = _serverApps.get(nameString);\n    if (existingApp) {\n        existingApp.incRefCount(_serverAppConfig.releaseOnDeref);\n        return existingApp;\n    }\n    const container = new ComponentContainer(nameString);\n    for (const component of _components.values()) {\n        container.addComponent(component);\n    }\n    const newApp = new FirebaseServerAppImpl(appOptions, _serverAppConfig, nameString, container);\n    _serverApps.set(nameString, newApp);\n    return newApp;\n}\n/**\n * Retrieves a {@link @firebase/app#FirebaseApp} instance.\n *\n * When called with no arguments, the default app is returned. When an app name\n * is provided, the app corresponding to that name is returned.\n *\n * An exception is thrown if the app being retrieved has not yet been\n * initialized.\n *\n * @example\n * ```javascript\n * // Return the default app\n * const app = getApp();\n * ```\n *\n * @example\n * ```javascript\n * // Return a named app\n * const otherApp = getApp(\"otherApp\");\n * ```\n *\n * @param name - Optional name of the app to return. If no name is\n *   provided, the default is `\"[DEFAULT]\"`.\n *\n * @returns The app corresponding to the provided app name.\n *   If no app name is provided, the default app is returned.\n *\n * @public\n */\nfunction getApp(name = DEFAULT_ENTRY_NAME) {\n    const app = _apps.get(name);\n    if (!app && name === DEFAULT_ENTRY_NAME && getDefaultAppConfig()) {\n        return initializeApp();\n    }\n    if (!app) {\n        throw ERROR_FACTORY.create(\"no-app\" /* AppError.NO_APP */, { appName: name });\n    }\n    return app;\n}\n/**\n * A (read-only) array of all initialized apps.\n * @public\n */\nfunction getApps() {\n    return Array.from(_apps.values());\n}\n/**\n * Renders this app unusable and frees the resources of all associated\n * services.\n *\n * @example\n * ```javascript\n * deleteApp(app)\n *   .then(function() {\n *     console.log(\"App deleted successfully\");\n *   })\n *   .catch(function(error) {\n *     console.log(\"Error deleting app:\", error);\n *   });\n * ```\n *\n * @public\n */\nasync function deleteApp(app) {\n    let cleanupProviders = false;\n    const name = app.name;\n    if (_apps.has(name)) {\n        cleanupProviders = true;\n        _apps.delete(name);\n    }\n    else if (_serverApps.has(name)) {\n        const firebaseServerApp = app;\n        if (firebaseServerApp.decRefCount() <= 0) {\n            _serverApps.delete(name);\n            cleanupProviders = true;\n        }\n    }\n    if (cleanupProviders) {\n        await Promise.all(app.container\n            .getProviders()\n            .map(provider => provider.delete()));\n        app.isDeleted = true;\n    }\n}\n/**\n * Registers a library's name and version for platform logging purposes.\n * @param library - Name of 1p or 3p library (e.g. firestore, angularfire)\n * @param version - Current version of that library.\n * @param variant - Bundle variant, e.g., node, rn, etc.\n *\n * @public\n */\nfunction registerVersion(libraryKeyOrName, version, variant) {\n    var _a;\n    // TODO: We can use this check to whitelist strings when/if we set up\n    // a good whitelist system.\n    let library = (_a = PLATFORM_LOG_STRING[libraryKeyOrName]) !== null && _a !== void 0 ? _a : libraryKeyOrName;\n    if (variant) {\n        library += `-${variant}`;\n    }\n    const libraryMismatch = library.match(/\\s|\\//);\n    const versionMismatch = version.match(/\\s|\\//);\n    if (libraryMismatch || versionMismatch) {\n        const warning = [\n            `Unable to register library \"${library}\" with version \"${version}\":`\n        ];\n        if (libraryMismatch) {\n            warning.push(`library name \"${library}\" contains illegal characters (whitespace or \"/\")`);\n        }\n        if (libraryMismatch && versionMismatch) {\n            warning.push('and');\n        }\n        if (versionMismatch) {\n            warning.push(`version name \"${version}\" contains illegal characters (whitespace or \"/\")`);\n        }\n        logger.warn(warning.join(' '));\n        return;\n    }\n    _registerComponent(new Component(`${library}-version`, () => ({ library, version }), \"VERSION\" /* ComponentType.VERSION */));\n}\n/**\n * Sets log handler for all Firebase SDKs.\n * @param logCallback - An optional custom log handler that executes user code whenever\n * the Firebase SDK makes a logging call.\n *\n * @public\n */\nfunction onLog(logCallback, options) {\n    if (logCallback !== null && typeof logCallback !== 'function') {\n        throw ERROR_FACTORY.create(\"invalid-log-argument\" /* AppError.INVALID_LOG_ARGUMENT */);\n    }\n    setUserLogHandler(logCallback, options);\n}\n/**\n * Sets log level for all Firebase SDKs.\n *\n * All of the log types above the current log level are captured (i.e. if\n * you set the log level to `info`, errors are logged, but `debug` and\n * `verbose` logs are not).\n *\n * @public\n */\nfunction setLogLevel(logLevel) {\n    setLogLevel$1(logLevel);\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 */\nconst DB_NAME = 'firebase-heartbeat-database';\nconst DB_VERSION = 1;\nconst STORE_NAME = 'firebase-heartbeat-store';\nlet dbPromise = null;\nfunction getDbPromise() {\n    if (!dbPromise) {\n        dbPromise = openDB(DB_NAME, DB_VERSION, {\n            upgrade: (db, oldVersion) => {\n                // We don't use 'break' in this switch statement, the fall-through\n                // behavior is what we want, because if there are multiple versions between\n                // the old version and the current version, we want ALL the migrations\n                // that correspond to those versions to run, not only the last one.\n                // eslint-disable-next-line default-case\n                switch (oldVersion) {\n                    case 0:\n                        try {\n                            db.createObjectStore(STORE_NAME);\n                        }\n                        catch (e) {\n                            // Safari/iOS browsers throw occasional exceptions on\n                            // db.createObjectStore() that may be a bug. Avoid blocking\n                            // the rest of the app functionality.\n                            console.warn(e);\n                        }\n                }\n            }\n        }).catch(e => {\n            throw ERROR_FACTORY.create(\"idb-open\" /* AppError.IDB_OPEN */, {\n                originalErrorMessage: e.message\n            });\n        });\n    }\n    return dbPromise;\n}\nasync function readHeartbeatsFromIndexedDB(app) {\n    try {\n        const db = await getDbPromise();\n        const tx = db.transaction(STORE_NAME);\n        const result = await tx.objectStore(STORE_NAME).get(computeKey(app));\n        // We already have the value but tx.done can throw,\n        // so we need to await it here to catch errors\n        await tx.done;\n        return result;\n    }\n    catch (e) {\n        if (e instanceof FirebaseError) {\n            logger.warn(e.message);\n        }\n        else {\n            const idbGetError = ERROR_FACTORY.create(\"idb-get\" /* AppError.IDB_GET */, {\n                originalErrorMessage: e === null || e === void 0 ? void 0 : e.message\n            });\n            logger.warn(idbGetError.message);\n        }\n    }\n}\nasync function writeHeartbeatsToIndexedDB(app, heartbeatObject) {\n    try {\n        const db = await getDbPromise();\n        const tx = db.transaction(STORE_NAME, 'readwrite');\n        const objectStore = tx.objectStore(STORE_NAME);\n        await objectStore.put(heartbeatObject, computeKey(app));\n        await tx.done;\n    }\n    catch (e) {\n        if (e instanceof FirebaseError) {\n            logger.warn(e.message);\n        }\n        else {\n            const idbGetError = ERROR_FACTORY.create(\"idb-set\" /* AppError.IDB_WRITE */, {\n                originalErrorMessage: e === null || e === void 0 ? void 0 : e.message\n            });\n            logger.warn(idbGetError.message);\n        }\n    }\n}\nfunction computeKey(app) {\n    return `${app.name}!${app.options.appId}`;\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 */\nconst MAX_HEADER_BYTES = 1024;\n// 30 days\nconst STORED_HEARTBEAT_RETENTION_MAX_MILLIS = 30 * 24 * 60 * 60 * 1000;\nclass HeartbeatServiceImpl {\n    constructor(container) {\n        this.container = container;\n        /**\n         * In-memory cache for heartbeats, used by getHeartbeatsHeader() to generate\n         * the header string.\n         * Stores one record per date. This will be consolidated into the standard\n         * format of one record per user agent string before being sent as a header.\n         * Populated from indexedDB when the controller is instantiated and should\n         * be kept in sync with indexedDB.\n         * Leave public for easier testing.\n         */\n        this._heartbeatsCache = null;\n        const app = this.container.getProvider('app').getImmediate();\n        this._storage = new HeartbeatStorageImpl(app);\n        this._heartbeatsCachePromise = this._storage.read().then(result => {\n            this._heartbeatsCache = result;\n            return result;\n        });\n    }\n    /**\n     * Called to report a heartbeat. The function will generate\n     * a HeartbeatsByUserAgent object, update heartbeatsCache, and persist it\n     * to IndexedDB.\n     * Note that we only store one heartbeat per day. So if a heartbeat for today is\n     * already logged, subsequent calls to this function in the same day will be ignored.\n     */\n    async triggerHeartbeat() {\n        var _a, _b;\n        try {\n            const platformLogger = this.container\n                .getProvider('platform-logger')\n                .getImmediate();\n            // This is the \"Firebase user agent\" string from the platform logger\n            // service, not the browser user agent.\n            const agent = platformLogger.getPlatformInfoString();\n            const date = getUTCDateString();\n            if (((_a = this._heartbeatsCache) === null || _a === void 0 ? void 0 : _a.heartbeats) == null) {\n                this._heartbeatsCache = await this._heartbeatsCachePromise;\n                // If we failed to construct a heartbeats cache, then return immediately.\n                if (((_b = this._heartbeatsCache) === null || _b === void 0 ? void 0 : _b.heartbeats) == null) {\n                    return;\n                }\n            }\n            // Do not store a heartbeat if one is already stored for this day\n            // or if a header has already been sent today.\n            if (this._heartbeatsCache.lastSentHeartbeatDate === date ||\n                this._heartbeatsCache.heartbeats.some(singleDateHeartbeat => singleDateHeartbeat.date === date)) {\n                return;\n            }\n            else {\n                // There is no entry for this date. Create one.\n                this._heartbeatsCache.heartbeats.push({ date, agent });\n            }\n            // Remove entries older than 30 days.\n            this._heartbeatsCache.heartbeats =\n                this._heartbeatsCache.heartbeats.filter(singleDateHeartbeat => {\n                    const hbTimestamp = new Date(singleDateHeartbeat.date).valueOf();\n                    const now = Date.now();\n                    return now - hbTimestamp <= STORED_HEARTBEAT_RETENTION_MAX_MILLIS;\n                });\n            return this._storage.overwrite(this._heartbeatsCache);\n        }\n        catch (e) {\n            logger.warn(e);\n        }\n    }\n    /**\n     * Returns a base64 encoded string which can be attached to the heartbeat-specific header directly.\n     * It also clears all heartbeats from memory as well as in IndexedDB.\n     *\n     * NOTE: Consuming product SDKs should not send the header if this method\n     * returns an empty string.\n     */\n    async getHeartbeatsHeader() {\n        var _a;\n        try {\n            if (this._heartbeatsCache === null) {\n                await this._heartbeatsCachePromise;\n            }\n            // If it's still null or the array is empty, there is no data to send.\n            if (((_a = this._heartbeatsCache) === null || _a === void 0 ? void 0 : _a.heartbeats) == null ||\n                this._heartbeatsCache.heartbeats.length === 0) {\n                return '';\n            }\n            const date = getUTCDateString();\n            // Extract as many heartbeats from the cache as will fit under the size limit.\n            const { heartbeatsToSend, unsentEntries } = extractHeartbeatsForHeader(this._heartbeatsCache.heartbeats);\n            const headerString = base64urlEncodeWithoutPadding(JSON.stringify({ version: 2, heartbeats: heartbeatsToSend }));\n            // Store last sent date to prevent another being logged/sent for the same day.\n            this._heartbeatsCache.lastSentHeartbeatDate = date;\n            if (unsentEntries.length > 0) {\n                // Store any unsent entries if they exist.\n                this._heartbeatsCache.heartbeats = unsentEntries;\n                // This seems more likely than emptying the array (below) to lead to some odd state\n                // since the cache isn't empty and this will be called again on the next request,\n                // and is probably safest if we await it.\n                await this._storage.overwrite(this._heartbeatsCache);\n            }\n            else {\n                this._heartbeatsCache.heartbeats = [];\n                // Do not wait for this, to reduce latency.\n                void this._storage.overwrite(this._heartbeatsCache);\n            }\n            return headerString;\n        }\n        catch (e) {\n            logger.warn(e);\n            return '';\n        }\n    }\n}\nfunction getUTCDateString() {\n    const today = new Date();\n    // Returns date format 'YYYY-MM-DD'\n    return today.toISOString().substring(0, 10);\n}\nfunction extractHeartbeatsForHeader(heartbeatsCache, maxSize = MAX_HEADER_BYTES) {\n    // Heartbeats grouped by user agent in the standard format to be sent in\n    // the header.\n    const heartbeatsToSend = [];\n    // Single date format heartbeats that are not sent.\n    let unsentEntries = heartbeatsCache.slice();\n    for (const singleDateHeartbeat of heartbeatsCache) {\n        // Look for an existing entry with the same user agent.\n        const heartbeatEntry = heartbeatsToSend.find(hb => hb.agent === singleDateHeartbeat.agent);\n        if (!heartbeatEntry) {\n            // If no entry for this user agent exists, create one.\n            heartbeatsToSend.push({\n                agent: singleDateHeartbeat.agent,\n                dates: [singleDateHeartbeat.date]\n            });\n            if (countBytes(heartbeatsToSend) > maxSize) {\n                // If the header would exceed max size, remove the added heartbeat\n                // entry and stop adding to the header.\n                heartbeatsToSend.pop();\n                break;\n            }\n        }\n        else {\n            heartbeatEntry.dates.push(singleDateHeartbeat.date);\n            // If the header would exceed max size, remove the added date\n            // and stop adding to the header.\n            if (countBytes(heartbeatsToSend) > maxSize) {\n                heartbeatEntry.dates.pop();\n                break;\n            }\n        }\n        // Pop unsent entry from queue. (Skipped if adding the entry exceeded\n        // quota and the loop breaks early.)\n        unsentEntries = unsentEntries.slice(1);\n    }\n    return {\n        heartbeatsToSend,\n        unsentEntries\n    };\n}\nclass HeartbeatStorageImpl {\n    constructor(app) {\n        this.app = app;\n        this._canUseIndexedDBPromise = this.runIndexedDBEnvironmentCheck();\n    }\n    async runIndexedDBEnvironmentCheck() {\n        if (!isIndexedDBAvailable()) {\n            return false;\n        }\n        else {\n            return validateIndexedDBOpenable()\n                .then(() => true)\n                .catch(() => false);\n        }\n    }\n    /**\n     * Read all heartbeats.\n     */\n    async read() {\n        const canUseIndexedDB = await this._canUseIndexedDBPromise;\n        if (!canUseIndexedDB) {\n            return { heartbeats: [] };\n        }\n        else {\n            const idbHeartbeatObject = await readHeartbeatsFromIndexedDB(this.app);\n            if (idbHeartbeatObject === null || idbHeartbeatObject === void 0 ? void 0 : idbHeartbeatObject.heartbeats) {\n                return idbHeartbeatObject;\n            }\n            else {\n                return { heartbeats: [] };\n            }\n        }\n    }\n    // overwrite the storage with the provided heartbeats\n    async overwrite(heartbeatsObject) {\n        var _a;\n        const canUseIndexedDB = await this._canUseIndexedDBPromise;\n        if (!canUseIndexedDB) {\n            return;\n        }\n        else {\n            const existingHeartbeatsObject = await this.read();\n            return writeHeartbeatsToIndexedDB(this.app, {\n                lastSentHeartbeatDate: (_a = heartbeatsObject.lastSentHeartbeatDate) !== null && _a !== void 0 ? _a : existingHeartbeatsObject.lastSentHeartbeatDate,\n                heartbeats: heartbeatsObject.heartbeats\n            });\n        }\n    }\n    // add heartbeats\n    async add(heartbeatsObject) {\n        var _a;\n        const canUseIndexedDB = await this._canUseIndexedDBPromise;\n        if (!canUseIndexedDB) {\n            return;\n        }\n        else {\n            const existingHeartbeatsObject = await this.read();\n            return writeHeartbeatsToIndexedDB(this.app, {\n                lastSentHeartbeatDate: (_a = heartbeatsObject.lastSentHeartbeatDate) !== null && _a !== void 0 ? _a : existingHeartbeatsObject.lastSentHeartbeatDate,\n                heartbeats: [\n                    ...existingHeartbeatsObject.heartbeats,\n                    ...heartbeatsObject.heartbeats\n                ]\n            });\n        }\n    }\n}\n/**\n * Calculate bytes of a HeartbeatsByUserAgent array after being wrapped\n * in a platform logging header JSON object, stringified, and converted\n * to base 64.\n */\nfunction countBytes(heartbeatsCache) {\n    // base64 has a restricted set of characters, all of which should be 1 byte.\n    return base64urlEncodeWithoutPadding(\n    // heartbeatsCache wrapper properties\n    JSON.stringify({ version: 2, heartbeats: heartbeatsCache })).length;\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 */\nfunction registerCoreComponents(variant) {\n    _registerComponent(new Component('platform-logger', container => new PlatformLoggerServiceImpl(container), \"PRIVATE\" /* ComponentType.PRIVATE */));\n    _registerComponent(new Component('heartbeat', container => new HeartbeatServiceImpl(container), \"PRIVATE\" /* ComponentType.PRIVATE */));\n    // Register `app` package.\n    registerVersion(name$q, version$1, variant);\n    // BUILD_TARGET will be replaced by values like esm2017, cjs2017, etc during the compilation\n    registerVersion(name$q, version$1, 'esm2017');\n    // Register platform SDK identifier (no version).\n    registerVersion('fire-js', '');\n}\n\n/**\n * Firebase App\n *\n * @remarks This package coordinates the communication between the different Firebase components\n * @packageDocumentation\n */\nregisterCoreComponents('');\n\nexport { SDK_VERSION, DEFAULT_ENTRY_NAME as _DEFAULT_ENTRY_NAME, _addComponent, _addOrOverwriteComponent, _apps, _clearComponents, _components, _getProvider, _isFirebaseApp, _isFirebaseServerApp, _registerComponent, _removeServiceInstance, _serverApps, deleteApp, getApp, getApps, initializeApp, initializeServerApp, onLog, registerVersion, setLogLevel };\n//# sourceMappingURL=index.esm2017.js.map\n","import { ErrorFactory, contains, deepExtend, createSubscribe, getGlobal } from '@firebase/util';\nimport { Component } from '@firebase/component';\nimport * as modularAPIs from '@firebase/app';\nimport { _addComponent, deleteApp, _DEFAULT_ENTRY_NAME, _addOrOverwriteComponent, registerVersion } from '@firebase/app';\nimport { Logger } from '@firebase/logger';\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 * Global context object for a collection of services using\n * a shared authentication state.\n *\n * marked as internal because it references internal types exported from @firebase/app\n * @internal\n */\nclass FirebaseAppImpl {\n    constructor(_delegate, firebase) {\n        this._delegate = _delegate;\n        this.firebase = firebase;\n        // add itself to container\n        _addComponent(_delegate, new Component('app-compat', () => this, \"PUBLIC\" /* ComponentType.PUBLIC */));\n        this.container = _delegate.container;\n    }\n    get automaticDataCollectionEnabled() {\n        return this._delegate.automaticDataCollectionEnabled;\n    }\n    set automaticDataCollectionEnabled(val) {\n        this._delegate.automaticDataCollectionEnabled = val;\n    }\n    get name() {\n        return this._delegate.name;\n    }\n    get options() {\n        return this._delegate.options;\n    }\n    delete() {\n        return new Promise(resolve => {\n            this._delegate.checkDestroyed();\n            resolve();\n        }).then(() => {\n            this.firebase.INTERNAL.removeApp(this.name);\n            return deleteApp(this._delegate);\n        });\n    }\n    /**\n     * Return a service instance associated with this app (creating it\n     * on demand), identified by the passed instanceIdentifier.\n     *\n     * NOTE: Currently storage and functions are the only ones that are leveraging this\n     * functionality. They invoke it by calling:\n     *\n     * ```javascript\n     * firebase.app().storage('STORAGE BUCKET ID')\n     * ```\n     *\n     * The service name is passed to this already\n     * @internal\n     */\n    _getService(name, instanceIdentifier = _DEFAULT_ENTRY_NAME) {\n        var _a;\n        this._delegate.checkDestroyed();\n        // Initialize instance if InstantiationMode is `EXPLICIT`.\n        const provider = this._delegate.container.getProvider(name);\n        if (!provider.isInitialized() &&\n            ((_a = provider.getComponent()) === null || _a === void 0 ? void 0 : _a.instantiationMode) === \"EXPLICIT\" /* InstantiationMode.EXPLICIT */) {\n            provider.initialize();\n        }\n        // getImmediate will always succeed because _getService is only called for registered components.\n        return provider.getImmediate({\n            identifier: instanceIdentifier\n        });\n    }\n    /**\n     * Remove a service instance from the cache, so we will create a new instance for this service\n     * when people try to get it again.\n     *\n     * NOTE: currently only firestore uses this functionality to support firestore shutdown.\n     *\n     * @param name The service name\n     * @param instanceIdentifier instance identifier in case multiple instances are allowed\n     * @internal\n     */\n    _removeServiceInstance(name, instanceIdentifier = _DEFAULT_ENTRY_NAME) {\n        this._delegate.container\n            // eslint-disable-next-line @typescript-eslint/no-explicit-any\n            .getProvider(name)\n            .clearInstance(instanceIdentifier);\n    }\n    /**\n     * @param component the component being added to this app's container\n     * @internal\n     */\n    _addComponent(component) {\n        _addComponent(this._delegate, component);\n    }\n    _addOrOverwriteComponent(component) {\n        _addOrOverwriteComponent(this._delegate, component);\n    }\n    toJSON() {\n        return {\n            name: this.name,\n            automaticDataCollectionEnabled: this.automaticDataCollectionEnabled,\n            options: this.options\n        };\n    }\n}\n// TODO: investigate why the following needs to be commented out\n// Prevent dead-code elimination of these methods w/o invalid property\n// copying.\n// (FirebaseAppImpl.prototype.name && FirebaseAppImpl.prototype.options) ||\n//   FirebaseAppImpl.prototype.delete ||\n//   console.log('dc');\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 */\nconst ERRORS = {\n    [\"no-app\" /* AppError.NO_APP */]: \"No Firebase App '{$appName}' has been created - \" +\n        'call Firebase App.initializeApp()',\n    [\"invalid-app-argument\" /* AppError.INVALID_APP_ARGUMENT */]: 'firebase.{$appName}() takes either no argument or a ' +\n        'Firebase App instance.'\n};\nconst ERROR_FACTORY = new ErrorFactory('app-compat', 'Firebase', ERRORS);\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 * Because auth can't share code with other components, we attach the utility functions\n * in an internal namespace to share code.\n * This function return a firebase namespace object without\n * any utility functions, so it can be shared between the regular firebaseNamespace and\n * the lite version.\n */\nfunction createFirebaseNamespaceCore(firebaseAppImpl) {\n    const apps = {};\n    // // eslint-disable-next-line @typescript-eslint/no-explicit-any\n    // const components = new Map<string, Component<any>>();\n    // A namespace is a plain JavaScript Object.\n    const namespace = {\n        // Hack to prevent Babel from modifying the object returned\n        // as the firebase namespace.\n        // @ts-ignore\n        __esModule: true,\n        initializeApp: initializeAppCompat,\n        // @ts-ignore\n        app,\n        registerVersion: modularAPIs.registerVersion,\n        setLogLevel: modularAPIs.setLogLevel,\n        onLog: modularAPIs.onLog,\n        // @ts-ignore\n        apps: null,\n        SDK_VERSION: modularAPIs.SDK_VERSION,\n        INTERNAL: {\n            registerComponent: registerComponentCompat,\n            removeApp,\n            useAsService,\n            modularAPIs\n        }\n    };\n    // Inject a circular default export to allow Babel users who were previously\n    // using:\n    //\n    //   import firebase from 'firebase';\n    //   which becomes: var firebase = require('firebase').default;\n    //\n    // instead of\n    //\n    //   import * as firebase from 'firebase';\n    //   which becomes: var firebase = require('firebase');\n    // eslint-disable-next-line @typescript-eslint/no-explicit-any\n    namespace['default'] = namespace;\n    // firebase.apps is a read-only getter.\n    Object.defineProperty(namespace, 'apps', {\n        get: getApps\n    });\n    /**\n     * Called by App.delete() - but before any services associated with the App\n     * are deleted.\n     */\n    function removeApp(name) {\n        delete apps[name];\n    }\n    /**\n     * Get the App object for a given name (or DEFAULT).\n     */\n    function app(name) {\n        name = name || modularAPIs._DEFAULT_ENTRY_NAME;\n        if (!contains(apps, name)) {\n            throw ERROR_FACTORY.create(\"no-app\" /* AppError.NO_APP */, { appName: name });\n        }\n        return apps[name];\n    }\n    // @ts-ignore\n    app['App'] = firebaseAppImpl;\n    /**\n     * Create a new App instance (name must be unique).\n     *\n     * This function is idempotent. It can be called more than once and return the same instance using the same options and config.\n     */\n    function initializeAppCompat(options, rawConfig = {}) {\n        const app = modularAPIs.initializeApp(options, rawConfig);\n        if (contains(apps, app.name)) {\n            return apps[app.name];\n        }\n        const appCompat = new firebaseAppImpl(app, namespace);\n        apps[app.name] = appCompat;\n        return appCompat;\n    }\n    /*\n     * Return an array of all the non-deleted FirebaseApps.\n     */\n    function getApps() {\n        // Make a copy so caller cannot mutate the apps list.\n        return Object.keys(apps).map(name => apps[name]);\n    }\n    function registerComponentCompat(component) {\n        const componentName = component.name;\n        const componentNameWithoutCompat = componentName.replace('-compat', '');\n        if (modularAPIs._registerComponent(component) &&\n            component.type === \"PUBLIC\" /* ComponentType.PUBLIC */) {\n            // create service namespace for public components\n            // The Service namespace is an accessor function ...\n            const serviceNamespace = (appArg = app()) => {\n                // eslint-disable-next-line @typescript-eslint/no-explicit-any\n                if (typeof appArg[componentNameWithoutCompat] !== 'function') {\n                    // Invalid argument.\n                    // This happens in the following case: firebase.storage('gs:/')\n                    throw ERROR_FACTORY.create(\"invalid-app-argument\" /* AppError.INVALID_APP_ARGUMENT */, {\n                        appName: componentName\n                    });\n                }\n                // Forward service instance lookup to the FirebaseApp.\n                // eslint-disable-next-line @typescript-eslint/no-explicit-any\n                return appArg[componentNameWithoutCompat]();\n            };\n            // ... and a container for service-level properties.\n            if (component.serviceProps !== undefined) {\n                deepExtend(serviceNamespace, component.serviceProps);\n            }\n            // eslint-disable-next-line @typescript-eslint/no-explicit-any\n            namespace[componentNameWithoutCompat] = serviceNamespace;\n            // Patch the FirebaseAppImpl prototype\n            // eslint-disable-next-line @typescript-eslint/no-explicit-any\n            firebaseAppImpl.prototype[componentNameWithoutCompat] =\n                // TODO: The eslint disable can be removed and the 'ignoreRestArgs'\n                // option added to the no-explicit-any rule when ESlint releases it.\n                // eslint-disable-next-line @typescript-eslint/no-explicit-any\n                function (...args) {\n                    const serviceFxn = this._getService.bind(this, componentName);\n                    return serviceFxn.apply(this, component.multipleInstances ? args : []);\n                };\n        }\n        return component.type === \"PUBLIC\" /* ComponentType.PUBLIC */\n            ? // eslint-disable-next-line @typescript-eslint/no-explicit-any\n                namespace[componentNameWithoutCompat]\n            : null;\n    }\n    // Map the requested service to a registered service name\n    // (used to map auth to serverAuth service when needed).\n    function useAsService(app, name) {\n        if (name === 'serverAuth') {\n            return null;\n        }\n        const useService = name;\n        return useService;\n    }\n    return namespace;\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 * Return a firebase namespace object.\n *\n * In production, this will be called exactly once and the result\n * assigned to the 'firebase' global.  It may be called multiple times\n * in unit tests.\n */\nfunction createFirebaseNamespace() {\n    const namespace = createFirebaseNamespaceCore(FirebaseAppImpl);\n    namespace.INTERNAL = Object.assign(Object.assign({}, namespace.INTERNAL), { createFirebaseNamespace,\n        extendNamespace,\n        createSubscribe,\n        ErrorFactory,\n        deepExtend });\n    /**\n     * Patch the top-level firebase namespace with additional properties.\n     *\n     * firebase.INTERNAL.extendNamespace()\n     */\n    function extendNamespace(props) {\n        deepExtend(namespace, props);\n    }\n    return namespace;\n}\nconst firebase$1 = createFirebaseNamespace();\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 */\nconst logger = new Logger('@firebase/app-compat');\n\nconst name = \"@firebase/app-compat\";\nconst version = \"0.2.47\";\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 */\nfunction registerCoreComponents(variant) {\n    // Register `app` package.\n    registerVersion(name, version, variant);\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 */\ntry {\n    const globals = getGlobal();\n    // Firebase Lite detection\n    // eslint-disable-next-line @typescript-eslint/no-explicit-any\n    if (globals.firebase !== undefined) {\n        logger.warn(`\n      Warning: Firebase is already defined in the global scope. Please make sure\n      Firebase library is only loaded once.\n    `);\n        // eslint-disable-next-line\n        const sdkVersion = globals.firebase\n            .SDK_VERSION;\n        if (sdkVersion && sdkVersion.indexOf('LITE') >= 0) {\n            logger.warn(`\n        Warning: You are trying to load Firebase while using Firebase Performance standalone script.\n        You should load Firebase Performance with this instance of Firebase to avoid loading duplicate code.\n        `);\n        }\n    }\n}\ncatch (_a) {\n    // ignore errors thrown by getGlobal\n}\nconst firebase = firebase$1;\nregisterCoreComponents();\n\nexport { firebase as default };\n//# sourceMappingURL=index.esm2017.js.map\n","import firebase from '@firebase/app-compat';\nexport { default } from '@firebase/app-compat';\n\nvar name = \"firebase\";\nvar version = \"11.1.0\";\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 */\nfirebase.registerVersion(name, version, 'app-compat');\n//# sourceMappingURL=index.esm.js.map\n","import { _getProvider, getApp, SDK_VERSION as SDK_VERSION$1, _registerComponent, registerVersion } from '@firebase/app';\nimport { Component, ComponentContainer, Provider } from '@firebase/component';\nimport { stringify, jsonEval, contains, assert, isNodeSdk, stringToByteArray, Sha1, base64, deepCopy, base64Encode, isMobileCordova, stringLength, Deferred, safeGet, isAdmin, isValidFormat, isEmpty, isReactNative, assertionError, map, querystring, errorPrefix, getModularInstance, getDefaultEmulatorHostnameAndPort, createMockUserToken } from '@firebase/util';\nimport { Logger, LogLevel } from '@firebase/logger';\n\nconst name = \"@firebase/database\";\nconst version = \"1.0.10\";\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 semver (www.semver.org) version of the SDK. */\nlet SDK_VERSION = '';\n/**\n * SDK_VERSION should be set before any database instance is created\n * @internal\n */\nfunction setSDKVersion(version) {\n    SDK_VERSION = version;\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 * Wraps a DOM Storage object and:\n * - automatically encode objects as JSON strings before storing them to allow us to store arbitrary types.\n * - prefixes names with \"firebase:\" to avoid collisions with app data.\n *\n * We automatically (see storage.js) create two such wrappers, one for sessionStorage,\n * and one for localStorage.\n *\n */\nclass DOMStorageWrapper {\n    /**\n     * @param domStorage_ - The underlying storage object (e.g. localStorage or sessionStorage)\n     */\n    constructor(domStorage_) {\n        this.domStorage_ = domStorage_;\n        // Use a prefix to avoid collisions with other stuff saved by the app.\n        this.prefix_ = 'firebase:';\n    }\n    /**\n     * @param key - The key to save the value under\n     * @param value - The value being stored, or null to remove the key.\n     */\n    set(key, value) {\n        if (value == null) {\n            this.domStorage_.removeItem(this.prefixedName_(key));\n        }\n        else {\n            this.domStorage_.setItem(this.prefixedName_(key), stringify(value));\n        }\n    }\n    /**\n     * @returns The value that was stored under this key, or null\n     */\n    get(key) {\n        const storedVal = this.domStorage_.getItem(this.prefixedName_(key));\n        if (storedVal == null) {\n            return null;\n        }\n        else {\n            return jsonEval(storedVal);\n        }\n    }\n    remove(key) {\n        this.domStorage_.removeItem(this.prefixedName_(key));\n    }\n    prefixedName_(name) {\n        return this.prefix_ + name;\n    }\n    toString() {\n        return this.domStorage_.toString();\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 in-memory storage implementation that matches the API of DOMStorageWrapper\n * (TODO: create interface for both to implement).\n */\nclass MemoryStorage {\n    constructor() {\n        this.cache_ = {};\n        this.isInMemoryStorage = true;\n    }\n    set(key, value) {\n        if (value == null) {\n            delete this.cache_[key];\n        }\n        else {\n            this.cache_[key] = value;\n        }\n    }\n    get(key) {\n        if (contains(this.cache_, key)) {\n            return this.cache_[key];\n        }\n        return null;\n    }\n    remove(key) {\n        delete this.cache_[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 * Helper to create a DOMStorageWrapper or else fall back to MemoryStorage.\n * TODO: Once MemoryStorage and DOMStorageWrapper have a shared interface this method annotation should change\n * to reflect this type\n *\n * @param domStorageName - Name of the underlying storage object\n *   (e.g. 'localStorage' or 'sessionStorage').\n * @returns Turning off type information until a common interface is defined.\n */\nconst createStoragefor = function (domStorageName) {\n    try {\n        // NOTE: just accessing \"localStorage\" or \"window['localStorage']\" may throw a security exception,\n        // so it must be inside the try/catch.\n        if (typeof window !== 'undefined' &&\n            typeof window[domStorageName] !== 'undefined') {\n            // Need to test cache. Just because it's here doesn't mean it works\n            const domStorage = window[domStorageName];\n            domStorage.setItem('firebase:sentinel', 'cache');\n            domStorage.removeItem('firebase:sentinel');\n            return new DOMStorageWrapper(domStorage);\n        }\n    }\n    catch (e) { }\n    // Failed to create wrapper.  Just return in-memory storage.\n    // TODO: log?\n    return new MemoryStorage();\n};\n/** A storage object that lasts across sessions */\nconst PersistentStorage = createStoragefor('localStorage');\n/** A storage object that only lasts one session */\nconst SessionStorage = createStoragefor('sessionStorage');\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 logClient = new Logger('@firebase/database');\n/**\n * Returns a locally-unique ID (generated by just incrementing up from 0 each time its called).\n */\nconst LUIDGenerator = (function () {\n    let id = 1;\n    return function () {\n        return id++;\n    };\n})();\n/**\n * Sha1 hash of the input string\n * @param str - The string to hash\n * @returns {!string} The resulting hash\n */\nconst sha1 = function (str) {\n    const utf8Bytes = stringToByteArray(str);\n    const sha1 = new Sha1();\n    sha1.update(utf8Bytes);\n    const sha1Bytes = sha1.digest();\n    return base64.encodeByteArray(sha1Bytes);\n};\nconst buildLogMessage_ = function (...varArgs) {\n    let message = '';\n    for (let i = 0; i < varArgs.length; i++) {\n        const arg = varArgs[i];\n        if (Array.isArray(arg) ||\n            (arg &&\n                typeof arg === 'object' &&\n                // eslint-disable-next-line @typescript-eslint/no-explicit-any\n                typeof arg.length === 'number')) {\n            message += buildLogMessage_.apply(null, arg);\n        }\n        else if (typeof arg === 'object') {\n            message += stringify(arg);\n        }\n        else {\n            message += arg;\n        }\n        message += ' ';\n    }\n    return message;\n};\n/**\n * Use this for all debug messages in Firebase.\n */\nlet logger = null;\n/**\n * Flag to check for log availability on first log message\n */\nlet firstLog_ = true;\n/**\n * The implementation of Firebase.enableLogging (defined here to break dependencies)\n * @param logger_ - A flag to turn on logging, or a custom logger\n * @param persistent - Whether or not to persist logging settings across refreshes\n */\nconst enableLogging$1 = function (logger_, persistent) {\n    assert(!persistent || logger_ === true || logger_ === false, \"Can't turn on custom loggers persistently.\");\n    if (logger_ === true) {\n        logClient.logLevel = LogLevel.VERBOSE;\n        logger = logClient.log.bind(logClient);\n        if (persistent) {\n            SessionStorage.set('logging_enabled', true);\n        }\n    }\n    else if (typeof logger_ === 'function') {\n        logger = logger_;\n    }\n    else {\n        logger = null;\n        SessionStorage.remove('logging_enabled');\n    }\n};\nconst log = function (...varArgs) {\n    if (firstLog_ === true) {\n        firstLog_ = false;\n        if (logger === null && SessionStorage.get('logging_enabled') === true) {\n            enableLogging$1(true);\n        }\n    }\n    if (logger) {\n        const message = buildLogMessage_.apply(null, varArgs);\n        logger(message);\n    }\n};\nconst logWrapper = function (prefix) {\n    return function (...varArgs) {\n        log(prefix, ...varArgs);\n    };\n};\nconst error = function (...varArgs) {\n    const message = 'FIREBASE INTERNAL ERROR: ' + buildLogMessage_(...varArgs);\n    logClient.error(message);\n};\nconst fatal = function (...varArgs) {\n    const message = `FIREBASE FATAL ERROR: ${buildLogMessage_(...varArgs)}`;\n    logClient.error(message);\n    throw new Error(message);\n};\nconst warn = function (...varArgs) {\n    const message = 'FIREBASE WARNING: ' + buildLogMessage_(...varArgs);\n    logClient.warn(message);\n};\n/**\n * Logs a warning if the containing page uses https. Called when a call to new Firebase\n * does not use https.\n */\nconst warnIfPageIsSecure = function () {\n    // Be very careful accessing browser globals. Who knows what may or may not exist.\n    if (typeof window !== 'undefined' &&\n        window.location &&\n        window.location.protocol &&\n        window.location.protocol.indexOf('https:') !== -1) {\n        warn('Insecure Firebase access from a secure page. ' +\n            'Please use https in calls to new Firebase().');\n    }\n};\n/**\n * Returns true if data is NaN, or +/- Infinity.\n */\nconst isInvalidJSONNumber = function (data) {\n    return (typeof data === 'number' &&\n        (data !== data || // NaN\n            data === Number.POSITIVE_INFINITY ||\n            data === Number.NEGATIVE_INFINITY));\n};\nconst executeWhenDOMReady = function (fn) {\n    if (isNodeSdk() || document.readyState === 'complete') {\n        fn();\n    }\n    else {\n        // Modeled after jQuery. Try DOMContentLoaded and onreadystatechange (which\n        // fire before onload), but fall back to onload.\n        let called = false;\n        const wrappedFn = function () {\n            if (!document.body) {\n                setTimeout(wrappedFn, Math.floor(10));\n                return;\n            }\n            if (!called) {\n                called = true;\n                fn();\n            }\n        };\n        if (document.addEventListener) {\n            document.addEventListener('DOMContentLoaded', wrappedFn, false);\n            // fallback to onload.\n            window.addEventListener('load', wrappedFn, false);\n            // eslint-disable-next-line @typescript-eslint/no-explicit-any\n        }\n        else if (document.attachEvent) {\n            // IE.\n            // eslint-disable-next-line @typescript-eslint/no-explicit-any\n            document.attachEvent('onreadystatechange', () => {\n                if (document.readyState === 'complete') {\n                    wrappedFn();\n                }\n            });\n            // fallback to onload.\n            // eslint-disable-next-line @typescript-eslint/no-explicit-any\n            window.attachEvent('onload', wrappedFn);\n            // jQuery has an extra hack for IE that we could employ (based on\n            // http://javascript.nwbox.com/IEContentLoaded/) But it looks really old.\n            // I'm hoping we don't need it.\n        }\n    }\n};\n/**\n * Minimum key name. Invalid for actual data, used as a marker to sort before any valid names\n */\nconst MIN_NAME = '[MIN_NAME]';\n/**\n * Maximum key name. Invalid for actual data, used as a marker to sort above any valid names\n */\nconst MAX_NAME = '[MAX_NAME]';\n/**\n * Compares valid Firebase key names, plus min and max name\n */\nconst nameCompare = function (a, b) {\n    if (a === b) {\n        return 0;\n    }\n    else if (a === MIN_NAME || b === MAX_NAME) {\n        return -1;\n    }\n    else if (b === MIN_NAME || a === MAX_NAME) {\n        return 1;\n    }\n    else {\n        const aAsInt = tryParseInt(a), bAsInt = tryParseInt(b);\n        if (aAsInt !== null) {\n            if (bAsInt !== null) {\n                return aAsInt - bAsInt === 0 ? a.length - b.length : aAsInt - bAsInt;\n            }\n            else {\n                return -1;\n            }\n        }\n        else if (bAsInt !== null) {\n            return 1;\n        }\n        else {\n            return a < b ? -1 : 1;\n        }\n    }\n};\n/**\n * @returns {!number} comparison result.\n */\nconst stringCompare = function (a, b) {\n    if (a === b) {\n        return 0;\n    }\n    else if (a < b) {\n        return -1;\n    }\n    else {\n        return 1;\n    }\n};\nconst requireKey = function (key, obj) {\n    if (obj && key in obj) {\n        return obj[key];\n    }\n    else {\n        throw new Error('Missing required key (' + key + ') in object: ' + stringify(obj));\n    }\n};\nconst ObjectToUniqueKey = function (obj) {\n    if (typeof obj !== 'object' || obj === null) {\n        return stringify(obj);\n    }\n    const keys = [];\n    // eslint-disable-next-line guard-for-in\n    for (const k in obj) {\n        keys.push(k);\n    }\n    // Export as json, but with the keys sorted.\n    keys.sort();\n    let key = '{';\n    for (let i = 0; i < keys.length; i++) {\n        if (i !== 0) {\n            key += ',';\n        }\n        key += stringify(keys[i]);\n        key += ':';\n        key += ObjectToUniqueKey(obj[keys[i]]);\n    }\n    key += '}';\n    return key;\n};\n/**\n * Splits a string into a number of smaller segments of maximum size\n * @param str - The string\n * @param segsize - The maximum number of chars in the string.\n * @returns The string, split into appropriately-sized chunks\n */\nconst splitStringBySize = function (str, segsize) {\n    const len = str.length;\n    if (len <= segsize) {\n        return [str];\n    }\n    const dataSegs = [];\n    for (let c = 0; c < len; c += segsize) {\n        if (c + segsize > len) {\n            dataSegs.push(str.substring(c, len));\n        }\n        else {\n            dataSegs.push(str.substring(c, c + segsize));\n        }\n    }\n    return dataSegs;\n};\n/**\n * Apply a function to each (key, value) pair in an object or\n * apply a function to each (index, value) pair in an array\n * @param obj - The object or array to iterate over\n * @param fn - The function to apply\n */\nfunction each(obj, fn) {\n    for (const key in obj) {\n        if (obj.hasOwnProperty(key)) {\n            fn(key, obj[key]);\n        }\n    }\n}\n/**\n * Borrowed from http://hg.secondlife.com/llsd/src/tip/js/typedarray.js (MIT License)\n * I made one modification at the end and removed the NaN / Infinity\n * handling (since it seemed broken [caused an overflow] and we don't need it).  See MJL comments.\n * @param v - A double\n *\n */\nconst doubleToIEEE754String = function (v) {\n    assert(!isInvalidJSONNumber(v), 'Invalid JSON number'); // MJL\n    const ebits = 11, fbits = 52;\n    const bias = (1 << (ebits - 1)) - 1;\n    let s, e, f, ln, i;\n    // Compute sign, exponent, fraction\n    // Skip NaN / Infinity handling --MJL.\n    if (v === 0) {\n        e = 0;\n        f = 0;\n        s = 1 / v === -Infinity ? 1 : 0;\n    }\n    else {\n        s = v < 0;\n        v = Math.abs(v);\n        if (v >= Math.pow(2, 1 - bias)) {\n            // Normalized\n            ln = Math.min(Math.floor(Math.log(v) / Math.LN2), bias);\n            e = ln + bias;\n            f = Math.round(v * Math.pow(2, fbits - ln) - Math.pow(2, fbits));\n        }\n        else {\n            // Denormalized\n            e = 0;\n            f = Math.round(v / Math.pow(2, 1 - bias - fbits));\n        }\n    }\n    // Pack sign, exponent, fraction\n    const bits = [];\n    for (i = fbits; i; i -= 1) {\n        bits.push(f % 2 ? 1 : 0);\n        f = Math.floor(f / 2);\n    }\n    for (i = ebits; i; i -= 1) {\n        bits.push(e % 2 ? 1 : 0);\n        e = Math.floor(e / 2);\n    }\n    bits.push(s ? 1 : 0);\n    bits.reverse();\n    const str = bits.join('');\n    // Return the data as a hex string. --MJL\n    let hexByteString = '';\n    for (i = 0; i < 64; i += 8) {\n        let hexByte = parseInt(str.substr(i, 8), 2).toString(16);\n        if (hexByte.length === 1) {\n            hexByte = '0' + hexByte;\n        }\n        hexByteString = hexByteString + hexByte;\n    }\n    return hexByteString.toLowerCase();\n};\n/**\n * Used to detect if we're in a Chrome content script (which executes in an\n * isolated environment where long-polling doesn't work).\n */\nconst isChromeExtensionContentScript = function () {\n    return !!(typeof window === 'object' &&\n        window['chrome'] &&\n        window['chrome']['extension'] &&\n        !/^chrome/.test(window.location.href));\n};\n/**\n * Used to detect if we're in a Windows 8 Store app.\n */\nconst isWindowsStoreApp = function () {\n    // Check for the presence of a couple WinRT globals\n    return typeof Windows === 'object' && typeof Windows.UI === 'object';\n};\n/**\n * Converts a server error code to a JavaScript Error\n */\nfunction errorForServerCode(code, query) {\n    let reason = 'Unknown Error';\n    if (code === 'too_big') {\n        reason =\n            'The data requested exceeds the maximum size ' +\n                'that can be accessed with a single request.';\n    }\n    else if (code === 'permission_denied') {\n        reason = \"Client doesn't have permission to access the desired data.\";\n    }\n    else if (code === 'unavailable') {\n        reason = 'The service is unavailable';\n    }\n    const error = new Error(code + ' at ' + query._path.toString() + ': ' + reason);\n    // eslint-disable-next-line @typescript-eslint/no-explicit-any\n    error.code = code.toUpperCase();\n    return error;\n}\n/**\n * Used to test for integer-looking strings\n */\nconst INTEGER_REGEXP_ = new RegExp('^-?(0*)\\\\d{1,10}$');\n/**\n * For use in keys, the minimum possible 32-bit integer.\n */\nconst INTEGER_32_MIN = -2147483648;\n/**\n * For use in keys, the maximum possible 32-bit integer.\n */\nconst INTEGER_32_MAX = 2147483647;\n/**\n * If the string contains a 32-bit integer, return it.  Else return null.\n */\nconst tryParseInt = function (str) {\n    if (INTEGER_REGEXP_.test(str)) {\n        const intVal = Number(str);\n        if (intVal >= INTEGER_32_MIN && intVal <= INTEGER_32_MAX) {\n            return intVal;\n        }\n    }\n    return null;\n};\n/**\n * Helper to run some code but catch any exceptions and re-throw them later.\n * Useful for preventing user callbacks from breaking internal code.\n *\n * Re-throwing the exception from a setTimeout is a little evil, but it's very\n * convenient (we don't have to try to figure out when is a safe point to\n * re-throw it), and the behavior seems reasonable:\n *\n * * If you aren't pausing on exceptions, you get an error in the console with\n *   the correct stack trace.\n * * If you're pausing on all exceptions, the debugger will pause on your\n *   exception and then again when we rethrow it.\n * * If you're only pausing on uncaught exceptions, the debugger will only pause\n *   on us re-throwing it.\n *\n * @param fn - The code to guard.\n */\nconst exceptionGuard = function (fn) {\n    try {\n        fn();\n    }\n    catch (e) {\n        // Re-throw exception when it's safe.\n        setTimeout(() => {\n            // It used to be that \"throw e\" would result in a good console error with\n            // relevant context, but as of Chrome 39, you just get the firebase.js\n            // file/line number where we re-throw it, which is useless. So we log\n            // e.stack explicitly.\n            const stack = e.stack || '';\n            warn('Exception was thrown by user callback.', stack);\n            throw e;\n        }, Math.floor(0));\n    }\n};\n/**\n * @returns {boolean} true if we think we're currently being crawled.\n */\nconst beingCrawled = function () {\n    const userAgent = (typeof window === 'object' &&\n        window['navigator'] &&\n        window['navigator']['userAgent']) ||\n        '';\n    // For now we whitelist the most popular crawlers.  We should refine this to be the set of crawlers we\n    // believe to support JavaScript/AJAX rendering.\n    // NOTE: Google Webmaster Tools doesn't really belong, but their \"This is how a visitor to your website\n    // would have seen the page\" is flaky if we don't treat it as a crawler.\n    return (userAgent.search(/googlebot|google webmaster tools|bingbot|yahoo! slurp|baiduspider|yandexbot|duckduckbot/i) >= 0);\n};\n/**\n * Same as setTimeout() except on Node.JS it will /not/ prevent the process from exiting.\n *\n * It is removed with clearTimeout() as normal.\n *\n * @param fn - Function to run.\n * @param time - Milliseconds to wait before running.\n * @returns The setTimeout() return value.\n */\nconst setTimeoutNonBlocking = function (fn, time) {\n    const timeout = setTimeout(fn, time);\n    // Note: at the time of this comment, unrefTimer is under the unstable set of APIs. Run with --unstable to enable the API.\n    if (typeof timeout === 'number' &&\n        // @ts-ignore Is only defined in Deno environments.\n        typeof Deno !== 'undefined' &&\n        // @ts-ignore Deno and unrefTimer are only defined in Deno environments.\n        Deno['unrefTimer']) {\n        // @ts-ignore Deno and unrefTimer are only defined in Deno environments.\n        Deno.unrefTimer(timeout);\n        // eslint-disable-next-line @typescript-eslint/no-explicit-any\n    }\n    else if (typeof timeout === 'object' && timeout['unref']) {\n        // eslint-disable-next-line @typescript-eslint/no-explicit-any\n        timeout['unref']();\n    }\n    return timeout;\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 * Abstraction around AppCheck's token fetching capabilities.\n */\nclass AppCheckTokenProvider {\n    constructor(appName_, appCheckProvider) {\n        this.appName_ = appName_;\n        this.appCheckProvider = appCheckProvider;\n        this.appCheck = appCheckProvider === null || appCheckProvider === void 0 ? void 0 : appCheckProvider.getImmediate({ optional: true });\n        if (!this.appCheck) {\n            appCheckProvider === null || appCheckProvider === void 0 ? void 0 : appCheckProvider.get().then(appCheck => (this.appCheck = appCheck));\n        }\n    }\n    getToken(forceRefresh) {\n        if (!this.appCheck) {\n            return new Promise((resolve, reject) => {\n                // Support delayed initialization of FirebaseAppCheck. This allows our\n                // customers to initialize the RTDB SDK before initializing Firebase\n                // AppCheck and ensures that all requests are authenticated if a token\n                // becomes available before the timeout below expires.\n                setTimeout(() => {\n                    if (this.appCheck) {\n                        this.getToken(forceRefresh).then(resolve, reject);\n                    }\n                    else {\n                        resolve(null);\n                    }\n                }, 0);\n            });\n        }\n        return this.appCheck.getToken(forceRefresh);\n    }\n    addTokenChangeListener(listener) {\n        var _a;\n        (_a = this.appCheckProvider) === null || _a === void 0 ? void 0 : _a.get().then(appCheck => appCheck.addTokenListener(listener));\n    }\n    notifyForInvalidToken() {\n        warn(`Provided AppCheck credentials for the app named \"${this.appName_}\" ` +\n            'are invalid. This usually indicates your app was not initialized correctly.');\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 * Abstraction around FirebaseApp's token fetching capabilities.\n */\nclass FirebaseAuthTokenProvider {\n    constructor(appName_, firebaseOptions_, authProvider_) {\n        this.appName_ = appName_;\n        this.firebaseOptions_ = firebaseOptions_;\n        this.authProvider_ = authProvider_;\n        this.auth_ = null;\n        this.auth_ = authProvider_.getImmediate({ optional: true });\n        if (!this.auth_) {\n            authProvider_.onInit(auth => (this.auth_ = auth));\n        }\n    }\n    getToken(forceRefresh) {\n        if (!this.auth_) {\n            return new Promise((resolve, reject) => {\n                // Support delayed initialization of FirebaseAuth. This allows our\n                // customers to initialize the RTDB SDK before initializing Firebase\n                // Auth and ensures that all requests are authenticated if a token\n                // becomes available before the timeout below expires.\n                setTimeout(() => {\n                    if (this.auth_) {\n                        this.getToken(forceRefresh).then(resolve, reject);\n                    }\n                    else {\n                        resolve(null);\n                    }\n                }, 0);\n            });\n        }\n        return this.auth_.getToken(forceRefresh).catch(error => {\n            // TODO: Need to figure out all the cases this is raised and whether\n            // this makes sense.\n            if (error && error.code === 'auth/token-not-initialized') {\n                log('Got auth/token-not-initialized error.  Treating as null token.');\n                return null;\n            }\n            else {\n                return Promise.reject(error);\n            }\n        });\n    }\n    addTokenChangeListener(listener) {\n        // TODO: We might want to wrap the listener and call it with no args to\n        // avoid a leaky abstraction, but that makes removing the listener harder.\n        if (this.auth_) {\n            this.auth_.addAuthTokenListener(listener);\n        }\n        else {\n            this.authProvider_\n                .get()\n                .then(auth => auth.addAuthTokenListener(listener));\n        }\n    }\n    removeTokenChangeListener(listener) {\n        this.authProvider_\n            .get()\n            .then(auth => auth.removeAuthTokenListener(listener));\n    }\n    notifyForInvalidToken() {\n        let errorMessage = 'Provided authentication credentials for the app named \"' +\n            this.appName_ +\n            '\" are invalid. This usually indicates your app was not ' +\n            'initialized correctly. ';\n        if ('credential' in this.firebaseOptions_) {\n            errorMessage +=\n                'Make sure the \"credential\" property provided to initializeApp() ' +\n                    'is authorized to access the specified \"databaseURL\" and is from the correct ' +\n                    'project.';\n        }\n        else if ('serviceAccount' in this.firebaseOptions_) {\n            errorMessage +=\n                'Make sure the \"serviceAccount\" property provided to initializeApp() ' +\n                    'is authorized to access the specified \"databaseURL\" and is from the correct ' +\n                    'project.';\n        }\n        else {\n            errorMessage +=\n                'Make sure the \"apiKey\" and \"databaseURL\" properties provided to ' +\n                    'initializeApp() match the values provided for your app at ' +\n                    'https://console.firebase.google.com/.';\n        }\n        warn(errorMessage);\n    }\n}\n/* AuthTokenProvider that supplies a constant token. Used by Admin SDK or mockUserToken with emulators. */\nclass EmulatorTokenProvider {\n    constructor(accessToken) {\n        this.accessToken = accessToken;\n    }\n    getToken(forceRefresh) {\n        return Promise.resolve({\n            accessToken: this.accessToken\n        });\n    }\n    addTokenChangeListener(listener) {\n        // Invoke the listener immediately to match the behavior in Firebase Auth\n        // (see packages/auth/src/auth.js#L1807)\n        listener(this.accessToken);\n    }\n    removeTokenChangeListener(listener) { }\n    notifyForInvalidToken() { }\n}\n/** A string that is treated as an admin access token by the RTDB emulator. Used by Admin SDK. */\nEmulatorTokenProvider.OWNER = 'owner';\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 PROTOCOL_VERSION = '5';\nconst VERSION_PARAM = 'v';\nconst TRANSPORT_SESSION_PARAM = 's';\nconst REFERER_PARAM = 'r';\nconst FORGE_REF = 'f';\n// Matches console.firebase.google.com, firebase-console-*.corp.google.com and\n// firebase.corp.google.com\nconst FORGE_DOMAIN_RE = /(console\\.firebase|firebase-console-\\w+\\.corp|firebase\\.corp)\\.google\\.com/;\nconst LAST_SESSION_PARAM = 'ls';\nconst APPLICATION_ID_PARAM = 'p';\nconst APP_CHECK_TOKEN_PARAM = 'ac';\nconst WEBSOCKET = 'websocket';\nconst LONG_POLLING = 'long_polling';\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 class that holds metadata about a Repo object\n */\nclass RepoInfo {\n    /**\n     * @param host - Hostname portion of the url for the repo\n     * @param secure - Whether or not this repo is accessed over ssl\n     * @param namespace - The namespace represented by the repo\n     * @param webSocketOnly - Whether to prefer websockets over all other transports (used by Nest).\n     * @param nodeAdmin - Whether this instance uses Admin SDK credentials\n     * @param persistenceKey - Override the default session persistence storage key\n     */\n    constructor(host, secure, namespace, webSocketOnly, nodeAdmin = false, persistenceKey = '', includeNamespaceInQueryParams = false, isUsingEmulator = false) {\n        this.secure = secure;\n        this.namespace = namespace;\n        this.webSocketOnly = webSocketOnly;\n        this.nodeAdmin = nodeAdmin;\n        this.persistenceKey = persistenceKey;\n        this.includeNamespaceInQueryParams = includeNamespaceInQueryParams;\n        this.isUsingEmulator = isUsingEmulator;\n        this._host = host.toLowerCase();\n        this._domain = this._host.substr(this._host.indexOf('.') + 1);\n        this.internalHost =\n            PersistentStorage.get('host:' + host) || this._host;\n    }\n    isCacheableHost() {\n        return this.internalHost.substr(0, 2) === 's-';\n    }\n    isCustomHost() {\n        return (this._domain !== 'firebaseio.com' &&\n            this._domain !== 'firebaseio-demo.com');\n    }\n    get host() {\n        return this._host;\n    }\n    set host(newHost) {\n        if (newHost !== this.internalHost) {\n            this.internalHost = newHost;\n            if (this.isCacheableHost()) {\n                PersistentStorage.set('host:' + this._host, this.internalHost);\n            }\n        }\n    }\n    toString() {\n        let str = this.toURLString();\n        if (this.persistenceKey) {\n            str += '<' + this.persistenceKey + '>';\n        }\n        return str;\n    }\n    toURLString() {\n        const protocol = this.secure ? 'https://' : 'http://';\n        const query = this.includeNamespaceInQueryParams\n            ? `?ns=${this.namespace}`\n            : '';\n        return `${protocol}${this.host}/${query}`;\n    }\n}\nfunction repoInfoNeedsQueryParam(repoInfo) {\n    return (repoInfo.host !== repoInfo.internalHost ||\n        repoInfo.isCustomHost() ||\n        repoInfo.includeNamespaceInQueryParams);\n}\n/**\n * Returns the websocket URL for this repo\n * @param repoInfo - RepoInfo object\n * @param type - of connection\n * @param params - list\n * @returns The URL for this repo\n */\nfunction repoInfoConnectionURL(repoInfo, type, params) {\n    assert(typeof type === 'string', 'typeof type must == string');\n    assert(typeof params === 'object', 'typeof params must == object');\n    let connURL;\n    if (type === WEBSOCKET) {\n        connURL =\n            (repoInfo.secure ? 'wss://' : 'ws://') + repoInfo.internalHost + '/.ws?';\n    }\n    else if (type === LONG_POLLING) {\n        connURL =\n            (repoInfo.secure ? 'https://' : 'http://') +\n                repoInfo.internalHost +\n                '/.lp?';\n    }\n    else {\n        throw new Error('Unknown connection type: ' + type);\n    }\n    if (repoInfoNeedsQueryParam(repoInfo)) {\n        params['ns'] = repoInfo.namespace;\n    }\n    const pairs = [];\n    each(params, (key, value) => {\n        pairs.push(key + '=' + value);\n    });\n    return connURL + pairs.join('&');\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 * Tracks a collection of stats.\n */\nclass StatsCollection {\n    constructor() {\n        this.counters_ = {};\n    }\n    incrementCounter(name, amount = 1) {\n        if (!contains(this.counters_, name)) {\n            this.counters_[name] = 0;\n        }\n        this.counters_[name] += amount;\n    }\n    get() {\n        return deepCopy(this.counters_);\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 */\nconst collections = {};\nconst reporters = {};\nfunction statsManagerGetCollection(repoInfo) {\n    const hashString = repoInfo.toString();\n    if (!collections[hashString]) {\n        collections[hashString] = new StatsCollection();\n    }\n    return collections[hashString];\n}\nfunction statsManagerGetOrCreateReporter(repoInfo, creatorFunction) {\n    const hashString = repoInfo.toString();\n    if (!reporters[hashString]) {\n        reporters[hashString] = creatorFunction();\n    }\n    return reporters[hashString];\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 * This class ensures the packets from the server arrive in order\n * This class takes data from the server and ensures it gets passed into the callbacks in order.\n */\nclass PacketReceiver {\n    /**\n     * @param onMessage_\n     */\n    constructor(onMessage_) {\n        this.onMessage_ = onMessage_;\n        this.pendingResponses = [];\n        this.currentResponseNum = 0;\n        this.closeAfterResponse = -1;\n        this.onClose = null;\n    }\n    closeAfter(responseNum, callback) {\n        this.closeAfterResponse = responseNum;\n        this.onClose = callback;\n        if (this.closeAfterResponse < this.currentResponseNum) {\n            this.onClose();\n            this.onClose = null;\n        }\n    }\n    /**\n     * Each message from the server comes with a response number, and an array of data. The responseNumber\n     * allows us to ensure that we process them in the right order, since we can't be guaranteed that all\n     * browsers will respond in the same order as the requests we sent\n     */\n    handleResponse(requestNum, data) {\n        this.pendingResponses[requestNum] = data;\n        while (this.pendingResponses[this.currentResponseNum]) {\n            const toProcess = this.pendingResponses[this.currentResponseNum];\n            delete this.pendingResponses[this.currentResponseNum];\n            for (let i = 0; i < toProcess.length; ++i) {\n                if (toProcess[i]) {\n                    exceptionGuard(() => {\n                        this.onMessage_(toProcess[i]);\n                    });\n                }\n            }\n            if (this.currentResponseNum === this.closeAfterResponse) {\n                if (this.onClose) {\n                    this.onClose();\n                    this.onClose = null;\n                }\n                break;\n            }\n            this.currentResponseNum++;\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// URL query parameters associated with longpolling\nconst FIREBASE_LONGPOLL_START_PARAM = 'start';\nconst FIREBASE_LONGPOLL_CLOSE_COMMAND = 'close';\nconst FIREBASE_LONGPOLL_COMMAND_CB_NAME = 'pLPCommand';\nconst FIREBASE_LONGPOLL_DATA_CB_NAME = 'pRTLPCB';\nconst FIREBASE_LONGPOLL_ID_PARAM = 'id';\nconst FIREBASE_LONGPOLL_PW_PARAM = 'pw';\nconst FIREBASE_LONGPOLL_SERIAL_PARAM = 'ser';\nconst FIREBASE_LONGPOLL_CALLBACK_ID_PARAM = 'cb';\nconst FIREBASE_LONGPOLL_SEGMENT_NUM_PARAM = 'seg';\nconst FIREBASE_LONGPOLL_SEGMENTS_IN_PACKET = 'ts';\nconst FIREBASE_LONGPOLL_DATA_PARAM = 'd';\nconst FIREBASE_LONGPOLL_DISCONN_FRAME_REQUEST_PARAM = 'dframe';\n//Data size constants.\n//TODO: Perf: the maximum length actually differs from browser to browser.\n// We should check what browser we're on and set accordingly.\nconst MAX_URL_DATA_SIZE = 1870;\nconst SEG_HEADER_SIZE = 30; //ie: &seg=8299234&ts=982389123&d=\nconst MAX_PAYLOAD_SIZE = MAX_URL_DATA_SIZE - SEG_HEADER_SIZE;\n/**\n * Keepalive period\n * send a fresh request at minimum every 25 seconds. Opera has a maximum request\n * length of 30 seconds that we can't exceed.\n */\nconst KEEPALIVE_REQUEST_INTERVAL = 25000;\n/**\n * How long to wait before aborting a long-polling connection attempt.\n */\nconst LP_CONNECT_TIMEOUT = 30000;\n/**\n * This class manages a single long-polling connection.\n */\nclass BrowserPollConnection {\n    /**\n     * @param connId An identifier for this connection, used for logging\n     * @param repoInfo The info for the endpoint to send data to.\n     * @param applicationId The Firebase App ID for this project.\n     * @param appCheckToken The AppCheck token for this client.\n     * @param authToken The AuthToken to use for this connection.\n     * @param transportSessionId Optional transportSessionid if we are\n     * reconnecting for an existing transport session\n     * @param lastSessionId Optional lastSessionId if the PersistentConnection has\n     * already created a connection previously\n     */\n    constructor(connId, repoInfo, applicationId, appCheckToken, authToken, transportSessionId, lastSessionId) {\n        this.connId = connId;\n        this.repoInfo = repoInfo;\n        this.applicationId = applicationId;\n        this.appCheckToken = appCheckToken;\n        this.authToken = authToken;\n        this.transportSessionId = transportSessionId;\n        this.lastSessionId = lastSessionId;\n        this.bytesSent = 0;\n        this.bytesReceived = 0;\n        this.everConnected_ = false;\n        this.log_ = logWrapper(connId);\n        this.stats_ = statsManagerGetCollection(repoInfo);\n        this.urlFn = (params) => {\n            // Always add the token if we have one.\n            if (this.appCheckToken) {\n                params[APP_CHECK_TOKEN_PARAM] = this.appCheckToken;\n            }\n            return repoInfoConnectionURL(repoInfo, LONG_POLLING, params);\n        };\n    }\n    /**\n     * @param onMessage - Callback when messages arrive\n     * @param onDisconnect - Callback with connection lost.\n     */\n    open(onMessage, onDisconnect) {\n        this.curSegmentNum = 0;\n        this.onDisconnect_ = onDisconnect;\n        this.myPacketOrderer = new PacketReceiver(onMessage);\n        this.isClosed_ = false;\n        this.connectTimeoutTimer_ = setTimeout(() => {\n            this.log_('Timed out trying to connect.');\n            // Make sure we clear the host cache\n            this.onClosed_();\n            this.connectTimeoutTimer_ = null;\n            // eslint-disable-next-line @typescript-eslint/no-explicit-any\n        }, Math.floor(LP_CONNECT_TIMEOUT));\n        // Ensure we delay the creation of the iframe until the DOM is loaded.\n        executeWhenDOMReady(() => {\n            if (this.isClosed_) {\n                return;\n            }\n            //Set up a callback that gets triggered once a connection is set up.\n            this.scriptTagHolder = new FirebaseIFrameScriptHolder((...args) => {\n                const [command, arg1, arg2, arg3, arg4] = args;\n                this.incrementIncomingBytes_(args);\n                if (!this.scriptTagHolder) {\n                    return; // we closed the connection.\n                }\n                if (this.connectTimeoutTimer_) {\n                    clearTimeout(this.connectTimeoutTimer_);\n                    this.connectTimeoutTimer_ = null;\n                }\n                this.everConnected_ = true;\n                if (command === FIREBASE_LONGPOLL_START_PARAM) {\n                    this.id = arg1;\n                    this.password = arg2;\n                }\n                else if (command === FIREBASE_LONGPOLL_CLOSE_COMMAND) {\n                    // Don't clear the host cache. We got a response from the server, so we know it's reachable\n                    if (arg1) {\n                        // We aren't expecting any more data (other than what the server's already in the process of sending us\n                        // through our already open polls), so don't send any more.\n                        this.scriptTagHolder.sendNewPolls = false;\n                        // arg1 in this case is the last response number sent by the server. We should try to receive\n                        // all of the responses up to this one before closing\n                        this.myPacketOrderer.closeAfter(arg1, () => {\n                            this.onClosed_();\n                        });\n                    }\n                    else {\n                        this.onClosed_();\n                    }\n                }\n                else {\n                    throw new Error('Unrecognized command received: ' + command);\n                }\n            }, (...args) => {\n                const [pN, data] = args;\n                this.incrementIncomingBytes_(args);\n                this.myPacketOrderer.handleResponse(pN, data);\n            }, () => {\n                this.onClosed_();\n            }, this.urlFn);\n            //Send the initial request to connect. The serial number is simply to keep the browser from pulling previous results\n            //from cache.\n            const urlParams = {};\n            urlParams[FIREBASE_LONGPOLL_START_PARAM] = 't';\n            urlParams[FIREBASE_LONGPOLL_SERIAL_PARAM] = Math.floor(Math.random() * 100000000);\n            if (this.scriptTagHolder.uniqueCallbackIdentifier) {\n                urlParams[FIREBASE_LONGPOLL_CALLBACK_ID_PARAM] =\n                    this.scriptTagHolder.uniqueCallbackIdentifier;\n            }\n            urlParams[VERSION_PARAM] = PROTOCOL_VERSION;\n            if (this.transportSessionId) {\n                urlParams[TRANSPORT_SESSION_PARAM] = this.transportSessionId;\n            }\n            if (this.lastSessionId) {\n                urlParams[LAST_SESSION_PARAM] = this.lastSessionId;\n            }\n            if (this.applicationId) {\n                urlParams[APPLICATION_ID_PARAM] = this.applicationId;\n            }\n            if (this.appCheckToken) {\n                urlParams[APP_CHECK_TOKEN_PARAM] = this.appCheckToken;\n            }\n            if (typeof location !== 'undefined' &&\n                location.hostname &&\n                FORGE_DOMAIN_RE.test(location.hostname)) {\n                urlParams[REFERER_PARAM] = FORGE_REF;\n            }\n            const connectURL = this.urlFn(urlParams);\n            this.log_('Connecting via long-poll to ' + connectURL);\n            this.scriptTagHolder.addTag(connectURL, () => {\n                /* do nothing */\n            });\n        });\n    }\n    /**\n     * Call this when a handshake has completed successfully and we want to consider the connection established\n     */\n    start() {\n        this.scriptTagHolder.startLongPoll(this.id, this.password);\n        this.addDisconnectPingFrame(this.id, this.password);\n    }\n    /**\n     * Forces long polling to be considered as a potential transport\n     */\n    static forceAllow() {\n        BrowserPollConnection.forceAllow_ = true;\n    }\n    /**\n     * Forces longpolling to not be considered as a potential transport\n     */\n    static forceDisallow() {\n        BrowserPollConnection.forceDisallow_ = true;\n    }\n    // Static method, use string literal so it can be accessed in a generic way\n    static isAvailable() {\n        if (isNodeSdk()) {\n            return false;\n        }\n        else if (BrowserPollConnection.forceAllow_) {\n            return true;\n        }\n        else {\n            // NOTE: In React-Native there's normally no 'document', but if you debug a React-Native app in\n            // the Chrome debugger, 'document' is defined, but document.createElement is null (2015/06/08).\n            return (!BrowserPollConnection.forceDisallow_ &&\n                typeof document !== 'undefined' &&\n                document.createElement != null &&\n                !isChromeExtensionContentScript() &&\n                !isWindowsStoreApp());\n        }\n    }\n    /**\n     * No-op for polling\n     */\n    markConnectionHealthy() { }\n    /**\n     * Stops polling and cleans up the iframe\n     */\n    shutdown_() {\n        this.isClosed_ = true;\n        if (this.scriptTagHolder) {\n            this.scriptTagHolder.close();\n            this.scriptTagHolder = null;\n        }\n        //remove the disconnect frame, which will trigger an XHR call to the server to tell it we're leaving.\n        if (this.myDisconnFrame) {\n            document.body.removeChild(this.myDisconnFrame);\n            this.myDisconnFrame = null;\n        }\n        if (this.connectTimeoutTimer_) {\n            clearTimeout(this.connectTimeoutTimer_);\n            this.connectTimeoutTimer_ = null;\n        }\n    }\n    /**\n     * Triggered when this transport is closed\n     */\n    onClosed_() {\n        if (!this.isClosed_) {\n            this.log_('Longpoll is closing itself');\n            this.shutdown_();\n            if (this.onDisconnect_) {\n                this.onDisconnect_(this.everConnected_);\n                this.onDisconnect_ = null;\n            }\n        }\n    }\n    /**\n     * External-facing close handler. RealTime has requested we shut down. Kill our connection and tell the server\n     * that we've left.\n     */\n    close() {\n        if (!this.isClosed_) {\n            this.log_('Longpoll is being closed.');\n            this.shutdown_();\n        }\n    }\n    /**\n     * Send the JSON object down to the server. It will need to be stringified, base64 encoded, and then\n     * broken into chunks (since URLs have a small maximum length).\n     * @param data - The JSON data to transmit.\n     */\n    send(data) {\n        const dataStr = stringify(data);\n        this.bytesSent += dataStr.length;\n        this.stats_.incrementCounter('bytes_sent', dataStr.length);\n        //first, lets get the base64-encoded data\n        const base64data = base64Encode(dataStr);\n        //We can only fit a certain amount in each URL, so we need to split this request\n        //up into multiple pieces if it doesn't fit in one request.\n        const dataSegs = splitStringBySize(base64data, MAX_PAYLOAD_SIZE);\n        //Enqueue each segment for transmission. We assign each chunk a sequential ID and a total number\n        //of segments so that we can reassemble the packet on the server.\n        for (let i = 0; i < dataSegs.length; i++) {\n            this.scriptTagHolder.enqueueSegment(this.curSegmentNum, dataSegs.length, dataSegs[i]);\n            this.curSegmentNum++;\n        }\n    }\n    /**\n     * This is how we notify the server that we're leaving.\n     * We aren't able to send requests with DHTML on a window close event, but we can\n     * trigger XHR requests in some browsers (everything but Opera basically).\n     */\n    addDisconnectPingFrame(id, pw) {\n        if (isNodeSdk()) {\n            return;\n        }\n        this.myDisconnFrame = document.createElement('iframe');\n        const urlParams = {};\n        urlParams[FIREBASE_LONGPOLL_DISCONN_FRAME_REQUEST_PARAM] = 't';\n        urlParams[FIREBASE_LONGPOLL_ID_PARAM] = id;\n        urlParams[FIREBASE_LONGPOLL_PW_PARAM] = pw;\n        this.myDisconnFrame.src = this.urlFn(urlParams);\n        this.myDisconnFrame.style.display = 'none';\n        document.body.appendChild(this.myDisconnFrame);\n    }\n    /**\n     * Used to track the bytes received by this client\n     */\n    incrementIncomingBytes_(args) {\n        // TODO: This is an annoying perf hit just to track the number of incoming bytes.  Maybe it should be opt-in.\n        const bytesReceived = stringify(args).length;\n        this.bytesReceived += bytesReceived;\n        this.stats_.incrementCounter('bytes_received', bytesReceived);\n    }\n}\n/*********************************************************************************************\n * A wrapper around an iframe that is used as a long-polling script holder.\n *********************************************************************************************/\nclass FirebaseIFrameScriptHolder {\n    /**\n     * @param commandCB - The callback to be called when control commands are received from the server.\n     * @param onMessageCB - The callback to be triggered when responses arrive from the server.\n     * @param onDisconnect - The callback to be triggered when this tag holder is closed\n     * @param urlFn - A function that provides the URL of the endpoint to send data to.\n     */\n    constructor(commandCB, onMessageCB, onDisconnect, urlFn) {\n        this.onDisconnect = onDisconnect;\n        this.urlFn = urlFn;\n        //We maintain a count of all of the outstanding requests, because if we have too many active at once it can cause\n        //problems in some browsers.\n        this.outstandingRequests = new Set();\n        //A queue of the pending segments waiting for transmission to the server.\n        this.pendingSegs = [];\n        //A serial number. We use this for two things:\n        // 1) A way to ensure the browser doesn't cache responses to polls\n        // 2) A way to make the server aware when long-polls arrive in a different order than we started them. The\n        //    server needs to release both polls in this case or it will cause problems in Opera since Opera can only execute\n        //    JSONP code in the order it was added to the iframe.\n        this.currentSerial = Math.floor(Math.random() * 100000000);\n        // This gets set to false when we're \"closing down\" the connection (e.g. we're switching transports but there's still\n        // incoming data from the server that we're waiting for).\n        this.sendNewPolls = true;\n        if (!isNodeSdk()) {\n            //Each script holder registers a couple of uniquely named callbacks with the window. These are called from the\n            //iframes where we put the long-polling script tags. We have two callbacks:\n            //   1) Command Callback - Triggered for control issues, like starting a connection.\n            //   2) Message Callback - Triggered when new data arrives.\n            this.uniqueCallbackIdentifier = LUIDGenerator();\n            window[FIREBASE_LONGPOLL_COMMAND_CB_NAME + this.uniqueCallbackIdentifier] = commandCB;\n            window[FIREBASE_LONGPOLL_DATA_CB_NAME + this.uniqueCallbackIdentifier] =\n                onMessageCB;\n            //Create an iframe for us to add script tags to.\n            this.myIFrame = FirebaseIFrameScriptHolder.createIFrame_();\n            // Set the iframe's contents.\n            let script = '';\n            // if we set a javascript url, it's IE and we need to set the document domain. The javascript url is sufficient\n            // for ie9, but ie8 needs to do it again in the document itself.\n            if (this.myIFrame.src &&\n                this.myIFrame.src.substr(0, 'javascript:'.length) === 'javascript:') {\n                const currentDomain = document.domain;\n                script = '<script>document.domain=\"' + currentDomain + '\";</script>';\n            }\n            const iframeContents = '<html><body>' + script + '</body></html>';\n            try {\n                this.myIFrame.doc.open();\n                this.myIFrame.doc.write(iframeContents);\n                this.myIFrame.doc.close();\n            }\n            catch (e) {\n                log('frame writing exception');\n                if (e.stack) {\n                    log(e.stack);\n                }\n                log(e);\n            }\n        }\n        else {\n            this.commandCB = commandCB;\n            this.onMessageCB = onMessageCB;\n        }\n    }\n    /**\n     * Each browser has its own funny way to handle iframes. Here we mush them all together into one object that I can\n     * actually use.\n     */\n    static createIFrame_() {\n        const iframe = document.createElement('iframe');\n        iframe.style.display = 'none';\n        // This is necessary in order to initialize the document inside the iframe\n        if (document.body) {\n            document.body.appendChild(iframe);\n            try {\n                // If document.domain has been modified in IE, this will throw an error, and we need to set the\n                // domain of the iframe's document manually. We can do this via a javascript: url as the src attribute\n                // Also note that we must do this *after* the iframe has been appended to the page. Otherwise it doesn't work.\n                const a = iframe.contentWindow.document;\n                if (!a) {\n                    // Apologies for the log-spam, I need to do something to keep closure from optimizing out the assignment above.\n                    log('No IE domain setting required');\n                }\n            }\n            catch (e) {\n                const domain = document.domain;\n                iframe.src =\n                    \"javascript:void((function(){document.open();document.domain='\" +\n                        domain +\n                        \"';document.close();})())\";\n            }\n        }\n        else {\n            // LongPollConnection attempts to delay initialization until the document is ready, so hopefully this\n            // never gets hit.\n            throw 'Document body has not initialized. Wait to initialize Firebase until after the document is ready.';\n        }\n        // Get the document of the iframe in a browser-specific way.\n        if (iframe.contentDocument) {\n            iframe.doc = iframe.contentDocument; // Firefox, Opera, Safari\n        }\n        else if (iframe.contentWindow) {\n            iframe.doc = iframe.contentWindow.document; // Internet Explorer\n            // eslint-disable-next-line @typescript-eslint/no-explicit-any\n        }\n        else if (iframe.document) {\n            // eslint-disable-next-line @typescript-eslint/no-explicit-any\n            iframe.doc = iframe.document; //others?\n        }\n        return iframe;\n    }\n    /**\n     * Cancel all outstanding queries and remove the frame.\n     */\n    close() {\n        //Mark this iframe as dead, so no new requests are sent.\n        this.alive = false;\n        if (this.myIFrame) {\n            //We have to actually remove all of the html inside this iframe before removing it from the\n            //window, or IE will continue loading and executing the script tags we've already added, which\n            //can lead to some errors being thrown. Setting textContent seems to be the safest way to do this.\n            this.myIFrame.doc.body.textContent = '';\n            setTimeout(() => {\n                if (this.myIFrame !== null) {\n                    document.body.removeChild(this.myIFrame);\n                    this.myIFrame = null;\n                }\n            }, Math.floor(0));\n        }\n        // Protect from being called recursively.\n        const onDisconnect = this.onDisconnect;\n        if (onDisconnect) {\n            this.onDisconnect = null;\n            onDisconnect();\n        }\n    }\n    /**\n     * Actually start the long-polling session by adding the first script tag(s) to the iframe.\n     * @param id - The ID of this connection\n     * @param pw - The password for this connection\n     */\n    startLongPoll(id, pw) {\n        this.myID = id;\n        this.myPW = pw;\n        this.alive = true;\n        //send the initial request. If there are requests queued, make sure that we transmit as many as we are currently able to.\n        while (this.newRequest_()) { }\n    }\n    /**\n     * This is called any time someone might want a script tag to be added. It adds a script tag when there aren't\n     * too many outstanding requests and we are still alive.\n     *\n     * If there are outstanding packet segments to send, it sends one. If there aren't, it sends a long-poll anyways if\n     * needed.\n     */\n    newRequest_() {\n        // We keep one outstanding request open all the time to receive data, but if we need to send data\n        // (pendingSegs.length > 0) then we create a new request to send the data.  The server will automatically\n        // close the old request.\n        if (this.alive &&\n            this.sendNewPolls &&\n            this.outstandingRequests.size < (this.pendingSegs.length > 0 ? 2 : 1)) {\n            //construct our url\n            this.currentSerial++;\n            const urlParams = {};\n            urlParams[FIREBASE_LONGPOLL_ID_PARAM] = this.myID;\n            urlParams[FIREBASE_LONGPOLL_PW_PARAM] = this.myPW;\n            urlParams[FIREBASE_LONGPOLL_SERIAL_PARAM] = this.currentSerial;\n            let theURL = this.urlFn(urlParams);\n            //Now add as much data as we can.\n            let curDataString = '';\n            let i = 0;\n            while (this.pendingSegs.length > 0) {\n                //first, lets see if the next segment will fit.\n                const nextSeg = this.pendingSegs[0];\n                if (nextSeg.d.length +\n                    SEG_HEADER_SIZE +\n                    curDataString.length <=\n                    MAX_URL_DATA_SIZE) {\n                    //great, the segment will fit. Lets append it.\n                    const theSeg = this.pendingSegs.shift();\n                    curDataString =\n                        curDataString +\n                            '&' +\n                            FIREBASE_LONGPOLL_SEGMENT_NUM_PARAM +\n                            i +\n                            '=' +\n                            theSeg.seg +\n                            '&' +\n                            FIREBASE_LONGPOLL_SEGMENTS_IN_PACKET +\n                            i +\n                            '=' +\n                            theSeg.ts +\n                            '&' +\n                            FIREBASE_LONGPOLL_DATA_PARAM +\n                            i +\n                            '=' +\n                            theSeg.d;\n                    i++;\n                }\n                else {\n                    break;\n                }\n            }\n            theURL = theURL + curDataString;\n            this.addLongPollTag_(theURL, this.currentSerial);\n            return true;\n        }\n        else {\n            return false;\n        }\n    }\n    /**\n     * Queue a packet for transmission to the server.\n     * @param segnum - A sequential id for this packet segment used for reassembly\n     * @param totalsegs - The total number of segments in this packet\n     * @param data - The data for this segment.\n     */\n    enqueueSegment(segnum, totalsegs, data) {\n        //add this to the queue of segments to send.\n        this.pendingSegs.push({ seg: segnum, ts: totalsegs, d: data });\n        //send the data immediately if there isn't already data being transmitted, unless\n        //startLongPoll hasn't been called yet.\n        if (this.alive) {\n            this.newRequest_();\n        }\n    }\n    /**\n     * Add a script tag for a regular long-poll request.\n     * @param url - The URL of the script tag.\n     * @param serial - The serial number of the request.\n     */\n    addLongPollTag_(url, serial) {\n        //remember that we sent this request.\n        this.outstandingRequests.add(serial);\n        const doNewRequest = () => {\n            this.outstandingRequests.delete(serial);\n            this.newRequest_();\n        };\n        // If this request doesn't return on its own accord (by the server sending us some data), we'll\n        // create a new one after the KEEPALIVE interval to make sure we always keep a fresh request open.\n        const keepaliveTimeout = setTimeout(doNewRequest, Math.floor(KEEPALIVE_REQUEST_INTERVAL));\n        const readyStateCB = () => {\n            // Request completed.  Cancel the keepalive.\n            clearTimeout(keepaliveTimeout);\n            // Trigger a new request so we can continue receiving data.\n            doNewRequest();\n        };\n        this.addTag(url, readyStateCB);\n    }\n    /**\n     * Add an arbitrary script tag to the iframe.\n     * @param url - The URL for the script tag source.\n     * @param loadCB - A callback to be triggered once the script has loaded.\n     */\n    addTag(url, loadCB) {\n        if (isNodeSdk()) {\n            // eslint-disable-next-line @typescript-eslint/no-explicit-any\n            this.doNodeLongPoll(url, loadCB);\n        }\n        else {\n            setTimeout(() => {\n                try {\n                    // if we're already closed, don't add this poll\n                    if (!this.sendNewPolls) {\n                        return;\n                    }\n                    const newScript = this.myIFrame.doc.createElement('script');\n                    newScript.type = 'text/javascript';\n                    newScript.async = true;\n                    newScript.src = url;\n                    // eslint-disable-next-line @typescript-eslint/no-explicit-any\n                    newScript.onload = newScript.onreadystatechange =\n                        function () {\n                            // eslint-disable-next-line @typescript-eslint/no-explicit-any\n                            const rstate = newScript.readyState;\n                            if (!rstate || rstate === 'loaded' || rstate === 'complete') {\n                                // eslint-disable-next-line @typescript-eslint/no-explicit-any\n                                newScript.onload = newScript.onreadystatechange = null;\n                                if (newScript.parentNode) {\n                                    newScript.parentNode.removeChild(newScript);\n                                }\n                                loadCB();\n                            }\n                        };\n                    newScript.onerror = () => {\n                        log('Long-poll script failed to load: ' + url);\n                        this.sendNewPolls = false;\n                        this.close();\n                    };\n                    this.myIFrame.doc.body.appendChild(newScript);\n                }\n                catch (e) {\n                    // TODO: we should make this error visible somehow\n                }\n            }, Math.floor(1));\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 */\nconst WEBSOCKET_MAX_FRAME_SIZE = 16384;\nconst WEBSOCKET_KEEPALIVE_INTERVAL = 45000;\nlet WebSocketImpl = null;\nif (typeof MozWebSocket !== 'undefined') {\n    WebSocketImpl = MozWebSocket;\n}\nelse if (typeof WebSocket !== 'undefined') {\n    WebSocketImpl = WebSocket;\n}\n/**\n * Create a new websocket connection with the given callbacks.\n */\nclass WebSocketConnection {\n    /**\n     * @param connId identifier for this transport\n     * @param repoInfo The info for the websocket endpoint.\n     * @param applicationId The Firebase App ID for this project.\n     * @param appCheckToken The App Check Token for this client.\n     * @param authToken The Auth Token for this client.\n     * @param transportSessionId Optional transportSessionId if this is connecting\n     * to an existing transport session\n     * @param lastSessionId Optional lastSessionId if there was a previous\n     * connection\n     */\n    constructor(connId, repoInfo, applicationId, appCheckToken, authToken, transportSessionId, lastSessionId) {\n        this.connId = connId;\n        this.applicationId = applicationId;\n        this.appCheckToken = appCheckToken;\n        this.authToken = authToken;\n        this.keepaliveTimer = null;\n        this.frames = null;\n        this.totalFrames = 0;\n        this.bytesSent = 0;\n        this.bytesReceived = 0;\n        this.log_ = logWrapper(this.connId);\n        this.stats_ = statsManagerGetCollection(repoInfo);\n        this.connURL = WebSocketConnection.connectionURL_(repoInfo, transportSessionId, lastSessionId, appCheckToken, applicationId);\n        this.nodeAdmin = repoInfo.nodeAdmin;\n    }\n    /**\n     * @param repoInfo - The info for the websocket endpoint.\n     * @param transportSessionId - Optional transportSessionId if this is connecting to an existing transport\n     *                                         session\n     * @param lastSessionId - Optional lastSessionId if there was a previous connection\n     * @returns connection url\n     */\n    static connectionURL_(repoInfo, transportSessionId, lastSessionId, appCheckToken, applicationId) {\n        const urlParams = {};\n        urlParams[VERSION_PARAM] = PROTOCOL_VERSION;\n        if (!isNodeSdk() &&\n            typeof location !== 'undefined' &&\n            location.hostname &&\n            FORGE_DOMAIN_RE.test(location.hostname)) {\n            urlParams[REFERER_PARAM] = FORGE_REF;\n        }\n        if (transportSessionId) {\n            urlParams[TRANSPORT_SESSION_PARAM] = transportSessionId;\n        }\n        if (lastSessionId) {\n            urlParams[LAST_SESSION_PARAM] = lastSessionId;\n        }\n        if (appCheckToken) {\n            urlParams[APP_CHECK_TOKEN_PARAM] = appCheckToken;\n        }\n        if (applicationId) {\n            urlParams[APPLICATION_ID_PARAM] = applicationId;\n        }\n        return repoInfoConnectionURL(repoInfo, WEBSOCKET, urlParams);\n    }\n    /**\n     * @param onMessage - Callback when messages arrive\n     * @param onDisconnect - Callback with connection lost.\n     */\n    open(onMessage, onDisconnect) {\n        this.onDisconnect = onDisconnect;\n        this.onMessage = onMessage;\n        this.log_('Websocket connecting to ' + this.connURL);\n        this.everConnected_ = false;\n        // Assume failure until proven otherwise.\n        PersistentStorage.set('previous_websocket_failure', true);\n        try {\n            let options;\n            if (isNodeSdk()) {\n                const device = this.nodeAdmin ? 'AdminNode' : 'Node';\n                // UA Format: Firebase/<wire_protocol>/<sdk_version>/<platform>/<device>\n                options = {\n                    headers: {\n                        'User-Agent': `Firebase/${PROTOCOL_VERSION}/${SDK_VERSION}/${process.platform}/${device}`,\n                        'X-Firebase-GMPID': this.applicationId || ''\n                    }\n                };\n                // If using Node with admin creds, AppCheck-related checks are unnecessary.\n                // Note that we send the credentials here even if they aren't admin credentials, which is\n                // not a problem.\n                // Note that this header is just used to bypass appcheck, and the token should still be sent\n                // through the websocket connection once it is established.\n                if (this.authToken) {\n                    options.headers['Authorization'] = `Bearer ${this.authToken}`;\n                }\n                if (this.appCheckToken) {\n                    options.headers['X-Firebase-AppCheck'] = this.appCheckToken;\n                }\n                // Plumb appropriate http_proxy environment variable into faye-websocket if it exists.\n                const env = process['env'];\n                const proxy = this.connURL.indexOf('wss://') === 0\n                    ? env['HTTPS_PROXY'] || env['https_proxy']\n                    : env['HTTP_PROXY'] || env['http_proxy'];\n                if (proxy) {\n                    options['proxy'] = { origin: proxy };\n                }\n            }\n            this.mySock = new WebSocketImpl(this.connURL, [], options);\n        }\n        catch (e) {\n            this.log_('Error instantiating WebSocket.');\n            const error = e.message || e.data;\n            if (error) {\n                this.log_(error);\n            }\n            this.onClosed_();\n            return;\n        }\n        this.mySock.onopen = () => {\n            this.log_('Websocket connected.');\n            this.everConnected_ = true;\n        };\n        this.mySock.onclose = () => {\n            this.log_('Websocket connection was disconnected.');\n            this.mySock = null;\n            this.onClosed_();\n        };\n        this.mySock.onmessage = m => {\n            this.handleIncomingFrame(m);\n        };\n        this.mySock.onerror = e => {\n            this.log_('WebSocket error.  Closing connection.');\n            // eslint-disable-next-line @typescript-eslint/no-explicit-any\n            const error = e.message || e.data;\n            if (error) {\n                this.log_(error);\n            }\n            this.onClosed_();\n        };\n    }\n    /**\n     * No-op for websockets, we don't need to do anything once the connection is confirmed as open\n     */\n    start() { }\n    static forceDisallow() {\n        WebSocketConnection.forceDisallow_ = true;\n    }\n    static isAvailable() {\n        let isOldAndroid = false;\n        if (typeof navigator !== 'undefined' && navigator.userAgent) {\n            const oldAndroidRegex = /Android ([0-9]{0,}\\.[0-9]{0,})/;\n            const oldAndroidMatch = navigator.userAgent.match(oldAndroidRegex);\n            if (oldAndroidMatch && oldAndroidMatch.length > 1) {\n                if (parseFloat(oldAndroidMatch[1]) < 4.4) {\n                    isOldAndroid = true;\n                }\n            }\n        }\n        return (!isOldAndroid &&\n            WebSocketImpl !== null &&\n            !WebSocketConnection.forceDisallow_);\n    }\n    /**\n     * Returns true if we previously failed to connect with this transport.\n     */\n    static previouslyFailed() {\n        // If our persistent storage is actually only in-memory storage,\n        // we default to assuming that it previously failed to be safe.\n        return (PersistentStorage.isInMemoryStorage ||\n            PersistentStorage.get('previous_websocket_failure') === true);\n    }\n    markConnectionHealthy() {\n        PersistentStorage.remove('previous_websocket_failure');\n    }\n    appendFrame_(data) {\n        this.frames.push(data);\n        if (this.frames.length === this.totalFrames) {\n            const fullMess = this.frames.join('');\n            this.frames = null;\n            const jsonMess = jsonEval(fullMess);\n            //handle the message\n            this.onMessage(jsonMess);\n        }\n    }\n    /**\n     * @param frameCount - The number of frames we are expecting from the server\n     */\n    handleNewFrameCount_(frameCount) {\n        this.totalFrames = frameCount;\n        this.frames = [];\n    }\n    /**\n     * Attempts to parse a frame count out of some text. If it can't, assumes a value of 1\n     * @returns Any remaining data to be process, or null if there is none\n     */\n    extractFrameCount_(data) {\n        assert(this.frames === null, 'We already have a frame buffer');\n        // TODO: The server is only supposed to send up to 9999 frames (i.e. length <= 4), but that isn't being enforced\n        // currently.  So allowing larger frame counts (length <= 6).  See https://app.asana.com/0/search/8688598998380/8237608042508\n        if (data.length <= 6) {\n            const frameCount = Number(data);\n            if (!isNaN(frameCount)) {\n                this.handleNewFrameCount_(frameCount);\n                return null;\n            }\n        }\n        this.handleNewFrameCount_(1);\n        return data;\n    }\n    /**\n     * Process a websocket frame that has arrived from the server.\n     * @param mess - The frame data\n     */\n    handleIncomingFrame(mess) {\n        if (this.mySock === null) {\n            return; // Chrome apparently delivers incoming packets even after we .close() the connection sometimes.\n        }\n        const data = mess['data'];\n        this.bytesReceived += data.length;\n        this.stats_.incrementCounter('bytes_received', data.length);\n        this.resetKeepAlive();\n        if (this.frames !== null) {\n            // we're buffering\n            this.appendFrame_(data);\n        }\n        else {\n            // try to parse out a frame count, otherwise, assume 1 and process it\n            const remainingData = this.extractFrameCount_(data);\n            if (remainingData !== null) {\n                this.appendFrame_(remainingData);\n            }\n        }\n    }\n    /**\n     * Send a message to the server\n     * @param data - The JSON object to transmit\n     */\n    send(data) {\n        this.resetKeepAlive();\n        const dataStr = stringify(data);\n        this.bytesSent += dataStr.length;\n        this.stats_.incrementCounter('bytes_sent', dataStr.length);\n        //We can only fit a certain amount in each websocket frame, so we need to split this request\n        //up into multiple pieces if it doesn't fit in one request.\n        const dataSegs = splitStringBySize(dataStr, WEBSOCKET_MAX_FRAME_SIZE);\n        //Send the length header\n        if (dataSegs.length > 1) {\n            this.sendString_(String(dataSegs.length));\n        }\n        //Send the actual data in segments.\n        for (let i = 0; i < dataSegs.length; i++) {\n            this.sendString_(dataSegs[i]);\n        }\n    }\n    shutdown_() {\n        this.isClosed_ = true;\n        if (this.keepaliveTimer) {\n            clearInterval(this.keepaliveTimer);\n            this.keepaliveTimer = null;\n        }\n        if (this.mySock) {\n            this.mySock.close();\n            this.mySock = null;\n        }\n    }\n    onClosed_() {\n        if (!this.isClosed_) {\n            this.log_('WebSocket is closing itself');\n            this.shutdown_();\n            // since this is an internal close, trigger the close listener\n            if (this.onDisconnect) {\n                this.onDisconnect(this.everConnected_);\n                this.onDisconnect = null;\n            }\n        }\n    }\n    /**\n     * External-facing close handler.\n     * Close the websocket and kill the connection.\n     */\n    close() {\n        if (!this.isClosed_) {\n            this.log_('WebSocket is being closed');\n            this.shutdown_();\n        }\n    }\n    /**\n     * Kill the current keepalive timer and start a new one, to ensure that it always fires N seconds after\n     * the last activity.\n     */\n    resetKeepAlive() {\n        clearInterval(this.keepaliveTimer);\n        this.keepaliveTimer = setInterval(() => {\n            //If there has been no websocket activity for a while, send a no-op\n            if (this.mySock) {\n                this.sendString_('0');\n            }\n            this.resetKeepAlive();\n            // eslint-disable-next-line @typescript-eslint/no-explicit-any\n        }, Math.floor(WEBSOCKET_KEEPALIVE_INTERVAL));\n    }\n    /**\n     * Send a string over the websocket.\n     *\n     * @param str - String to send.\n     */\n    sendString_(str) {\n        // Firefox seems to sometimes throw exceptions (NS_ERROR_UNEXPECTED) from websocket .send()\n        // calls for some unknown reason.  We treat these as an error and disconnect.\n        // See https://app.asana.com/0/58926111402292/68021340250410\n        try {\n            this.mySock.send(str);\n        }\n        catch (e) {\n            this.log_('Exception thrown from WebSocket.send():', e.message || e.data, 'Closing connection.');\n            setTimeout(this.onClosed_.bind(this), 0);\n        }\n    }\n}\n/**\n * Number of response before we consider the connection \"healthy.\"\n */\nWebSocketConnection.responsesRequiredToBeHealthy = 2;\n/**\n * Time to wait for the connection te become healthy before giving up.\n */\nWebSocketConnection.healthyTimeout = 30000;\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 * Currently simplistic, this class manages what transport a Connection should use at various stages of its\n * lifecycle.\n *\n * It starts with longpolling in a browser, and httppolling on node. It then upgrades to websockets if\n * they are available.\n */\nclass TransportManager {\n    static get ALL_TRANSPORTS() {\n        return [BrowserPollConnection, WebSocketConnection];\n    }\n    /**\n     * Returns whether transport has been selected to ensure WebSocketConnection or BrowserPollConnection are not called after\n     * TransportManager has already set up transports_\n     */\n    static get IS_TRANSPORT_INITIALIZED() {\n        return this.globalTransportInitialized_;\n    }\n    /**\n     * @param repoInfo - Metadata around the namespace we're connecting to\n     */\n    constructor(repoInfo) {\n        this.initTransports_(repoInfo);\n    }\n    initTransports_(repoInfo) {\n        const isWebSocketsAvailable = WebSocketConnection && WebSocketConnection['isAvailable']();\n        let isSkipPollConnection = isWebSocketsAvailable && !WebSocketConnection.previouslyFailed();\n        if (repoInfo.webSocketOnly) {\n            if (!isWebSocketsAvailable) {\n                warn(\"wss:// URL used, but browser isn't known to support websockets.  Trying anyway.\");\n            }\n            isSkipPollConnection = true;\n        }\n        if (isSkipPollConnection) {\n            this.transports_ = [WebSocketConnection];\n        }\n        else {\n            const transports = (this.transports_ = []);\n            for (const transport of TransportManager.ALL_TRANSPORTS) {\n                if (transport && transport['isAvailable']()) {\n                    transports.push(transport);\n                }\n            }\n            TransportManager.globalTransportInitialized_ = true;\n        }\n    }\n    /**\n     * @returns The constructor for the initial transport to use\n     */\n    initialTransport() {\n        if (this.transports_.length > 0) {\n            return this.transports_[0];\n        }\n        else {\n            throw new Error('No transports available');\n        }\n    }\n    /**\n     * @returns The constructor for the next transport, or null\n     */\n    upgradeTransport() {\n        if (this.transports_.length > 1) {\n            return this.transports_[1];\n        }\n        else {\n            return null;\n        }\n    }\n}\n// Keeps track of whether the TransportManager has already chosen a transport to use\nTransportManager.globalTransportInitialized_ = false;\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// Abort upgrade attempt if it takes longer than 60s.\nconst UPGRADE_TIMEOUT = 60000;\n// For some transports (WebSockets), we need to \"validate\" the transport by exchanging a few requests and responses.\n// If we haven't sent enough requests within 5s, we'll start sending noop ping requests.\nconst DELAY_BEFORE_SENDING_EXTRA_REQUESTS = 5000;\n// If the initial data sent triggers a lot of bandwidth (i.e. it's a large put or a listen for a large amount of data)\n// then we may not be able to exchange our ping/pong requests within the healthy timeout.  So if we reach the timeout\n// but we've sent/received enough bytes, we don't cancel the connection.\nconst BYTES_SENT_HEALTHY_OVERRIDE = 10 * 1024;\nconst BYTES_RECEIVED_HEALTHY_OVERRIDE = 100 * 1024;\nconst MESSAGE_TYPE = 't';\nconst MESSAGE_DATA = 'd';\nconst CONTROL_SHUTDOWN = 's';\nconst CONTROL_RESET = 'r';\nconst CONTROL_ERROR = 'e';\nconst CONTROL_PONG = 'o';\nconst SWITCH_ACK = 'a';\nconst END_TRANSMISSION = 'n';\nconst PING = 'p';\nconst SERVER_HELLO = 'h';\n/**\n * Creates a new real-time connection to the server using whichever method works\n * best in the current browser.\n */\nclass Connection {\n    /**\n     * @param id - an id for this connection\n     * @param repoInfo_ - the info for the endpoint to connect to\n     * @param applicationId_ - the Firebase App ID for this project\n     * @param appCheckToken_ - The App Check Token for this device.\n     * @param authToken_ - The auth token for this session.\n     * @param onMessage_ - the callback to be triggered when a server-push message arrives\n     * @param onReady_ - the callback to be triggered when this connection is ready to send messages.\n     * @param onDisconnect_ - the callback to be triggered when a connection was lost\n     * @param onKill_ - the callback to be triggered when this connection has permanently shut down.\n     * @param lastSessionId - last session id in persistent connection. is used to clean up old session in real-time server\n     */\n    constructor(id, repoInfo_, applicationId_, appCheckToken_, authToken_, onMessage_, onReady_, onDisconnect_, onKill_, lastSessionId) {\n        this.id = id;\n        this.repoInfo_ = repoInfo_;\n        this.applicationId_ = applicationId_;\n        this.appCheckToken_ = appCheckToken_;\n        this.authToken_ = authToken_;\n        this.onMessage_ = onMessage_;\n        this.onReady_ = onReady_;\n        this.onDisconnect_ = onDisconnect_;\n        this.onKill_ = onKill_;\n        this.lastSessionId = lastSessionId;\n        this.connectionCount = 0;\n        this.pendingDataMessages = [];\n        this.state_ = 0 /* RealtimeState.CONNECTING */;\n        this.log_ = logWrapper('c:' + this.id + ':');\n        this.transportManager_ = new TransportManager(repoInfo_);\n        this.log_('Connection created');\n        this.start_();\n    }\n    /**\n     * Starts a connection attempt\n     */\n    start_() {\n        const conn = this.transportManager_.initialTransport();\n        this.conn_ = new conn(this.nextTransportId_(), this.repoInfo_, this.applicationId_, this.appCheckToken_, this.authToken_, null, this.lastSessionId);\n        // For certain transports (WebSockets), we need to send and receive several messages back and forth before we\n        // can consider the transport healthy.\n        this.primaryResponsesRequired_ = conn['responsesRequiredToBeHealthy'] || 0;\n        const onMessageReceived = this.connReceiver_(this.conn_);\n        const onConnectionLost = this.disconnReceiver_(this.conn_);\n        this.tx_ = this.conn_;\n        this.rx_ = this.conn_;\n        this.secondaryConn_ = null;\n        this.isHealthy_ = false;\n        /*\n         * Firefox doesn't like when code from one iframe tries to create another iframe by way of the parent frame.\n         * This can occur in the case of a redirect, i.e. we guessed wrong on what server to connect to and received a reset.\n         * Somehow, setTimeout seems to make this ok. That doesn't make sense from a security perspective, since you should\n         * still have the context of your originating frame.\n         */\n        setTimeout(() => {\n            // this.conn_ gets set to null in some of the tests. Check to make sure it still exists before using it\n            this.conn_ && this.conn_.open(onMessageReceived, onConnectionLost);\n        }, Math.floor(0));\n        const healthyTimeoutMS = conn['healthyTimeout'] || 0;\n        if (healthyTimeoutMS > 0) {\n            this.healthyTimeout_ = setTimeoutNonBlocking(() => {\n                this.healthyTimeout_ = null;\n                if (!this.isHealthy_) {\n                    if (this.conn_ &&\n                        this.conn_.bytesReceived > BYTES_RECEIVED_HEALTHY_OVERRIDE) {\n                        this.log_('Connection exceeded healthy timeout but has received ' +\n                            this.conn_.bytesReceived +\n                            ' bytes.  Marking connection healthy.');\n                        this.isHealthy_ = true;\n                        this.conn_.markConnectionHealthy();\n                    }\n                    else if (this.conn_ &&\n                        this.conn_.bytesSent > BYTES_SENT_HEALTHY_OVERRIDE) {\n                        this.log_('Connection exceeded healthy timeout but has sent ' +\n                            this.conn_.bytesSent +\n                            ' bytes.  Leaving connection alive.');\n                        // NOTE: We don't want to mark it healthy, since we have no guarantee that the bytes have made it to\n                        // the server.\n                    }\n                    else {\n                        this.log_('Closing unhealthy connection after timeout.');\n                        this.close();\n                    }\n                }\n                // eslint-disable-next-line @typescript-eslint/no-explicit-any\n            }, Math.floor(healthyTimeoutMS));\n        }\n    }\n    nextTransportId_() {\n        return 'c:' + this.id + ':' + this.connectionCount++;\n    }\n    disconnReceiver_(conn) {\n        return everConnected => {\n            if (conn === this.conn_) {\n                this.onConnectionLost_(everConnected);\n            }\n            else if (conn === this.secondaryConn_) {\n                this.log_('Secondary connection lost.');\n                this.onSecondaryConnectionLost_();\n            }\n            else {\n                this.log_('closing an old connection');\n            }\n        };\n    }\n    connReceiver_(conn) {\n        return (message) => {\n            if (this.state_ !== 2 /* RealtimeState.DISCONNECTED */) {\n                if (conn === this.rx_) {\n                    this.onPrimaryMessageReceived_(message);\n                }\n                else if (conn === this.secondaryConn_) {\n                    this.onSecondaryMessageReceived_(message);\n                }\n                else {\n                    this.log_('message on old connection');\n                }\n            }\n        };\n    }\n    /**\n     * @param dataMsg - An arbitrary data message to be sent to the server\n     */\n    sendRequest(dataMsg) {\n        // wrap in a data message envelope and send it on\n        const msg = { t: 'd', d: dataMsg };\n        this.sendData_(msg);\n    }\n    tryCleanupConnection() {\n        if (this.tx_ === this.secondaryConn_ && this.rx_ === this.secondaryConn_) {\n            this.log_('cleaning up and promoting a connection: ' + this.secondaryConn_.connId);\n            this.conn_ = this.secondaryConn_;\n            this.secondaryConn_ = null;\n            // the server will shutdown the old connection\n        }\n    }\n    onSecondaryControl_(controlData) {\n        if (MESSAGE_TYPE in controlData) {\n            const cmd = controlData[MESSAGE_TYPE];\n            if (cmd === SWITCH_ACK) {\n                this.upgradeIfSecondaryHealthy_();\n            }\n            else if (cmd === CONTROL_RESET) {\n                // Most likely the session wasn't valid. Abandon the switch attempt\n                this.log_('Got a reset on secondary, closing it');\n                this.secondaryConn_.close();\n                // If we were already using this connection for something, than we need to fully close\n                if (this.tx_ === this.secondaryConn_ ||\n                    this.rx_ === this.secondaryConn_) {\n                    this.close();\n                }\n            }\n            else if (cmd === CONTROL_PONG) {\n                this.log_('got pong on secondary.');\n                this.secondaryResponsesRequired_--;\n                this.upgradeIfSecondaryHealthy_();\n            }\n        }\n    }\n    onSecondaryMessageReceived_(parsedData) {\n        const layer = requireKey('t', parsedData);\n        const data = requireKey('d', parsedData);\n        if (layer === 'c') {\n            this.onSecondaryControl_(data);\n        }\n        else if (layer === 'd') {\n            // got a data message, but we're still second connection. Need to buffer it up\n            this.pendingDataMessages.push(data);\n        }\n        else {\n            throw new Error('Unknown protocol layer: ' + layer);\n        }\n    }\n    upgradeIfSecondaryHealthy_() {\n        if (this.secondaryResponsesRequired_ <= 0) {\n            this.log_('Secondary connection is healthy.');\n            this.isHealthy_ = true;\n            this.secondaryConn_.markConnectionHealthy();\n            this.proceedWithUpgrade_();\n        }\n        else {\n            // Send a ping to make sure the connection is healthy.\n            this.log_('sending ping on secondary.');\n            this.secondaryConn_.send({ t: 'c', d: { t: PING, d: {} } });\n        }\n    }\n    proceedWithUpgrade_() {\n        // tell this connection to consider itself open\n        this.secondaryConn_.start();\n        // send ack\n        this.log_('sending client ack on secondary');\n        this.secondaryConn_.send({ t: 'c', d: { t: SWITCH_ACK, d: {} } });\n        // send end packet on primary transport, switch to sending on this one\n        // can receive on this one, buffer responses until end received on primary transport\n        this.log_('Ending transmission on primary');\n        this.conn_.send({ t: 'c', d: { t: END_TRANSMISSION, d: {} } });\n        this.tx_ = this.secondaryConn_;\n        this.tryCleanupConnection();\n    }\n    onPrimaryMessageReceived_(parsedData) {\n        // Must refer to parsedData properties in quotes, so closure doesn't touch them.\n        const layer = requireKey('t', parsedData);\n        const data = requireKey('d', parsedData);\n        if (layer === 'c') {\n            this.onControl_(data);\n        }\n        else if (layer === 'd') {\n            this.onDataMessage_(data);\n        }\n    }\n    onDataMessage_(message) {\n        this.onPrimaryResponse_();\n        // We don't do anything with data messages, just kick them up a level\n        this.onMessage_(message);\n    }\n    onPrimaryResponse_() {\n        if (!this.isHealthy_) {\n            this.primaryResponsesRequired_--;\n            if (this.primaryResponsesRequired_ <= 0) {\n                this.log_('Primary connection is healthy.');\n                this.isHealthy_ = true;\n                this.conn_.markConnectionHealthy();\n            }\n        }\n    }\n    onControl_(controlData) {\n        const cmd = requireKey(MESSAGE_TYPE, controlData);\n        if (MESSAGE_DATA in controlData) {\n            const payload = controlData[MESSAGE_DATA];\n            if (cmd === SERVER_HELLO) {\n                const handshakePayload = Object.assign({}, payload);\n                if (this.repoInfo_.isUsingEmulator) {\n                    // Upon connecting, the emulator will pass the hostname that it's aware of, but we prefer the user's set hostname via `connectDatabaseEmulator` over what the emulator passes.\n                    handshakePayload.h = this.repoInfo_.host;\n                }\n                this.onHandshake_(handshakePayload);\n            }\n            else if (cmd === END_TRANSMISSION) {\n                this.log_('recvd end transmission on primary');\n                this.rx_ = this.secondaryConn_;\n                for (let i = 0; i < this.pendingDataMessages.length; ++i) {\n                    this.onDataMessage_(this.pendingDataMessages[i]);\n                }\n                this.pendingDataMessages = [];\n                this.tryCleanupConnection();\n            }\n            else if (cmd === CONTROL_SHUTDOWN) {\n                // This was previously the 'onKill' callback passed to the lower-level connection\n                // payload in this case is the reason for the shutdown. Generally a human-readable error\n                this.onConnectionShutdown_(payload);\n            }\n            else if (cmd === CONTROL_RESET) {\n                // payload in this case is the host we should contact\n                this.onReset_(payload);\n            }\n            else if (cmd === CONTROL_ERROR) {\n                error('Server Error: ' + payload);\n            }\n            else if (cmd === CONTROL_PONG) {\n                this.log_('got pong on primary.');\n                this.onPrimaryResponse_();\n                this.sendPingOnPrimaryIfNecessary_();\n            }\n            else {\n                error('Unknown control packet command: ' + cmd);\n            }\n        }\n    }\n    /**\n     * @param handshake - The handshake data returned from the server\n     */\n    onHandshake_(handshake) {\n        const timestamp = handshake.ts;\n        const version = handshake.v;\n        const host = handshake.h;\n        this.sessionId = handshake.s;\n        this.repoInfo_.host = host;\n        // if we've already closed the connection, then don't bother trying to progress further\n        if (this.state_ === 0 /* RealtimeState.CONNECTING */) {\n            this.conn_.start();\n            this.onConnectionEstablished_(this.conn_, timestamp);\n            if (PROTOCOL_VERSION !== version) {\n                warn('Protocol version mismatch detected');\n            }\n            // TODO: do we want to upgrade? when? maybe a delay?\n            this.tryStartUpgrade_();\n        }\n    }\n    tryStartUpgrade_() {\n        const conn = this.transportManager_.upgradeTransport();\n        if (conn) {\n            this.startUpgrade_(conn);\n        }\n    }\n    startUpgrade_(conn) {\n        this.secondaryConn_ = new conn(this.nextTransportId_(), this.repoInfo_, this.applicationId_, this.appCheckToken_, this.authToken_, this.sessionId);\n        // For certain transports (WebSockets), we need to send and receive several messages back and forth before we\n        // can consider the transport healthy.\n        this.secondaryResponsesRequired_ =\n            conn['responsesRequiredToBeHealthy'] || 0;\n        const onMessage = this.connReceiver_(this.secondaryConn_);\n        const onDisconnect = this.disconnReceiver_(this.secondaryConn_);\n        this.secondaryConn_.open(onMessage, onDisconnect);\n        // If we haven't successfully upgraded after UPGRADE_TIMEOUT, give up and kill the secondary.\n        setTimeoutNonBlocking(() => {\n            if (this.secondaryConn_) {\n                this.log_('Timed out trying to upgrade.');\n                this.secondaryConn_.close();\n            }\n        }, Math.floor(UPGRADE_TIMEOUT));\n    }\n    onReset_(host) {\n        this.log_('Reset packet received.  New host: ' + host);\n        this.repoInfo_.host = host;\n        // TODO: if we're already \"connected\", we need to trigger a disconnect at the next layer up.\n        // We don't currently support resets after the connection has already been established\n        if (this.state_ === 1 /* RealtimeState.CONNECTED */) {\n            this.close();\n        }\n        else {\n            // Close whatever connections we have open and start again.\n            this.closeConnections_();\n            this.start_();\n        }\n    }\n    onConnectionEstablished_(conn, timestamp) {\n        this.log_('Realtime connection established.');\n        this.conn_ = conn;\n        this.state_ = 1 /* RealtimeState.CONNECTED */;\n        if (this.onReady_) {\n            this.onReady_(timestamp, this.sessionId);\n            this.onReady_ = null;\n        }\n        // If after 5 seconds we haven't sent enough requests to the server to get the connection healthy,\n        // send some pings.\n        if (this.primaryResponsesRequired_ === 0) {\n            this.log_('Primary connection is healthy.');\n            this.isHealthy_ = true;\n        }\n        else {\n            setTimeoutNonBlocking(() => {\n                this.sendPingOnPrimaryIfNecessary_();\n            }, Math.floor(DELAY_BEFORE_SENDING_EXTRA_REQUESTS));\n        }\n    }\n    sendPingOnPrimaryIfNecessary_() {\n        // If the connection isn't considered healthy yet, we'll send a noop ping packet request.\n        if (!this.isHealthy_ && this.state_ === 1 /* RealtimeState.CONNECTED */) {\n            this.log_('sending ping on primary.');\n            this.sendData_({ t: 'c', d: { t: PING, d: {} } });\n        }\n    }\n    onSecondaryConnectionLost_() {\n        const conn = this.secondaryConn_;\n        this.secondaryConn_ = null;\n        if (this.tx_ === conn || this.rx_ === conn) {\n            // we are relying on this connection already in some capacity. Therefore, a failure is real\n            this.close();\n        }\n    }\n    /**\n     * @param everConnected - Whether or not the connection ever reached a server. Used to determine if\n     * we should flush the host cache\n     */\n    onConnectionLost_(everConnected) {\n        this.conn_ = null;\n        // NOTE: IF you're seeing a Firefox error for this line, I think it might be because it's getting\n        // called on window close and RealtimeState.CONNECTING is no longer defined.  Just a guess.\n        if (!everConnected && this.state_ === 0 /* RealtimeState.CONNECTING */) {\n            this.log_('Realtime connection failed.');\n            // Since we failed to connect at all, clear any cached entry for this namespace in case the machine went away\n            if (this.repoInfo_.isCacheableHost()) {\n                PersistentStorage.remove('host:' + this.repoInfo_.host);\n                // reset the internal host to what we would show the user, i.e. <ns>.firebaseio.com\n                this.repoInfo_.internalHost = this.repoInfo_.host;\n            }\n        }\n        else if (this.state_ === 1 /* RealtimeState.CONNECTED */) {\n            this.log_('Realtime connection lost.');\n        }\n        this.close();\n    }\n    onConnectionShutdown_(reason) {\n        this.log_('Connection shutdown command received. Shutting down...');\n        if (this.onKill_) {\n            this.onKill_(reason);\n            this.onKill_ = null;\n        }\n        // We intentionally don't want to fire onDisconnect (kill is a different case),\n        // so clear the callback.\n        this.onDisconnect_ = null;\n        this.close();\n    }\n    sendData_(data) {\n        if (this.state_ !== 1 /* RealtimeState.CONNECTED */) {\n            throw 'Connection is not connected';\n        }\n        else {\n            this.tx_.send(data);\n        }\n    }\n    /**\n     * Cleans up this connection, calling the appropriate callbacks\n     */\n    close() {\n        if (this.state_ !== 2 /* RealtimeState.DISCONNECTED */) {\n            this.log_('Closing realtime connection.');\n            this.state_ = 2 /* RealtimeState.DISCONNECTED */;\n            this.closeConnections_();\n            if (this.onDisconnect_) {\n                this.onDisconnect_();\n                this.onDisconnect_ = null;\n            }\n        }\n    }\n    closeConnections_() {\n        this.log_('Shutting down all connections');\n        if (this.conn_) {\n            this.conn_.close();\n            this.conn_ = null;\n        }\n        if (this.secondaryConn_) {\n            this.secondaryConn_.close();\n            this.secondaryConn_ = null;\n        }\n        if (this.healthyTimeout_) {\n            clearTimeout(this.healthyTimeout_);\n            this.healthyTimeout_ = null;\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 * Interface defining the set of actions that can be performed against the Firebase server\n * (basically corresponds to our wire protocol).\n *\n * @interface\n */\nclass ServerActions {\n    put(pathString, data, onComplete, hash) { }\n    merge(pathString, data, onComplete, hash) { }\n    /**\n     * Refreshes the auth token for the current connection.\n     * @param token - The authentication token\n     */\n    refreshAuthToken(token) { }\n    /**\n     * Refreshes the app check token for the current connection.\n     * @param token The app check token\n     */\n    refreshAppCheckToken(token) { }\n    onDisconnectPut(pathString, data, onComplete) { }\n    onDisconnectMerge(pathString, data, onComplete) { }\n    onDisconnectCancel(pathString, onComplete) { }\n    reportStats(stats) { }\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 * Base class to be used if you want to emit events. Call the constructor with\n * the set of allowed event names.\n */\nclass EventEmitter {\n    constructor(allowedEvents_) {\n        this.allowedEvents_ = allowedEvents_;\n        this.listeners_ = {};\n        assert(Array.isArray(allowedEvents_) && allowedEvents_.length > 0, 'Requires a non-empty array');\n    }\n    /**\n     * To be called by derived classes to trigger events.\n     */\n    trigger(eventType, ...varArgs) {\n        if (Array.isArray(this.listeners_[eventType])) {\n            // Clone the list, since callbacks could add/remove listeners.\n            const listeners = [...this.listeners_[eventType]];\n            for (let i = 0; i < listeners.length; i++) {\n                listeners[i].callback.apply(listeners[i].context, varArgs);\n            }\n        }\n    }\n    on(eventType, callback, context) {\n        this.validateEventType_(eventType);\n        this.listeners_[eventType] = this.listeners_[eventType] || [];\n        this.listeners_[eventType].push({ callback, context });\n        const eventData = this.getInitialEvent(eventType);\n        if (eventData) {\n            callback.apply(context, eventData);\n        }\n    }\n    off(eventType, callback, context) {\n        this.validateEventType_(eventType);\n        const listeners = this.listeners_[eventType] || [];\n        for (let i = 0; i < listeners.length; i++) {\n            if (listeners[i].callback === callback &&\n                (!context || context === listeners[i].context)) {\n                listeners.splice(i, 1);\n                return;\n            }\n        }\n    }\n    validateEventType_(eventType) {\n        assert(this.allowedEvents_.find(et => {\n            return et === eventType;\n        }), 'Unknown event: ' + eventType);\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 * Monitors online state (as reported by window.online/offline events).\n *\n * The expectation is that this could have many false positives (thinks we are online\n * when we're not), but no false negatives.  So we can safely use it to determine when\n * we definitely cannot reach the internet.\n */\nclass OnlineMonitor extends EventEmitter {\n    static getInstance() {\n        return new OnlineMonitor();\n    }\n    constructor() {\n        super(['online']);\n        this.online_ = true;\n        // We've had repeated complaints that Cordova apps can get stuck \"offline\", e.g.\n        // https://forum.ionicframework.com/t/firebase-connection-is-lost-and-never-come-back/43810\n        // It would seem that the 'online' event does not always fire consistently. So we disable it\n        // for Cordova.\n        if (typeof window !== 'undefined' &&\n            typeof window.addEventListener !== 'undefined' &&\n            !isMobileCordova()) {\n            window.addEventListener('online', () => {\n                if (!this.online_) {\n                    this.online_ = true;\n                    this.trigger('online', true);\n                }\n            }, false);\n            window.addEventListener('offline', () => {\n                if (this.online_) {\n                    this.online_ = false;\n                    this.trigger('online', false);\n                }\n            }, false);\n        }\n    }\n    getInitialEvent(eventType) {\n        assert(eventType === 'online', 'Unknown event type: ' + eventType);\n        return [this.online_];\n    }\n    currentlyOnline() {\n        return this.online_;\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/** Maximum key depth. */\nconst MAX_PATH_DEPTH = 32;\n/** Maximum number of (UTF8) bytes in a Firebase path. */\nconst MAX_PATH_LENGTH_BYTES = 768;\n/**\n * An immutable object representing a parsed path.  It's immutable so that you\n * can pass them around to other functions without worrying about them changing\n * it.\n */\nclass Path {\n    /**\n     * @param pathOrString - Path string to parse, or another path, or the raw\n     * tokens array\n     */\n    constructor(pathOrString, pieceNum) {\n        if (pieceNum === void 0) {\n            this.pieces_ = pathOrString.split('/');\n            // Remove empty pieces.\n            let copyTo = 0;\n            for (let i = 0; i < this.pieces_.length; i++) {\n                if (this.pieces_[i].length > 0) {\n                    this.pieces_[copyTo] = this.pieces_[i];\n                    copyTo++;\n                }\n            }\n            this.pieces_.length = copyTo;\n            this.pieceNum_ = 0;\n        }\n        else {\n            this.pieces_ = pathOrString;\n            this.pieceNum_ = pieceNum;\n        }\n    }\n    toString() {\n        let pathString = '';\n        for (let i = this.pieceNum_; i < this.pieces_.length; i++) {\n            if (this.pieces_[i] !== '') {\n                pathString += '/' + this.pieces_[i];\n            }\n        }\n        return pathString || '/';\n    }\n}\nfunction newEmptyPath() {\n    return new Path('');\n}\nfunction pathGetFront(path) {\n    if (path.pieceNum_ >= path.pieces_.length) {\n        return null;\n    }\n    return path.pieces_[path.pieceNum_];\n}\n/**\n * @returns The number of segments in this path\n */\nfunction pathGetLength(path) {\n    return path.pieces_.length - path.pieceNum_;\n}\nfunction pathPopFront(path) {\n    let pieceNum = path.pieceNum_;\n    if (pieceNum < path.pieces_.length) {\n        pieceNum++;\n    }\n    return new Path(path.pieces_, pieceNum);\n}\nfunction pathGetBack(path) {\n    if (path.pieceNum_ < path.pieces_.length) {\n        return path.pieces_[path.pieces_.length - 1];\n    }\n    return null;\n}\nfunction pathToUrlEncodedString(path) {\n    let pathString = '';\n    for (let i = path.pieceNum_; i < path.pieces_.length; i++) {\n        if (path.pieces_[i] !== '') {\n            pathString += '/' + encodeURIComponent(String(path.pieces_[i]));\n        }\n    }\n    return pathString || '/';\n}\n/**\n * Shallow copy of the parts of the path.\n *\n */\nfunction pathSlice(path, begin = 0) {\n    return path.pieces_.slice(path.pieceNum_ + begin);\n}\nfunction pathParent(path) {\n    if (path.pieceNum_ >= path.pieces_.length) {\n        return null;\n    }\n    const pieces = [];\n    for (let i = path.pieceNum_; i < path.pieces_.length - 1; i++) {\n        pieces.push(path.pieces_[i]);\n    }\n    return new Path(pieces, 0);\n}\nfunction pathChild(path, childPathObj) {\n    const pieces = [];\n    for (let i = path.pieceNum_; i < path.pieces_.length; i++) {\n        pieces.push(path.pieces_[i]);\n    }\n    if (childPathObj instanceof Path) {\n        for (let i = childPathObj.pieceNum_; i < childPathObj.pieces_.length; i++) {\n            pieces.push(childPathObj.pieces_[i]);\n        }\n    }\n    else {\n        const childPieces = childPathObj.split('/');\n        for (let i = 0; i < childPieces.length; i++) {\n            if (childPieces[i].length > 0) {\n                pieces.push(childPieces[i]);\n            }\n        }\n    }\n    return new Path(pieces, 0);\n}\n/**\n * @returns True if there are no segments in this path\n */\nfunction pathIsEmpty(path) {\n    return path.pieceNum_ >= path.pieces_.length;\n}\n/**\n * @returns The path from outerPath to innerPath\n */\nfunction newRelativePath(outerPath, innerPath) {\n    const outer = pathGetFront(outerPath), inner = pathGetFront(innerPath);\n    if (outer === null) {\n        return innerPath;\n    }\n    else if (outer === inner) {\n        return newRelativePath(pathPopFront(outerPath), pathPopFront(innerPath));\n    }\n    else {\n        throw new Error('INTERNAL ERROR: innerPath (' +\n            innerPath +\n            ') is not within ' +\n            'outerPath (' +\n            outerPath +\n            ')');\n    }\n}\n/**\n * @returns -1, 0, 1 if left is less, equal, or greater than the right.\n */\nfunction pathCompare(left, right) {\n    const leftKeys = pathSlice(left, 0);\n    const rightKeys = pathSlice(right, 0);\n    for (let i = 0; i < leftKeys.length && i < rightKeys.length; i++) {\n        const cmp = nameCompare(leftKeys[i], rightKeys[i]);\n        if (cmp !== 0) {\n            return cmp;\n        }\n    }\n    if (leftKeys.length === rightKeys.length) {\n        return 0;\n    }\n    return leftKeys.length < rightKeys.length ? -1 : 1;\n}\n/**\n * @returns true if paths are the same.\n */\nfunction pathEquals(path, other) {\n    if (pathGetLength(path) !== pathGetLength(other)) {\n        return false;\n    }\n    for (let i = path.pieceNum_, j = other.pieceNum_; i <= path.pieces_.length; i++, j++) {\n        if (path.pieces_[i] !== other.pieces_[j]) {\n            return false;\n        }\n    }\n    return true;\n}\n/**\n * @returns True if this path is a parent of (or the same as) other\n */\nfunction pathContains(path, other) {\n    let i = path.pieceNum_;\n    let j = other.pieceNum_;\n    if (pathGetLength(path) > pathGetLength(other)) {\n        return false;\n    }\n    while (i < path.pieces_.length) {\n        if (path.pieces_[i] !== other.pieces_[j]) {\n            return false;\n        }\n        ++i;\n        ++j;\n    }\n    return true;\n}\n/**\n * Dynamic (mutable) path used to count path lengths.\n *\n * This class is used to efficiently check paths for valid\n * length (in UTF8 bytes) and depth (used in path validation).\n *\n * Throws Error exception if path is ever invalid.\n *\n * The definition of a path always begins with '/'.\n */\nclass ValidationPath {\n    /**\n     * @param path - Initial Path.\n     * @param errorPrefix_ - Prefix for any error messages.\n     */\n    constructor(path, errorPrefix_) {\n        this.errorPrefix_ = errorPrefix_;\n        this.parts_ = pathSlice(path, 0);\n        /** Initialize to number of '/' chars needed in path. */\n        this.byteLength_ = Math.max(1, this.parts_.length);\n        for (let i = 0; i < this.parts_.length; i++) {\n            this.byteLength_ += stringLength(this.parts_[i]);\n        }\n        validationPathCheckValid(this);\n    }\n}\nfunction validationPathPush(validationPath, child) {\n    // Count the needed '/'\n    if (validationPath.parts_.length > 0) {\n        validationPath.byteLength_ += 1;\n    }\n    validationPath.parts_.push(child);\n    validationPath.byteLength_ += stringLength(child);\n    validationPathCheckValid(validationPath);\n}\nfunction validationPathPop(validationPath) {\n    const last = validationPath.parts_.pop();\n    validationPath.byteLength_ -= stringLength(last);\n    // Un-count the previous '/'\n    if (validationPath.parts_.length > 0) {\n        validationPath.byteLength_ -= 1;\n    }\n}\nfunction validationPathCheckValid(validationPath) {\n    if (validationPath.byteLength_ > MAX_PATH_LENGTH_BYTES) {\n        throw new Error(validationPath.errorPrefix_ +\n            'has a key path longer than ' +\n            MAX_PATH_LENGTH_BYTES +\n            ' bytes (' +\n            validationPath.byteLength_ +\n            ').');\n    }\n    if (validationPath.parts_.length > MAX_PATH_DEPTH) {\n        throw new Error(validationPath.errorPrefix_ +\n            'path specified exceeds the maximum depth that can be written (' +\n            MAX_PATH_DEPTH +\n            ') or object contains a cycle ' +\n            validationPathToErrorString(validationPath));\n    }\n}\n/**\n * String for use in error messages - uses '.' notation for path.\n */\nfunction validationPathToErrorString(validationPath) {\n    if (validationPath.parts_.length === 0) {\n        return '';\n    }\n    return \"in property '\" + validationPath.parts_.join('.') + \"'\";\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 */\nclass VisibilityMonitor extends EventEmitter {\n    static getInstance() {\n        return new VisibilityMonitor();\n    }\n    constructor() {\n        super(['visible']);\n        let hidden;\n        let visibilityChange;\n        if (typeof document !== 'undefined' &&\n            typeof document.addEventListener !== 'undefined') {\n            if (typeof document['hidden'] !== 'undefined') {\n                // Opera 12.10 and Firefox 18 and later support\n                visibilityChange = 'visibilitychange';\n                hidden = 'hidden';\n            }\n            else if (typeof document['mozHidden'] !== 'undefined') {\n                visibilityChange = 'mozvisibilitychange';\n                hidden = 'mozHidden';\n            }\n            else if (typeof document['msHidden'] !== 'undefined') {\n                visibilityChange = 'msvisibilitychange';\n                hidden = 'msHidden';\n            }\n            else if (typeof document['webkitHidden'] !== 'undefined') {\n                visibilityChange = 'webkitvisibilitychange';\n                hidden = 'webkitHidden';\n            }\n        }\n        // Initially, we always assume we are visible. This ensures that in browsers\n        // without page visibility support or in cases where we are never visible\n        // (e.g. chrome extension), we act as if we are visible, i.e. don't delay\n        // reconnects\n        this.visible_ = true;\n        if (visibilityChange) {\n            document.addEventListener(visibilityChange, () => {\n                const visible = !document[hidden];\n                if (visible !== this.visible_) {\n                    this.visible_ = visible;\n                    this.trigger('visible', visible);\n                }\n            }, false);\n        }\n    }\n    getInitialEvent(eventType) {\n        assert(eventType === 'visible', 'Unknown event type: ' + eventType);\n        return [this.visible_];\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 */\nconst RECONNECT_MIN_DELAY = 1000;\nconst RECONNECT_MAX_DELAY_DEFAULT = 60 * 5 * 1000; // 5 minutes in milliseconds (Case: 1858)\nconst RECONNECT_MAX_DELAY_FOR_ADMINS = 30 * 1000; // 30 seconds for admin clients (likely to be a backend server)\nconst RECONNECT_DELAY_MULTIPLIER = 1.3;\nconst RECONNECT_DELAY_RESET_TIMEOUT = 30000; // Reset delay back to MIN_DELAY after being connected for 30sec.\nconst SERVER_KILL_INTERRUPT_REASON = 'server_kill';\n// If auth fails repeatedly, we'll assume something is wrong and log a warning / back off.\nconst INVALID_TOKEN_THRESHOLD = 3;\n/**\n * Firebase connection.  Abstracts wire protocol and handles reconnecting.\n *\n * NOTE: All JSON objects sent to the realtime connection must have property names enclosed\n * in quotes to make sure the closure compiler does not minify them.\n */\nclass PersistentConnection extends ServerActions {\n    /**\n     * @param repoInfo_ - Data about the namespace we are connecting to\n     * @param applicationId_ - The Firebase App ID for this project\n     * @param onDataUpdate_ - A callback for new data from the server\n     */\n    constructor(repoInfo_, applicationId_, onDataUpdate_, onConnectStatus_, onServerInfoUpdate_, authTokenProvider_, appCheckTokenProvider_, authOverride_) {\n        super();\n        this.repoInfo_ = repoInfo_;\n        this.applicationId_ = applicationId_;\n        this.onDataUpdate_ = onDataUpdate_;\n        this.onConnectStatus_ = onConnectStatus_;\n        this.onServerInfoUpdate_ = onServerInfoUpdate_;\n        this.authTokenProvider_ = authTokenProvider_;\n        this.appCheckTokenProvider_ = appCheckTokenProvider_;\n        this.authOverride_ = authOverride_;\n        // Used for diagnostic logging.\n        this.id = PersistentConnection.nextPersistentConnectionId_++;\n        this.log_ = logWrapper('p:' + this.id + ':');\n        this.interruptReasons_ = {};\n        this.listens = new Map();\n        this.outstandingPuts_ = [];\n        this.outstandingGets_ = [];\n        this.outstandingPutCount_ = 0;\n        this.outstandingGetCount_ = 0;\n        this.onDisconnectRequestQueue_ = [];\n        this.connected_ = false;\n        this.reconnectDelay_ = RECONNECT_MIN_DELAY;\n        this.maxReconnectDelay_ = RECONNECT_MAX_DELAY_DEFAULT;\n        this.securityDebugCallback_ = null;\n        this.lastSessionId = null;\n        this.establishConnectionTimer_ = null;\n        this.visible_ = false;\n        // Before we get connected, we keep a queue of pending messages to send.\n        this.requestCBHash_ = {};\n        this.requestNumber_ = 0;\n        this.realtime_ = null;\n        this.authToken_ = null;\n        this.appCheckToken_ = null;\n        this.forceTokenRefresh_ = false;\n        this.invalidAuthTokenCount_ = 0;\n        this.invalidAppCheckTokenCount_ = 0;\n        this.firstConnection_ = true;\n        this.lastConnectionAttemptTime_ = null;\n        this.lastConnectionEstablishedTime_ = null;\n        if (authOverride_ && !isNodeSdk()) {\n            throw new Error('Auth override specified in options, but not supported on non Node.js platforms');\n        }\n        VisibilityMonitor.getInstance().on('visible', this.onVisible_, this);\n        if (repoInfo_.host.indexOf('fblocal') === -1) {\n            OnlineMonitor.getInstance().on('online', this.onOnline_, this);\n        }\n    }\n    sendRequest(action, body, onResponse) {\n        const curReqNum = ++this.requestNumber_;\n        const msg = { r: curReqNum, a: action, b: body };\n        this.log_(stringify(msg));\n        assert(this.connected_, \"sendRequest call when we're not connected not allowed.\");\n        this.realtime_.sendRequest(msg);\n        if (onResponse) {\n            this.requestCBHash_[curReqNum] = onResponse;\n        }\n    }\n    get(query) {\n        this.initConnection_();\n        const deferred = new Deferred();\n        const request = {\n            p: query._path.toString(),\n            q: query._queryObject\n        };\n        const outstandingGet = {\n            action: 'g',\n            request,\n            onComplete: (message) => {\n                const payload = message['d'];\n                if (message['s'] === 'ok') {\n                    deferred.resolve(payload);\n                }\n                else {\n                    deferred.reject(payload);\n                }\n            }\n        };\n        this.outstandingGets_.push(outstandingGet);\n        this.outstandingGetCount_++;\n        const index = this.outstandingGets_.length - 1;\n        if (this.connected_) {\n            this.sendGet_(index);\n        }\n        return deferred.promise;\n    }\n    listen(query, currentHashFn, tag, onComplete) {\n        this.initConnection_();\n        const queryId = query._queryIdentifier;\n        const pathString = query._path.toString();\n        this.log_('Listen called for ' + pathString + ' ' + queryId);\n        if (!this.listens.has(pathString)) {\n            this.listens.set(pathString, new Map());\n        }\n        assert(query._queryParams.isDefault() || !query._queryParams.loadsAllData(), 'listen() called for non-default but complete query');\n        assert(!this.listens.get(pathString).has(queryId), `listen() called twice for same path/queryId.`);\n        const listenSpec = {\n            onComplete,\n            hashFn: currentHashFn,\n            query,\n            tag\n        };\n        this.listens.get(pathString).set(queryId, listenSpec);\n        if (this.connected_) {\n            this.sendListen_(listenSpec);\n        }\n    }\n    sendGet_(index) {\n        const get = this.outstandingGets_[index];\n        this.sendRequest('g', get.request, (message) => {\n            delete this.outstandingGets_[index];\n            this.outstandingGetCount_--;\n            if (this.outstandingGetCount_ === 0) {\n                this.outstandingGets_ = [];\n            }\n            if (get.onComplete) {\n                get.onComplete(message);\n            }\n        });\n    }\n    sendListen_(listenSpec) {\n        const query = listenSpec.query;\n        const pathString = query._path.toString();\n        const queryId = query._queryIdentifier;\n        this.log_('Listen on ' + pathString + ' for ' + queryId);\n        const req = { /*path*/ p: pathString };\n        const action = 'q';\n        // Only bother to send query if it's non-default.\n        if (listenSpec.tag) {\n            req['q'] = query._queryObject;\n            req['t'] = listenSpec.tag;\n        }\n        req[ /*hash*/'h'] = listenSpec.hashFn();\n        this.sendRequest(action, req, (message) => {\n            const payload = message[ /*data*/'d'];\n            const status = message[ /*status*/'s'];\n            // print warnings in any case...\n            PersistentConnection.warnOnListenWarnings_(payload, query);\n            const currentListenSpec = this.listens.get(pathString) &&\n                this.listens.get(pathString).get(queryId);\n            // only trigger actions if the listen hasn't been removed and readded\n            if (currentListenSpec === listenSpec) {\n                this.log_('listen response', message);\n                if (status !== 'ok') {\n                    this.removeListen_(pathString, queryId);\n                }\n                if (listenSpec.onComplete) {\n                    listenSpec.onComplete(status, payload);\n                }\n            }\n        });\n    }\n    static warnOnListenWarnings_(payload, query) {\n        if (payload && typeof payload === 'object' && contains(payload, 'w')) {\n            // eslint-disable-next-line @typescript-eslint/no-explicit-any\n            const warnings = safeGet(payload, 'w');\n            if (Array.isArray(warnings) && ~warnings.indexOf('no_index')) {\n                const indexSpec = '\".indexOn\": \"' + query._queryParams.getIndex().toString() + '\"';\n                const indexPath = query._path.toString();\n                warn(`Using an unspecified index. Your data will be downloaded and ` +\n                    `filtered on the client. Consider adding ${indexSpec} at ` +\n                    `${indexPath} to your security rules for better performance.`);\n            }\n        }\n    }\n    refreshAuthToken(token) {\n        this.authToken_ = token;\n        this.log_('Auth token refreshed');\n        if (this.authToken_) {\n            this.tryAuth();\n        }\n        else {\n            //If we're connected we want to let the server know to unauthenticate us. If we're not connected, simply delete\n            //the credential so we dont become authenticated next time we connect.\n            if (this.connected_) {\n                this.sendRequest('unauth', {}, () => { });\n            }\n        }\n        this.reduceReconnectDelayIfAdminCredential_(token);\n    }\n    reduceReconnectDelayIfAdminCredential_(credential) {\n        // NOTE: This isn't intended to be bulletproof (a malicious developer can always just modify the client).\n        // Additionally, we don't bother resetting the max delay back to the default if auth fails / expires.\n        const isFirebaseSecret = credential && credential.length === 40;\n        if (isFirebaseSecret || isAdmin(credential)) {\n            this.log_('Admin auth credential detected.  Reducing max reconnect time.');\n            this.maxReconnectDelay_ = RECONNECT_MAX_DELAY_FOR_ADMINS;\n        }\n    }\n    refreshAppCheckToken(token) {\n        this.appCheckToken_ = token;\n        this.log_('App check token refreshed');\n        if (this.appCheckToken_) {\n            this.tryAppCheck();\n        }\n        else {\n            //If we're connected we want to let the server know to unauthenticate us.\n            //If we're not connected, simply delete the credential so we dont become\n            // authenticated next time we connect.\n            if (this.connected_) {\n                this.sendRequest('unappeck', {}, () => { });\n            }\n        }\n    }\n    /**\n     * Attempts to authenticate with the given credentials. If the authentication attempt fails, it's triggered like\n     * a auth revoked (the connection is closed).\n     */\n    tryAuth() {\n        if (this.connected_ && this.authToken_) {\n            const token = this.authToken_;\n            const authMethod = isValidFormat(token) ? 'auth' : 'gauth';\n            const requestData = { cred: token };\n            if (this.authOverride_ === null) {\n                requestData['noauth'] = true;\n            }\n            else if (typeof this.authOverride_ === 'object') {\n                requestData['authvar'] = this.authOverride_;\n            }\n            this.sendRequest(authMethod, requestData, (res) => {\n                const status = res[ /*status*/'s'];\n                const data = res[ /*data*/'d'] || 'error';\n                if (this.authToken_ === token) {\n                    if (status === 'ok') {\n                        this.invalidAuthTokenCount_ = 0;\n                    }\n                    else {\n                        // Triggers reconnect and force refresh for auth token\n                        this.onAuthRevoked_(status, data);\n                    }\n                }\n            });\n        }\n    }\n    /**\n     * Attempts to authenticate with the given token. If the authentication\n     * attempt fails, it's triggered like the token was revoked (the connection is\n     * closed).\n     */\n    tryAppCheck() {\n        if (this.connected_ && this.appCheckToken_) {\n            this.sendRequest('appcheck', { 'token': this.appCheckToken_ }, (res) => {\n                const status = res[ /*status*/'s'];\n                const data = res[ /*data*/'d'] || 'error';\n                if (status === 'ok') {\n                    this.invalidAppCheckTokenCount_ = 0;\n                }\n                else {\n                    this.onAppCheckRevoked_(status, data);\n                }\n            });\n        }\n    }\n    /**\n     * @inheritDoc\n     */\n    unlisten(query, tag) {\n        const pathString = query._path.toString();\n        const queryId = query._queryIdentifier;\n        this.log_('Unlisten called for ' + pathString + ' ' + queryId);\n        assert(query._queryParams.isDefault() || !query._queryParams.loadsAllData(), 'unlisten() called for non-default but complete query');\n        const listen = this.removeListen_(pathString, queryId);\n        if (listen && this.connected_) {\n            this.sendUnlisten_(pathString, queryId, query._queryObject, tag);\n        }\n    }\n    sendUnlisten_(pathString, queryId, queryObj, tag) {\n        this.log_('Unlisten on ' + pathString + ' for ' + queryId);\n        const req = { /*path*/ p: pathString };\n        const action = 'n';\n        // Only bother sending queryId if it's non-default.\n        if (tag) {\n            req['q'] = queryObj;\n            req['t'] = tag;\n        }\n        this.sendRequest(action, req);\n    }\n    onDisconnectPut(pathString, data, onComplete) {\n        this.initConnection_();\n        if (this.connected_) {\n            this.sendOnDisconnect_('o', pathString, data, onComplete);\n        }\n        else {\n            this.onDisconnectRequestQueue_.push({\n                pathString,\n                action: 'o',\n                data,\n                onComplete\n            });\n        }\n    }\n    onDisconnectMerge(pathString, data, onComplete) {\n        this.initConnection_();\n        if (this.connected_) {\n            this.sendOnDisconnect_('om', pathString, data, onComplete);\n        }\n        else {\n            this.onDisconnectRequestQueue_.push({\n                pathString,\n                action: 'om',\n                data,\n                onComplete\n            });\n        }\n    }\n    onDisconnectCancel(pathString, onComplete) {\n        this.initConnection_();\n        if (this.connected_) {\n            this.sendOnDisconnect_('oc', pathString, null, onComplete);\n        }\n        else {\n            this.onDisconnectRequestQueue_.push({\n                pathString,\n                action: 'oc',\n                data: null,\n                onComplete\n            });\n        }\n    }\n    sendOnDisconnect_(action, pathString, data, onComplete) {\n        const request = { /*path*/ p: pathString, /*data*/ d: data };\n        this.log_('onDisconnect ' + action, request);\n        this.sendRequest(action, request, (response) => {\n            if (onComplete) {\n                setTimeout(() => {\n                    onComplete(response[ /*status*/'s'], response[ /* data */'d']);\n                }, Math.floor(0));\n            }\n        });\n    }\n    put(pathString, data, onComplete, hash) {\n        this.putInternal('p', pathString, data, onComplete, hash);\n    }\n    merge(pathString, data, onComplete, hash) {\n        this.putInternal('m', pathString, data, onComplete, hash);\n    }\n    putInternal(action, pathString, data, onComplete, hash) {\n        this.initConnection_();\n        const request = {\n            /*path*/ p: pathString,\n            /*data*/ d: data\n        };\n        if (hash !== undefined) {\n            request[ /*hash*/'h'] = hash;\n        }\n        // TODO: Only keep track of the most recent put for a given path?\n        this.outstandingPuts_.push({\n            action,\n            request,\n            onComplete\n        });\n        this.outstandingPutCount_++;\n        const index = this.outstandingPuts_.length - 1;\n        if (this.connected_) {\n            this.sendPut_(index);\n        }\n        else {\n            this.log_('Buffering put: ' + pathString);\n        }\n    }\n    sendPut_(index) {\n        const action = this.outstandingPuts_[index].action;\n        const request = this.outstandingPuts_[index].request;\n        const onComplete = this.outstandingPuts_[index].onComplete;\n        this.outstandingPuts_[index].queued = this.connected_;\n        this.sendRequest(action, request, (message) => {\n            this.log_(action + ' response', message);\n            delete this.outstandingPuts_[index];\n            this.outstandingPutCount_--;\n            // Clean up array occasionally.\n            if (this.outstandingPutCount_ === 0) {\n                this.outstandingPuts_ = [];\n            }\n            if (onComplete) {\n                onComplete(message[ /*status*/'s'], message[ /* data */'d']);\n            }\n        });\n    }\n    reportStats(stats) {\n        // If we're not connected, we just drop the stats.\n        if (this.connected_) {\n            const request = { /*counters*/ c: stats };\n            this.log_('reportStats', request);\n            this.sendRequest(/*stats*/ 's', request, result => {\n                const status = result[ /*status*/'s'];\n                if (status !== 'ok') {\n                    const errorReason = result[ /* data */'d'];\n                    this.log_('reportStats', 'Error sending stats: ' + errorReason);\n                }\n            });\n        }\n    }\n    onDataMessage_(message) {\n        if ('r' in message) {\n            // this is a response\n            this.log_('from server: ' + stringify(message));\n            const reqNum = message['r'];\n            const onResponse = this.requestCBHash_[reqNum];\n            if (onResponse) {\n                delete this.requestCBHash_[reqNum];\n                onResponse(message[ /*body*/'b']);\n            }\n        }\n        else if ('error' in message) {\n            throw 'A server-side error has occurred: ' + message['error'];\n        }\n        else if ('a' in message) {\n            // a and b are action and body, respectively\n            this.onDataPush_(message['a'], message['b']);\n        }\n    }\n    onDataPush_(action, body) {\n        this.log_('handleServerMessage', action, body);\n        if (action === 'd') {\n            this.onDataUpdate_(body[ /*path*/'p'], body[ /*data*/'d'], \n            /*isMerge*/ false, body['t']);\n        }\n        else if (action === 'm') {\n            this.onDataUpdate_(body[ /*path*/'p'], body[ /*data*/'d'], \n            /*isMerge=*/ true, body['t']);\n        }\n        else if (action === 'c') {\n            this.onListenRevoked_(body[ /*path*/'p'], body[ /*query*/'q']);\n        }\n        else if (action === 'ac') {\n            this.onAuthRevoked_(body[ /*status code*/'s'], body[ /* explanation */'d']);\n        }\n        else if (action === 'apc') {\n            this.onAppCheckRevoked_(body[ /*status code*/'s'], body[ /* explanation */'d']);\n        }\n        else if (action === 'sd') {\n            this.onSecurityDebugPacket_(body);\n        }\n        else {\n            error('Unrecognized action received from server: ' +\n                stringify(action) +\n                '\\nAre you using the latest client?');\n        }\n    }\n    onReady_(timestamp, sessionId) {\n        this.log_('connection ready');\n        this.connected_ = true;\n        this.lastConnectionEstablishedTime_ = new Date().getTime();\n        this.handleTimestamp_(timestamp);\n        this.lastSessionId = sessionId;\n        if (this.firstConnection_) {\n            this.sendConnectStats_();\n        }\n        this.restoreState_();\n        this.firstConnection_ = false;\n        this.onConnectStatus_(true);\n    }\n    scheduleConnect_(timeout) {\n        assert(!this.realtime_, \"Scheduling a connect when we're already connected/ing?\");\n        if (this.establishConnectionTimer_) {\n            clearTimeout(this.establishConnectionTimer_);\n        }\n        // NOTE: Even when timeout is 0, it's important to do a setTimeout to work around an infuriating \"Security Error\" in\n        // Firefox when trying to write to our long-polling iframe in some scenarios (e.g. Forge or our unit tests).\n        this.establishConnectionTimer_ = setTimeout(() => {\n            this.establishConnectionTimer_ = null;\n            this.establishConnection_();\n            // eslint-disable-next-line @typescript-eslint/no-explicit-any\n        }, Math.floor(timeout));\n    }\n    initConnection_() {\n        if (!this.realtime_ && this.firstConnection_) {\n            this.scheduleConnect_(0);\n        }\n    }\n    onVisible_(visible) {\n        // NOTE: Tabbing away and back to a window will defeat our reconnect backoff, but I think that's fine.\n        if (visible &&\n            !this.visible_ &&\n            this.reconnectDelay_ === this.maxReconnectDelay_) {\n            this.log_('Window became visible.  Reducing delay.');\n            this.reconnectDelay_ = RECONNECT_MIN_DELAY;\n            if (!this.realtime_) {\n                this.scheduleConnect_(0);\n            }\n        }\n        this.visible_ = visible;\n    }\n    onOnline_(online) {\n        if (online) {\n            this.log_('Browser went online.');\n            this.reconnectDelay_ = RECONNECT_MIN_DELAY;\n            if (!this.realtime_) {\n                this.scheduleConnect_(0);\n            }\n        }\n        else {\n            this.log_('Browser went offline.  Killing connection.');\n            if (this.realtime_) {\n                this.realtime_.close();\n            }\n        }\n    }\n    onRealtimeDisconnect_() {\n        this.log_('data client disconnected');\n        this.connected_ = false;\n        this.realtime_ = null;\n        // Since we don't know if our sent transactions succeeded or not, we need to cancel them.\n        this.cancelSentTransactions_();\n        // Clear out the pending requests.\n        this.requestCBHash_ = {};\n        if (this.shouldReconnect_()) {\n            if (!this.visible_) {\n                this.log_(\"Window isn't visible.  Delaying reconnect.\");\n                this.reconnectDelay_ = this.maxReconnectDelay_;\n                this.lastConnectionAttemptTime_ = new Date().getTime();\n            }\n            else if (this.lastConnectionEstablishedTime_) {\n                // If we've been connected long enough, reset reconnect delay to minimum.\n                const timeSinceLastConnectSucceeded = new Date().getTime() - this.lastConnectionEstablishedTime_;\n                if (timeSinceLastConnectSucceeded > RECONNECT_DELAY_RESET_TIMEOUT) {\n                    this.reconnectDelay_ = RECONNECT_MIN_DELAY;\n                }\n                this.lastConnectionEstablishedTime_ = null;\n            }\n            const timeSinceLastConnectAttempt = new Date().getTime() - this.lastConnectionAttemptTime_;\n            let reconnectDelay = Math.max(0, this.reconnectDelay_ - timeSinceLastConnectAttempt);\n            reconnectDelay = Math.random() * reconnectDelay;\n            this.log_('Trying to reconnect in ' + reconnectDelay + 'ms');\n            this.scheduleConnect_(reconnectDelay);\n            // Adjust reconnect delay for next time.\n            this.reconnectDelay_ = Math.min(this.maxReconnectDelay_, this.reconnectDelay_ * RECONNECT_DELAY_MULTIPLIER);\n        }\n        this.onConnectStatus_(false);\n    }\n    async establishConnection_() {\n        if (this.shouldReconnect_()) {\n            this.log_('Making a connection attempt');\n            this.lastConnectionAttemptTime_ = new Date().getTime();\n            this.lastConnectionEstablishedTime_ = null;\n            const onDataMessage = this.onDataMessage_.bind(this);\n            const onReady = this.onReady_.bind(this);\n            const onDisconnect = this.onRealtimeDisconnect_.bind(this);\n            const connId = this.id + ':' + PersistentConnection.nextConnectionId_++;\n            const lastSessionId = this.lastSessionId;\n            let canceled = false;\n            let connection = null;\n            const closeFn = function () {\n                if (connection) {\n                    connection.close();\n                }\n                else {\n                    canceled = true;\n                    onDisconnect();\n                }\n            };\n            const sendRequestFn = function (msg) {\n                assert(connection, \"sendRequest call when we're not connected not allowed.\");\n                connection.sendRequest(msg);\n            };\n            this.realtime_ = {\n                close: closeFn,\n                sendRequest: sendRequestFn\n            };\n            const forceRefresh = this.forceTokenRefresh_;\n            this.forceTokenRefresh_ = false;\n            try {\n                // First fetch auth and app check token, and establish connection after\n                // fetching the token was successful\n                const [authToken, appCheckToken] = await Promise.all([\n                    this.authTokenProvider_.getToken(forceRefresh),\n                    this.appCheckTokenProvider_.getToken(forceRefresh)\n                ]);\n                if (!canceled) {\n                    log('getToken() completed. Creating connection.');\n                    this.authToken_ = authToken && authToken.accessToken;\n                    this.appCheckToken_ = appCheckToken && appCheckToken.token;\n                    connection = new Connection(connId, this.repoInfo_, this.applicationId_, this.appCheckToken_, this.authToken_, onDataMessage, onReady, onDisconnect, \n                    /* onKill= */ reason => {\n                        warn(reason + ' (' + this.repoInfo_.toString() + ')');\n                        this.interrupt(SERVER_KILL_INTERRUPT_REASON);\n                    }, lastSessionId);\n                }\n                else {\n                    log('getToken() completed but was canceled');\n                }\n            }\n            catch (error) {\n                this.log_('Failed to get token: ' + error);\n                if (!canceled) {\n                    if (this.repoInfo_.nodeAdmin) {\n                        // This may be a critical error for the Admin Node.js SDK, so log a warning.\n                        // But getToken() may also just have temporarily failed, so we still want to\n                        // continue retrying.\n                        warn(error);\n                    }\n                    closeFn();\n                }\n            }\n        }\n    }\n    interrupt(reason) {\n        log('Interrupting connection for reason: ' + reason);\n        this.interruptReasons_[reason] = true;\n        if (this.realtime_) {\n            this.realtime_.close();\n        }\n        else {\n            if (this.establishConnectionTimer_) {\n                clearTimeout(this.establishConnectionTimer_);\n                this.establishConnectionTimer_ = null;\n            }\n            if (this.connected_) {\n                this.onRealtimeDisconnect_();\n            }\n        }\n    }\n    resume(reason) {\n        log('Resuming connection for reason: ' + reason);\n        delete this.interruptReasons_[reason];\n        if (isEmpty(this.interruptReasons_)) {\n            this.reconnectDelay_ = RECONNECT_MIN_DELAY;\n            if (!this.realtime_) {\n                this.scheduleConnect_(0);\n            }\n        }\n    }\n    handleTimestamp_(timestamp) {\n        const delta = timestamp - new Date().getTime();\n        this.onServerInfoUpdate_({ serverTimeOffset: delta });\n    }\n    cancelSentTransactions_() {\n        for (let i = 0; i < this.outstandingPuts_.length; i++) {\n            const put = this.outstandingPuts_[i];\n            if (put && /*hash*/ 'h' in put.request && put.queued) {\n                if (put.onComplete) {\n                    put.onComplete('disconnect');\n                }\n                delete this.outstandingPuts_[i];\n                this.outstandingPutCount_--;\n            }\n        }\n        // Clean up array occasionally.\n        if (this.outstandingPutCount_ === 0) {\n            this.outstandingPuts_ = [];\n        }\n    }\n    onListenRevoked_(pathString, query) {\n        // Remove the listen and manufacture a \"permission_denied\" error for the failed listen.\n        let queryId;\n        if (!query) {\n            queryId = 'default';\n        }\n        else {\n            queryId = query.map(q => ObjectToUniqueKey(q)).join('$');\n        }\n        const listen = this.removeListen_(pathString, queryId);\n        if (listen && listen.onComplete) {\n            listen.onComplete('permission_denied');\n        }\n    }\n    removeListen_(pathString, queryId) {\n        const normalizedPathString = new Path(pathString).toString(); // normalize path.\n        let listen;\n        if (this.listens.has(normalizedPathString)) {\n            const map = this.listens.get(normalizedPathString);\n            listen = map.get(queryId);\n            map.delete(queryId);\n            if (map.size === 0) {\n                this.listens.delete(normalizedPathString);\n            }\n        }\n        else {\n            // all listens for this path has already been removed\n            listen = undefined;\n        }\n        return listen;\n    }\n    onAuthRevoked_(statusCode, explanation) {\n        log('Auth token revoked: ' + statusCode + '/' + explanation);\n        this.authToken_ = null;\n        this.forceTokenRefresh_ = true;\n        this.realtime_.close();\n        if (statusCode === 'invalid_token' || statusCode === 'permission_denied') {\n            // We'll wait a couple times before logging the warning / increasing the\n            // retry period since oauth tokens will report as \"invalid\" if they're\n            // just expired. Plus there may be transient issues that resolve themselves.\n            this.invalidAuthTokenCount_++;\n            if (this.invalidAuthTokenCount_ >= INVALID_TOKEN_THRESHOLD) {\n                // Set a long reconnect delay because recovery is unlikely\n                this.reconnectDelay_ = RECONNECT_MAX_DELAY_FOR_ADMINS;\n                // Notify the auth token provider that the token is invalid, which will log\n                // a warning\n                this.authTokenProvider_.notifyForInvalidToken();\n            }\n        }\n    }\n    onAppCheckRevoked_(statusCode, explanation) {\n        log('App check token revoked: ' + statusCode + '/' + explanation);\n        this.appCheckToken_ = null;\n        this.forceTokenRefresh_ = true;\n        // Note: We don't close the connection as the developer may not have\n        // enforcement enabled. The backend closes connections with enforcements.\n        if (statusCode === 'invalid_token' || statusCode === 'permission_denied') {\n            // We'll wait a couple times before logging the warning / increasing the\n            // retry period since oauth tokens will report as \"invalid\" if they're\n            // just expired. Plus there may be transient issues that resolve themselves.\n            this.invalidAppCheckTokenCount_++;\n            if (this.invalidAppCheckTokenCount_ >= INVALID_TOKEN_THRESHOLD) {\n                this.appCheckTokenProvider_.notifyForInvalidToken();\n            }\n        }\n    }\n    onSecurityDebugPacket_(body) {\n        if (this.securityDebugCallback_) {\n            this.securityDebugCallback_(body);\n        }\n        else {\n            if ('msg' in body) {\n                console.log('FIREBASE: ' + body['msg'].replace('\\n', '\\nFIREBASE: '));\n            }\n        }\n    }\n    restoreState_() {\n        //Re-authenticate ourselves if we have a credential stored.\n        this.tryAuth();\n        this.tryAppCheck();\n        // Puts depend on having received the corresponding data update from the server before they complete, so we must\n        // make sure to send listens before puts.\n        for (const queries of this.listens.values()) {\n            for (const listenSpec of queries.values()) {\n                this.sendListen_(listenSpec);\n            }\n        }\n        for (let i = 0; i < this.outstandingPuts_.length; i++) {\n            if (this.outstandingPuts_[i]) {\n                this.sendPut_(i);\n            }\n        }\n        while (this.onDisconnectRequestQueue_.length) {\n            const request = this.onDisconnectRequestQueue_.shift();\n            this.sendOnDisconnect_(request.action, request.pathString, request.data, request.onComplete);\n        }\n        for (let i = 0; i < this.outstandingGets_.length; i++) {\n            if (this.outstandingGets_[i]) {\n                this.sendGet_(i);\n            }\n        }\n    }\n    /**\n     * Sends client stats for first connection\n     */\n    sendConnectStats_() {\n        const stats = {};\n        let clientName = 'js';\n        if (isNodeSdk()) {\n            if (this.repoInfo_.nodeAdmin) {\n                clientName = 'admin_node';\n            }\n            else {\n                clientName = 'node';\n            }\n        }\n        stats['sdk.' + clientName + '.' + SDK_VERSION.replace(/\\./g, '-')] = 1;\n        if (isMobileCordova()) {\n            stats['framework.cordova'] = 1;\n        }\n        else if (isReactNative()) {\n            stats['framework.reactnative'] = 1;\n        }\n        this.reportStats(stats);\n    }\n    shouldReconnect_() {\n        const online = OnlineMonitor.getInstance().currentlyOnline();\n        return isEmpty(this.interruptReasons_) && online;\n    }\n}\nPersistentConnection.nextPersistentConnectionId_ = 0;\n/**\n * Counter for number of connections created. Mainly used for tagging in the logs\n */\nPersistentConnection.nextConnectionId_ = 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 */\nclass NamedNode {\n    constructor(name, node) {\n        this.name = name;\n        this.node = node;\n    }\n    static Wrap(name, node) {\n        return new NamedNode(name, node);\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 */\nclass Index {\n    /**\n     * @returns A standalone comparison function for\n     * this index\n     */\n    getCompare() {\n        return this.compare.bind(this);\n    }\n    /**\n     * Given a before and after value for a node, determine if the indexed value has changed. Even if they are different,\n     * it's possible that the changes are isolated to parts of the snapshot that are not indexed.\n     *\n     *\n     * @returns True if the portion of the snapshot being indexed changed between oldNode and newNode\n     */\n    indexedValueChanged(oldNode, newNode) {\n        const oldWrapped = new NamedNode(MIN_NAME, oldNode);\n        const newWrapped = new NamedNode(MIN_NAME, newNode);\n        return this.compare(oldWrapped, newWrapped) !== 0;\n    }\n    /**\n     * @returns a node wrapper that will sort equal to or less than\n     * any other node wrapper, using this index\n     */\n    minPost() {\n        // eslint-disable-next-line @typescript-eslint/no-explicit-any\n        return NamedNode.MIN;\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 */\nlet __EMPTY_NODE;\nclass KeyIndex extends Index {\n    static get __EMPTY_NODE() {\n        return __EMPTY_NODE;\n    }\n    static set __EMPTY_NODE(val) {\n        __EMPTY_NODE = val;\n    }\n    compare(a, b) {\n        return nameCompare(a.name, b.name);\n    }\n    isDefinedOn(node) {\n        // We could probably return true here (since every node has a key), but it's never called\n        // so just leaving unimplemented for now.\n        throw assertionError('KeyIndex.isDefinedOn not expected to be called.');\n    }\n    indexedValueChanged(oldNode, newNode) {\n        return false; // The key for a node never changes.\n    }\n    minPost() {\n        // eslint-disable-next-line @typescript-eslint/no-explicit-any\n        return NamedNode.MIN;\n    }\n    maxPost() {\n        // TODO: This should really be created once and cached in a static property, but\n        // NamedNode isn't defined yet, so I can't use it in a static.  Bleh.\n        return new NamedNode(MAX_NAME, __EMPTY_NODE);\n    }\n    makePost(indexValue, name) {\n        assert(typeof indexValue === 'string', 'KeyIndex indexValue must always be a string.');\n        // We just use empty node, but it'll never be compared, since our comparator only looks at name.\n        return new NamedNode(indexValue, __EMPTY_NODE);\n    }\n    /**\n     * @returns String representation for inclusion in a query spec\n     */\n    toString() {\n        return '.key';\n    }\n}\nconst KEY_INDEX = new KeyIndex();\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 iterator over an LLRBNode.\n */\nclass SortedMapIterator {\n    /**\n     * @param node - Node to iterate.\n     * @param isReverse_ - Whether or not to iterate in reverse\n     */\n    constructor(node, startKey, comparator, isReverse_, resultGenerator_ = null) {\n        this.isReverse_ = isReverse_;\n        this.resultGenerator_ = resultGenerator_;\n        this.nodeStack_ = [];\n        let cmp = 1;\n        while (!node.isEmpty()) {\n            node = node;\n            cmp = startKey ? comparator(node.key, startKey) : 1;\n            // flip the comparison if we're going in reverse\n            if (isReverse_) {\n                cmp *= -1;\n            }\n            if (cmp < 0) {\n                // This node is less than our start key. ignore it\n                if (this.isReverse_) {\n                    node = node.left;\n                }\n                else {\n                    node = node.right;\n                }\n            }\n            else if (cmp === 0) {\n                // This node is exactly equal to our start key. Push it on the stack, but stop iterating;\n                this.nodeStack_.push(node);\n                break;\n            }\n            else {\n                // This node is greater than our start key, add it to the stack and move to the next one\n                this.nodeStack_.push(node);\n                if (this.isReverse_) {\n                    node = node.right;\n                }\n                else {\n                    node = node.left;\n                }\n            }\n        }\n    }\n    getNext() {\n        if (this.nodeStack_.length === 0) {\n            return null;\n        }\n        let node = this.nodeStack_.pop();\n        let result;\n        if (this.resultGenerator_) {\n            result = this.resultGenerator_(node.key, node.value);\n        }\n        else {\n            result = { key: node.key, value: node.value };\n        }\n        if (this.isReverse_) {\n            node = node.left;\n            while (!node.isEmpty()) {\n                this.nodeStack_.push(node);\n                node = node.right;\n            }\n        }\n        else {\n            node = node.right;\n            while (!node.isEmpty()) {\n                this.nodeStack_.push(node);\n                node = node.left;\n            }\n        }\n        return result;\n    }\n    hasNext() {\n        return this.nodeStack_.length > 0;\n    }\n    peek() {\n        if (this.nodeStack_.length === 0) {\n            return null;\n        }\n        const node = this.nodeStack_[this.nodeStack_.length - 1];\n        if (this.resultGenerator_) {\n            return this.resultGenerator_(node.key, node.value);\n        }\n        else {\n            return { key: node.key, value: node.value };\n        }\n    }\n}\n/**\n * Represents a node in a Left-leaning Red-Black tree.\n */\nclass LLRBNode {\n    /**\n     * @param key - Key associated with this node.\n     * @param value - Value associated with this node.\n     * @param color - Whether this node is red.\n     * @param left - Left child.\n     * @param right - Right child.\n     */\n    constructor(key, value, color, left, right) {\n        this.key = key;\n        this.value = value;\n        this.color = color != null ? color : LLRBNode.RED;\n        this.left =\n            left != null ? left : SortedMap.EMPTY_NODE;\n        this.right =\n            right != null ? right : SortedMap.EMPTY_NODE;\n    }\n    /**\n     * Returns a copy of the current node, optionally replacing pieces of it.\n     *\n     * @param key - New key for the node, or null.\n     * @param value - New value for the node, or null.\n     * @param color - New color for the node, or null.\n     * @param left - New left child for the node, or null.\n     * @param right - New right child for the node, or null.\n     * @returns The node copy.\n     */\n    copy(key, value, color, left, right) {\n        return new LLRBNode(key != null ? key : this.key, value != null ? value : this.value, color != null ? color : this.color, left != null ? left : this.left, right != null ? right : this.right);\n    }\n    /**\n     * @returns The total number of nodes in the tree.\n     */\n    count() {\n        return this.left.count() + 1 + this.right.count();\n    }\n    /**\n     * @returns True if the tree is empty.\n     */\n    isEmpty() {\n        return false;\n    }\n    /**\n     * Traverses the tree in key order and calls the specified action function\n     * for each node.\n     *\n     * @param action - Callback function to be called for each\n     *   node.  If it returns true, traversal is aborted.\n     * @returns The first truthy value returned by action, or the last falsey\n     *   value returned by action\n     */\n    inorderTraversal(action) {\n        return (this.left.inorderTraversal(action) ||\n            !!action(this.key, this.value) ||\n            this.right.inorderTraversal(action));\n    }\n    /**\n     * Traverses the tree in reverse key order and calls the specified action function\n     * for each node.\n     *\n     * @param action - Callback function to be called for each\n     * node.  If it returns true, traversal is aborted.\n     * @returns True if traversal was aborted.\n     */\n    reverseTraversal(action) {\n        return (this.right.reverseTraversal(action) ||\n            action(this.key, this.value) ||\n            this.left.reverseTraversal(action));\n    }\n    /**\n     * @returns The minimum node in the tree.\n     */\n    min_() {\n        if (this.left.isEmpty()) {\n            return this;\n        }\n        else {\n            return this.left.min_();\n        }\n    }\n    /**\n     * @returns The maximum key in the tree.\n     */\n    minKey() {\n        return this.min_().key;\n    }\n    /**\n     * @returns The maximum key in the tree.\n     */\n    maxKey() {\n        if (this.right.isEmpty()) {\n            return this.key;\n        }\n        else {\n            return this.right.maxKey();\n        }\n    }\n    /**\n     * @param key - Key to insert.\n     * @param value - Value to insert.\n     * @param comparator - Comparator.\n     * @returns New tree, with the key/value added.\n     */\n    insert(key, value, comparator) {\n        let n = this;\n        const cmp = comparator(key, n.key);\n        if (cmp < 0) {\n            n = n.copy(null, null, null, n.left.insert(key, value, comparator), null);\n        }\n        else if (cmp === 0) {\n            n = n.copy(null, value, null, null, null);\n        }\n        else {\n            n = n.copy(null, null, null, null, n.right.insert(key, value, comparator));\n        }\n        return n.fixUp_();\n    }\n    /**\n     * @returns New tree, with the minimum key removed.\n     */\n    removeMin_() {\n        if (this.left.isEmpty()) {\n            return SortedMap.EMPTY_NODE;\n        }\n        let n = this;\n        if (!n.left.isRed_() && !n.left.left.isRed_()) {\n            n = n.moveRedLeft_();\n        }\n        n = n.copy(null, null, null, n.left.removeMin_(), null);\n        return n.fixUp_();\n    }\n    /**\n     * @param key - The key of the item to remove.\n     * @param comparator - Comparator.\n     * @returns New tree, with the specified item removed.\n     */\n    remove(key, comparator) {\n        let n, smallest;\n        n = this;\n        if (comparator(key, n.key) < 0) {\n            if (!n.left.isEmpty() && !n.left.isRed_() && !n.left.left.isRed_()) {\n                n = n.moveRedLeft_();\n            }\n            n = n.copy(null, null, null, n.left.remove(key, comparator), null);\n        }\n        else {\n            if (n.left.isRed_()) {\n                n = n.rotateRight_();\n            }\n            if (!n.right.isEmpty() && !n.right.isRed_() && !n.right.left.isRed_()) {\n                n = n.moveRedRight_();\n            }\n            if (comparator(key, n.key) === 0) {\n                if (n.right.isEmpty()) {\n                    return SortedMap.EMPTY_NODE;\n                }\n                else {\n                    smallest = n.right.min_();\n                    n = n.copy(smallest.key, smallest.value, null, null, n.right.removeMin_());\n                }\n            }\n            n = n.copy(null, null, null, null, n.right.remove(key, comparator));\n        }\n        return n.fixUp_();\n    }\n    /**\n     * @returns Whether this is a RED node.\n     */\n    isRed_() {\n        return this.color;\n    }\n    /**\n     * @returns New tree after performing any needed rotations.\n     */\n    fixUp_() {\n        let n = this;\n        if (n.right.isRed_() && !n.left.isRed_()) {\n            n = n.rotateLeft_();\n        }\n        if (n.left.isRed_() && n.left.left.isRed_()) {\n            n = n.rotateRight_();\n        }\n        if (n.left.isRed_() && n.right.isRed_()) {\n            n = n.colorFlip_();\n        }\n        return n;\n    }\n    /**\n     * @returns New tree, after moveRedLeft.\n     */\n    moveRedLeft_() {\n        let n = this.colorFlip_();\n        if (n.right.left.isRed_()) {\n            n = n.copy(null, null, null, null, n.right.rotateRight_());\n            n = n.rotateLeft_();\n            n = n.colorFlip_();\n        }\n        return n;\n    }\n    /**\n     * @returns New tree, after moveRedRight.\n     */\n    moveRedRight_() {\n        let n = this.colorFlip_();\n        if (n.left.left.isRed_()) {\n            n = n.rotateRight_();\n            n = n.colorFlip_();\n        }\n        return n;\n    }\n    /**\n     * @returns New tree, after rotateLeft.\n     */\n    rotateLeft_() {\n        const nl = this.copy(null, null, LLRBNode.RED, null, this.right.left);\n        return this.right.copy(null, null, this.color, nl, null);\n    }\n    /**\n     * @returns New tree, after rotateRight.\n     */\n    rotateRight_() {\n        const nr = this.copy(null, null, LLRBNode.RED, this.left.right, null);\n        return this.left.copy(null, null, this.color, null, nr);\n    }\n    /**\n     * @returns Newt ree, after colorFlip.\n     */\n    colorFlip_() {\n        const left = this.left.copy(null, null, !this.left.color, null, null);\n        const right = this.right.copy(null, null, !this.right.color, null, null);\n        return this.copy(null, null, !this.color, left, right);\n    }\n    /**\n     * For testing.\n     *\n     * @returns True if all is well.\n     */\n    checkMaxDepth_() {\n        const blackDepth = this.check_();\n        return Math.pow(2.0, blackDepth) <= this.count() + 1;\n    }\n    check_() {\n        if (this.isRed_() && this.left.isRed_()) {\n            throw new Error('Red node has red child(' + this.key + ',' + this.value + ')');\n        }\n        if (this.right.isRed_()) {\n            throw new Error('Right child of (' + this.key + ',' + this.value + ') is red');\n        }\n        const blackDepth = this.left.check_();\n        if (blackDepth !== this.right.check_()) {\n            throw new Error('Black depths differ');\n        }\n        else {\n            return blackDepth + (this.isRed_() ? 0 : 1);\n        }\n    }\n}\nLLRBNode.RED = true;\nLLRBNode.BLACK = false;\n/**\n * Represents an empty node (a leaf node in the Red-Black Tree).\n */\nclass LLRBEmptyNode {\n    /**\n     * Returns a copy of the current node.\n     *\n     * @returns The node copy.\n     */\n    copy(key, value, color, left, right) {\n        return this;\n    }\n    /**\n     * Returns a copy of the tree, with the specified key/value added.\n     *\n     * @param key - Key to be added.\n     * @param value - Value to be added.\n     * @param comparator - Comparator.\n     * @returns New tree, with item added.\n     */\n    insert(key, value, comparator) {\n        return new LLRBNode(key, value, null);\n    }\n    /**\n     * Returns a copy of the tree, with the specified key removed.\n     *\n     * @param key - The key to remove.\n     * @param comparator - Comparator.\n     * @returns New tree, with item removed.\n     */\n    remove(key, comparator) {\n        return this;\n    }\n    /**\n     * @returns The total number of nodes in the tree.\n     */\n    count() {\n        return 0;\n    }\n    /**\n     * @returns True if the tree is empty.\n     */\n    isEmpty() {\n        return true;\n    }\n    /**\n     * Traverses the tree in key order and calls the specified action function\n     * for each node.\n     *\n     * @param action - Callback function to be called for each\n     * node.  If it returns true, traversal is aborted.\n     * @returns True if traversal was aborted.\n     */\n    inorderTraversal(action) {\n        return false;\n    }\n    /**\n     * Traverses the tree in reverse key order and calls the specified action function\n     * for each node.\n     *\n     * @param action - Callback function to be called for each\n     * node.  If it returns true, traversal is aborted.\n     * @returns True if traversal was aborted.\n     */\n    reverseTraversal(action) {\n        return false;\n    }\n    minKey() {\n        return null;\n    }\n    maxKey() {\n        return null;\n    }\n    check_() {\n        return 0;\n    }\n    /**\n     * @returns Whether this node is red.\n     */\n    isRed_() {\n        return false;\n    }\n}\n/**\n * An immutable sorted map implementation, based on a Left-leaning Red-Black\n * tree.\n */\nclass SortedMap {\n    /**\n     * @param comparator_ - Key comparator.\n     * @param root_ - Optional root node for the map.\n     */\n    constructor(comparator_, root_ = SortedMap.EMPTY_NODE) {\n        this.comparator_ = comparator_;\n        this.root_ = root_;\n    }\n    /**\n     * Returns a copy of the map, with the specified key/value added or replaced.\n     * (TODO: We should perhaps rename this method to 'put')\n     *\n     * @param key - Key to be added.\n     * @param value - Value to be added.\n     * @returns New map, with item added.\n     */\n    insert(key, value) {\n        return new SortedMap(this.comparator_, this.root_\n            .insert(key, value, this.comparator_)\n            .copy(null, null, LLRBNode.BLACK, null, null));\n    }\n    /**\n     * Returns a copy of the map, with the specified key removed.\n     *\n     * @param key - The key to remove.\n     * @returns New map, with item removed.\n     */\n    remove(key) {\n        return new SortedMap(this.comparator_, this.root_\n            .remove(key, this.comparator_)\n            .copy(null, null, LLRBNode.BLACK, null, null));\n    }\n    /**\n     * Returns the value of the node with the given key, or null.\n     *\n     * @param key - The key to look up.\n     * @returns The value of the node with the given key, or null if the\n     * key doesn't exist.\n     */\n    get(key) {\n        let cmp;\n        let node = this.root_;\n        while (!node.isEmpty()) {\n            cmp = this.comparator_(key, node.key);\n            if (cmp === 0) {\n                return node.value;\n            }\n            else if (cmp < 0) {\n                node = node.left;\n            }\n            else if (cmp > 0) {\n                node = node.right;\n            }\n        }\n        return null;\n    }\n    /**\n     * Returns the key of the item *before* the specified key, or null if key is the first item.\n     * @param key - The key to find the predecessor of\n     * @returns The predecessor key.\n     */\n    getPredecessorKey(key) {\n        let cmp, node = this.root_, rightParent = null;\n        while (!node.isEmpty()) {\n            cmp = this.comparator_(key, node.key);\n            if (cmp === 0) {\n                if (!node.left.isEmpty()) {\n                    node = node.left;\n                    while (!node.right.isEmpty()) {\n                        node = node.right;\n                    }\n                    return node.key;\n                }\n                else if (rightParent) {\n                    return rightParent.key;\n                }\n                else {\n                    return null; // first item.\n                }\n            }\n            else if (cmp < 0) {\n                node = node.left;\n            }\n            else if (cmp > 0) {\n                rightParent = node;\n                node = node.right;\n            }\n        }\n        throw new Error('Attempted to find predecessor key for a nonexistent key.  What gives?');\n    }\n    /**\n     * @returns True if the map is empty.\n     */\n    isEmpty() {\n        return this.root_.isEmpty();\n    }\n    /**\n     * @returns The total number of nodes in the map.\n     */\n    count() {\n        return this.root_.count();\n    }\n    /**\n     * @returns The minimum key in the map.\n     */\n    minKey() {\n        return this.root_.minKey();\n    }\n    /**\n     * @returns The maximum key in the map.\n     */\n    maxKey() {\n        return this.root_.maxKey();\n    }\n    /**\n     * Traverses the map in key order and calls the specified action function\n     * for each key/value pair.\n     *\n     * @param action - Callback function to be called\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     */\n    inorderTraversal(action) {\n        return this.root_.inorderTraversal(action);\n    }\n    /**\n     * Traverses the map in reverse key order and calls the specified action function\n     * for each key/value pair.\n     *\n     * @param action - Callback function to be called\n     * for each key/value pair.  If action returns true, traversal is aborted.\n     * @returns True if the traversal was aborted.\n     */\n    reverseTraversal(action) {\n        return this.root_.reverseTraversal(action);\n    }\n    /**\n     * Returns an iterator over the SortedMap.\n     * @returns The iterator.\n     */\n    getIterator(resultGenerator) {\n        return new SortedMapIterator(this.root_, null, this.comparator_, false, resultGenerator);\n    }\n    getIteratorFrom(key, resultGenerator) {\n        return new SortedMapIterator(this.root_, key, this.comparator_, false, resultGenerator);\n    }\n    getReverseIteratorFrom(key, resultGenerator) {\n        return new SortedMapIterator(this.root_, key, this.comparator_, true, resultGenerator);\n    }\n    getReverseIterator(resultGenerator) {\n        return new SortedMapIterator(this.root_, null, this.comparator_, true, resultGenerator);\n    }\n}\n/**\n * Always use the same empty node, to reduce memory.\n */\nSortedMap.EMPTY_NODE = new LLRBEmptyNode();\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 NAME_ONLY_COMPARATOR(left, right) {\n    return nameCompare(left.name, right.name);\n}\nfunction NAME_COMPARATOR(left, right) {\n    return nameCompare(left, right);\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 */\nlet MAX_NODE$2;\nfunction setMaxNode$1(val) {\n    MAX_NODE$2 = val;\n}\nconst priorityHashText = function (priority) {\n    if (typeof priority === 'number') {\n        return 'number:' + doubleToIEEE754String(priority);\n    }\n    else {\n        return 'string:' + priority;\n    }\n};\n/**\n * Validates that a priority snapshot Node is valid.\n */\nconst validatePriorityNode = function (priorityNode) {\n    if (priorityNode.isLeafNode()) {\n        const val = priorityNode.val();\n        assert(typeof val === 'string' ||\n            typeof val === 'number' ||\n            (typeof val === 'object' && contains(val, '.sv')), 'Priority must be a string or number.');\n    }\n    else {\n        assert(priorityNode === MAX_NODE$2 || priorityNode.isEmpty(), 'priority of unexpected type.');\n    }\n    // Don't call getPriority() on MAX_NODE to avoid hitting assertion.\n    assert(priorityNode === MAX_NODE$2 || priorityNode.getPriority().isEmpty(), \"Priority nodes can't have a priority of their own.\");\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 */\nlet __childrenNodeConstructor;\n/**\n * LeafNode is a class for storing leaf nodes in a DataSnapshot.  It\n * implements Node and stores the value of the node (a string,\n * number, or boolean) accessible via getValue().\n */\nclass LeafNode {\n    static set __childrenNodeConstructor(val) {\n        __childrenNodeConstructor = val;\n    }\n    static get __childrenNodeConstructor() {\n        return __childrenNodeConstructor;\n    }\n    /**\n     * @param value_ - The value to store in this leaf node. The object type is\n     * possible in the event of a deferred value\n     * @param priorityNode_ - The priority of this node.\n     */\n    constructor(value_, priorityNode_ = LeafNode.__childrenNodeConstructor.EMPTY_NODE) {\n        this.value_ = value_;\n        this.priorityNode_ = priorityNode_;\n        this.lazyHash_ = null;\n        assert(this.value_ !== undefined && this.value_ !== null, \"LeafNode shouldn't be created with null/undefined value.\");\n        validatePriorityNode(this.priorityNode_);\n    }\n    /** @inheritDoc */\n    isLeafNode() {\n        return true;\n    }\n    /** @inheritDoc */\n    getPriority() {\n        return this.priorityNode_;\n    }\n    /** @inheritDoc */\n    updatePriority(newPriorityNode) {\n        return new LeafNode(this.value_, newPriorityNode);\n    }\n    /** @inheritDoc */\n    getImmediateChild(childName) {\n        // Hack to treat priority as a regular child\n        if (childName === '.priority') {\n            return this.priorityNode_;\n        }\n        else {\n            return LeafNode.__childrenNodeConstructor.EMPTY_NODE;\n        }\n    }\n    /** @inheritDoc */\n    getChild(path) {\n        if (pathIsEmpty(path)) {\n            return this;\n        }\n        else if (pathGetFront(path) === '.priority') {\n            return this.priorityNode_;\n        }\n        else {\n            return LeafNode.__childrenNodeConstructor.EMPTY_NODE;\n        }\n    }\n    hasChild() {\n        return false;\n    }\n    /** @inheritDoc */\n    getPredecessorChildName(childName, childNode) {\n        return null;\n    }\n    /** @inheritDoc */\n    updateImmediateChild(childName, newChildNode) {\n        if (childName === '.priority') {\n            return this.updatePriority(newChildNode);\n        }\n        else if (newChildNode.isEmpty() && childName !== '.priority') {\n            return this;\n        }\n        else {\n            return LeafNode.__childrenNodeConstructor.EMPTY_NODE.updateImmediateChild(childName, newChildNode).updatePriority(this.priorityNode_);\n        }\n    }\n    /** @inheritDoc */\n    updateChild(path, newChildNode) {\n        const front = pathGetFront(path);\n        if (front === null) {\n            return newChildNode;\n        }\n        else if (newChildNode.isEmpty() && front !== '.priority') {\n            return this;\n        }\n        else {\n            assert(front !== '.priority' || pathGetLength(path) === 1, '.priority must be the last token in a path');\n            return this.updateImmediateChild(front, LeafNode.__childrenNodeConstructor.EMPTY_NODE.updateChild(pathPopFront(path), newChildNode));\n        }\n    }\n    /** @inheritDoc */\n    isEmpty() {\n        return false;\n    }\n    /** @inheritDoc */\n    numChildren() {\n        return 0;\n    }\n    /** @inheritDoc */\n    forEachChild(index, action) {\n        return false;\n    }\n    val(exportFormat) {\n        if (exportFormat && !this.getPriority().isEmpty()) {\n            return {\n                '.value': this.getValue(),\n                '.priority': this.getPriority().val()\n            };\n        }\n        else {\n            return this.getValue();\n        }\n    }\n    /** @inheritDoc */\n    hash() {\n        if (this.lazyHash_ === null) {\n            let toHash = '';\n            if (!this.priorityNode_.isEmpty()) {\n                toHash +=\n                    'priority:' +\n                        priorityHashText(this.priorityNode_.val()) +\n                        ':';\n            }\n            const type = typeof this.value_;\n            toHash += type + ':';\n            if (type === 'number') {\n                toHash += doubleToIEEE754String(this.value_);\n            }\n            else {\n                toHash += this.value_;\n            }\n            this.lazyHash_ = sha1(toHash);\n        }\n        return this.lazyHash_;\n    }\n    /**\n     * Returns the value of the leaf node.\n     * @returns The value of the node.\n     */\n    getValue() {\n        return this.value_;\n    }\n    compareTo(other) {\n        if (other === LeafNode.__childrenNodeConstructor.EMPTY_NODE) {\n            return 1;\n        }\n        else if (other instanceof LeafNode.__childrenNodeConstructor) {\n            return -1;\n        }\n        else {\n            assert(other.isLeafNode(), 'Unknown node type');\n            return this.compareToLeafNode_(other);\n        }\n    }\n    /**\n     * Comparison specifically for two leaf nodes\n     */\n    compareToLeafNode_(otherLeaf) {\n        const otherLeafType = typeof otherLeaf.value_;\n        const thisLeafType = typeof this.value_;\n        const otherIndex = LeafNode.VALUE_TYPE_ORDER.indexOf(otherLeafType);\n        const thisIndex = LeafNode.VALUE_TYPE_ORDER.indexOf(thisLeafType);\n        assert(otherIndex >= 0, 'Unknown leaf type: ' + otherLeafType);\n        assert(thisIndex >= 0, 'Unknown leaf type: ' + thisLeafType);\n        if (otherIndex === thisIndex) {\n            // Same type, compare values\n            if (thisLeafType === 'object') {\n                // Deferred value nodes are all equal, but we should also never get to this point...\n                return 0;\n            }\n            else {\n                // Note that this works because true > false, all others are number or string comparisons\n                if (this.value_ < otherLeaf.value_) {\n                    return -1;\n                }\n                else if (this.value_ === otherLeaf.value_) {\n                    return 0;\n                }\n                else {\n                    return 1;\n                }\n            }\n        }\n        else {\n            return thisIndex - otherIndex;\n        }\n    }\n    withIndex() {\n        return this;\n    }\n    isIndexed() {\n        return true;\n    }\n    equals(other) {\n        if (other === this) {\n            return true;\n        }\n        else if (other.isLeafNode()) {\n            const otherLeaf = other;\n            return (this.value_ === otherLeaf.value_ &&\n                this.priorityNode_.equals(otherLeaf.priorityNode_));\n        }\n        else {\n            return false;\n        }\n    }\n}\n/**\n * The sort order for comparing leaf nodes of different types. If two leaf nodes have\n * the same type, the comparison falls back to their value\n */\nLeafNode.VALUE_TYPE_ORDER = ['object', 'boolean', 'number', 'string'];\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 nodeFromJSON$1;\nlet MAX_NODE$1;\nfunction setNodeFromJSON(val) {\n    nodeFromJSON$1 = val;\n}\nfunction setMaxNode(val) {\n    MAX_NODE$1 = val;\n}\nclass PriorityIndex extends Index {\n    compare(a, b) {\n        const aPriority = a.node.getPriority();\n        const bPriority = b.node.getPriority();\n        const indexCmp = aPriority.compareTo(bPriority);\n        if (indexCmp === 0) {\n            return nameCompare(a.name, b.name);\n        }\n        else {\n            return indexCmp;\n        }\n    }\n    isDefinedOn(node) {\n        return !node.getPriority().isEmpty();\n    }\n    indexedValueChanged(oldNode, newNode) {\n        return !oldNode.getPriority().equals(newNode.getPriority());\n    }\n    minPost() {\n        // eslint-disable-next-line @typescript-eslint/no-explicit-any\n        return NamedNode.MIN;\n    }\n    maxPost() {\n        return new NamedNode(MAX_NAME, new LeafNode('[PRIORITY-POST]', MAX_NODE$1));\n    }\n    makePost(indexValue, name) {\n        const priorityNode = nodeFromJSON$1(indexValue);\n        return new NamedNode(name, new LeafNode('[PRIORITY-POST]', priorityNode));\n    }\n    /**\n     * @returns String representation for inclusion in a query spec\n     */\n    toString() {\n        return '.priority';\n    }\n}\nconst PRIORITY_INDEX = new PriorityIndex();\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 LOG_2 = Math.log(2);\nclass Base12Num {\n    constructor(length) {\n        const logBase2 = (num) => \n        // eslint-disable-next-line @typescript-eslint/no-explicit-any\n        parseInt((Math.log(num) / LOG_2), 10);\n        const bitMask = (bits) => parseInt(Array(bits + 1).join('1'), 2);\n        this.count = logBase2(length + 1);\n        this.current_ = this.count - 1;\n        const mask = bitMask(this.count);\n        this.bits_ = (length + 1) & mask;\n    }\n    nextBitIsOne() {\n        //noinspection JSBitwiseOperatorUsage\n        const result = !(this.bits_ & (0x1 << this.current_));\n        this.current_--;\n        return result;\n    }\n}\n/**\n * Takes a list of child nodes and constructs a SortedSet using the given comparison\n * function\n *\n * Uses the algorithm described in the paper linked here:\n * http://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.46.1458\n *\n * @param childList - Unsorted list of children\n * @param cmp - The comparison method to be used\n * @param keyFn - An optional function to extract K from a node wrapper, if K's\n * type is not NamedNode\n * @param mapSortFn - An optional override for comparator used by the generated sorted map\n */\nconst buildChildSet = function (childList, cmp, keyFn, mapSortFn) {\n    childList.sort(cmp);\n    const buildBalancedTree = function (low, high) {\n        const length = high - low;\n        let namedNode;\n        let key;\n        if (length === 0) {\n            return null;\n        }\n        else if (length === 1) {\n            namedNode = childList[low];\n            key = keyFn ? keyFn(namedNode) : namedNode;\n            return new LLRBNode(key, namedNode.node, LLRBNode.BLACK, null, null);\n        }\n        else {\n            // eslint-disable-next-line @typescript-eslint/no-explicit-any\n            const middle = parseInt((length / 2), 10) + low;\n            const left = buildBalancedTree(low, middle);\n            const right = buildBalancedTree(middle + 1, high);\n            namedNode = childList[middle];\n            key = keyFn ? keyFn(namedNode) : namedNode;\n            return new LLRBNode(key, namedNode.node, LLRBNode.BLACK, left, right);\n        }\n    };\n    const buildFrom12Array = function (base12) {\n        let node = null;\n        let root = null;\n        let index = childList.length;\n        const buildPennant = function (chunkSize, color) {\n            const low = index - chunkSize;\n            const high = index;\n            index -= chunkSize;\n            const childTree = buildBalancedTree(low + 1, high);\n            const namedNode = childList[low];\n            const key = keyFn ? keyFn(namedNode) : namedNode;\n            attachPennant(new LLRBNode(key, namedNode.node, color, null, childTree));\n        };\n        const attachPennant = function (pennant) {\n            if (node) {\n                node.left = pennant;\n                node = pennant;\n            }\n            else {\n                root = pennant;\n                node = pennant;\n            }\n        };\n        for (let i = 0; i < base12.count; ++i) {\n            const isOne = base12.nextBitIsOne();\n            // The number of nodes taken in each slice is 2^(arr.length - (i + 1))\n            const chunkSize = Math.pow(2, base12.count - (i + 1));\n            if (isOne) {\n                buildPennant(chunkSize, LLRBNode.BLACK);\n            }\n            else {\n                // current == 2\n                buildPennant(chunkSize, LLRBNode.BLACK);\n                buildPennant(chunkSize, LLRBNode.RED);\n            }\n        }\n        return root;\n    };\n    const base12 = new Base12Num(childList.length);\n    const root = buildFrom12Array(base12);\n    // eslint-disable-next-line @typescript-eslint/no-explicit-any\n    return new SortedMap(mapSortFn || cmp, root);\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 */\nlet _defaultIndexMap;\nconst fallbackObject = {};\nclass IndexMap {\n    /**\n     * The default IndexMap for nodes without a priority\n     */\n    static get Default() {\n        assert(fallbackObject && PRIORITY_INDEX, 'ChildrenNode.ts has not been loaded');\n        _defaultIndexMap =\n            _defaultIndexMap ||\n                new IndexMap({ '.priority': fallbackObject }, { '.priority': PRIORITY_INDEX });\n        return _defaultIndexMap;\n    }\n    constructor(indexes_, indexSet_) {\n        this.indexes_ = indexes_;\n        this.indexSet_ = indexSet_;\n    }\n    get(indexKey) {\n        const sortedMap = safeGet(this.indexes_, indexKey);\n        if (!sortedMap) {\n            throw new Error('No index defined for ' + indexKey);\n        }\n        if (sortedMap instanceof SortedMap) {\n            return sortedMap;\n        }\n        else {\n            // The index exists, but it falls back to just name comparison. Return null so that the calling code uses the\n            // regular child map\n            return null;\n        }\n    }\n    hasIndex(indexDefinition) {\n        return contains(this.indexSet_, indexDefinition.toString());\n    }\n    addIndex(indexDefinition, existingChildren) {\n        assert(indexDefinition !== KEY_INDEX, \"KeyIndex always exists and isn't meant to be added to the IndexMap.\");\n        const childList = [];\n        let sawIndexedValue = false;\n        const iter = existingChildren.getIterator(NamedNode.Wrap);\n        let next = iter.getNext();\n        while (next) {\n            sawIndexedValue =\n                sawIndexedValue || indexDefinition.isDefinedOn(next.node);\n            childList.push(next);\n            next = iter.getNext();\n        }\n        let newIndex;\n        if (sawIndexedValue) {\n            newIndex = buildChildSet(childList, indexDefinition.getCompare());\n        }\n        else {\n            newIndex = fallbackObject;\n        }\n        const indexName = indexDefinition.toString();\n        const newIndexSet = Object.assign({}, this.indexSet_);\n        newIndexSet[indexName] = indexDefinition;\n        const newIndexes = Object.assign({}, this.indexes_);\n        newIndexes[indexName] = newIndex;\n        return new IndexMap(newIndexes, newIndexSet);\n    }\n    /**\n     * Ensure that this node is properly tracked in any indexes that we're maintaining\n     */\n    addToIndexes(namedNode, existingChildren) {\n        const newIndexes = map(this.indexes_, (indexedChildren, indexName) => {\n            const index = safeGet(this.indexSet_, indexName);\n            assert(index, 'Missing index implementation for ' + indexName);\n            if (indexedChildren === fallbackObject) {\n                // Check to see if we need to index everything\n                if (index.isDefinedOn(namedNode.node)) {\n                    // We need to build this index\n                    const childList = [];\n                    const iter = existingChildren.getIterator(NamedNode.Wrap);\n                    let next = iter.getNext();\n                    while (next) {\n                        if (next.name !== namedNode.name) {\n                            childList.push(next);\n                        }\n                        next = iter.getNext();\n                    }\n                    childList.push(namedNode);\n                    return buildChildSet(childList, index.getCompare());\n                }\n                else {\n                    // No change, this remains a fallback\n                    return fallbackObject;\n                }\n            }\n            else {\n                const existingSnap = existingChildren.get(namedNode.name);\n                let newChildren = indexedChildren;\n                if (existingSnap) {\n                    newChildren = newChildren.remove(new NamedNode(namedNode.name, existingSnap));\n                }\n                return newChildren.insert(namedNode, namedNode.node);\n            }\n        });\n        return new IndexMap(newIndexes, this.indexSet_);\n    }\n    /**\n     * Create a new IndexMap instance with the given value removed\n     */\n    removeFromIndexes(namedNode, existingChildren) {\n        const newIndexes = map(this.indexes_, (indexedChildren) => {\n            if (indexedChildren === fallbackObject) {\n                // This is the fallback. Just return it, nothing to do in this case\n                return indexedChildren;\n            }\n            else {\n                const existingSnap = existingChildren.get(namedNode.name);\n                if (existingSnap) {\n                    return indexedChildren.remove(new NamedNode(namedNode.name, existingSnap));\n                }\n                else {\n                    // No record of this child\n                    return indexedChildren;\n                }\n            }\n        });\n        return new IndexMap(newIndexes, this.indexSet_);\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// TODO: For memory savings, don't store priorityNode_ if it's empty.\nlet EMPTY_NODE;\n/**\n * ChildrenNode is a class for storing internal nodes in a DataSnapshot\n * (i.e. nodes with children).  It implements Node and stores the\n * list of children in the children property, sorted by child name.\n */\nclass ChildrenNode {\n    static get EMPTY_NODE() {\n        return (EMPTY_NODE ||\n            (EMPTY_NODE = new ChildrenNode(new SortedMap(NAME_COMPARATOR), null, IndexMap.Default)));\n    }\n    /**\n     * @param children_ - List of children of this node..\n     * @param priorityNode_ - The priority of this node (as a snapshot node).\n     */\n    constructor(children_, priorityNode_, indexMap_) {\n        this.children_ = children_;\n        this.priorityNode_ = priorityNode_;\n        this.indexMap_ = indexMap_;\n        this.lazyHash_ = null;\n        /**\n         * Note: The only reason we allow null priority is for EMPTY_NODE, since we can't use\n         * EMPTY_NODE as the priority of EMPTY_NODE.  We might want to consider making EMPTY_NODE its own\n         * class instead of an empty ChildrenNode.\n         */\n        if (this.priorityNode_) {\n            validatePriorityNode(this.priorityNode_);\n        }\n        if (this.children_.isEmpty()) {\n            assert(!this.priorityNode_ || this.priorityNode_.isEmpty(), 'An empty node cannot have a priority');\n        }\n    }\n    /** @inheritDoc */\n    isLeafNode() {\n        return false;\n    }\n    /** @inheritDoc */\n    getPriority() {\n        return this.priorityNode_ || EMPTY_NODE;\n    }\n    /** @inheritDoc */\n    updatePriority(newPriorityNode) {\n        if (this.children_.isEmpty()) {\n            // Don't allow priorities on empty nodes\n            return this;\n        }\n        else {\n            return new ChildrenNode(this.children_, newPriorityNode, this.indexMap_);\n        }\n    }\n    /** @inheritDoc */\n    getImmediateChild(childName) {\n        // Hack to treat priority as a regular child\n        if (childName === '.priority') {\n            return this.getPriority();\n        }\n        else {\n            const child = this.children_.get(childName);\n            return child === null ? EMPTY_NODE : child;\n        }\n    }\n    /** @inheritDoc */\n    getChild(path) {\n        const front = pathGetFront(path);\n        if (front === null) {\n            return this;\n        }\n        return this.getImmediateChild(front).getChild(pathPopFront(path));\n    }\n    /** @inheritDoc */\n    hasChild(childName) {\n        return this.children_.get(childName) !== null;\n    }\n    /** @inheritDoc */\n    updateImmediateChild(childName, newChildNode) {\n        assert(newChildNode, 'We should always be passing snapshot nodes');\n        if (childName === '.priority') {\n            return this.updatePriority(newChildNode);\n        }\n        else {\n            const namedNode = new NamedNode(childName, newChildNode);\n            let newChildren, newIndexMap;\n            if (newChildNode.isEmpty()) {\n                newChildren = this.children_.remove(childName);\n                newIndexMap = this.indexMap_.removeFromIndexes(namedNode, this.children_);\n            }\n            else {\n                newChildren = this.children_.insert(childName, newChildNode);\n                newIndexMap = this.indexMap_.addToIndexes(namedNode, this.children_);\n            }\n            const newPriority = newChildren.isEmpty()\n                ? EMPTY_NODE\n                : this.priorityNode_;\n            return new ChildrenNode(newChildren, newPriority, newIndexMap);\n        }\n    }\n    /** @inheritDoc */\n    updateChild(path, newChildNode) {\n        const front = pathGetFront(path);\n        if (front === null) {\n            return newChildNode;\n        }\n        else {\n            assert(pathGetFront(path) !== '.priority' || pathGetLength(path) === 1, '.priority must be the last token in a path');\n            const newImmediateChild = this.getImmediateChild(front).updateChild(pathPopFront(path), newChildNode);\n            return this.updateImmediateChild(front, newImmediateChild);\n        }\n    }\n    /** @inheritDoc */\n    isEmpty() {\n        return this.children_.isEmpty();\n    }\n    /** @inheritDoc */\n    numChildren() {\n        return this.children_.count();\n    }\n    /** @inheritDoc */\n    val(exportFormat) {\n        if (this.isEmpty()) {\n            return null;\n        }\n        const obj = {};\n        let numKeys = 0, maxKey = 0, allIntegerKeys = true;\n        this.forEachChild(PRIORITY_INDEX, (key, childNode) => {\n            obj[key] = childNode.val(exportFormat);\n            numKeys++;\n            if (allIntegerKeys && ChildrenNode.INTEGER_REGEXP_.test(key)) {\n                maxKey = Math.max(maxKey, Number(key));\n            }\n            else {\n                allIntegerKeys = false;\n            }\n        });\n        if (!exportFormat && allIntegerKeys && maxKey < 2 * numKeys) {\n            // convert to array.\n            const array = [];\n            // eslint-disable-next-line guard-for-in\n            for (const key in obj) {\n                array[key] = obj[key];\n            }\n            return array;\n        }\n        else {\n            if (exportFormat && !this.getPriority().isEmpty()) {\n                obj['.priority'] = this.getPriority().val();\n            }\n            return obj;\n        }\n    }\n    /** @inheritDoc */\n    hash() {\n        if (this.lazyHash_ === null) {\n            let toHash = '';\n            if (!this.getPriority().isEmpty()) {\n                toHash +=\n                    'priority:' +\n                        priorityHashText(this.getPriority().val()) +\n                        ':';\n            }\n            this.forEachChild(PRIORITY_INDEX, (key, childNode) => {\n                const childHash = childNode.hash();\n                if (childHash !== '') {\n                    toHash += ':' + key + ':' + childHash;\n                }\n            });\n            this.lazyHash_ = toHash === '' ? '' : sha1(toHash);\n        }\n        return this.lazyHash_;\n    }\n    /** @inheritDoc */\n    getPredecessorChildName(childName, childNode, index) {\n        const idx = this.resolveIndex_(index);\n        if (idx) {\n            const predecessor = idx.getPredecessorKey(new NamedNode(childName, childNode));\n            return predecessor ? predecessor.name : null;\n        }\n        else {\n            return this.children_.getPredecessorKey(childName);\n        }\n    }\n    getFirstChildName(indexDefinition) {\n        const idx = this.resolveIndex_(indexDefinition);\n        if (idx) {\n            const minKey = idx.minKey();\n            return minKey && minKey.name;\n        }\n        else {\n            return this.children_.minKey();\n        }\n    }\n    getFirstChild(indexDefinition) {\n        const minKey = this.getFirstChildName(indexDefinition);\n        if (minKey) {\n            return new NamedNode(minKey, this.children_.get(minKey));\n        }\n        else {\n            return null;\n        }\n    }\n    /**\n     * Given an index, return the key name of the largest value we have, according to that index\n     */\n    getLastChildName(indexDefinition) {\n        const idx = this.resolveIndex_(indexDefinition);\n        if (idx) {\n            const maxKey = idx.maxKey();\n            return maxKey && maxKey.name;\n        }\n        else {\n            return this.children_.maxKey();\n        }\n    }\n    getLastChild(indexDefinition) {\n        const maxKey = this.getLastChildName(indexDefinition);\n        if (maxKey) {\n            return new NamedNode(maxKey, this.children_.get(maxKey));\n        }\n        else {\n            return null;\n        }\n    }\n    forEachChild(index, action) {\n        const idx = this.resolveIndex_(index);\n        if (idx) {\n            return idx.inorderTraversal(wrappedNode => {\n                return action(wrappedNode.name, wrappedNode.node);\n            });\n        }\n        else {\n            return this.children_.inorderTraversal(action);\n        }\n    }\n    getIterator(indexDefinition) {\n        return this.getIteratorFrom(indexDefinition.minPost(), indexDefinition);\n    }\n    getIteratorFrom(startPost, indexDefinition) {\n        const idx = this.resolveIndex_(indexDefinition);\n        if (idx) {\n            return idx.getIteratorFrom(startPost, key => key);\n        }\n        else {\n            const iterator = this.children_.getIteratorFrom(startPost.name, NamedNode.Wrap);\n            let next = iterator.peek();\n            while (next != null && indexDefinition.compare(next, startPost) < 0) {\n                iterator.getNext();\n                next = iterator.peek();\n            }\n            return iterator;\n        }\n    }\n    getReverseIterator(indexDefinition) {\n        return this.getReverseIteratorFrom(indexDefinition.maxPost(), indexDefinition);\n    }\n    getReverseIteratorFrom(endPost, indexDefinition) {\n        const idx = this.resolveIndex_(indexDefinition);\n        if (idx) {\n            return idx.getReverseIteratorFrom(endPost, key => {\n                return key;\n            });\n        }\n        else {\n            const iterator = this.children_.getReverseIteratorFrom(endPost.name, NamedNode.Wrap);\n            let next = iterator.peek();\n            while (next != null && indexDefinition.compare(next, endPost) > 0) {\n                iterator.getNext();\n                next = iterator.peek();\n            }\n            return iterator;\n        }\n    }\n    compareTo(other) {\n        if (this.isEmpty()) {\n            if (other.isEmpty()) {\n                return 0;\n            }\n            else {\n                return -1;\n            }\n        }\n        else if (other.isLeafNode() || other.isEmpty()) {\n            return 1;\n        }\n        else if (other === MAX_NODE) {\n            return -1;\n        }\n        else {\n            // Must be another node with children.\n            return 0;\n        }\n    }\n    withIndex(indexDefinition) {\n        if (indexDefinition === KEY_INDEX ||\n            this.indexMap_.hasIndex(indexDefinition)) {\n            return this;\n        }\n        else {\n            const newIndexMap = this.indexMap_.addIndex(indexDefinition, this.children_);\n            return new ChildrenNode(this.children_, this.priorityNode_, newIndexMap);\n        }\n    }\n    isIndexed(index) {\n        return index === KEY_INDEX || this.indexMap_.hasIndex(index);\n    }\n    equals(other) {\n        if (other === this) {\n            return true;\n        }\n        else if (other.isLeafNode()) {\n            return false;\n        }\n        else {\n            const otherChildrenNode = other;\n            if (!this.getPriority().equals(otherChildrenNode.getPriority())) {\n                return false;\n            }\n            else if (this.children_.count() === otherChildrenNode.children_.count()) {\n                const thisIter = this.getIterator(PRIORITY_INDEX);\n                const otherIter = otherChildrenNode.getIterator(PRIORITY_INDEX);\n                let thisCurrent = thisIter.getNext();\n                let otherCurrent = otherIter.getNext();\n                while (thisCurrent && otherCurrent) {\n                    if (thisCurrent.name !== otherCurrent.name ||\n                        !thisCurrent.node.equals(otherCurrent.node)) {\n                        return false;\n                    }\n                    thisCurrent = thisIter.getNext();\n                    otherCurrent = otherIter.getNext();\n                }\n                return thisCurrent === null && otherCurrent === null;\n            }\n            else {\n                return false;\n            }\n        }\n    }\n    /**\n     * Returns a SortedMap ordered by index, or null if the default (by-key) ordering can be used\n     * instead.\n     *\n     */\n    resolveIndex_(indexDefinition) {\n        if (indexDefinition === KEY_INDEX) {\n            return null;\n        }\n        else {\n            return this.indexMap_.get(indexDefinition.toString());\n        }\n    }\n}\nChildrenNode.INTEGER_REGEXP_ = /^(0|[1-9]\\d*)$/;\nclass MaxNode extends ChildrenNode {\n    constructor() {\n        super(new SortedMap(NAME_COMPARATOR), ChildrenNode.EMPTY_NODE, IndexMap.Default);\n    }\n    compareTo(other) {\n        if (other === this) {\n            return 0;\n        }\n        else {\n            return 1;\n        }\n    }\n    equals(other) {\n        // Not that we every compare it, but MAX_NODE is only ever equal to itself\n        return other === this;\n    }\n    getPriority() {\n        return this;\n    }\n    getImmediateChild(childName) {\n        return ChildrenNode.EMPTY_NODE;\n    }\n    isEmpty() {\n        return false;\n    }\n}\n/**\n * Marker that will sort higher than any other snapshot.\n */\nconst MAX_NODE = new MaxNode();\nObject.defineProperties(NamedNode, {\n    MIN: {\n        value: new NamedNode(MIN_NAME, ChildrenNode.EMPTY_NODE)\n    },\n    MAX: {\n        value: new NamedNode(MAX_NAME, MAX_NODE)\n    }\n});\n/**\n * Reference Extensions\n */\nKeyIndex.__EMPTY_NODE = ChildrenNode.EMPTY_NODE;\nLeafNode.__childrenNodeConstructor = ChildrenNode;\nsetMaxNode$1(MAX_NODE);\nsetMaxNode(MAX_NODE);\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 USE_HINZE = true;\n/**\n * Constructs a snapshot node representing the passed JSON and returns it.\n * @param json - JSON to create a node for.\n * @param priority - Optional priority to use.  This will be ignored if the\n * passed JSON contains a .priority property.\n */\nfunction nodeFromJSON(json, priority = null) {\n    if (json === null) {\n        return ChildrenNode.EMPTY_NODE;\n    }\n    if (typeof json === 'object' && '.priority' in json) {\n        priority = json['.priority'];\n    }\n    assert(priority === null ||\n        typeof priority === 'string' ||\n        typeof priority === 'number' ||\n        (typeof priority === 'object' && '.sv' in priority), 'Invalid priority type found: ' + typeof priority);\n    if (typeof json === 'object' && '.value' in json && json['.value'] !== null) {\n        json = json['.value'];\n    }\n    // Valid leaf nodes include non-objects or server-value wrapper objects\n    if (typeof json !== 'object' || '.sv' in json) {\n        const jsonLeaf = json;\n        return new LeafNode(jsonLeaf, nodeFromJSON(priority));\n    }\n    if (!(json instanceof Array) && USE_HINZE) {\n        const children = [];\n        let childrenHavePriority = false;\n        const hinzeJsonObj = json;\n        each(hinzeJsonObj, (key, child) => {\n            if (key.substring(0, 1) !== '.') {\n                // Ignore metadata nodes\n                const childNode = nodeFromJSON(child);\n                if (!childNode.isEmpty()) {\n                    childrenHavePriority =\n                        childrenHavePriority || !childNode.getPriority().isEmpty();\n                    children.push(new NamedNode(key, childNode));\n                }\n            }\n        });\n        if (children.length === 0) {\n            return ChildrenNode.EMPTY_NODE;\n        }\n        const childSet = buildChildSet(children, NAME_ONLY_COMPARATOR, namedNode => namedNode.name, NAME_COMPARATOR);\n        if (childrenHavePriority) {\n            const sortedChildSet = buildChildSet(children, PRIORITY_INDEX.getCompare());\n            return new ChildrenNode(childSet, nodeFromJSON(priority), new IndexMap({ '.priority': sortedChildSet }, { '.priority': PRIORITY_INDEX }));\n        }\n        else {\n            return new ChildrenNode(childSet, nodeFromJSON(priority), IndexMap.Default);\n        }\n    }\n    else {\n        let node = ChildrenNode.EMPTY_NODE;\n        each(json, (key, childData) => {\n            if (contains(json, key)) {\n                if (key.substring(0, 1) !== '.') {\n                    // ignore metadata nodes.\n                    const childNode = nodeFromJSON(childData);\n                    if (childNode.isLeafNode() || !childNode.isEmpty()) {\n                        node = node.updateImmediateChild(key, childNode);\n                    }\n                }\n            }\n        });\n        return node.updatePriority(nodeFromJSON(priority));\n    }\n}\nsetNodeFromJSON(nodeFromJSON);\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 PathIndex extends Index {\n    constructor(indexPath_) {\n        super();\n        this.indexPath_ = indexPath_;\n        assert(!pathIsEmpty(indexPath_) && pathGetFront(indexPath_) !== '.priority', \"Can't create PathIndex with empty path or .priority key\");\n    }\n    extractChild(snap) {\n        return snap.getChild(this.indexPath_);\n    }\n    isDefinedOn(node) {\n        return !node.getChild(this.indexPath_).isEmpty();\n    }\n    compare(a, b) {\n        const aChild = this.extractChild(a.node);\n        const bChild = this.extractChild(b.node);\n        const indexCmp = aChild.compareTo(bChild);\n        if (indexCmp === 0) {\n            return nameCompare(a.name, b.name);\n        }\n        else {\n            return indexCmp;\n        }\n    }\n    makePost(indexValue, name) {\n        const valueNode = nodeFromJSON(indexValue);\n        const node = ChildrenNode.EMPTY_NODE.updateChild(this.indexPath_, valueNode);\n        return new NamedNode(name, node);\n    }\n    maxPost() {\n        const node = ChildrenNode.EMPTY_NODE.updateChild(this.indexPath_, MAX_NODE);\n        return new NamedNode(MAX_NAME, node);\n    }\n    toString() {\n        return pathSlice(this.indexPath_, 0).join('/');\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 */\nclass ValueIndex extends Index {\n    compare(a, b) {\n        const indexCmp = a.node.compareTo(b.node);\n        if (indexCmp === 0) {\n            return nameCompare(a.name, b.name);\n        }\n        else {\n            return indexCmp;\n        }\n    }\n    isDefinedOn(node) {\n        return true;\n    }\n    indexedValueChanged(oldNode, newNode) {\n        return !oldNode.equals(newNode);\n    }\n    minPost() {\n        // eslint-disable-next-line @typescript-eslint/no-explicit-any\n        return NamedNode.MIN;\n    }\n    maxPost() {\n        // eslint-disable-next-line @typescript-eslint/no-explicit-any\n        return NamedNode.MAX;\n    }\n    makePost(indexValue, name) {\n        const valueNode = nodeFromJSON(indexValue);\n        return new NamedNode(name, valueNode);\n    }\n    /**\n     * @returns String representation for inclusion in a query spec\n     */\n    toString() {\n        return '.value';\n    }\n}\nconst VALUE_INDEX = new ValueIndex();\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 changeValue(snapshotNode) {\n    return { type: \"value\" /* ChangeType.VALUE */, snapshotNode };\n}\nfunction changeChildAdded(childName, snapshotNode) {\n    return { type: \"child_added\" /* ChangeType.CHILD_ADDED */, snapshotNode, childName };\n}\nfunction changeChildRemoved(childName, snapshotNode) {\n    return { type: \"child_removed\" /* ChangeType.CHILD_REMOVED */, snapshotNode, childName };\n}\nfunction changeChildChanged(childName, snapshotNode, oldSnap) {\n    return {\n        type: \"child_changed\" /* ChangeType.CHILD_CHANGED */,\n        snapshotNode,\n        childName,\n        oldSnap\n    };\n}\nfunction changeChildMoved(childName, snapshotNode) {\n    return { type: \"child_moved\" /* ChangeType.CHILD_MOVED */, snapshotNode, childName };\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 * Doesn't really filter nodes but applies an index to the node and keeps track of any changes\n */\nclass IndexedFilter {\n    constructor(index_) {\n        this.index_ = index_;\n    }\n    updateChild(snap, key, newChild, affectedPath, source, optChangeAccumulator) {\n        assert(snap.isIndexed(this.index_), 'A node must be indexed if only a child is updated');\n        const oldChild = snap.getImmediateChild(key);\n        // Check if anything actually changed.\n        if (oldChild.getChild(affectedPath).equals(newChild.getChild(affectedPath))) {\n            // There's an edge case where a child can enter or leave the view because affectedPath was set to null.\n            // In this case, affectedPath will appear null in both the old and new snapshots.  So we need\n            // to avoid treating these cases as \"nothing changed.\"\n            if (oldChild.isEmpty() === newChild.isEmpty()) {\n                // Nothing changed.\n                // This assert should be valid, but it's expensive (can dominate perf testing) so don't actually do it.\n                //assert(oldChild.equals(newChild), 'Old and new snapshots should be equal.');\n                return snap;\n            }\n        }\n        if (optChangeAccumulator != null) {\n            if (newChild.isEmpty()) {\n                if (snap.hasChild(key)) {\n                    optChangeAccumulator.trackChildChange(changeChildRemoved(key, oldChild));\n                }\n                else {\n                    assert(snap.isLeafNode(), 'A child remove without an old child only makes sense on a leaf node');\n                }\n            }\n            else if (oldChild.isEmpty()) {\n                optChangeAccumulator.trackChildChange(changeChildAdded(key, newChild));\n            }\n            else {\n                optChangeAccumulator.trackChildChange(changeChildChanged(key, newChild, oldChild));\n            }\n        }\n        if (snap.isLeafNode() && newChild.isEmpty()) {\n            return snap;\n        }\n        else {\n            // Make sure the node is indexed\n            return snap.updateImmediateChild(key, newChild).withIndex(this.index_);\n        }\n    }\n    updateFullNode(oldSnap, newSnap, optChangeAccumulator) {\n        if (optChangeAccumulator != null) {\n            if (!oldSnap.isLeafNode()) {\n                oldSnap.forEachChild(PRIORITY_INDEX, (key, childNode) => {\n                    if (!newSnap.hasChild(key)) {\n                        optChangeAccumulator.trackChildChange(changeChildRemoved(key, childNode));\n                    }\n                });\n            }\n            if (!newSnap.isLeafNode()) {\n                newSnap.forEachChild(PRIORITY_INDEX, (key, childNode) => {\n                    if (oldSnap.hasChild(key)) {\n                        const oldChild = oldSnap.getImmediateChild(key);\n                        if (!oldChild.equals(childNode)) {\n                            optChangeAccumulator.trackChildChange(changeChildChanged(key, childNode, oldChild));\n                        }\n                    }\n                    else {\n                        optChangeAccumulator.trackChildChange(changeChildAdded(key, childNode));\n                    }\n                });\n            }\n        }\n        return newSnap.withIndex(this.index_);\n    }\n    updatePriority(oldSnap, newPriority) {\n        if (oldSnap.isEmpty()) {\n            return ChildrenNode.EMPTY_NODE;\n        }\n        else {\n            return oldSnap.updatePriority(newPriority);\n        }\n    }\n    filtersNodes() {\n        return false;\n    }\n    getIndexedFilter() {\n        return this;\n    }\n    getIndex() {\n        return this.index_;\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 * Filters nodes by range and uses an IndexFilter to track any changes after filtering the node\n */\nclass RangedFilter {\n    constructor(params) {\n        this.indexedFilter_ = new IndexedFilter(params.getIndex());\n        this.index_ = params.getIndex();\n        this.startPost_ = RangedFilter.getStartPost_(params);\n        this.endPost_ = RangedFilter.getEndPost_(params);\n        this.startIsInclusive_ = !params.startAfterSet_;\n        this.endIsInclusive_ = !params.endBeforeSet_;\n    }\n    getStartPost() {\n        return this.startPost_;\n    }\n    getEndPost() {\n        return this.endPost_;\n    }\n    matches(node) {\n        const isWithinStart = this.startIsInclusive_\n            ? this.index_.compare(this.getStartPost(), node) <= 0\n            : this.index_.compare(this.getStartPost(), node) < 0;\n        const isWithinEnd = this.endIsInclusive_\n            ? this.index_.compare(node, this.getEndPost()) <= 0\n            : this.index_.compare(node, this.getEndPost()) < 0;\n        return isWithinStart && isWithinEnd;\n    }\n    updateChild(snap, key, newChild, affectedPath, source, optChangeAccumulator) {\n        if (!this.matches(new NamedNode(key, newChild))) {\n            newChild = ChildrenNode.EMPTY_NODE;\n        }\n        return this.indexedFilter_.updateChild(snap, key, newChild, affectedPath, source, optChangeAccumulator);\n    }\n    updateFullNode(oldSnap, newSnap, optChangeAccumulator) {\n        if (newSnap.isLeafNode()) {\n            // Make sure we have a children node with the correct index, not a leaf node;\n            newSnap = ChildrenNode.EMPTY_NODE;\n        }\n        let filtered = newSnap.withIndex(this.index_);\n        // Don't support priorities on queries\n        filtered = filtered.updatePriority(ChildrenNode.EMPTY_NODE);\n        const self = this;\n        newSnap.forEachChild(PRIORITY_INDEX, (key, childNode) => {\n            if (!self.matches(new NamedNode(key, childNode))) {\n                filtered = filtered.updateImmediateChild(key, ChildrenNode.EMPTY_NODE);\n            }\n        });\n        return this.indexedFilter_.updateFullNode(oldSnap, filtered, optChangeAccumulator);\n    }\n    updatePriority(oldSnap, newPriority) {\n        // Don't support priorities on queries\n        return oldSnap;\n    }\n    filtersNodes() {\n        return true;\n    }\n    getIndexedFilter() {\n        return this.indexedFilter_;\n    }\n    getIndex() {\n        return this.index_;\n    }\n    static getStartPost_(params) {\n        if (params.hasStart()) {\n            const startName = params.getIndexStartName();\n            return params.getIndex().makePost(params.getIndexStartValue(), startName);\n        }\n        else {\n            return params.getIndex().minPost();\n        }\n    }\n    static getEndPost_(params) {\n        if (params.hasEnd()) {\n            const endName = params.getIndexEndName();\n            return params.getIndex().makePost(params.getIndexEndValue(), endName);\n        }\n        else {\n            return params.getIndex().maxPost();\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 * Applies a limit and a range to a node and uses RangedFilter to do the heavy lifting where possible\n */\nclass LimitedFilter {\n    constructor(params) {\n        this.withinDirectionalStart = (node) => this.reverse_ ? this.withinEndPost(node) : this.withinStartPost(node);\n        this.withinDirectionalEnd = (node) => this.reverse_ ? this.withinStartPost(node) : this.withinEndPost(node);\n        this.withinStartPost = (node) => {\n            const compareRes = this.index_.compare(this.rangedFilter_.getStartPost(), node);\n            return this.startIsInclusive_ ? compareRes <= 0 : compareRes < 0;\n        };\n        this.withinEndPost = (node) => {\n            const compareRes = this.index_.compare(node, this.rangedFilter_.getEndPost());\n            return this.endIsInclusive_ ? compareRes <= 0 : compareRes < 0;\n        };\n        this.rangedFilter_ = new RangedFilter(params);\n        this.index_ = params.getIndex();\n        this.limit_ = params.getLimit();\n        this.reverse_ = !params.isViewFromLeft();\n        this.startIsInclusive_ = !params.startAfterSet_;\n        this.endIsInclusive_ = !params.endBeforeSet_;\n    }\n    updateChild(snap, key, newChild, affectedPath, source, optChangeAccumulator) {\n        if (!this.rangedFilter_.matches(new NamedNode(key, newChild))) {\n            newChild = ChildrenNode.EMPTY_NODE;\n        }\n        if (snap.getImmediateChild(key).equals(newChild)) {\n            // No change\n            return snap;\n        }\n        else if (snap.numChildren() < this.limit_) {\n            return this.rangedFilter_\n                .getIndexedFilter()\n                .updateChild(snap, key, newChild, affectedPath, source, optChangeAccumulator);\n        }\n        else {\n            return this.fullLimitUpdateChild_(snap, key, newChild, source, optChangeAccumulator);\n        }\n    }\n    updateFullNode(oldSnap, newSnap, optChangeAccumulator) {\n        let filtered;\n        if (newSnap.isLeafNode() || newSnap.isEmpty()) {\n            // Make sure we have a children node with the correct index, not a leaf node;\n            filtered = ChildrenNode.EMPTY_NODE.withIndex(this.index_);\n        }\n        else {\n            if (this.limit_ * 2 < newSnap.numChildren() &&\n                newSnap.isIndexed(this.index_)) {\n                // Easier to build up a snapshot, since what we're given has more than twice the elements we want\n                filtered = ChildrenNode.EMPTY_NODE.withIndex(this.index_);\n                // anchor to the startPost, endPost, or last element as appropriate\n                let iterator;\n                if (this.reverse_) {\n                    iterator = newSnap.getReverseIteratorFrom(this.rangedFilter_.getEndPost(), this.index_);\n                }\n                else {\n                    iterator = newSnap.getIteratorFrom(this.rangedFilter_.getStartPost(), this.index_);\n                }\n                let count = 0;\n                while (iterator.hasNext() && count < this.limit_) {\n                    const next = iterator.getNext();\n                    if (!this.withinDirectionalStart(next)) {\n                        // if we have not reached the start, skip to the next element\n                        continue;\n                    }\n                    else if (!this.withinDirectionalEnd(next)) {\n                        // if we have reached the end, stop adding elements\n                        break;\n                    }\n                    else {\n                        filtered = filtered.updateImmediateChild(next.name, next.node);\n                        count++;\n                    }\n                }\n            }\n            else {\n                // The snap contains less than twice the limit. Faster to delete from the snap than build up a new one\n                filtered = newSnap.withIndex(this.index_);\n                // Don't support priorities on queries\n                filtered = filtered.updatePriority(ChildrenNode.EMPTY_NODE);\n                let iterator;\n                if (this.reverse_) {\n                    iterator = filtered.getReverseIterator(this.index_);\n                }\n                else {\n                    iterator = filtered.getIterator(this.index_);\n                }\n                let count = 0;\n                while (iterator.hasNext()) {\n                    const next = iterator.getNext();\n                    const inRange = count < this.limit_ &&\n                        this.withinDirectionalStart(next) &&\n                        this.withinDirectionalEnd(next);\n                    if (inRange) {\n                        count++;\n                    }\n                    else {\n                        filtered = filtered.updateImmediateChild(next.name, ChildrenNode.EMPTY_NODE);\n                    }\n                }\n            }\n        }\n        return this.rangedFilter_\n            .getIndexedFilter()\n            .updateFullNode(oldSnap, filtered, optChangeAccumulator);\n    }\n    updatePriority(oldSnap, newPriority) {\n        // Don't support priorities on queries\n        return oldSnap;\n    }\n    filtersNodes() {\n        return true;\n    }\n    getIndexedFilter() {\n        return this.rangedFilter_.getIndexedFilter();\n    }\n    getIndex() {\n        return this.index_;\n    }\n    fullLimitUpdateChild_(snap, childKey, childSnap, source, changeAccumulator) {\n        // TODO: rename all cache stuff etc to general snap terminology\n        let cmp;\n        if (this.reverse_) {\n            const indexCmp = this.index_.getCompare();\n            cmp = (a, b) => indexCmp(b, a);\n        }\n        else {\n            cmp = this.index_.getCompare();\n        }\n        const oldEventCache = snap;\n        assert(oldEventCache.numChildren() === this.limit_, '');\n        const newChildNamedNode = new NamedNode(childKey, childSnap);\n        const windowBoundary = this.reverse_\n            ? oldEventCache.getFirstChild(this.index_)\n            : oldEventCache.getLastChild(this.index_);\n        const inRange = this.rangedFilter_.matches(newChildNamedNode);\n        if (oldEventCache.hasChild(childKey)) {\n            const oldChildSnap = oldEventCache.getImmediateChild(childKey);\n            let nextChild = source.getChildAfterChild(this.index_, windowBoundary, this.reverse_);\n            while (nextChild != null &&\n                (nextChild.name === childKey || oldEventCache.hasChild(nextChild.name))) {\n                // There is a weird edge case where a node is updated as part of a merge in the write tree, but hasn't\n                // been applied to the limited filter yet. Ignore this next child which will be updated later in\n                // the limited filter...\n                nextChild = source.getChildAfterChild(this.index_, nextChild, this.reverse_);\n            }\n            const compareNext = nextChild == null ? 1 : cmp(nextChild, newChildNamedNode);\n            const remainsInWindow = inRange && !childSnap.isEmpty() && compareNext >= 0;\n            if (remainsInWindow) {\n                if (changeAccumulator != null) {\n                    changeAccumulator.trackChildChange(changeChildChanged(childKey, childSnap, oldChildSnap));\n                }\n                return oldEventCache.updateImmediateChild(childKey, childSnap);\n            }\n            else {\n                if (changeAccumulator != null) {\n                    changeAccumulator.trackChildChange(changeChildRemoved(childKey, oldChildSnap));\n                }\n                const newEventCache = oldEventCache.updateImmediateChild(childKey, ChildrenNode.EMPTY_NODE);\n                const nextChildInRange = nextChild != null && this.rangedFilter_.matches(nextChild);\n                if (nextChildInRange) {\n                    if (changeAccumulator != null) {\n                        changeAccumulator.trackChildChange(changeChildAdded(nextChild.name, nextChild.node));\n                    }\n                    return newEventCache.updateImmediateChild(nextChild.name, nextChild.node);\n                }\n                else {\n                    return newEventCache;\n                }\n            }\n        }\n        else if (childSnap.isEmpty()) {\n            // we're deleting a node, but it was not in the window, so ignore it\n            return snap;\n        }\n        else if (inRange) {\n            if (cmp(windowBoundary, newChildNamedNode) >= 0) {\n                if (changeAccumulator != null) {\n                    changeAccumulator.trackChildChange(changeChildRemoved(windowBoundary.name, windowBoundary.node));\n                    changeAccumulator.trackChildChange(changeChildAdded(childKey, childSnap));\n                }\n                return oldEventCache\n                    .updateImmediateChild(childKey, childSnap)\n                    .updateImmediateChild(windowBoundary.name, ChildrenNode.EMPTY_NODE);\n            }\n            else {\n                return snap;\n            }\n        }\n        else {\n            return snap;\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 * This class is an immutable-from-the-public-api struct containing a set of query parameters defining a\n * range to be returned for a particular location. It is assumed that validation of parameters is done at the\n * user-facing API level, so it is not done here.\n *\n * @internal\n */\nclass QueryParams {\n    constructor() {\n        this.limitSet_ = false;\n        this.startSet_ = false;\n        this.startNameSet_ = false;\n        this.startAfterSet_ = false; // can only be true if startSet_ is true\n        this.endSet_ = false;\n        this.endNameSet_ = false;\n        this.endBeforeSet_ = false; // can only be true if endSet_ is true\n        this.limit_ = 0;\n        this.viewFrom_ = '';\n        this.indexStartValue_ = null;\n        this.indexStartName_ = '';\n        this.indexEndValue_ = null;\n        this.indexEndName_ = '';\n        this.index_ = PRIORITY_INDEX;\n    }\n    hasStart() {\n        return this.startSet_;\n    }\n    /**\n     * @returns True if it would return from left.\n     */\n    isViewFromLeft() {\n        if (this.viewFrom_ === '') {\n            // limit(), rather than limitToFirst or limitToLast was called.\n            // This means that only one of startSet_ and endSet_ is true. Use them\n            // to calculate which side of the view to anchor to. If neither is set,\n            // anchor to the end.\n            return this.startSet_;\n        }\n        else {\n            return this.viewFrom_ === \"l\" /* WIRE_PROTOCOL_CONSTANTS.VIEW_FROM_LEFT */;\n        }\n    }\n    /**\n     * Only valid to call if hasStart() returns true\n     */\n    getIndexStartValue() {\n        assert(this.startSet_, 'Only valid if start has been set');\n        return this.indexStartValue_;\n    }\n    /**\n     * Only valid to call if hasStart() returns true.\n     * Returns the starting key name for the range defined by these query parameters\n     */\n    getIndexStartName() {\n        assert(this.startSet_, 'Only valid if start has been set');\n        if (this.startNameSet_) {\n            return this.indexStartName_;\n        }\n        else {\n            return MIN_NAME;\n        }\n    }\n    hasEnd() {\n        return this.endSet_;\n    }\n    /**\n     * Only valid to call if hasEnd() returns true.\n     */\n    getIndexEndValue() {\n        assert(this.endSet_, 'Only valid if end has been set');\n        return this.indexEndValue_;\n    }\n    /**\n     * Only valid to call if hasEnd() returns true.\n     * Returns the end key name for the range defined by these query parameters\n     */\n    getIndexEndName() {\n        assert(this.endSet_, 'Only valid if end has been set');\n        if (this.endNameSet_) {\n            return this.indexEndName_;\n        }\n        else {\n            return MAX_NAME;\n        }\n    }\n    hasLimit() {\n        return this.limitSet_;\n    }\n    /**\n     * @returns True if a limit has been set and it has been explicitly anchored\n     */\n    hasAnchoredLimit() {\n        return this.limitSet_ && this.viewFrom_ !== '';\n    }\n    /**\n     * Only valid to call if hasLimit() returns true\n     */\n    getLimit() {\n        assert(this.limitSet_, 'Only valid if limit has been set');\n        return this.limit_;\n    }\n    getIndex() {\n        return this.index_;\n    }\n    loadsAllData() {\n        return !(this.startSet_ || this.endSet_ || this.limitSet_);\n    }\n    isDefault() {\n        return this.loadsAllData() && this.index_ === PRIORITY_INDEX;\n    }\n    copy() {\n        const copy = new QueryParams();\n        copy.limitSet_ = this.limitSet_;\n        copy.limit_ = this.limit_;\n        copy.startSet_ = this.startSet_;\n        copy.startAfterSet_ = this.startAfterSet_;\n        copy.indexStartValue_ = this.indexStartValue_;\n        copy.startNameSet_ = this.startNameSet_;\n        copy.indexStartName_ = this.indexStartName_;\n        copy.endSet_ = this.endSet_;\n        copy.endBeforeSet_ = this.endBeforeSet_;\n        copy.indexEndValue_ = this.indexEndValue_;\n        copy.endNameSet_ = this.endNameSet_;\n        copy.indexEndName_ = this.indexEndName_;\n        copy.index_ = this.index_;\n        copy.viewFrom_ = this.viewFrom_;\n        return copy;\n    }\n}\nfunction queryParamsGetNodeFilter(queryParams) {\n    if (queryParams.loadsAllData()) {\n        return new IndexedFilter(queryParams.getIndex());\n    }\n    else if (queryParams.hasLimit()) {\n        return new LimitedFilter(queryParams);\n    }\n    else {\n        return new RangedFilter(queryParams);\n    }\n}\nfunction queryParamsLimitToFirst(queryParams, newLimit) {\n    const newParams = queryParams.copy();\n    newParams.limitSet_ = true;\n    newParams.limit_ = newLimit;\n    newParams.viewFrom_ = \"l\" /* WIRE_PROTOCOL_CONSTANTS.VIEW_FROM_LEFT */;\n    return newParams;\n}\nfunction queryParamsLimitToLast(queryParams, newLimit) {\n    const newParams = queryParams.copy();\n    newParams.limitSet_ = true;\n    newParams.limit_ = newLimit;\n    newParams.viewFrom_ = \"r\" /* WIRE_PROTOCOL_CONSTANTS.VIEW_FROM_RIGHT */;\n    return newParams;\n}\nfunction queryParamsStartAt(queryParams, indexValue, key) {\n    const newParams = queryParams.copy();\n    newParams.startSet_ = true;\n    if (indexValue === undefined) {\n        indexValue = null;\n    }\n    newParams.indexStartValue_ = indexValue;\n    if (key != null) {\n        newParams.startNameSet_ = true;\n        newParams.indexStartName_ = key;\n    }\n    else {\n        newParams.startNameSet_ = false;\n        newParams.indexStartName_ = '';\n    }\n    return newParams;\n}\nfunction queryParamsStartAfter(queryParams, indexValue, key) {\n    let params;\n    if (queryParams.index_ === KEY_INDEX || !!key) {\n        params = queryParamsStartAt(queryParams, indexValue, key);\n    }\n    else {\n        params = queryParamsStartAt(queryParams, indexValue, MAX_NAME);\n    }\n    params.startAfterSet_ = true;\n    return params;\n}\nfunction queryParamsEndAt(queryParams, indexValue, key) {\n    const newParams = queryParams.copy();\n    newParams.endSet_ = true;\n    if (indexValue === undefined) {\n        indexValue = null;\n    }\n    newParams.indexEndValue_ = indexValue;\n    if (key !== undefined) {\n        newParams.endNameSet_ = true;\n        newParams.indexEndName_ = key;\n    }\n    else {\n        newParams.endNameSet_ = false;\n        newParams.indexEndName_ = '';\n    }\n    return newParams;\n}\nfunction queryParamsEndBefore(queryParams, indexValue, key) {\n    let params;\n    if (queryParams.index_ === KEY_INDEX || !!key) {\n        params = queryParamsEndAt(queryParams, indexValue, key);\n    }\n    else {\n        params = queryParamsEndAt(queryParams, indexValue, MIN_NAME);\n    }\n    params.endBeforeSet_ = true;\n    return params;\n}\nfunction queryParamsOrderBy(queryParams, index) {\n    const newParams = queryParams.copy();\n    newParams.index_ = index;\n    return newParams;\n}\n/**\n * Returns a set of REST query string parameters representing this query.\n *\n * @returns query string parameters\n */\nfunction queryParamsToRestQueryStringParameters(queryParams) {\n    const qs = {};\n    if (queryParams.isDefault()) {\n        return qs;\n    }\n    let orderBy;\n    if (queryParams.index_ === PRIORITY_INDEX) {\n        orderBy = \"$priority\" /* REST_QUERY_CONSTANTS.PRIORITY_INDEX */;\n    }\n    else if (queryParams.index_ === VALUE_INDEX) {\n        orderBy = \"$value\" /* REST_QUERY_CONSTANTS.VALUE_INDEX */;\n    }\n    else if (queryParams.index_ === KEY_INDEX) {\n        orderBy = \"$key\" /* REST_QUERY_CONSTANTS.KEY_INDEX */;\n    }\n    else {\n        assert(queryParams.index_ instanceof PathIndex, 'Unrecognized index type!');\n        orderBy = queryParams.index_.toString();\n    }\n    qs[\"orderBy\" /* REST_QUERY_CONSTANTS.ORDER_BY */] = stringify(orderBy);\n    if (queryParams.startSet_) {\n        const startParam = queryParams.startAfterSet_\n            ? \"startAfter\" /* REST_QUERY_CONSTANTS.START_AFTER */\n            : \"startAt\" /* REST_QUERY_CONSTANTS.START_AT */;\n        qs[startParam] = stringify(queryParams.indexStartValue_);\n        if (queryParams.startNameSet_) {\n            qs[startParam] += ',' + stringify(queryParams.indexStartName_);\n        }\n    }\n    if (queryParams.endSet_) {\n        const endParam = queryParams.endBeforeSet_\n            ? \"endBefore\" /* REST_QUERY_CONSTANTS.END_BEFORE */\n            : \"endAt\" /* REST_QUERY_CONSTANTS.END_AT */;\n        qs[endParam] = stringify(queryParams.indexEndValue_);\n        if (queryParams.endNameSet_) {\n            qs[endParam] += ',' + stringify(queryParams.indexEndName_);\n        }\n    }\n    if (queryParams.limitSet_) {\n        if (queryParams.isViewFromLeft()) {\n            qs[\"limitToFirst\" /* REST_QUERY_CONSTANTS.LIMIT_TO_FIRST */] = queryParams.limit_;\n        }\n        else {\n            qs[\"limitToLast\" /* REST_QUERY_CONSTANTS.LIMIT_TO_LAST */] = queryParams.limit_;\n        }\n    }\n    return qs;\n}\nfunction queryParamsGetQueryObject(queryParams) {\n    const obj = {};\n    if (queryParams.startSet_) {\n        obj[\"sp\" /* WIRE_PROTOCOL_CONSTANTS.INDEX_START_VALUE */] =\n            queryParams.indexStartValue_;\n        if (queryParams.startNameSet_) {\n            obj[\"sn\" /* WIRE_PROTOCOL_CONSTANTS.INDEX_START_NAME */] =\n                queryParams.indexStartName_;\n        }\n        obj[\"sin\" /* WIRE_PROTOCOL_CONSTANTS.INDEX_START_IS_INCLUSIVE */] =\n            !queryParams.startAfterSet_;\n    }\n    if (queryParams.endSet_) {\n        obj[\"ep\" /* WIRE_PROTOCOL_CONSTANTS.INDEX_END_VALUE */] = queryParams.indexEndValue_;\n        if (queryParams.endNameSet_) {\n            obj[\"en\" /* WIRE_PROTOCOL_CONSTANTS.INDEX_END_NAME */] = queryParams.indexEndName_;\n        }\n        obj[\"ein\" /* WIRE_PROTOCOL_CONSTANTS.INDEX_END_IS_INCLUSIVE */] =\n            !queryParams.endBeforeSet_;\n    }\n    if (queryParams.limitSet_) {\n        obj[\"l\" /* WIRE_PROTOCOL_CONSTANTS.LIMIT */] = queryParams.limit_;\n        let viewFrom = queryParams.viewFrom_;\n        if (viewFrom === '') {\n            if (queryParams.isViewFromLeft()) {\n                viewFrom = \"l\" /* WIRE_PROTOCOL_CONSTANTS.VIEW_FROM_LEFT */;\n            }\n            else {\n                viewFrom = \"r\" /* WIRE_PROTOCOL_CONSTANTS.VIEW_FROM_RIGHT */;\n            }\n        }\n        obj[\"vf\" /* WIRE_PROTOCOL_CONSTANTS.VIEW_FROM */] = viewFrom;\n    }\n    // For now, priority index is the default, so we only specify if it's some other index\n    if (queryParams.index_ !== PRIORITY_INDEX) {\n        obj[\"i\" /* WIRE_PROTOCOL_CONSTANTS.INDEX */] = queryParams.index_.toString();\n    }\n    return obj;\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 implementation of ServerActions that communicates with the server via REST requests.\n * This is mostly useful for compatibility with crawlers, where we don't want to spin up a full\n * persistent connection (using WebSockets or long-polling)\n */\nclass ReadonlyRestClient extends ServerActions {\n    reportStats(stats) {\n        throw new Error('Method not implemented.');\n    }\n    static getListenId_(query, tag) {\n        if (tag !== undefined) {\n            return 'tag$' + tag;\n        }\n        else {\n            assert(query._queryParams.isDefault(), \"should have a tag if it's not a default query.\");\n            return query._path.toString();\n        }\n    }\n    /**\n     * @param repoInfo_ - Data about the namespace we are connecting to\n     * @param onDataUpdate_ - A callback for new data from the server\n     */\n    constructor(repoInfo_, onDataUpdate_, authTokenProvider_, appCheckTokenProvider_) {\n        super();\n        this.repoInfo_ = repoInfo_;\n        this.onDataUpdate_ = onDataUpdate_;\n        this.authTokenProvider_ = authTokenProvider_;\n        this.appCheckTokenProvider_ = appCheckTokenProvider_;\n        /** @private {function(...[*])} */\n        this.log_ = logWrapper('p:rest:');\n        /**\n         * We don't actually need to track listens, except to prevent us calling an onComplete for a listen\n         * that's been removed. :-/\n         */\n        this.listens_ = {};\n    }\n    /** @inheritDoc */\n    listen(query, currentHashFn, tag, onComplete) {\n        const pathString = query._path.toString();\n        this.log_('Listen called for ' + pathString + ' ' + query._queryIdentifier);\n        // Mark this listener so we can tell if it's removed.\n        const listenId = ReadonlyRestClient.getListenId_(query, tag);\n        const thisListen = {};\n        this.listens_[listenId] = thisListen;\n        const queryStringParameters = queryParamsToRestQueryStringParameters(query._queryParams);\n        this.restRequest_(pathString + '.json', queryStringParameters, (error, result) => {\n            let data = result;\n            if (error === 404) {\n                data = null;\n                error = null;\n            }\n            if (error === null) {\n                this.onDataUpdate_(pathString, data, /*isMerge=*/ false, tag);\n            }\n            if (safeGet(this.listens_, listenId) === thisListen) {\n                let status;\n                if (!error) {\n                    status = 'ok';\n                }\n                else if (error === 401) {\n                    status = 'permission_denied';\n                }\n                else {\n                    status = 'rest_error:' + error;\n                }\n                onComplete(status, null);\n            }\n        });\n    }\n    /** @inheritDoc */\n    unlisten(query, tag) {\n        const listenId = ReadonlyRestClient.getListenId_(query, tag);\n        delete this.listens_[listenId];\n    }\n    get(query) {\n        const queryStringParameters = queryParamsToRestQueryStringParameters(query._queryParams);\n        const pathString = query._path.toString();\n        const deferred = new Deferred();\n        this.restRequest_(pathString + '.json', queryStringParameters, (error, result) => {\n            let data = result;\n            if (error === 404) {\n                data = null;\n                error = null;\n            }\n            if (error === null) {\n                this.onDataUpdate_(pathString, data, \n                /*isMerge=*/ false, \n                /*tag=*/ null);\n                deferred.resolve(data);\n            }\n            else {\n                deferred.reject(new Error(data));\n            }\n        });\n        return deferred.promise;\n    }\n    /** @inheritDoc */\n    refreshAuthToken(token) {\n        // no-op since we just always call getToken.\n    }\n    /**\n     * Performs a REST request to the given path, with the provided query string parameters,\n     * and any auth credentials we have.\n     */\n    restRequest_(pathString, queryStringParameters = {}, callback) {\n        queryStringParameters['format'] = 'export';\n        return Promise.all([\n            this.authTokenProvider_.getToken(/*forceRefresh=*/ false),\n            this.appCheckTokenProvider_.getToken(/*forceRefresh=*/ false)\n        ]).then(([authToken, appCheckToken]) => {\n            if (authToken && authToken.accessToken) {\n                queryStringParameters['auth'] = authToken.accessToken;\n            }\n            if (appCheckToken && appCheckToken.token) {\n                queryStringParameters['ac'] = appCheckToken.token;\n            }\n            const url = (this.repoInfo_.secure ? 'https://' : 'http://') +\n                this.repoInfo_.host +\n                pathString +\n                '?' +\n                'ns=' +\n                this.repoInfo_.namespace +\n                querystring(queryStringParameters);\n            this.log_('Sending REST request for ' + url);\n            const xhr = new XMLHttpRequest();\n            xhr.onreadystatechange = () => {\n                if (callback && xhr.readyState === 4) {\n                    this.log_('REST Response for ' + url + ' received. status:', xhr.status, 'response:', xhr.responseText);\n                    let res = null;\n                    if (xhr.status >= 200 && xhr.status < 300) {\n                        try {\n                            res = jsonEval(xhr.responseText);\n                        }\n                        catch (e) {\n                            warn('Failed to parse JSON response for ' +\n                                url +\n                                ': ' +\n                                xhr.responseText);\n                        }\n                        callback(null, res);\n                    }\n                    else {\n                        // 401 and 404 are expected.\n                        if (xhr.status !== 401 && xhr.status !== 404) {\n                            warn('Got unsuccessful REST response for ' +\n                                url +\n                                ' Status: ' +\n                                xhr.status);\n                        }\n                        callback(xhr.status);\n                    }\n                    callback = null;\n                }\n            };\n            xhr.open('GET', url, /*asynchronous=*/ true);\n            xhr.send();\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 * Mutable object which basically just stores a reference to the \"latest\" immutable snapshot.\n */\nclass SnapshotHolder {\n    constructor() {\n        this.rootNode_ = ChildrenNode.EMPTY_NODE;\n    }\n    getNode(path) {\n        return this.rootNode_.getChild(path);\n    }\n    updateSnapshot(path, newSnapshotNode) {\n        this.rootNode_ = this.rootNode_.updateChild(path, newSnapshotNode);\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 */\nfunction newSparseSnapshotTree() {\n    return {\n        value: null,\n        children: new Map()\n    };\n}\n/**\n * Stores the given node at the specified path. If there is already a node\n * at a shallower path, it merges the new data into that snapshot node.\n *\n * @param path - Path to look up snapshot for.\n * @param data - The new data, or null.\n */\nfunction sparseSnapshotTreeRemember(sparseSnapshotTree, path, data) {\n    if (pathIsEmpty(path)) {\n        sparseSnapshotTree.value = data;\n        sparseSnapshotTree.children.clear();\n    }\n    else if (sparseSnapshotTree.value !== null) {\n        sparseSnapshotTree.value = sparseSnapshotTree.value.updateChild(path, data);\n    }\n    else {\n        const childKey = pathGetFront(path);\n        if (!sparseSnapshotTree.children.has(childKey)) {\n            sparseSnapshotTree.children.set(childKey, newSparseSnapshotTree());\n        }\n        const child = sparseSnapshotTree.children.get(childKey);\n        path = pathPopFront(path);\n        sparseSnapshotTreeRemember(child, path, data);\n    }\n}\n/**\n * Purge the data at path from the cache.\n *\n * @param path - Path to look up snapshot for.\n * @returns True if this node should now be removed.\n */\nfunction sparseSnapshotTreeForget(sparseSnapshotTree, path) {\n    if (pathIsEmpty(path)) {\n        sparseSnapshotTree.value = null;\n        sparseSnapshotTree.children.clear();\n        return true;\n    }\n    else {\n        if (sparseSnapshotTree.value !== null) {\n            if (sparseSnapshotTree.value.isLeafNode()) {\n                // We're trying to forget a node that doesn't exist\n                return false;\n            }\n            else {\n                const value = sparseSnapshotTree.value;\n                sparseSnapshotTree.value = null;\n                value.forEachChild(PRIORITY_INDEX, (key, tree) => {\n                    sparseSnapshotTreeRemember(sparseSnapshotTree, new Path(key), tree);\n                });\n                return sparseSnapshotTreeForget(sparseSnapshotTree, path);\n            }\n        }\n        else if (sparseSnapshotTree.children.size > 0) {\n            const childKey = pathGetFront(path);\n            path = pathPopFront(path);\n            if (sparseSnapshotTree.children.has(childKey)) {\n                const safeToRemove = sparseSnapshotTreeForget(sparseSnapshotTree.children.get(childKey), path);\n                if (safeToRemove) {\n                    sparseSnapshotTree.children.delete(childKey);\n                }\n            }\n            return sparseSnapshotTree.children.size === 0;\n        }\n        else {\n            return true;\n        }\n    }\n}\n/**\n * Recursively iterates through all of the stored tree and calls the\n * callback on each one.\n *\n * @param prefixPath - Path to look up node for.\n * @param func - The function to invoke for each tree.\n */\nfunction sparseSnapshotTreeForEachTree(sparseSnapshotTree, prefixPath, func) {\n    if (sparseSnapshotTree.value !== null) {\n        func(prefixPath, sparseSnapshotTree.value);\n    }\n    else {\n        sparseSnapshotTreeForEachChild(sparseSnapshotTree, (key, tree) => {\n            const path = new Path(prefixPath.toString() + '/' + key);\n            sparseSnapshotTreeForEachTree(tree, path, func);\n        });\n    }\n}\n/**\n * Iterates through each immediate child and triggers the callback.\n * Only seems to be used in tests.\n *\n * @param func - The function to invoke for each child.\n */\nfunction sparseSnapshotTreeForEachChild(sparseSnapshotTree, func) {\n    sparseSnapshotTree.children.forEach((tree, key) => {\n        func(key, tree);\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 * Returns the delta from the previous call to get stats.\n *\n * @param collection_ - The collection to \"listen\" to.\n */\nclass StatsListener {\n    constructor(collection_) {\n        this.collection_ = collection_;\n        this.last_ = null;\n    }\n    get() {\n        const newStats = this.collection_.get();\n        const delta = Object.assign({}, newStats);\n        if (this.last_) {\n            each(this.last_, (stat, value) => {\n                delta[stat] = delta[stat] - value;\n            });\n        }\n        this.last_ = newStats;\n        return delta;\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// Assuming some apps may have a short amount of time on page, and a bulk of firebase operations probably\n// happen on page load, we try to report our first set of stats pretty quickly, but we wait at least 10\n// seconds to try to ensure the Firebase connection is established / settled.\nconst FIRST_STATS_MIN_TIME = 10 * 1000;\nconst FIRST_STATS_MAX_TIME = 30 * 1000;\n// We'll continue to report stats on average every 5 minutes.\nconst REPORT_STATS_INTERVAL = 5 * 60 * 1000;\nclass StatsReporter {\n    constructor(collection, server_) {\n        this.server_ = server_;\n        this.statsToReport_ = {};\n        this.statsListener_ = new StatsListener(collection);\n        const timeout = FIRST_STATS_MIN_TIME +\n            (FIRST_STATS_MAX_TIME - FIRST_STATS_MIN_TIME) * Math.random();\n        setTimeoutNonBlocking(this.reportStats_.bind(this), Math.floor(timeout));\n    }\n    reportStats_() {\n        const stats = this.statsListener_.get();\n        const reportedStats = {};\n        let haveStatsToReport = false;\n        each(stats, (stat, value) => {\n            if (value > 0 && contains(this.statsToReport_, stat)) {\n                reportedStats[stat] = value;\n                haveStatsToReport = true;\n            }\n        });\n        if (haveStatsToReport) {\n            this.server_.reportStats(reportedStats);\n        }\n        // queue our next run.\n        setTimeoutNonBlocking(this.reportStats_.bind(this), Math.floor(Math.random() * 2 * REPORT_STATS_INTERVAL));\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 *\n * @enum\n */\nvar OperationType;\n(function (OperationType) {\n    OperationType[OperationType[\"OVERWRITE\"] = 0] = \"OVERWRITE\";\n    OperationType[OperationType[\"MERGE\"] = 1] = \"MERGE\";\n    OperationType[OperationType[\"ACK_USER_WRITE\"] = 2] = \"ACK_USER_WRITE\";\n    OperationType[OperationType[\"LISTEN_COMPLETE\"] = 3] = \"LISTEN_COMPLETE\";\n})(OperationType || (OperationType = {}));\nfunction newOperationSourceUser() {\n    return {\n        fromUser: true,\n        fromServer: false,\n        queryId: null,\n        tagged: false\n    };\n}\nfunction newOperationSourceServer() {\n    return {\n        fromUser: false,\n        fromServer: true,\n        queryId: null,\n        tagged: false\n    };\n}\nfunction newOperationSourceServerTaggedQuery(queryId) {\n    return {\n        fromUser: false,\n        fromServer: true,\n        queryId,\n        tagged: true\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 */\nclass AckUserWrite {\n    /**\n     * @param affectedTree - A tree containing true for each affected path. Affected paths can't overlap.\n     */\n    constructor(\n    /** @inheritDoc */ path, \n    /** @inheritDoc */ affectedTree, \n    /** @inheritDoc */ revert) {\n        this.path = path;\n        this.affectedTree = affectedTree;\n        this.revert = revert;\n        /** @inheritDoc */\n        this.type = OperationType.ACK_USER_WRITE;\n        /** @inheritDoc */\n        this.source = newOperationSourceUser();\n    }\n    operationForChild(childName) {\n        if (!pathIsEmpty(this.path)) {\n            assert(pathGetFront(this.path) === childName, 'operationForChild called for unrelated child.');\n            return new AckUserWrite(pathPopFront(this.path), this.affectedTree, this.revert);\n        }\n        else if (this.affectedTree.value != null) {\n            assert(this.affectedTree.children.isEmpty(), 'affectedTree should not have overlapping affected paths.');\n            // All child locations are affected as well; just return same operation.\n            return this;\n        }\n        else {\n            const childTree = this.affectedTree.subtree(new Path(childName));\n            return new AckUserWrite(newEmptyPath(), childTree, this.revert);\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 */\nclass ListenComplete {\n    constructor(source, path) {\n        this.source = source;\n        this.path = path;\n        /** @inheritDoc */\n        this.type = OperationType.LISTEN_COMPLETE;\n    }\n    operationForChild(childName) {\n        if (pathIsEmpty(this.path)) {\n            return new ListenComplete(this.source, newEmptyPath());\n        }\n        else {\n            return new ListenComplete(this.source, pathPopFront(this.path));\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 */\nclass Overwrite {\n    constructor(source, path, snap) {\n        this.source = source;\n        this.path = path;\n        this.snap = snap;\n        /** @inheritDoc */\n        this.type = OperationType.OVERWRITE;\n    }\n    operationForChild(childName) {\n        if (pathIsEmpty(this.path)) {\n            return new Overwrite(this.source, newEmptyPath(), this.snap.getImmediateChild(childName));\n        }\n        else {\n            return new Overwrite(this.source, pathPopFront(this.path), this.snap);\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 */\nclass Merge {\n    constructor(\n    /** @inheritDoc */ source, \n    /** @inheritDoc */ path, \n    /** @inheritDoc */ children) {\n        this.source = source;\n        this.path = path;\n        this.children = children;\n        /** @inheritDoc */\n        this.type = OperationType.MERGE;\n    }\n    operationForChild(childName) {\n        if (pathIsEmpty(this.path)) {\n            const childTree = this.children.subtree(new Path(childName));\n            if (childTree.isEmpty()) {\n                // This child is unaffected\n                return null;\n            }\n            else if (childTree.value) {\n                // We have a snapshot for the child in question.  This becomes an overwrite of the child.\n                return new Overwrite(this.source, newEmptyPath(), childTree.value);\n            }\n            else {\n                // This is a merge at a deeper level\n                return new Merge(this.source, newEmptyPath(), childTree);\n            }\n        }\n        else {\n            assert(pathGetFront(this.path) === childName, \"Can't get a merge for a child not on the path of the operation\");\n            return new Merge(this.source, pathPopFront(this.path), this.children);\n        }\n    }\n    toString() {\n        return ('Operation(' +\n            this.path +\n            ': ' +\n            this.source.toString() +\n            ' merge: ' +\n            this.children.toString() +\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 * A cache node only stores complete children. Additionally it holds a flag whether the node can be considered fully\n * initialized in the sense that we know at one point in time this represented a valid state of the world, e.g.\n * initialized with data from the server, or a complete overwrite by the client. The filtered flag also tracks\n * whether a node potentially had children removed due to a filter.\n */\nclass CacheNode {\n    constructor(node_, fullyInitialized_, filtered_) {\n        this.node_ = node_;\n        this.fullyInitialized_ = fullyInitialized_;\n        this.filtered_ = filtered_;\n    }\n    /**\n     * Returns whether this node was fully initialized with either server data or a complete overwrite by the client\n     */\n    isFullyInitialized() {\n        return this.fullyInitialized_;\n    }\n    /**\n     * Returns whether this node is potentially missing children due to a filter applied to the node\n     */\n    isFiltered() {\n        return this.filtered_;\n    }\n    isCompleteForPath(path) {\n        if (pathIsEmpty(path)) {\n            return this.isFullyInitialized() && !this.filtered_;\n        }\n        const childKey = pathGetFront(path);\n        return this.isCompleteForChild(childKey);\n    }\n    isCompleteForChild(key) {\n        return ((this.isFullyInitialized() && !this.filtered_) || this.node_.hasChild(key));\n    }\n    getNode() {\n        return this.node_;\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 EventGenerator is used to convert \"raw\" changes (Change) as computed by the\n * CacheDiffer into actual events (Event) that can be raised.  See generateEventsForChanges()\n * for details.\n *\n */\nclass EventGenerator {\n    constructor(query_) {\n        this.query_ = query_;\n        this.index_ = this.query_._queryParams.getIndex();\n    }\n}\n/**\n * Given a set of raw changes (no moved events and prevName not specified yet), and a set of\n * EventRegistrations that should be notified of these changes, generate the actual events to be raised.\n *\n * Notes:\n *  - child_moved events will be synthesized at this time for any child_changed events that affect\n *    our index.\n *  - prevName will be calculated based on the index ordering.\n */\nfunction eventGeneratorGenerateEventsForChanges(eventGenerator, changes, eventCache, eventRegistrations) {\n    const events = [];\n    const moves = [];\n    changes.forEach(change => {\n        if (change.type === \"child_changed\" /* ChangeType.CHILD_CHANGED */ &&\n            eventGenerator.index_.indexedValueChanged(change.oldSnap, change.snapshotNode)) {\n            moves.push(changeChildMoved(change.childName, change.snapshotNode));\n        }\n    });\n    eventGeneratorGenerateEventsForType(eventGenerator, events, \"child_removed\" /* ChangeType.CHILD_REMOVED */, changes, eventRegistrations, eventCache);\n    eventGeneratorGenerateEventsForType(eventGenerator, events, \"child_added\" /* ChangeType.CHILD_ADDED */, changes, eventRegistrations, eventCache);\n    eventGeneratorGenerateEventsForType(eventGenerator, events, \"child_moved\" /* ChangeType.CHILD_MOVED */, moves, eventRegistrations, eventCache);\n    eventGeneratorGenerateEventsForType(eventGenerator, events, \"child_changed\" /* ChangeType.CHILD_CHANGED */, changes, eventRegistrations, eventCache);\n    eventGeneratorGenerateEventsForType(eventGenerator, events, \"value\" /* ChangeType.VALUE */, changes, eventRegistrations, eventCache);\n    return events;\n}\n/**\n * Given changes of a single change type, generate the corresponding events.\n */\nfunction eventGeneratorGenerateEventsForType(eventGenerator, events, eventType, changes, registrations, eventCache) {\n    const filteredChanges = changes.filter(change => change.type === eventType);\n    filteredChanges.sort((a, b) => eventGeneratorCompareChanges(eventGenerator, a, b));\n    filteredChanges.forEach(change => {\n        const materializedChange = eventGeneratorMaterializeSingleChange(eventGenerator, change, eventCache);\n        registrations.forEach(registration => {\n            if (registration.respondsTo(change.type)) {\n                events.push(registration.createEvent(materializedChange, eventGenerator.query_));\n            }\n        });\n    });\n}\nfunction eventGeneratorMaterializeSingleChange(eventGenerator, change, eventCache) {\n    if (change.type === 'value' || change.type === 'child_removed') {\n        return change;\n    }\n    else {\n        change.prevName = eventCache.getPredecessorChildName(change.childName, change.snapshotNode, eventGenerator.index_);\n        return change;\n    }\n}\nfunction eventGeneratorCompareChanges(eventGenerator, a, b) {\n    if (a.childName == null || b.childName == null) {\n        throw assertionError('Should only compare child_ events.');\n    }\n    const aWrapped = new NamedNode(a.childName, a.snapshotNode);\n    const bWrapped = new NamedNode(b.childName, b.snapshotNode);\n    return eventGenerator.index_.compare(aWrapped, bWrapped);\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 */\nfunction newViewCache(eventCache, serverCache) {\n    return { eventCache, serverCache };\n}\nfunction viewCacheUpdateEventSnap(viewCache, eventSnap, complete, filtered) {\n    return newViewCache(new CacheNode(eventSnap, complete, filtered), viewCache.serverCache);\n}\nfunction viewCacheUpdateServerSnap(viewCache, serverSnap, complete, filtered) {\n    return newViewCache(viewCache.eventCache, new CacheNode(serverSnap, complete, filtered));\n}\nfunction viewCacheGetCompleteEventSnap(viewCache) {\n    return viewCache.eventCache.isFullyInitialized()\n        ? viewCache.eventCache.getNode()\n        : null;\n}\nfunction viewCacheGetCompleteServerSnap(viewCache) {\n    return viewCache.serverCache.isFullyInitialized()\n        ? viewCache.serverCache.getNode()\n        : null;\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 */\nlet emptyChildrenSingleton;\n/**\n * Singleton empty children collection.\n *\n */\nconst EmptyChildren = () => {\n    if (!emptyChildrenSingleton) {\n        emptyChildrenSingleton = new SortedMap(stringCompare);\n    }\n    return emptyChildrenSingleton;\n};\n/**\n * A tree with immutable elements.\n */\nclass ImmutableTree {\n    static fromObject(obj) {\n        let tree = new ImmutableTree(null);\n        each(obj, (childPath, childSnap) => {\n            tree = tree.set(new Path(childPath), childSnap);\n        });\n        return tree;\n    }\n    constructor(value, children = EmptyChildren()) {\n        this.value = value;\n        this.children = children;\n    }\n    /**\n     * True if the value is empty and there are no children\n     */\n    isEmpty() {\n        return this.value === null && this.children.isEmpty();\n    }\n    /**\n     * Given a path and predicate, return the first node and the path to that node\n     * where the predicate returns true.\n     *\n     * TODO Do a perf test -- If we're creating a bunch of `{path: value:}`\n     * objects on the way back out, it may be better to pass down a pathSoFar obj.\n     *\n     * @param relativePath - The remainder of the path\n     * @param predicate - The predicate to satisfy to return a node\n     */\n    findRootMostMatchingPathAndValue(relativePath, predicate) {\n        if (this.value != null && predicate(this.value)) {\n            return { path: newEmptyPath(), value: this.value };\n        }\n        else {\n            if (pathIsEmpty(relativePath)) {\n                return null;\n            }\n            else {\n                const front = pathGetFront(relativePath);\n                const child = this.children.get(front);\n                if (child !== null) {\n                    const childExistingPathAndValue = child.findRootMostMatchingPathAndValue(pathPopFront(relativePath), predicate);\n                    if (childExistingPathAndValue != null) {\n                        const fullPath = pathChild(new Path(front), childExistingPathAndValue.path);\n                        return { path: fullPath, value: childExistingPathAndValue.value };\n                    }\n                    else {\n                        return null;\n                    }\n                }\n                else {\n                    return null;\n                }\n            }\n        }\n    }\n    /**\n     * Find, if it exists, the shortest subpath of the given path that points a defined\n     * value in the tree\n     */\n    findRootMostValueAndPath(relativePath) {\n        return this.findRootMostMatchingPathAndValue(relativePath, () => true);\n    }\n    /**\n     * @returns The subtree at the given path\n     */\n    subtree(relativePath) {\n        if (pathIsEmpty(relativePath)) {\n            return this;\n        }\n        else {\n            const front = pathGetFront(relativePath);\n            const childTree = this.children.get(front);\n            if (childTree !== null) {\n                return childTree.subtree(pathPopFront(relativePath));\n            }\n            else {\n                return new ImmutableTree(null);\n            }\n        }\n    }\n    /**\n     * Sets a value at the specified path.\n     *\n     * @param relativePath - Path to set value at.\n     * @param toSet - Value to set.\n     * @returns Resulting tree.\n     */\n    set(relativePath, toSet) {\n        if (pathIsEmpty(relativePath)) {\n            return new ImmutableTree(toSet, this.children);\n        }\n        else {\n            const front = pathGetFront(relativePath);\n            const child = this.children.get(front) || new ImmutableTree(null);\n            const newChild = child.set(pathPopFront(relativePath), toSet);\n            const newChildren = this.children.insert(front, newChild);\n            return new ImmutableTree(this.value, newChildren);\n        }\n    }\n    /**\n     * Removes the value at the specified path.\n     *\n     * @param relativePath - Path to value to remove.\n     * @returns Resulting tree.\n     */\n    remove(relativePath) {\n        if (pathIsEmpty(relativePath)) {\n            if (this.children.isEmpty()) {\n                return new ImmutableTree(null);\n            }\n            else {\n                return new ImmutableTree(null, this.children);\n            }\n        }\n        else {\n            const front = pathGetFront(relativePath);\n            const child = this.children.get(front);\n            if (child) {\n                const newChild = child.remove(pathPopFront(relativePath));\n                let newChildren;\n                if (newChild.isEmpty()) {\n                    newChildren = this.children.remove(front);\n                }\n                else {\n                    newChildren = this.children.insert(front, newChild);\n                }\n                if (this.value === null && newChildren.isEmpty()) {\n                    return new ImmutableTree(null);\n                }\n                else {\n                    return new ImmutableTree(this.value, newChildren);\n                }\n            }\n            else {\n                return this;\n            }\n        }\n    }\n    /**\n     * Gets a value from the tree.\n     *\n     * @param relativePath - Path to get value for.\n     * @returns Value at path, or null.\n     */\n    get(relativePath) {\n        if (pathIsEmpty(relativePath)) {\n            return this.value;\n        }\n        else {\n            const front = pathGetFront(relativePath);\n            const child = this.children.get(front);\n            if (child) {\n                return child.get(pathPopFront(relativePath));\n            }\n            else {\n                return null;\n            }\n        }\n    }\n    /**\n     * Replace the subtree at the specified path with the given new tree.\n     *\n     * @param relativePath - Path to replace subtree for.\n     * @param newTree - New tree.\n     * @returns Resulting tree.\n     */\n    setTree(relativePath, newTree) {\n        if (pathIsEmpty(relativePath)) {\n            return newTree;\n        }\n        else {\n            const front = pathGetFront(relativePath);\n            const child = this.children.get(front) || new ImmutableTree(null);\n            const newChild = child.setTree(pathPopFront(relativePath), newTree);\n            let newChildren;\n            if (newChild.isEmpty()) {\n                newChildren = this.children.remove(front);\n            }\n            else {\n                newChildren = this.children.insert(front, newChild);\n            }\n            return new ImmutableTree(this.value, newChildren);\n        }\n    }\n    /**\n     * Performs a depth first fold on this tree. Transforms a tree into a single\n     * value, given a function that operates on the path to a node, an optional\n     * current value, and a map of child names to folded subtrees\n     */\n    fold(fn) {\n        return this.fold_(newEmptyPath(), fn);\n    }\n    /**\n     * Recursive helper for public-facing fold() method\n     */\n    fold_(pathSoFar, fn) {\n        const accum = {};\n        this.children.inorderTraversal((childKey, childTree) => {\n            accum[childKey] = childTree.fold_(pathChild(pathSoFar, childKey), fn);\n        });\n        return fn(pathSoFar, this.value, accum);\n    }\n    /**\n     * Find the first matching value on the given path. Return the result of applying f to it.\n     */\n    findOnPath(path, f) {\n        return this.findOnPath_(path, newEmptyPath(), f);\n    }\n    findOnPath_(pathToFollow, pathSoFar, f) {\n        const result = this.value ? f(pathSoFar, this.value) : false;\n        if (result) {\n            return result;\n        }\n        else {\n            if (pathIsEmpty(pathToFollow)) {\n                return null;\n            }\n            else {\n                const front = pathGetFront(pathToFollow);\n                const nextChild = this.children.get(front);\n                if (nextChild) {\n                    return nextChild.findOnPath_(pathPopFront(pathToFollow), pathChild(pathSoFar, front), f);\n                }\n                else {\n                    return null;\n                }\n            }\n        }\n    }\n    foreachOnPath(path, f) {\n        return this.foreachOnPath_(path, newEmptyPath(), f);\n    }\n    foreachOnPath_(pathToFollow, currentRelativePath, f) {\n        if (pathIsEmpty(pathToFollow)) {\n            return this;\n        }\n        else {\n            if (this.value) {\n                f(currentRelativePath, this.value);\n            }\n            const front = pathGetFront(pathToFollow);\n            const nextChild = this.children.get(front);\n            if (nextChild) {\n                return nextChild.foreachOnPath_(pathPopFront(pathToFollow), pathChild(currentRelativePath, front), f);\n            }\n            else {\n                return new ImmutableTree(null);\n            }\n        }\n    }\n    /**\n     * Calls the given function for each node in the tree that has a value.\n     *\n     * @param f - A function to be called with the path from the root of the tree to\n     * a node, and the value at that node. Called in depth-first order.\n     */\n    foreach(f) {\n        this.foreach_(newEmptyPath(), f);\n    }\n    foreach_(currentRelativePath, f) {\n        this.children.inorderTraversal((childName, childTree) => {\n            childTree.foreach_(pathChild(currentRelativePath, childName), f);\n        });\n        if (this.value) {\n            f(currentRelativePath, this.value);\n        }\n    }\n    foreachChild(f) {\n        this.children.inorderTraversal((childName, childTree) => {\n            if (childTree.value) {\n                f(childName, childTree.value);\n            }\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 * This class holds a collection of writes that can be applied to nodes in unison. It abstracts away the logic with\n * dealing with priority writes and multiple nested writes. At any given path there is only allowed to be one write\n * modifying that path. Any write to an existing path or shadowing an existing path will modify that existing write\n * to reflect the write added.\n */\nclass CompoundWrite {\n    constructor(writeTree_) {\n        this.writeTree_ = writeTree_;\n    }\n    static empty() {\n        return new CompoundWrite(new ImmutableTree(null));\n    }\n}\nfunction compoundWriteAddWrite(compoundWrite, path, node) {\n    if (pathIsEmpty(path)) {\n        return new CompoundWrite(new ImmutableTree(node));\n    }\n    else {\n        const rootmost = compoundWrite.writeTree_.findRootMostValueAndPath(path);\n        if (rootmost != null) {\n            const rootMostPath = rootmost.path;\n            let value = rootmost.value;\n            const relativePath = newRelativePath(rootMostPath, path);\n            value = value.updateChild(relativePath, node);\n            return new CompoundWrite(compoundWrite.writeTree_.set(rootMostPath, value));\n        }\n        else {\n            const subtree = new ImmutableTree(node);\n            const newWriteTree = compoundWrite.writeTree_.setTree(path, subtree);\n            return new CompoundWrite(newWriteTree);\n        }\n    }\n}\nfunction compoundWriteAddWrites(compoundWrite, path, updates) {\n    let newWrite = compoundWrite;\n    each(updates, (childKey, node) => {\n        newWrite = compoundWriteAddWrite(newWrite, pathChild(path, childKey), node);\n    });\n    return newWrite;\n}\n/**\n * Will remove a write at the given path and deeper paths. This will <em>not</em> modify a write at a higher\n * location, which must be removed by calling this method with that path.\n *\n * @param compoundWrite - The CompoundWrite to remove.\n * @param path - The path at which a write and all deeper writes should be removed\n * @returns The new CompoundWrite with the removed path\n */\nfunction compoundWriteRemoveWrite(compoundWrite, path) {\n    if (pathIsEmpty(path)) {\n        return CompoundWrite.empty();\n    }\n    else {\n        const newWriteTree = compoundWrite.writeTree_.setTree(path, new ImmutableTree(null));\n        return new CompoundWrite(newWriteTree);\n    }\n}\n/**\n * Returns whether this CompoundWrite will fully overwrite a node at a given location and can therefore be\n * considered \"complete\".\n *\n * @param compoundWrite - The CompoundWrite to check.\n * @param path - The path to check for\n * @returns Whether there is a complete write at that path\n */\nfunction compoundWriteHasCompleteWrite(compoundWrite, path) {\n    return compoundWriteGetCompleteNode(compoundWrite, path) != null;\n}\n/**\n * Returns a node for a path if and only if the node is a \"complete\" overwrite at that path. This will not aggregate\n * writes from deeper paths, but will return child nodes from a more shallow path.\n *\n * @param compoundWrite - The CompoundWrite to get the node from.\n * @param path - The path to get a complete write\n * @returns The node if complete at that path, or null otherwise.\n */\nfunction compoundWriteGetCompleteNode(compoundWrite, path) {\n    const rootmost = compoundWrite.writeTree_.findRootMostValueAndPath(path);\n    if (rootmost != null) {\n        return compoundWrite.writeTree_\n            .get(rootmost.path)\n            .getChild(newRelativePath(rootmost.path, path));\n    }\n    else {\n        return null;\n    }\n}\n/**\n * Returns all children that are guaranteed to be a complete overwrite.\n *\n * @param compoundWrite - The CompoundWrite to get children from.\n * @returns A list of all complete children.\n */\nfunction compoundWriteGetCompleteChildren(compoundWrite) {\n    const children = [];\n    const node = compoundWrite.writeTree_.value;\n    if (node != null) {\n        // If it's a leaf node, it has no children; so nothing to do.\n        if (!node.isLeafNode()) {\n            node.forEachChild(PRIORITY_INDEX, (childName, childNode) => {\n                children.push(new NamedNode(childName, childNode));\n            });\n        }\n    }\n    else {\n        compoundWrite.writeTree_.children.inorderTraversal((childName, childTree) => {\n            if (childTree.value != null) {\n                children.push(new NamedNode(childName, childTree.value));\n            }\n        });\n    }\n    return children;\n}\nfunction compoundWriteChildCompoundWrite(compoundWrite, path) {\n    if (pathIsEmpty(path)) {\n        return compoundWrite;\n    }\n    else {\n        const shadowingNode = compoundWriteGetCompleteNode(compoundWrite, path);\n        if (shadowingNode != null) {\n            return new CompoundWrite(new ImmutableTree(shadowingNode));\n        }\n        else {\n            return new CompoundWrite(compoundWrite.writeTree_.subtree(path));\n        }\n    }\n}\n/**\n * Returns true if this CompoundWrite is empty and therefore does not modify any nodes.\n * @returns Whether this CompoundWrite is empty\n */\nfunction compoundWriteIsEmpty(compoundWrite) {\n    return compoundWrite.writeTree_.isEmpty();\n}\n/**\n * Applies this CompoundWrite to a node. The node is returned with all writes from this CompoundWrite applied to the\n * node\n * @param node - The node to apply this CompoundWrite to\n * @returns The node with all writes applied\n */\nfunction compoundWriteApply(compoundWrite, node) {\n    return applySubtreeWrite(newEmptyPath(), compoundWrite.writeTree_, node);\n}\nfunction applySubtreeWrite(relativePath, writeTree, node) {\n    if (writeTree.value != null) {\n        // Since there a write is always a leaf, we're done here\n        return node.updateChild(relativePath, writeTree.value);\n    }\n    else {\n        let priorityWrite = null;\n        writeTree.children.inorderTraversal((childKey, childTree) => {\n            if (childKey === '.priority') {\n                // Apply priorities at the end so we don't update priorities for either empty nodes or forget\n                // to apply priorities to empty nodes that are later filled\n                assert(childTree.value !== null, 'Priority writes must always be leaf nodes');\n                priorityWrite = childTree.value;\n            }\n            else {\n                node = applySubtreeWrite(pathChild(relativePath, childKey), childTree, node);\n            }\n        });\n        // If there was a priority write, we only apply it if the node is not empty\n        if (!node.getChild(relativePath).isEmpty() && priorityWrite !== null) {\n            node = node.updateChild(pathChild(relativePath, '.priority'), priorityWrite);\n        }\n        return node;\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 * Create a new WriteTreeRef for the given path. For use with a new sync point at the given path.\n *\n */\nfunction writeTreeChildWrites(writeTree, path) {\n    return newWriteTreeRef(path, writeTree);\n}\n/**\n * Record a new overwrite from user code.\n *\n * @param visible - This is set to false by some transactions. It should be excluded from event caches\n */\nfunction writeTreeAddOverwrite(writeTree, path, snap, writeId, visible) {\n    assert(writeId > writeTree.lastWriteId, 'Stacking an older write on top of newer ones');\n    if (visible === undefined) {\n        visible = true;\n    }\n    writeTree.allWrites.push({\n        path,\n        snap,\n        writeId,\n        visible\n    });\n    if (visible) {\n        writeTree.visibleWrites = compoundWriteAddWrite(writeTree.visibleWrites, path, snap);\n    }\n    writeTree.lastWriteId = writeId;\n}\n/**\n * Record a new merge from user code.\n */\nfunction writeTreeAddMerge(writeTree, path, changedChildren, writeId) {\n    assert(writeId > writeTree.lastWriteId, 'Stacking an older merge on top of newer ones');\n    writeTree.allWrites.push({\n        path,\n        children: changedChildren,\n        writeId,\n        visible: true\n    });\n    writeTree.visibleWrites = compoundWriteAddWrites(writeTree.visibleWrites, path, changedChildren);\n    writeTree.lastWriteId = writeId;\n}\nfunction writeTreeGetWrite(writeTree, writeId) {\n    for (let i = 0; i < writeTree.allWrites.length; i++) {\n        const record = writeTree.allWrites[i];\n        if (record.writeId === writeId) {\n            return record;\n        }\n    }\n    return null;\n}\n/**\n * Remove a write (either an overwrite or merge) that has been successfully acknowledge by the server. Recalculates\n * the tree if necessary.  We return true if it may have been visible, meaning views need to reevaluate.\n *\n * @returns true if the write may have been visible (meaning we'll need to reevaluate / raise\n * events as a result).\n */\nfunction writeTreeRemoveWrite(writeTree, writeId) {\n    // Note: disabling this check. It could be a transaction that preempted another transaction, and thus was applied\n    // out of order.\n    //const validClear = revert || this.allWrites_.length === 0 || writeId <= this.allWrites_[0].writeId;\n    //assert(validClear, \"Either we don't have this write, or it's the first one in the queue\");\n    const idx = writeTree.allWrites.findIndex(s => {\n        return s.writeId === writeId;\n    });\n    assert(idx >= 0, 'removeWrite called with nonexistent writeId.');\n    const writeToRemove = writeTree.allWrites[idx];\n    writeTree.allWrites.splice(idx, 1);\n    let removedWriteWasVisible = writeToRemove.visible;\n    let removedWriteOverlapsWithOtherWrites = false;\n    let i = writeTree.allWrites.length - 1;\n    while (removedWriteWasVisible && i >= 0) {\n        const currentWrite = writeTree.allWrites[i];\n        if (currentWrite.visible) {\n            if (i >= idx &&\n                writeTreeRecordContainsPath_(currentWrite, writeToRemove.path)) {\n                // The removed write was completely shadowed by a subsequent write.\n                removedWriteWasVisible = false;\n            }\n            else if (pathContains(writeToRemove.path, currentWrite.path)) {\n                // Either we're covering some writes or they're covering part of us (depending on which came first).\n                removedWriteOverlapsWithOtherWrites = true;\n            }\n        }\n        i--;\n    }\n    if (!removedWriteWasVisible) {\n        return false;\n    }\n    else if (removedWriteOverlapsWithOtherWrites) {\n        // There's some shadowing going on. Just rebuild the visible writes from scratch.\n        writeTreeResetTree_(writeTree);\n        return true;\n    }\n    else {\n        // There's no shadowing.  We can safely just remove the write(s) from visibleWrites.\n        if (writeToRemove.snap) {\n            writeTree.visibleWrites = compoundWriteRemoveWrite(writeTree.visibleWrites, writeToRemove.path);\n        }\n        else {\n            const children = writeToRemove.children;\n            each(children, (childName) => {\n                writeTree.visibleWrites = compoundWriteRemoveWrite(writeTree.visibleWrites, pathChild(writeToRemove.path, childName));\n            });\n        }\n        return true;\n    }\n}\nfunction writeTreeRecordContainsPath_(writeRecord, path) {\n    if (writeRecord.snap) {\n        return pathContains(writeRecord.path, path);\n    }\n    else {\n        for (const childName in writeRecord.children) {\n            if (writeRecord.children.hasOwnProperty(childName) &&\n                pathContains(pathChild(writeRecord.path, childName), path)) {\n                return true;\n            }\n        }\n        return false;\n    }\n}\n/**\n * Re-layer the writes and merges into a tree so we can efficiently calculate event snapshots\n */\nfunction writeTreeResetTree_(writeTree) {\n    writeTree.visibleWrites = writeTreeLayerTree_(writeTree.allWrites, writeTreeDefaultFilter_, newEmptyPath());\n    if (writeTree.allWrites.length > 0) {\n        writeTree.lastWriteId =\n            writeTree.allWrites[writeTree.allWrites.length - 1].writeId;\n    }\n    else {\n        writeTree.lastWriteId = -1;\n    }\n}\n/**\n * The default filter used when constructing the tree. Keep everything that's visible.\n */\nfunction writeTreeDefaultFilter_(write) {\n    return write.visible;\n}\n/**\n * Static method. Given an array of WriteRecords, a filter for which ones to include, and a path, construct the tree of\n * event data at that path.\n */\nfunction writeTreeLayerTree_(writes, filter, treeRoot) {\n    let compoundWrite = CompoundWrite.empty();\n    for (let i = 0; i < writes.length; ++i) {\n        const write = writes[i];\n        // Theory, a later set will either:\n        // a) abort a relevant transaction, so no need to worry about excluding it from calculating that transaction\n        // b) not be relevant to a transaction (separate branch), so again will not affect the data for that transaction\n        if (filter(write)) {\n            const writePath = write.path;\n            let relativePath;\n            if (write.snap) {\n                if (pathContains(treeRoot, writePath)) {\n                    relativePath = newRelativePath(treeRoot, writePath);\n                    compoundWrite = compoundWriteAddWrite(compoundWrite, relativePath, write.snap);\n                }\n                else if (pathContains(writePath, treeRoot)) {\n                    relativePath = newRelativePath(writePath, treeRoot);\n                    compoundWrite = compoundWriteAddWrite(compoundWrite, newEmptyPath(), write.snap.getChild(relativePath));\n                }\n                else ;\n            }\n            else if (write.children) {\n                if (pathContains(treeRoot, writePath)) {\n                    relativePath = newRelativePath(treeRoot, writePath);\n                    compoundWrite = compoundWriteAddWrites(compoundWrite, relativePath, write.children);\n                }\n                else if (pathContains(writePath, treeRoot)) {\n                    relativePath = newRelativePath(writePath, treeRoot);\n                    if (pathIsEmpty(relativePath)) {\n                        compoundWrite = compoundWriteAddWrites(compoundWrite, newEmptyPath(), write.children);\n                    }\n                    else {\n                        const child = safeGet(write.children, pathGetFront(relativePath));\n                        if (child) {\n                            // There exists a child in this node that matches the root path\n                            const deepNode = child.getChild(pathPopFront(relativePath));\n                            compoundWrite = compoundWriteAddWrite(compoundWrite, newEmptyPath(), deepNode);\n                        }\n                    }\n                }\n                else ;\n            }\n            else {\n                throw assertionError('WriteRecord should have .snap or .children');\n            }\n        }\n    }\n    return compoundWrite;\n}\n/**\n * Given optional, underlying server data, and an optional set of constraints (exclude some sets, include hidden\n * writes), attempt to calculate a complete snapshot for the given path\n *\n * @param writeIdsToExclude - An optional set to be excluded\n * @param includeHiddenWrites - Defaults to false, whether or not to layer on writes with visible set to false\n */\nfunction writeTreeCalcCompleteEventCache(writeTree, treePath, completeServerCache, writeIdsToExclude, includeHiddenWrites) {\n    if (!writeIdsToExclude && !includeHiddenWrites) {\n        const shadowingNode = compoundWriteGetCompleteNode(writeTree.visibleWrites, treePath);\n        if (shadowingNode != null) {\n            return shadowingNode;\n        }\n        else {\n            const subMerge = compoundWriteChildCompoundWrite(writeTree.visibleWrites, treePath);\n            if (compoundWriteIsEmpty(subMerge)) {\n                return completeServerCache;\n            }\n            else if (completeServerCache == null &&\n                !compoundWriteHasCompleteWrite(subMerge, newEmptyPath())) {\n                // We wouldn't have a complete snapshot, since there's no underlying data and no complete shadow\n                return null;\n            }\n            else {\n                const layeredCache = completeServerCache || ChildrenNode.EMPTY_NODE;\n                return compoundWriteApply(subMerge, layeredCache);\n            }\n        }\n    }\n    else {\n        const merge = compoundWriteChildCompoundWrite(writeTree.visibleWrites, treePath);\n        if (!includeHiddenWrites && compoundWriteIsEmpty(merge)) {\n            return completeServerCache;\n        }\n        else {\n            // If the server cache is null, and we don't have a complete cache, we need to return null\n            if (!includeHiddenWrites &&\n                completeServerCache == null &&\n                !compoundWriteHasCompleteWrite(merge, newEmptyPath())) {\n                return null;\n            }\n            else {\n                const filter = function (write) {\n                    return ((write.visible || includeHiddenWrites) &&\n                        (!writeIdsToExclude ||\n                            !~writeIdsToExclude.indexOf(write.writeId)) &&\n                        (pathContains(write.path, treePath) ||\n                            pathContains(treePath, write.path)));\n                };\n                const mergeAtPath = writeTreeLayerTree_(writeTree.allWrites, filter, treePath);\n                const layeredCache = completeServerCache || ChildrenNode.EMPTY_NODE;\n                return compoundWriteApply(mergeAtPath, layeredCache);\n            }\n        }\n    }\n}\n/**\n * With optional, underlying server data, attempt to return a children node of children that we have complete data for.\n * Used when creating new views, to pre-fill their complete event children snapshot.\n */\nfunction writeTreeCalcCompleteEventChildren(writeTree, treePath, completeServerChildren) {\n    let completeChildren = ChildrenNode.EMPTY_NODE;\n    const topLevelSet = compoundWriteGetCompleteNode(writeTree.visibleWrites, treePath);\n    if (topLevelSet) {\n        if (!topLevelSet.isLeafNode()) {\n            // we're shadowing everything. Return the children.\n            topLevelSet.forEachChild(PRIORITY_INDEX, (childName, childSnap) => {\n                completeChildren = completeChildren.updateImmediateChild(childName, childSnap);\n            });\n        }\n        return completeChildren;\n    }\n    else if (completeServerChildren) {\n        // Layer any children we have on top of this\n        // We know we don't have a top-level set, so just enumerate existing children\n        const merge = compoundWriteChildCompoundWrite(writeTree.visibleWrites, treePath);\n        completeServerChildren.forEachChild(PRIORITY_INDEX, (childName, childNode) => {\n            const node = compoundWriteApply(compoundWriteChildCompoundWrite(merge, new Path(childName)), childNode);\n            completeChildren = completeChildren.updateImmediateChild(childName, node);\n        });\n        // Add any complete children we have from the set\n        compoundWriteGetCompleteChildren(merge).forEach(namedNode => {\n            completeChildren = completeChildren.updateImmediateChild(namedNode.name, namedNode.node);\n        });\n        return completeChildren;\n    }\n    else {\n        // We don't have anything to layer on top of. Layer on any children we have\n        // Note that we can return an empty snap if we have a defined delete\n        const merge = compoundWriteChildCompoundWrite(writeTree.visibleWrites, treePath);\n        compoundWriteGetCompleteChildren(merge).forEach(namedNode => {\n            completeChildren = completeChildren.updateImmediateChild(namedNode.name, namedNode.node);\n        });\n        return completeChildren;\n    }\n}\n/**\n * Given that the underlying server data has updated, determine what, if anything, needs to be\n * applied to the event cache.\n *\n * Possibilities:\n *\n * 1. No writes are shadowing. Events should be raised, the snap to be applied comes from the server data\n *\n * 2. Some write is completely shadowing. No events to be raised\n *\n * 3. Is partially shadowed. Events\n *\n * Either existingEventSnap or existingServerSnap must exist\n */\nfunction writeTreeCalcEventCacheAfterServerOverwrite(writeTree, treePath, childPath, existingEventSnap, existingServerSnap) {\n    assert(existingEventSnap || existingServerSnap, 'Either existingEventSnap or existingServerSnap must exist');\n    const path = pathChild(treePath, childPath);\n    if (compoundWriteHasCompleteWrite(writeTree.visibleWrites, path)) {\n        // At this point we can probably guarantee that we're in case 2, meaning no events\n        // May need to check visibility while doing the findRootMostValueAndPath call\n        return null;\n    }\n    else {\n        // No complete shadowing. We're either partially shadowing or not shadowing at all.\n        const childMerge = compoundWriteChildCompoundWrite(writeTree.visibleWrites, path);\n        if (compoundWriteIsEmpty(childMerge)) {\n            // We're not shadowing at all. Case 1\n            return existingServerSnap.getChild(childPath);\n        }\n        else {\n            // This could be more efficient if the serverNode + updates doesn't change the eventSnap\n            // However this is tricky to find out, since user updates don't necessary change the server\n            // snap, e.g. priority updates on empty nodes, or deep deletes. Another special case is if the server\n            // adds nodes, but doesn't change any existing writes. It is therefore not enough to\n            // only check if the updates change the serverNode.\n            // Maybe check if the merge tree contains these special cases and only do a full overwrite in that case?\n            return compoundWriteApply(childMerge, existingServerSnap.getChild(childPath));\n        }\n    }\n}\n/**\n * Returns a complete child for a given server snap after applying all user writes or null if there is no\n * complete child for this ChildKey.\n */\nfunction writeTreeCalcCompleteChild(writeTree, treePath, childKey, existingServerSnap) {\n    const path = pathChild(treePath, childKey);\n    const shadowingNode = compoundWriteGetCompleteNode(writeTree.visibleWrites, path);\n    if (shadowingNode != null) {\n        return shadowingNode;\n    }\n    else {\n        if (existingServerSnap.isCompleteForChild(childKey)) {\n            const childMerge = compoundWriteChildCompoundWrite(writeTree.visibleWrites, path);\n            return compoundWriteApply(childMerge, existingServerSnap.getNode().getImmediateChild(childKey));\n        }\n        else {\n            return null;\n        }\n    }\n}\n/**\n * Returns a node if there is a complete overwrite for this path. More specifically, if there is a write at\n * a higher path, this will return the child of that write relative to the write and this path.\n * Returns null if there is no write at this path.\n */\nfunction writeTreeShadowingWrite(writeTree, path) {\n    return compoundWriteGetCompleteNode(writeTree.visibleWrites, path);\n}\n/**\n * This method is used when processing child remove events on a query. If we can, we pull in children that were outside\n * the window, but may now be in the window.\n */\nfunction writeTreeCalcIndexedSlice(writeTree, treePath, completeServerData, startPost, count, reverse, index) {\n    let toIterate;\n    const merge = compoundWriteChildCompoundWrite(writeTree.visibleWrites, treePath);\n    const shadowingNode = compoundWriteGetCompleteNode(merge, newEmptyPath());\n    if (shadowingNode != null) {\n        toIterate = shadowingNode;\n    }\n    else if (completeServerData != null) {\n        toIterate = compoundWriteApply(merge, completeServerData);\n    }\n    else {\n        // no children to iterate on\n        return [];\n    }\n    toIterate = toIterate.withIndex(index);\n    if (!toIterate.isEmpty() && !toIterate.isLeafNode()) {\n        const nodes = [];\n        const cmp = index.getCompare();\n        const iter = reverse\n            ? toIterate.getReverseIteratorFrom(startPost, index)\n            : toIterate.getIteratorFrom(startPost, index);\n        let next = iter.getNext();\n        while (next && nodes.length < count) {\n            if (cmp(next, startPost) !== 0) {\n                nodes.push(next);\n            }\n            next = iter.getNext();\n        }\n        return nodes;\n    }\n    else {\n        return [];\n    }\n}\nfunction newWriteTree() {\n    return {\n        visibleWrites: CompoundWrite.empty(),\n        allWrites: [],\n        lastWriteId: -1\n    };\n}\n/**\n * If possible, returns a complete event cache, using the underlying server data if possible. In addition, can be used\n * to get a cache that includes hidden writes, and excludes arbitrary writes. Note that customizing the returned node\n * can lead to a more expensive calculation.\n *\n * @param writeIdsToExclude - Optional writes to exclude.\n * @param includeHiddenWrites - Defaults to false, whether or not to layer on writes with visible set to false\n */\nfunction writeTreeRefCalcCompleteEventCache(writeTreeRef, completeServerCache, writeIdsToExclude, includeHiddenWrites) {\n    return writeTreeCalcCompleteEventCache(writeTreeRef.writeTree, writeTreeRef.treePath, completeServerCache, writeIdsToExclude, includeHiddenWrites);\n}\n/**\n * If possible, returns a children node containing all of the complete children we have data for. The returned data is a\n * mix of the given server data and write data.\n *\n */\nfunction writeTreeRefCalcCompleteEventChildren(writeTreeRef, completeServerChildren) {\n    return writeTreeCalcCompleteEventChildren(writeTreeRef.writeTree, writeTreeRef.treePath, completeServerChildren);\n}\n/**\n * Given that either the underlying server data has updated or the outstanding writes have updated, determine what,\n * if anything, needs to be applied to the event cache.\n *\n * Possibilities:\n *\n * 1. No writes are shadowing. Events should be raised, the snap to be applied comes from the server data\n *\n * 2. Some write is completely shadowing. No events to be raised\n *\n * 3. Is partially shadowed. Events should be raised\n *\n * Either existingEventSnap or existingServerSnap must exist, this is validated via an assert\n *\n *\n */\nfunction writeTreeRefCalcEventCacheAfterServerOverwrite(writeTreeRef, path, existingEventSnap, existingServerSnap) {\n    return writeTreeCalcEventCacheAfterServerOverwrite(writeTreeRef.writeTree, writeTreeRef.treePath, path, existingEventSnap, existingServerSnap);\n}\n/**\n * Returns a node if there is a complete overwrite for this path. More specifically, if there is a write at\n * a higher path, this will return the child of that write relative to the write and this path.\n * Returns null if there is no write at this path.\n *\n */\nfunction writeTreeRefShadowingWrite(writeTreeRef, path) {\n    return writeTreeShadowingWrite(writeTreeRef.writeTree, pathChild(writeTreeRef.treePath, path));\n}\n/**\n * This method is used when processing child remove events on a query. If we can, we pull in children that were outside\n * the window, but may now be in the window\n */\nfunction writeTreeRefCalcIndexedSlice(writeTreeRef, completeServerData, startPost, count, reverse, index) {\n    return writeTreeCalcIndexedSlice(writeTreeRef.writeTree, writeTreeRef.treePath, completeServerData, startPost, count, reverse, index);\n}\n/**\n * Returns a complete child for a given server snap after applying all user writes or null if there is no\n * complete child for this ChildKey.\n */\nfunction writeTreeRefCalcCompleteChild(writeTreeRef, childKey, existingServerCache) {\n    return writeTreeCalcCompleteChild(writeTreeRef.writeTree, writeTreeRef.treePath, childKey, existingServerCache);\n}\n/**\n * Return a WriteTreeRef for a child.\n */\nfunction writeTreeRefChild(writeTreeRef, childName) {\n    return newWriteTreeRef(pathChild(writeTreeRef.treePath, childName), writeTreeRef.writeTree);\n}\nfunction newWriteTreeRef(path, writeTree) {\n    return {\n        treePath: path,\n        writeTree\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 */\nclass ChildChangeAccumulator {\n    constructor() {\n        this.changeMap = new Map();\n    }\n    trackChildChange(change) {\n        const type = change.type;\n        const childKey = change.childName;\n        assert(type === \"child_added\" /* ChangeType.CHILD_ADDED */ ||\n            type === \"child_changed\" /* ChangeType.CHILD_CHANGED */ ||\n            type === \"child_removed\" /* ChangeType.CHILD_REMOVED */, 'Only child changes supported for tracking');\n        assert(childKey !== '.priority', 'Only non-priority child changes can be tracked.');\n        const oldChange = this.changeMap.get(childKey);\n        if (oldChange) {\n            const oldType = oldChange.type;\n            if (type === \"child_added\" /* ChangeType.CHILD_ADDED */ &&\n                oldType === \"child_removed\" /* ChangeType.CHILD_REMOVED */) {\n                this.changeMap.set(childKey, changeChildChanged(childKey, change.snapshotNode, oldChange.snapshotNode));\n            }\n            else if (type === \"child_removed\" /* ChangeType.CHILD_REMOVED */ &&\n                oldType === \"child_added\" /* ChangeType.CHILD_ADDED */) {\n                this.changeMap.delete(childKey);\n            }\n            else if (type === \"child_removed\" /* ChangeType.CHILD_REMOVED */ &&\n                oldType === \"child_changed\" /* ChangeType.CHILD_CHANGED */) {\n                this.changeMap.set(childKey, changeChildRemoved(childKey, oldChange.oldSnap));\n            }\n            else if (type === \"child_changed\" /* ChangeType.CHILD_CHANGED */ &&\n                oldType === \"child_added\" /* ChangeType.CHILD_ADDED */) {\n                this.changeMap.set(childKey, changeChildAdded(childKey, change.snapshotNode));\n            }\n            else if (type === \"child_changed\" /* ChangeType.CHILD_CHANGED */ &&\n                oldType === \"child_changed\" /* ChangeType.CHILD_CHANGED */) {\n                this.changeMap.set(childKey, changeChildChanged(childKey, change.snapshotNode, oldChange.oldSnap));\n            }\n            else {\n                throw assertionError('Illegal combination of changes: ' +\n                    change +\n                    ' occurred after ' +\n                    oldChange);\n            }\n        }\n        else {\n            this.changeMap.set(childKey, change);\n        }\n    }\n    getChanges() {\n        return Array.from(this.changeMap.values());\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 implementation of CompleteChildSource that never returns any additional children\n */\n// eslint-disable-next-line @typescript-eslint/naming-convention\nclass NoCompleteChildSource_ {\n    getCompleteChild(childKey) {\n        return null;\n    }\n    getChildAfterChild(index, child, reverse) {\n        return null;\n    }\n}\n/**\n * Singleton instance.\n */\nconst NO_COMPLETE_CHILD_SOURCE = new NoCompleteChildSource_();\n/**\n * An implementation of CompleteChildSource that uses a WriteTree in addition to any other server data or\n * old event caches available to calculate complete children.\n */\nclass WriteTreeCompleteChildSource {\n    constructor(writes_, viewCache_, optCompleteServerCache_ = null) {\n        this.writes_ = writes_;\n        this.viewCache_ = viewCache_;\n        this.optCompleteServerCache_ = optCompleteServerCache_;\n    }\n    getCompleteChild(childKey) {\n        const node = this.viewCache_.eventCache;\n        if (node.isCompleteForChild(childKey)) {\n            return node.getNode().getImmediateChild(childKey);\n        }\n        else {\n            const serverNode = this.optCompleteServerCache_ != null\n                ? new CacheNode(this.optCompleteServerCache_, true, false)\n                : this.viewCache_.serverCache;\n            return writeTreeRefCalcCompleteChild(this.writes_, childKey, serverNode);\n        }\n    }\n    getChildAfterChild(index, child, reverse) {\n        const completeServerData = this.optCompleteServerCache_ != null\n            ? this.optCompleteServerCache_\n            : viewCacheGetCompleteServerSnap(this.viewCache_);\n        const nodes = writeTreeRefCalcIndexedSlice(this.writes_, completeServerData, child, 1, reverse, index);\n        if (nodes.length === 0) {\n            return null;\n        }\n        else {\n            return nodes[0];\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 */\nfunction newViewProcessor(filter) {\n    return { filter };\n}\nfunction viewProcessorAssertIndexed(viewProcessor, viewCache) {\n    assert(viewCache.eventCache.getNode().isIndexed(viewProcessor.filter.getIndex()), 'Event snap not indexed');\n    assert(viewCache.serverCache.getNode().isIndexed(viewProcessor.filter.getIndex()), 'Server snap not indexed');\n}\nfunction viewProcessorApplyOperation(viewProcessor, oldViewCache, operation, writesCache, completeCache) {\n    const accumulator = new ChildChangeAccumulator();\n    let newViewCache, filterServerNode;\n    if (operation.type === OperationType.OVERWRITE) {\n        const overwrite = operation;\n        if (overwrite.source.fromUser) {\n            newViewCache = viewProcessorApplyUserOverwrite(viewProcessor, oldViewCache, overwrite.path, overwrite.snap, writesCache, completeCache, accumulator);\n        }\n        else {\n            assert(overwrite.source.fromServer, 'Unknown source.');\n            // We filter the node if it's a tagged update or the node has been previously filtered  and the\n            // update is not at the root in which case it is ok (and necessary) to mark the node unfiltered\n            // again\n            filterServerNode =\n                overwrite.source.tagged ||\n                    (oldViewCache.serverCache.isFiltered() && !pathIsEmpty(overwrite.path));\n            newViewCache = viewProcessorApplyServerOverwrite(viewProcessor, oldViewCache, overwrite.path, overwrite.snap, writesCache, completeCache, filterServerNode, accumulator);\n        }\n    }\n    else if (operation.type === OperationType.MERGE) {\n        const merge = operation;\n        if (merge.source.fromUser) {\n            newViewCache = viewProcessorApplyUserMerge(viewProcessor, oldViewCache, merge.path, merge.children, writesCache, completeCache, accumulator);\n        }\n        else {\n            assert(merge.source.fromServer, 'Unknown source.');\n            // We filter the node if it's a tagged update or the node has been previously filtered\n            filterServerNode =\n                merge.source.tagged || oldViewCache.serverCache.isFiltered();\n            newViewCache = viewProcessorApplyServerMerge(viewProcessor, oldViewCache, merge.path, merge.children, writesCache, completeCache, filterServerNode, accumulator);\n        }\n    }\n    else if (operation.type === OperationType.ACK_USER_WRITE) {\n        const ackUserWrite = operation;\n        if (!ackUserWrite.revert) {\n            newViewCache = viewProcessorAckUserWrite(viewProcessor, oldViewCache, ackUserWrite.path, ackUserWrite.affectedTree, writesCache, completeCache, accumulator);\n        }\n        else {\n            newViewCache = viewProcessorRevertUserWrite(viewProcessor, oldViewCache, ackUserWrite.path, writesCache, completeCache, accumulator);\n        }\n    }\n    else if (operation.type === OperationType.LISTEN_COMPLETE) {\n        newViewCache = viewProcessorListenComplete(viewProcessor, oldViewCache, operation.path, writesCache, accumulator);\n    }\n    else {\n        throw assertionError('Unknown operation type: ' + operation.type);\n    }\n    const changes = accumulator.getChanges();\n    viewProcessorMaybeAddValueEvent(oldViewCache, newViewCache, changes);\n    return { viewCache: newViewCache, changes };\n}\nfunction viewProcessorMaybeAddValueEvent(oldViewCache, newViewCache, accumulator) {\n    const eventSnap = newViewCache.eventCache;\n    if (eventSnap.isFullyInitialized()) {\n        const isLeafOrEmpty = eventSnap.getNode().isLeafNode() || eventSnap.getNode().isEmpty();\n        const oldCompleteSnap = viewCacheGetCompleteEventSnap(oldViewCache);\n        if (accumulator.length > 0 ||\n            !oldViewCache.eventCache.isFullyInitialized() ||\n            (isLeafOrEmpty && !eventSnap.getNode().equals(oldCompleteSnap)) ||\n            !eventSnap.getNode().getPriority().equals(oldCompleteSnap.getPriority())) {\n            accumulator.push(changeValue(viewCacheGetCompleteEventSnap(newViewCache)));\n        }\n    }\n}\nfunction viewProcessorGenerateEventCacheAfterServerEvent(viewProcessor, viewCache, changePath, writesCache, source, accumulator) {\n    const oldEventSnap = viewCache.eventCache;\n    if (writeTreeRefShadowingWrite(writesCache, changePath) != null) {\n        // we have a shadowing write, ignore changes\n        return viewCache;\n    }\n    else {\n        let newEventCache, serverNode;\n        if (pathIsEmpty(changePath)) {\n            // TODO: figure out how this plays with \"sliding ack windows\"\n            assert(viewCache.serverCache.isFullyInitialized(), 'If change path is empty, we must have complete server data');\n            if (viewCache.serverCache.isFiltered()) {\n                // We need to special case this, because we need to only apply writes to complete children, or\n                // we might end up raising events for incomplete children. If the server data is filtered deep\n                // writes cannot be guaranteed to be complete\n                const serverCache = viewCacheGetCompleteServerSnap(viewCache);\n                const completeChildren = serverCache instanceof ChildrenNode\n                    ? serverCache\n                    : ChildrenNode.EMPTY_NODE;\n                const completeEventChildren = writeTreeRefCalcCompleteEventChildren(writesCache, completeChildren);\n                newEventCache = viewProcessor.filter.updateFullNode(viewCache.eventCache.getNode(), completeEventChildren, accumulator);\n            }\n            else {\n                const completeNode = writeTreeRefCalcCompleteEventCache(writesCache, viewCacheGetCompleteServerSnap(viewCache));\n                newEventCache = viewProcessor.filter.updateFullNode(viewCache.eventCache.getNode(), completeNode, accumulator);\n            }\n        }\n        else {\n            const childKey = pathGetFront(changePath);\n            if (childKey === '.priority') {\n                assert(pathGetLength(changePath) === 1, \"Can't have a priority with additional path components\");\n                const oldEventNode = oldEventSnap.getNode();\n                serverNode = viewCache.serverCache.getNode();\n                // we might have overwrites for this priority\n                const updatedPriority = writeTreeRefCalcEventCacheAfterServerOverwrite(writesCache, changePath, oldEventNode, serverNode);\n                if (updatedPriority != null) {\n                    newEventCache = viewProcessor.filter.updatePriority(oldEventNode, updatedPriority);\n                }\n                else {\n                    // priority didn't change, keep old node\n                    newEventCache = oldEventSnap.getNode();\n                }\n            }\n            else {\n                const childChangePath = pathPopFront(changePath);\n                // update child\n                let newEventChild;\n                if (oldEventSnap.isCompleteForChild(childKey)) {\n                    serverNode = viewCache.serverCache.getNode();\n                    const eventChildUpdate = writeTreeRefCalcEventCacheAfterServerOverwrite(writesCache, changePath, oldEventSnap.getNode(), serverNode);\n                    if (eventChildUpdate != null) {\n                        newEventChild = oldEventSnap\n                            .getNode()\n                            .getImmediateChild(childKey)\n                            .updateChild(childChangePath, eventChildUpdate);\n                    }\n                    else {\n                        // Nothing changed, just keep the old child\n                        newEventChild = oldEventSnap.getNode().getImmediateChild(childKey);\n                    }\n                }\n                else {\n                    newEventChild = writeTreeRefCalcCompleteChild(writesCache, childKey, viewCache.serverCache);\n                }\n                if (newEventChild != null) {\n                    newEventCache = viewProcessor.filter.updateChild(oldEventSnap.getNode(), childKey, newEventChild, childChangePath, source, accumulator);\n                }\n                else {\n                    // no complete child available or no change\n                    newEventCache = oldEventSnap.getNode();\n                }\n            }\n        }\n        return viewCacheUpdateEventSnap(viewCache, newEventCache, oldEventSnap.isFullyInitialized() || pathIsEmpty(changePath), viewProcessor.filter.filtersNodes());\n    }\n}\nfunction viewProcessorApplyServerOverwrite(viewProcessor, oldViewCache, changePath, changedSnap, writesCache, completeCache, filterServerNode, accumulator) {\n    const oldServerSnap = oldViewCache.serverCache;\n    let newServerCache;\n    const serverFilter = filterServerNode\n        ? viewProcessor.filter\n        : viewProcessor.filter.getIndexedFilter();\n    if (pathIsEmpty(changePath)) {\n        newServerCache = serverFilter.updateFullNode(oldServerSnap.getNode(), changedSnap, null);\n    }\n    else if (serverFilter.filtersNodes() && !oldServerSnap.isFiltered()) {\n        // we want to filter the server node, but we didn't filter the server node yet, so simulate a full update\n        const newServerNode = oldServerSnap\n            .getNode()\n            .updateChild(changePath, changedSnap);\n        newServerCache = serverFilter.updateFullNode(oldServerSnap.getNode(), newServerNode, null);\n    }\n    else {\n        const childKey = pathGetFront(changePath);\n        if (!oldServerSnap.isCompleteForPath(changePath) &&\n            pathGetLength(changePath) > 1) {\n            // We don't update incomplete nodes with updates intended for other listeners\n            return oldViewCache;\n        }\n        const childChangePath = pathPopFront(changePath);\n        const childNode = oldServerSnap.getNode().getImmediateChild(childKey);\n        const newChildNode = childNode.updateChild(childChangePath, changedSnap);\n        if (childKey === '.priority') {\n            newServerCache = serverFilter.updatePriority(oldServerSnap.getNode(), newChildNode);\n        }\n        else {\n            newServerCache = serverFilter.updateChild(oldServerSnap.getNode(), childKey, newChildNode, childChangePath, NO_COMPLETE_CHILD_SOURCE, null);\n        }\n    }\n    const newViewCache = viewCacheUpdateServerSnap(oldViewCache, newServerCache, oldServerSnap.isFullyInitialized() || pathIsEmpty(changePath), serverFilter.filtersNodes());\n    const source = new WriteTreeCompleteChildSource(writesCache, newViewCache, completeCache);\n    return viewProcessorGenerateEventCacheAfterServerEvent(viewProcessor, newViewCache, changePath, writesCache, source, accumulator);\n}\nfunction viewProcessorApplyUserOverwrite(viewProcessor, oldViewCache, changePath, changedSnap, writesCache, completeCache, accumulator) {\n    const oldEventSnap = oldViewCache.eventCache;\n    let newViewCache, newEventCache;\n    const source = new WriteTreeCompleteChildSource(writesCache, oldViewCache, completeCache);\n    if (pathIsEmpty(changePath)) {\n        newEventCache = viewProcessor.filter.updateFullNode(oldViewCache.eventCache.getNode(), changedSnap, accumulator);\n        newViewCache = viewCacheUpdateEventSnap(oldViewCache, newEventCache, true, viewProcessor.filter.filtersNodes());\n    }\n    else {\n        const childKey = pathGetFront(changePath);\n        if (childKey === '.priority') {\n            newEventCache = viewProcessor.filter.updatePriority(oldViewCache.eventCache.getNode(), changedSnap);\n            newViewCache = viewCacheUpdateEventSnap(oldViewCache, newEventCache, oldEventSnap.isFullyInitialized(), oldEventSnap.isFiltered());\n        }\n        else {\n            const childChangePath = pathPopFront(changePath);\n            const oldChild = oldEventSnap.getNode().getImmediateChild(childKey);\n            let newChild;\n            if (pathIsEmpty(childChangePath)) {\n                // Child overwrite, we can replace the child\n                newChild = changedSnap;\n            }\n            else {\n                const childNode = source.getCompleteChild(childKey);\n                if (childNode != null) {\n                    if (pathGetBack(childChangePath) === '.priority' &&\n                        childNode.getChild(pathParent(childChangePath)).isEmpty()) {\n                        // This is a priority update on an empty node. If this node exists on the server, the\n                        // server will send down the priority in the update, so ignore for now\n                        newChild = childNode;\n                    }\n                    else {\n                        newChild = childNode.updateChild(childChangePath, changedSnap);\n                    }\n                }\n                else {\n                    // There is no complete child node available\n                    newChild = ChildrenNode.EMPTY_NODE;\n                }\n            }\n            if (!oldChild.equals(newChild)) {\n                const newEventSnap = viewProcessor.filter.updateChild(oldEventSnap.getNode(), childKey, newChild, childChangePath, source, accumulator);\n                newViewCache = viewCacheUpdateEventSnap(oldViewCache, newEventSnap, oldEventSnap.isFullyInitialized(), viewProcessor.filter.filtersNodes());\n            }\n            else {\n                newViewCache = oldViewCache;\n            }\n        }\n    }\n    return newViewCache;\n}\nfunction viewProcessorCacheHasChild(viewCache, childKey) {\n    return viewCache.eventCache.isCompleteForChild(childKey);\n}\nfunction viewProcessorApplyUserMerge(viewProcessor, viewCache, path, changedChildren, writesCache, serverCache, accumulator) {\n    // HACK: In the case of a limit query, there may be some changes that bump things out of the\n    // window leaving room for new items.  It's important we process these changes first, so we\n    // iterate the changes twice, first processing any that affect items currently in view.\n    // TODO: I consider an item \"in view\" if cacheHasChild is true, which checks both the server\n    // and event snap.  I'm not sure if this will result in edge cases when a child is in one but\n    // not the other.\n    let curViewCache = viewCache;\n    changedChildren.foreach((relativePath, childNode) => {\n        const writePath = pathChild(path, relativePath);\n        if (viewProcessorCacheHasChild(viewCache, pathGetFront(writePath))) {\n            curViewCache = viewProcessorApplyUserOverwrite(viewProcessor, curViewCache, writePath, childNode, writesCache, serverCache, accumulator);\n        }\n    });\n    changedChildren.foreach((relativePath, childNode) => {\n        const writePath = pathChild(path, relativePath);\n        if (!viewProcessorCacheHasChild(viewCache, pathGetFront(writePath))) {\n            curViewCache = viewProcessorApplyUserOverwrite(viewProcessor, curViewCache, writePath, childNode, writesCache, serverCache, accumulator);\n        }\n    });\n    return curViewCache;\n}\nfunction viewProcessorApplyMerge(viewProcessor, node, merge) {\n    merge.foreach((relativePath, childNode) => {\n        node = node.updateChild(relativePath, childNode);\n    });\n    return node;\n}\nfunction viewProcessorApplyServerMerge(viewProcessor, viewCache, path, changedChildren, writesCache, serverCache, filterServerNode, accumulator) {\n    // If we don't have a cache yet, this merge was intended for a previously listen in the same location. Ignore it and\n    // wait for the complete data update coming soon.\n    if (viewCache.serverCache.getNode().isEmpty() &&\n        !viewCache.serverCache.isFullyInitialized()) {\n        return viewCache;\n    }\n    // HACK: In the case of a limit query, there may be some changes that bump things out of the\n    // window leaving room for new items.  It's important we process these changes first, so we\n    // iterate the changes twice, first processing any that affect items currently in view.\n    // TODO: I consider an item \"in view\" if cacheHasChild is true, which checks both the server\n    // and event snap.  I'm not sure if this will result in edge cases when a child is in one but\n    // not the other.\n    let curViewCache = viewCache;\n    let viewMergeTree;\n    if (pathIsEmpty(path)) {\n        viewMergeTree = changedChildren;\n    }\n    else {\n        viewMergeTree = new ImmutableTree(null).setTree(path, changedChildren);\n    }\n    const serverNode = viewCache.serverCache.getNode();\n    viewMergeTree.children.inorderTraversal((childKey, childTree) => {\n        if (serverNode.hasChild(childKey)) {\n            const serverChild = viewCache.serverCache\n                .getNode()\n                .getImmediateChild(childKey);\n            const newChild = viewProcessorApplyMerge(viewProcessor, serverChild, childTree);\n            curViewCache = viewProcessorApplyServerOverwrite(viewProcessor, curViewCache, new Path(childKey), newChild, writesCache, serverCache, filterServerNode, accumulator);\n        }\n    });\n    viewMergeTree.children.inorderTraversal((childKey, childMergeTree) => {\n        const isUnknownDeepMerge = !viewCache.serverCache.isCompleteForChild(childKey) &&\n            childMergeTree.value === null;\n        if (!serverNode.hasChild(childKey) && !isUnknownDeepMerge) {\n            const serverChild = viewCache.serverCache\n                .getNode()\n                .getImmediateChild(childKey);\n            const newChild = viewProcessorApplyMerge(viewProcessor, serverChild, childMergeTree);\n            curViewCache = viewProcessorApplyServerOverwrite(viewProcessor, curViewCache, new Path(childKey), newChild, writesCache, serverCache, filterServerNode, accumulator);\n        }\n    });\n    return curViewCache;\n}\nfunction viewProcessorAckUserWrite(viewProcessor, viewCache, ackPath, affectedTree, writesCache, completeCache, accumulator) {\n    if (writeTreeRefShadowingWrite(writesCache, ackPath) != null) {\n        return viewCache;\n    }\n    // Only filter server node if it is currently filtered\n    const filterServerNode = viewCache.serverCache.isFiltered();\n    // Essentially we'll just get our existing server cache for the affected paths and re-apply it as a server update\n    // now that it won't be shadowed.\n    const serverCache = viewCache.serverCache;\n    if (affectedTree.value != null) {\n        // This is an overwrite.\n        if ((pathIsEmpty(ackPath) && serverCache.isFullyInitialized()) ||\n            serverCache.isCompleteForPath(ackPath)) {\n            return viewProcessorApplyServerOverwrite(viewProcessor, viewCache, ackPath, serverCache.getNode().getChild(ackPath), writesCache, completeCache, filterServerNode, accumulator);\n        }\n        else if (pathIsEmpty(ackPath)) {\n            // This is a goofy edge case where we are acking data at this location but don't have full data.  We\n            // should just re-apply whatever we have in our cache as a merge.\n            let changedChildren = new ImmutableTree(null);\n            serverCache.getNode().forEachChild(KEY_INDEX, (name, node) => {\n                changedChildren = changedChildren.set(new Path(name), node);\n            });\n            return viewProcessorApplyServerMerge(viewProcessor, viewCache, ackPath, changedChildren, writesCache, completeCache, filterServerNode, accumulator);\n        }\n        else {\n            return viewCache;\n        }\n    }\n    else {\n        // This is a merge.\n        let changedChildren = new ImmutableTree(null);\n        affectedTree.foreach((mergePath, value) => {\n            const serverCachePath = pathChild(ackPath, mergePath);\n            if (serverCache.isCompleteForPath(serverCachePath)) {\n                changedChildren = changedChildren.set(mergePath, serverCache.getNode().getChild(serverCachePath));\n            }\n        });\n        return viewProcessorApplyServerMerge(viewProcessor, viewCache, ackPath, changedChildren, writesCache, completeCache, filterServerNode, accumulator);\n    }\n}\nfunction viewProcessorListenComplete(viewProcessor, viewCache, path, writesCache, accumulator) {\n    const oldServerNode = viewCache.serverCache;\n    const newViewCache = viewCacheUpdateServerSnap(viewCache, oldServerNode.getNode(), oldServerNode.isFullyInitialized() || pathIsEmpty(path), oldServerNode.isFiltered());\n    return viewProcessorGenerateEventCacheAfterServerEvent(viewProcessor, newViewCache, path, writesCache, NO_COMPLETE_CHILD_SOURCE, accumulator);\n}\nfunction viewProcessorRevertUserWrite(viewProcessor, viewCache, path, writesCache, completeServerCache, accumulator) {\n    let complete;\n    if (writeTreeRefShadowingWrite(writesCache, path) != null) {\n        return viewCache;\n    }\n    else {\n        const source = new WriteTreeCompleteChildSource(writesCache, viewCache, completeServerCache);\n        const oldEventCache = viewCache.eventCache.getNode();\n        let newEventCache;\n        if (pathIsEmpty(path) || pathGetFront(path) === '.priority') {\n            let newNode;\n            if (viewCache.serverCache.isFullyInitialized()) {\n                newNode = writeTreeRefCalcCompleteEventCache(writesCache, viewCacheGetCompleteServerSnap(viewCache));\n            }\n            else {\n                const serverChildren = viewCache.serverCache.getNode();\n                assert(serverChildren instanceof ChildrenNode, 'serverChildren would be complete if leaf node');\n                newNode = writeTreeRefCalcCompleteEventChildren(writesCache, serverChildren);\n            }\n            newNode = newNode;\n            newEventCache = viewProcessor.filter.updateFullNode(oldEventCache, newNode, accumulator);\n        }\n        else {\n            const childKey = pathGetFront(path);\n            let newChild = writeTreeRefCalcCompleteChild(writesCache, childKey, viewCache.serverCache);\n            if (newChild == null &&\n                viewCache.serverCache.isCompleteForChild(childKey)) {\n                newChild = oldEventCache.getImmediateChild(childKey);\n            }\n            if (newChild != null) {\n                newEventCache = viewProcessor.filter.updateChild(oldEventCache, childKey, newChild, pathPopFront(path), source, accumulator);\n            }\n            else if (viewCache.eventCache.getNode().hasChild(childKey)) {\n                // No complete child available, delete the existing one, if any\n                newEventCache = viewProcessor.filter.updateChild(oldEventCache, childKey, ChildrenNode.EMPTY_NODE, pathPopFront(path), source, accumulator);\n            }\n            else {\n                newEventCache = oldEventCache;\n            }\n            if (newEventCache.isEmpty() &&\n                viewCache.serverCache.isFullyInitialized()) {\n                // We might have reverted all child writes. Maybe the old event was a leaf node\n                complete = writeTreeRefCalcCompleteEventCache(writesCache, viewCacheGetCompleteServerSnap(viewCache));\n                if (complete.isLeafNode()) {\n                    newEventCache = viewProcessor.filter.updateFullNode(newEventCache, complete, accumulator);\n                }\n            }\n        }\n        complete =\n            viewCache.serverCache.isFullyInitialized() ||\n                writeTreeRefShadowingWrite(writesCache, newEmptyPath()) != null;\n        return viewCacheUpdateEventSnap(viewCache, newEventCache, complete, viewProcessor.filter.filtersNodes());\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 view represents a specific location and query that has 1 or more event registrations.\n *\n * It does several things:\n *  - Maintains the list of event registrations for this location/query.\n *  - Maintains a cache of the data visible for this location/query.\n *  - Applies new operations (via applyOperation), updates the cache, and based on the event\n *    registrations returns the set of events to be raised.\n */\nclass View {\n    constructor(query_, initialViewCache) {\n        this.query_ = query_;\n        this.eventRegistrations_ = [];\n        const params = this.query_._queryParams;\n        const indexFilter = new IndexedFilter(params.getIndex());\n        const filter = queryParamsGetNodeFilter(params);\n        this.processor_ = newViewProcessor(filter);\n        const initialServerCache = initialViewCache.serverCache;\n        const initialEventCache = initialViewCache.eventCache;\n        // Don't filter server node with other filter than index, wait for tagged listen\n        const serverSnap = indexFilter.updateFullNode(ChildrenNode.EMPTY_NODE, initialServerCache.getNode(), null);\n        const eventSnap = filter.updateFullNode(ChildrenNode.EMPTY_NODE, initialEventCache.getNode(), null);\n        const newServerCache = new CacheNode(serverSnap, initialServerCache.isFullyInitialized(), indexFilter.filtersNodes());\n        const newEventCache = new CacheNode(eventSnap, initialEventCache.isFullyInitialized(), filter.filtersNodes());\n        this.viewCache_ = newViewCache(newEventCache, newServerCache);\n        this.eventGenerator_ = new EventGenerator(this.query_);\n    }\n    get query() {\n        return this.query_;\n    }\n}\nfunction viewGetServerCache(view) {\n    return view.viewCache_.serverCache.getNode();\n}\nfunction viewGetCompleteNode(view) {\n    return viewCacheGetCompleteEventSnap(view.viewCache_);\n}\nfunction viewGetCompleteServerCache(view, path) {\n    const cache = viewCacheGetCompleteServerSnap(view.viewCache_);\n    if (cache) {\n        // If this isn't a \"loadsAllData\" view, then cache isn't actually a complete cache and\n        // we need to see if it contains the child we're interested in.\n        if (view.query._queryParams.loadsAllData() ||\n            (!pathIsEmpty(path) &&\n                !cache.getImmediateChild(pathGetFront(path)).isEmpty())) {\n            return cache.getChild(path);\n        }\n    }\n    return null;\n}\nfunction viewIsEmpty(view) {\n    return view.eventRegistrations_.length === 0;\n}\nfunction viewAddEventRegistration(view, eventRegistration) {\n    view.eventRegistrations_.push(eventRegistration);\n}\n/**\n * @param eventRegistration - If null, remove all callbacks.\n * @param cancelError - If a cancelError is provided, appropriate cancel events will be returned.\n * @returns Cancel events, if cancelError was provided.\n */\nfunction viewRemoveEventRegistration(view, eventRegistration, cancelError) {\n    const cancelEvents = [];\n    if (cancelError) {\n        assert(eventRegistration == null, 'A cancel should cancel all event registrations.');\n        const path = view.query._path;\n        view.eventRegistrations_.forEach(registration => {\n            const maybeEvent = registration.createCancelEvent(cancelError, path);\n            if (maybeEvent) {\n                cancelEvents.push(maybeEvent);\n            }\n        });\n    }\n    if (eventRegistration) {\n        let remaining = [];\n        for (let i = 0; i < view.eventRegistrations_.length; ++i) {\n            const existing = view.eventRegistrations_[i];\n            if (!existing.matches(eventRegistration)) {\n                remaining.push(existing);\n            }\n            else if (eventRegistration.hasAnyCallback()) {\n                // We're removing just this one\n                remaining = remaining.concat(view.eventRegistrations_.slice(i + 1));\n                break;\n            }\n        }\n        view.eventRegistrations_ = remaining;\n    }\n    else {\n        view.eventRegistrations_ = [];\n    }\n    return cancelEvents;\n}\n/**\n * Applies the given Operation, updates our cache, and returns the appropriate events.\n */\nfunction viewApplyOperation(view, operation, writesCache, completeServerCache) {\n    if (operation.type === OperationType.MERGE &&\n        operation.source.queryId !== null) {\n        assert(viewCacheGetCompleteServerSnap(view.viewCache_), 'We should always have a full cache before handling merges');\n        assert(viewCacheGetCompleteEventSnap(view.viewCache_), 'Missing event cache, even though we have a server cache');\n    }\n    const oldViewCache = view.viewCache_;\n    const result = viewProcessorApplyOperation(view.processor_, oldViewCache, operation, writesCache, completeServerCache);\n    viewProcessorAssertIndexed(view.processor_, result.viewCache);\n    assert(result.viewCache.serverCache.isFullyInitialized() ||\n        !oldViewCache.serverCache.isFullyInitialized(), 'Once a server snap is complete, it should never go back');\n    view.viewCache_ = result.viewCache;\n    return viewGenerateEventsForChanges_(view, result.changes, result.viewCache.eventCache.getNode(), null);\n}\nfunction viewGetInitialEvents(view, registration) {\n    const eventSnap = view.viewCache_.eventCache;\n    const initialChanges = [];\n    if (!eventSnap.getNode().isLeafNode()) {\n        const eventNode = eventSnap.getNode();\n        eventNode.forEachChild(PRIORITY_INDEX, (key, childNode) => {\n            initialChanges.push(changeChildAdded(key, childNode));\n        });\n    }\n    if (eventSnap.isFullyInitialized()) {\n        initialChanges.push(changeValue(eventSnap.getNode()));\n    }\n    return viewGenerateEventsForChanges_(view, initialChanges, eventSnap.getNode(), registration);\n}\nfunction viewGenerateEventsForChanges_(view, changes, eventCache, eventRegistration) {\n    const registrations = eventRegistration\n        ? [eventRegistration]\n        : view.eventRegistrations_;\n    return eventGeneratorGenerateEventsForChanges(view.eventGenerator_, changes, eventCache, registrations);\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 */\nlet referenceConstructor$1;\n/**\n * SyncPoint represents a single location in a SyncTree with 1 or more event registrations, meaning we need to\n * maintain 1 or more Views at this location to cache server data and raise appropriate events for server changes\n * and user writes (set, transaction, update).\n *\n * It's responsible for:\n *  - Maintaining the set of 1 or more views necessary at this location (a SyncPoint with 0 views should be removed).\n *  - Proxying user / server operations to the views as appropriate (i.e. applyServerOverwrite,\n *    applyUserOverwrite, etc.)\n */\nclass SyncPoint {\n    constructor() {\n        /**\n         * The Views being tracked at this location in the tree, stored as a map where the key is a\n         * queryId and the value is the View for that query.\n         *\n         * NOTE: This list will be quite small (usually 1, but perhaps 2 or 3; any more is an odd use case).\n         */\n        this.views = new Map();\n    }\n}\nfunction syncPointSetReferenceConstructor(val) {\n    assert(!referenceConstructor$1, '__referenceConstructor has already been defined');\n    referenceConstructor$1 = val;\n}\nfunction syncPointGetReferenceConstructor() {\n    assert(referenceConstructor$1, 'Reference.ts has not been loaded');\n    return referenceConstructor$1;\n}\nfunction syncPointIsEmpty(syncPoint) {\n    return syncPoint.views.size === 0;\n}\nfunction syncPointApplyOperation(syncPoint, operation, writesCache, optCompleteServerCache) {\n    const queryId = operation.source.queryId;\n    if (queryId !== null) {\n        const view = syncPoint.views.get(queryId);\n        assert(view != null, 'SyncTree gave us an op for an invalid query.');\n        return viewApplyOperation(view, operation, writesCache, optCompleteServerCache);\n    }\n    else {\n        let events = [];\n        for (const view of syncPoint.views.values()) {\n            events = events.concat(viewApplyOperation(view, operation, writesCache, optCompleteServerCache));\n        }\n        return events;\n    }\n}\n/**\n * Get a view for the specified query.\n *\n * @param query - The query to return a view for\n * @param writesCache\n * @param serverCache\n * @param serverCacheComplete\n * @returns Events to raise.\n */\nfunction syncPointGetView(syncPoint, query, writesCache, serverCache, serverCacheComplete) {\n    const queryId = query._queryIdentifier;\n    const view = syncPoint.views.get(queryId);\n    if (!view) {\n        // TODO: make writesCache take flag for complete server node\n        let eventCache = writeTreeRefCalcCompleteEventCache(writesCache, serverCacheComplete ? serverCache : null);\n        let eventCacheComplete = false;\n        if (eventCache) {\n            eventCacheComplete = true;\n        }\n        else if (serverCache instanceof ChildrenNode) {\n            eventCache = writeTreeRefCalcCompleteEventChildren(writesCache, serverCache);\n            eventCacheComplete = false;\n        }\n        else {\n            eventCache = ChildrenNode.EMPTY_NODE;\n            eventCacheComplete = false;\n        }\n        const viewCache = newViewCache(new CacheNode(eventCache, eventCacheComplete, false), new CacheNode(serverCache, serverCacheComplete, false));\n        return new View(query, viewCache);\n    }\n    return view;\n}\n/**\n * Add an event callback for the specified query.\n *\n * @param query\n * @param eventRegistration\n * @param writesCache\n * @param serverCache - Complete server cache, if we have it.\n * @param serverCacheComplete\n * @returns Events to raise.\n */\nfunction syncPointAddEventRegistration(syncPoint, query, eventRegistration, writesCache, serverCache, serverCacheComplete) {\n    const view = syncPointGetView(syncPoint, query, writesCache, serverCache, serverCacheComplete);\n    if (!syncPoint.views.has(query._queryIdentifier)) {\n        syncPoint.views.set(query._queryIdentifier, view);\n    }\n    // This is guaranteed to exist now, we just created anything that was missing\n    viewAddEventRegistration(view, eventRegistration);\n    return viewGetInitialEvents(view, eventRegistration);\n}\n/**\n * Remove event callback(s).  Return cancelEvents if a cancelError is specified.\n *\n * If query is the default query, we'll check all views for the specified eventRegistration.\n * If eventRegistration is null, we'll remove all callbacks for the specified view(s).\n *\n * @param eventRegistration - If null, remove all callbacks.\n * @param cancelError - If a cancelError is provided, appropriate cancel events will be returned.\n * @returns removed queries and any cancel events\n */\nfunction syncPointRemoveEventRegistration(syncPoint, query, eventRegistration, cancelError) {\n    const queryId = query._queryIdentifier;\n    const removed = [];\n    let cancelEvents = [];\n    const hadCompleteView = syncPointHasCompleteView(syncPoint);\n    if (queryId === 'default') {\n        // When you do ref.off(...), we search all views for the registration to remove.\n        for (const [viewQueryId, view] of syncPoint.views.entries()) {\n            cancelEvents = cancelEvents.concat(viewRemoveEventRegistration(view, eventRegistration, cancelError));\n            if (viewIsEmpty(view)) {\n                syncPoint.views.delete(viewQueryId);\n                // We'll deal with complete views later.\n                if (!view.query._queryParams.loadsAllData()) {\n                    removed.push(view.query);\n                }\n            }\n        }\n    }\n    else {\n        // remove the callback from the specific view.\n        const view = syncPoint.views.get(queryId);\n        if (view) {\n            cancelEvents = cancelEvents.concat(viewRemoveEventRegistration(view, eventRegistration, cancelError));\n            if (viewIsEmpty(view)) {\n                syncPoint.views.delete(queryId);\n                // We'll deal with complete views later.\n                if (!view.query._queryParams.loadsAllData()) {\n                    removed.push(view.query);\n                }\n            }\n        }\n    }\n    if (hadCompleteView && !syncPointHasCompleteView(syncPoint)) {\n        // We removed our last complete view.\n        removed.push(new (syncPointGetReferenceConstructor())(query._repo, query._path));\n    }\n    return { removed, events: cancelEvents };\n}\nfunction syncPointGetQueryViews(syncPoint) {\n    const result = [];\n    for (const view of syncPoint.views.values()) {\n        if (!view.query._queryParams.loadsAllData()) {\n            result.push(view);\n        }\n    }\n    return result;\n}\n/**\n * @param path - The path to the desired complete snapshot\n * @returns A complete cache, if it exists\n */\nfunction syncPointGetCompleteServerCache(syncPoint, path) {\n    let serverCache = null;\n    for (const view of syncPoint.views.values()) {\n        serverCache = serverCache || viewGetCompleteServerCache(view, path);\n    }\n    return serverCache;\n}\nfunction syncPointViewForQuery(syncPoint, query) {\n    const params = query._queryParams;\n    if (params.loadsAllData()) {\n        return syncPointGetCompleteView(syncPoint);\n    }\n    else {\n        const queryId = query._queryIdentifier;\n        return syncPoint.views.get(queryId);\n    }\n}\nfunction syncPointViewExistsForQuery(syncPoint, query) {\n    return syncPointViewForQuery(syncPoint, query) != null;\n}\nfunction syncPointHasCompleteView(syncPoint) {\n    return syncPointGetCompleteView(syncPoint) != null;\n}\nfunction syncPointGetCompleteView(syncPoint) {\n    for (const view of syncPoint.views.values()) {\n        if (view.query._queryParams.loadsAllData()) {\n            return view;\n        }\n    }\n    return null;\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 */\nlet referenceConstructor;\nfunction syncTreeSetReferenceConstructor(val) {\n    assert(!referenceConstructor, '__referenceConstructor has already been defined');\n    referenceConstructor = val;\n}\nfunction syncTreeGetReferenceConstructor() {\n    assert(referenceConstructor, 'Reference.ts has not been loaded');\n    return referenceConstructor;\n}\n/**\n * Static tracker for next query tag.\n */\nlet syncTreeNextQueryTag_ = 1;\n/**\n * SyncTree is the central class for managing event callback registration, data caching, views\n * (query processing), and event generation.  There are typically two SyncTree instances for\n * each Repo, one for the normal Firebase data, and one for the .info data.\n *\n * It has a number of responsibilities, including:\n *  - Tracking all user event callbacks (registered via addEventRegistration() and removeEventRegistration()).\n *  - Applying and caching data changes for user set(), transaction(), and update() calls\n *    (applyUserOverwrite(), applyUserMerge()).\n *  - Applying and caching data changes for server data changes (applyServerOverwrite(),\n *    applyServerMerge()).\n *  - Generating user-facing events for server and user changes (all of the apply* methods\n *    return the set of events that need to be raised as a result).\n *  - Maintaining the appropriate set of server listens to ensure we are always subscribed\n *    to the correct set of paths and queries to satisfy the current set of user event\n *    callbacks (listens are started/stopped using the provided listenProvider).\n *\n * NOTE: Although SyncTree tracks event callbacks and calculates events to raise, the actual\n * events are returned to the caller rather than raised synchronously.\n *\n */\nclass SyncTree {\n    /**\n     * @param listenProvider_ - Used by SyncTree to start / stop listening\n     *   to server data.\n     */\n    constructor(listenProvider_) {\n        this.listenProvider_ = listenProvider_;\n        /**\n         * Tree of SyncPoints.  There's a SyncPoint at any location that has 1 or more views.\n         */\n        this.syncPointTree_ = new ImmutableTree(null);\n        /**\n         * A tree of all pending user writes (user-initiated set()'s, transaction()'s, update()'s, etc.).\n         */\n        this.pendingWriteTree_ = newWriteTree();\n        this.tagToQueryMap = new Map();\n        this.queryToTagMap = new Map();\n    }\n}\n/**\n * Apply the data changes for a user-generated set() or transaction() call.\n *\n * @returns Events to raise.\n */\nfunction syncTreeApplyUserOverwrite(syncTree, path, newData, writeId, visible) {\n    // Record pending write.\n    writeTreeAddOverwrite(syncTree.pendingWriteTree_, path, newData, writeId, visible);\n    if (!visible) {\n        return [];\n    }\n    else {\n        return syncTreeApplyOperationToSyncPoints_(syncTree, new Overwrite(newOperationSourceUser(), path, newData));\n    }\n}\n/**\n * Apply the data from a user-generated update() call\n *\n * @returns Events to raise.\n */\nfunction syncTreeApplyUserMerge(syncTree, path, changedChildren, writeId) {\n    // Record pending merge.\n    writeTreeAddMerge(syncTree.pendingWriteTree_, path, changedChildren, writeId);\n    const changeTree = ImmutableTree.fromObject(changedChildren);\n    return syncTreeApplyOperationToSyncPoints_(syncTree, new Merge(newOperationSourceUser(), path, changeTree));\n}\n/**\n * Acknowledge a pending user write that was previously registered with applyUserOverwrite() or applyUserMerge().\n *\n * @param revert - True if the given write failed and needs to be reverted\n * @returns Events to raise.\n */\nfunction syncTreeAckUserWrite(syncTree, writeId, revert = false) {\n    const write = writeTreeGetWrite(syncTree.pendingWriteTree_, writeId);\n    const needToReevaluate = writeTreeRemoveWrite(syncTree.pendingWriteTree_, writeId);\n    if (!needToReevaluate) {\n        return [];\n    }\n    else {\n        let affectedTree = new ImmutableTree(null);\n        if (write.snap != null) {\n            // overwrite\n            affectedTree = affectedTree.set(newEmptyPath(), true);\n        }\n        else {\n            each(write.children, (pathString) => {\n                affectedTree = affectedTree.set(new Path(pathString), true);\n            });\n        }\n        return syncTreeApplyOperationToSyncPoints_(syncTree, new AckUserWrite(write.path, affectedTree, revert));\n    }\n}\n/**\n * Apply new server data for the specified path..\n *\n * @returns Events to raise.\n */\nfunction syncTreeApplyServerOverwrite(syncTree, path, newData) {\n    return syncTreeApplyOperationToSyncPoints_(syncTree, new Overwrite(newOperationSourceServer(), path, newData));\n}\n/**\n * Apply new server data to be merged in at the specified path.\n *\n * @returns Events to raise.\n */\nfunction syncTreeApplyServerMerge(syncTree, path, changedChildren) {\n    const changeTree = ImmutableTree.fromObject(changedChildren);\n    return syncTreeApplyOperationToSyncPoints_(syncTree, new Merge(newOperationSourceServer(), path, changeTree));\n}\n/**\n * Apply a listen complete for a query\n *\n * @returns Events to raise.\n */\nfunction syncTreeApplyListenComplete(syncTree, path) {\n    return syncTreeApplyOperationToSyncPoints_(syncTree, new ListenComplete(newOperationSourceServer(), path));\n}\n/**\n * Apply a listen complete for a tagged query\n *\n * @returns Events to raise.\n */\nfunction syncTreeApplyTaggedListenComplete(syncTree, path, tag) {\n    const queryKey = syncTreeQueryKeyForTag_(syncTree, tag);\n    if (queryKey) {\n        const r = syncTreeParseQueryKey_(queryKey);\n        const queryPath = r.path, queryId = r.queryId;\n        const relativePath = newRelativePath(queryPath, path);\n        const op = new ListenComplete(newOperationSourceServerTaggedQuery(queryId), relativePath);\n        return syncTreeApplyTaggedOperation_(syncTree, queryPath, op);\n    }\n    else {\n        // We've already removed the query. No big deal, ignore the update\n        return [];\n    }\n}\n/**\n * Remove event callback(s).\n *\n * If query is the default query, we'll check all queries for the specified eventRegistration.\n * If eventRegistration is null, we'll remove all callbacks for the specified query/queries.\n *\n * @param eventRegistration - If null, all callbacks are removed.\n * @param cancelError - If a cancelError is provided, appropriate cancel events will be returned.\n * @param skipListenerDedup - When performing a `get()`, we don't add any new listeners, so no\n *  deduping needs to take place. This flag allows toggling of that behavior\n * @returns Cancel events, if cancelError was provided.\n */\nfunction syncTreeRemoveEventRegistration(syncTree, query, eventRegistration, cancelError, skipListenerDedup = false) {\n    // Find the syncPoint first. Then deal with whether or not it has matching listeners\n    const path = query._path;\n    const maybeSyncPoint = syncTree.syncPointTree_.get(path);\n    let cancelEvents = [];\n    // A removal on a default query affects all queries at that location. A removal on an indexed query, even one without\n    // other query constraints, does *not* affect all queries at that location. So this check must be for 'default', and\n    // not loadsAllData().\n    if (maybeSyncPoint &&\n        (query._queryIdentifier === 'default' ||\n            syncPointViewExistsForQuery(maybeSyncPoint, query))) {\n        const removedAndEvents = syncPointRemoveEventRegistration(maybeSyncPoint, query, eventRegistration, cancelError);\n        if (syncPointIsEmpty(maybeSyncPoint)) {\n            syncTree.syncPointTree_ = syncTree.syncPointTree_.remove(path);\n        }\n        const removed = removedAndEvents.removed;\n        cancelEvents = removedAndEvents.events;\n        if (!skipListenerDedup) {\n            /**\n             * We may have just removed one of many listeners and can short-circuit this whole process\n             * We may also not have removed a default listener, in which case all of the descendant listeners should already be\n             * properly set up.\n             */\n            // Since indexed queries can shadow if they don't have other query constraints, check for loadsAllData(), instead of\n            // queryId === 'default'\n            const removingDefault = -1 !==\n                removed.findIndex(query => {\n                    return query._queryParams.loadsAllData();\n                });\n            const covered = syncTree.syncPointTree_.findOnPath(path, (relativePath, parentSyncPoint) => syncPointHasCompleteView(parentSyncPoint));\n            if (removingDefault && !covered) {\n                const subtree = syncTree.syncPointTree_.subtree(path);\n                // There are potentially child listeners. Determine what if any listens we need to send before executing the\n                // removal\n                if (!subtree.isEmpty()) {\n                    // We need to fold over our subtree and collect the listeners to send\n                    const newViews = syncTreeCollectDistinctViewsForSubTree_(subtree);\n                    // Ok, we've collected all the listens we need. Set them up.\n                    for (let i = 0; i < newViews.length; ++i) {\n                        const view = newViews[i], newQuery = view.query;\n                        const listener = syncTreeCreateListenerForView_(syncTree, view);\n                        syncTree.listenProvider_.startListening(syncTreeQueryForListening_(newQuery), syncTreeTagForQuery(syncTree, newQuery), listener.hashFn, listener.onComplete);\n                    }\n                }\n                // Otherwise there's nothing below us, so nothing we need to start listening on\n            }\n            // If we removed anything and we're not covered by a higher up listen, we need to stop listening on this query\n            // The above block has us covered in terms of making sure we're set up on listens lower in the tree.\n            // Also, note that if we have a cancelError, it's already been removed at the provider level.\n            if (!covered && removed.length > 0 && !cancelError) {\n                // If we removed a default, then we weren't listening on any of the other queries here. Just cancel the one\n                // default. Otherwise, we need to iterate through and cancel each individual query\n                if (removingDefault) {\n                    // We don't tag default listeners\n                    const defaultTag = null;\n                    syncTree.listenProvider_.stopListening(syncTreeQueryForListening_(query), defaultTag);\n                }\n                else {\n                    removed.forEach((queryToRemove) => {\n                        const tagToRemove = syncTree.queryToTagMap.get(syncTreeMakeQueryKey_(queryToRemove));\n                        syncTree.listenProvider_.stopListening(syncTreeQueryForListening_(queryToRemove), tagToRemove);\n                    });\n                }\n            }\n        }\n        // Now, clear all of the tags we're tracking for the removed listens\n        syncTreeRemoveTags_(syncTree, removed);\n    }\n    return cancelEvents;\n}\n/**\n * Apply new server data for the specified tagged query.\n *\n * @returns Events to raise.\n */\nfunction syncTreeApplyTaggedQueryOverwrite(syncTree, path, snap, tag) {\n    const queryKey = syncTreeQueryKeyForTag_(syncTree, tag);\n    if (queryKey != null) {\n        const r = syncTreeParseQueryKey_(queryKey);\n        const queryPath = r.path, queryId = r.queryId;\n        const relativePath = newRelativePath(queryPath, path);\n        const op = new Overwrite(newOperationSourceServerTaggedQuery(queryId), relativePath, snap);\n        return syncTreeApplyTaggedOperation_(syncTree, queryPath, op);\n    }\n    else {\n        // Query must have been removed already\n        return [];\n    }\n}\n/**\n * Apply server data to be merged in for the specified tagged query.\n *\n * @returns Events to raise.\n */\nfunction syncTreeApplyTaggedQueryMerge(syncTree, path, changedChildren, tag) {\n    const queryKey = syncTreeQueryKeyForTag_(syncTree, tag);\n    if (queryKey) {\n        const r = syncTreeParseQueryKey_(queryKey);\n        const queryPath = r.path, queryId = r.queryId;\n        const relativePath = newRelativePath(queryPath, path);\n        const changeTree = ImmutableTree.fromObject(changedChildren);\n        const op = new Merge(newOperationSourceServerTaggedQuery(queryId), relativePath, changeTree);\n        return syncTreeApplyTaggedOperation_(syncTree, queryPath, op);\n    }\n    else {\n        // We've already removed the query. No big deal, ignore the update\n        return [];\n    }\n}\n/**\n * Add an event callback for the specified query.\n *\n * @returns Events to raise.\n */\nfunction syncTreeAddEventRegistration(syncTree, query, eventRegistration, skipSetupListener = false) {\n    const path = query._path;\n    let serverCache = null;\n    let foundAncestorDefaultView = false;\n    // Any covering writes will necessarily be at the root, so really all we need to find is the server cache.\n    // Consider optimizing this once there's a better understanding of what actual behavior will be.\n    syncTree.syncPointTree_.foreachOnPath(path, (pathToSyncPoint, sp) => {\n        const relativePath = newRelativePath(pathToSyncPoint, path);\n        serverCache =\n            serverCache || syncPointGetCompleteServerCache(sp, relativePath);\n        foundAncestorDefaultView =\n            foundAncestorDefaultView || syncPointHasCompleteView(sp);\n    });\n    let syncPoint = syncTree.syncPointTree_.get(path);\n    if (!syncPoint) {\n        syncPoint = new SyncPoint();\n        syncTree.syncPointTree_ = syncTree.syncPointTree_.set(path, syncPoint);\n    }\n    else {\n        foundAncestorDefaultView =\n            foundAncestorDefaultView || syncPointHasCompleteView(syncPoint);\n        serverCache =\n            serverCache || syncPointGetCompleteServerCache(syncPoint, newEmptyPath());\n    }\n    let serverCacheComplete;\n    if (serverCache != null) {\n        serverCacheComplete = true;\n    }\n    else {\n        serverCacheComplete = false;\n        serverCache = ChildrenNode.EMPTY_NODE;\n        const subtree = syncTree.syncPointTree_.subtree(path);\n        subtree.foreachChild((childName, childSyncPoint) => {\n            const completeCache = syncPointGetCompleteServerCache(childSyncPoint, newEmptyPath());\n            if (completeCache) {\n                serverCache = serverCache.updateImmediateChild(childName, completeCache);\n            }\n        });\n    }\n    const viewAlreadyExists = syncPointViewExistsForQuery(syncPoint, query);\n    if (!viewAlreadyExists && !query._queryParams.loadsAllData()) {\n        // We need to track a tag for this query\n        const queryKey = syncTreeMakeQueryKey_(query);\n        assert(!syncTree.queryToTagMap.has(queryKey), 'View does not exist, but we have a tag');\n        const tag = syncTreeGetNextQueryTag_();\n        syncTree.queryToTagMap.set(queryKey, tag);\n        syncTree.tagToQueryMap.set(tag, queryKey);\n    }\n    const writesCache = writeTreeChildWrites(syncTree.pendingWriteTree_, path);\n    let events = syncPointAddEventRegistration(syncPoint, query, eventRegistration, writesCache, serverCache, serverCacheComplete);\n    if (!viewAlreadyExists && !foundAncestorDefaultView && !skipSetupListener) {\n        const view = syncPointViewForQuery(syncPoint, query);\n        events = events.concat(syncTreeSetupListener_(syncTree, query, view));\n    }\n    return events;\n}\n/**\n * Returns a complete cache, if we have one, of the data at a particular path. If the location does not have a\n * listener above it, we will get a false \"null\". This shouldn't be a problem because transactions will always\n * have a listener above, and atomic operations would correctly show a jitter of <increment value> ->\n *     <incremented total> as the write is applied locally and then acknowledged at the server.\n *\n * Note: this method will *include* hidden writes from transaction with applyLocally set to false.\n *\n * @param path - The path to the data we want\n * @param writeIdsToExclude - A specific set to be excluded\n */\nfunction syncTreeCalcCompleteEventCache(syncTree, path, writeIdsToExclude) {\n    const includeHiddenSets = true;\n    const writeTree = syncTree.pendingWriteTree_;\n    const serverCache = syncTree.syncPointTree_.findOnPath(path, (pathSoFar, syncPoint) => {\n        const relativePath = newRelativePath(pathSoFar, path);\n        const serverCache = syncPointGetCompleteServerCache(syncPoint, relativePath);\n        if (serverCache) {\n            return serverCache;\n        }\n    });\n    return writeTreeCalcCompleteEventCache(writeTree, path, serverCache, writeIdsToExclude, includeHiddenSets);\n}\nfunction syncTreeGetServerValue(syncTree, query) {\n    const path = query._path;\n    let serverCache = null;\n    // Any covering writes will necessarily be at the root, so really all we need to find is the server cache.\n    // Consider optimizing this once there's a better understanding of what actual behavior will be.\n    syncTree.syncPointTree_.foreachOnPath(path, (pathToSyncPoint, sp) => {\n        const relativePath = newRelativePath(pathToSyncPoint, path);\n        serverCache =\n            serverCache || syncPointGetCompleteServerCache(sp, relativePath);\n    });\n    let syncPoint = syncTree.syncPointTree_.get(path);\n    if (!syncPoint) {\n        syncPoint = new SyncPoint();\n        syncTree.syncPointTree_ = syncTree.syncPointTree_.set(path, syncPoint);\n    }\n    else {\n        serverCache =\n            serverCache || syncPointGetCompleteServerCache(syncPoint, newEmptyPath());\n    }\n    const serverCacheComplete = serverCache != null;\n    const serverCacheNode = serverCacheComplete\n        ? new CacheNode(serverCache, true, false)\n        : null;\n    const writesCache = writeTreeChildWrites(syncTree.pendingWriteTree_, query._path);\n    const view = syncPointGetView(syncPoint, query, writesCache, serverCacheComplete ? serverCacheNode.getNode() : ChildrenNode.EMPTY_NODE, serverCacheComplete);\n    return viewGetCompleteNode(view);\n}\n/**\n * A helper method that visits all descendant and ancestor SyncPoints, applying the operation.\n *\n * NOTES:\n * - Descendant SyncPoints will be visited first (since we raise events depth-first).\n *\n * - We call applyOperation() on each SyncPoint passing three things:\n *   1. A version of the Operation that has been made relative to the SyncPoint location.\n *   2. A WriteTreeRef of any writes we have cached at the SyncPoint location.\n *   3. A snapshot Node with cached server data, if we have it.\n *\n * - We concatenate all of the events returned by each SyncPoint and return the result.\n */\nfunction syncTreeApplyOperationToSyncPoints_(syncTree, operation) {\n    return syncTreeApplyOperationHelper_(operation, syncTree.syncPointTree_, \n    /*serverCache=*/ null, writeTreeChildWrites(syncTree.pendingWriteTree_, newEmptyPath()));\n}\n/**\n * Recursive helper for applyOperationToSyncPoints_\n */\nfunction syncTreeApplyOperationHelper_(operation, syncPointTree, serverCache, writesCache) {\n    if (pathIsEmpty(operation.path)) {\n        return syncTreeApplyOperationDescendantsHelper_(operation, syncPointTree, serverCache, writesCache);\n    }\n    else {\n        const syncPoint = syncPointTree.get(newEmptyPath());\n        // If we don't have cached server data, see if we can get it from this SyncPoint.\n        if (serverCache == null && syncPoint != null) {\n            serverCache = syncPointGetCompleteServerCache(syncPoint, newEmptyPath());\n        }\n        let events = [];\n        const childName = pathGetFront(operation.path);\n        const childOperation = operation.operationForChild(childName);\n        const childTree = syncPointTree.children.get(childName);\n        if (childTree && childOperation) {\n            const childServerCache = serverCache\n                ? serverCache.getImmediateChild(childName)\n                : null;\n            const childWritesCache = writeTreeRefChild(writesCache, childName);\n            events = events.concat(syncTreeApplyOperationHelper_(childOperation, childTree, childServerCache, childWritesCache));\n        }\n        if (syncPoint) {\n            events = events.concat(syncPointApplyOperation(syncPoint, operation, writesCache, serverCache));\n        }\n        return events;\n    }\n}\n/**\n * Recursive helper for applyOperationToSyncPoints_\n */\nfunction syncTreeApplyOperationDescendantsHelper_(operation, syncPointTree, serverCache, writesCache) {\n    const syncPoint = syncPointTree.get(newEmptyPath());\n    // If we don't have cached server data, see if we can get it from this SyncPoint.\n    if (serverCache == null && syncPoint != null) {\n        serverCache = syncPointGetCompleteServerCache(syncPoint, newEmptyPath());\n    }\n    let events = [];\n    syncPointTree.children.inorderTraversal((childName, childTree) => {\n        const childServerCache = serverCache\n            ? serverCache.getImmediateChild(childName)\n            : null;\n        const childWritesCache = writeTreeRefChild(writesCache, childName);\n        const childOperation = operation.operationForChild(childName);\n        if (childOperation) {\n            events = events.concat(syncTreeApplyOperationDescendantsHelper_(childOperation, childTree, childServerCache, childWritesCache));\n        }\n    });\n    if (syncPoint) {\n        events = events.concat(syncPointApplyOperation(syncPoint, operation, writesCache, serverCache));\n    }\n    return events;\n}\nfunction syncTreeCreateListenerForView_(syncTree, view) {\n    const query = view.query;\n    const tag = syncTreeTagForQuery(syncTree, query);\n    return {\n        hashFn: () => {\n            const cache = viewGetServerCache(view) || ChildrenNode.EMPTY_NODE;\n            return cache.hash();\n        },\n        onComplete: (status) => {\n            if (status === 'ok') {\n                if (tag) {\n                    return syncTreeApplyTaggedListenComplete(syncTree, query._path, tag);\n                }\n                else {\n                    return syncTreeApplyListenComplete(syncTree, query._path);\n                }\n            }\n            else {\n                // If a listen failed, kill all of the listeners here, not just the one that triggered the error.\n                // Note that this may need to be scoped to just this listener if we change permissions on filtered children\n                const error = errorForServerCode(status, query);\n                return syncTreeRemoveEventRegistration(syncTree, query, \n                /*eventRegistration*/ null, error);\n            }\n        }\n    };\n}\n/**\n * Return the tag associated with the given query.\n */\nfunction syncTreeTagForQuery(syncTree, query) {\n    const queryKey = syncTreeMakeQueryKey_(query);\n    return syncTree.queryToTagMap.get(queryKey);\n}\n/**\n * Given a query, computes a \"queryKey\" suitable for use in our queryToTagMap_.\n */\nfunction syncTreeMakeQueryKey_(query) {\n    return query._path.toString() + '$' + query._queryIdentifier;\n}\n/**\n * Return the query associated with the given tag, if we have one\n */\nfunction syncTreeQueryKeyForTag_(syncTree, tag) {\n    return syncTree.tagToQueryMap.get(tag);\n}\n/**\n * Given a queryKey (created by makeQueryKey), parse it back into a path and queryId.\n */\nfunction syncTreeParseQueryKey_(queryKey) {\n    const splitIndex = queryKey.indexOf('$');\n    assert(splitIndex !== -1 && splitIndex < queryKey.length - 1, 'Bad queryKey.');\n    return {\n        queryId: queryKey.substr(splitIndex + 1),\n        path: new Path(queryKey.substr(0, splitIndex))\n    };\n}\n/**\n * A helper method to apply tagged operations\n */\nfunction syncTreeApplyTaggedOperation_(syncTree, queryPath, operation) {\n    const syncPoint = syncTree.syncPointTree_.get(queryPath);\n    assert(syncPoint, \"Missing sync point for query tag that we're tracking\");\n    const writesCache = writeTreeChildWrites(syncTree.pendingWriteTree_, queryPath);\n    return syncPointApplyOperation(syncPoint, operation, writesCache, null);\n}\n/**\n * This collapses multiple unfiltered views into a single view, since we only need a single\n * listener for them.\n */\nfunction syncTreeCollectDistinctViewsForSubTree_(subtree) {\n    return subtree.fold((relativePath, maybeChildSyncPoint, childMap) => {\n        if (maybeChildSyncPoint && syncPointHasCompleteView(maybeChildSyncPoint)) {\n            const completeView = syncPointGetCompleteView(maybeChildSyncPoint);\n            return [completeView];\n        }\n        else {\n            // No complete view here, flatten any deeper listens into an array\n            let views = [];\n            if (maybeChildSyncPoint) {\n                views = syncPointGetQueryViews(maybeChildSyncPoint);\n            }\n            each(childMap, (_key, childViews) => {\n                views = views.concat(childViews);\n            });\n            return views;\n        }\n    });\n}\n/**\n * Normalizes a query to a query we send the server for listening\n *\n * @returns The normalized query\n */\nfunction syncTreeQueryForListening_(query) {\n    if (query._queryParams.loadsAllData() && !query._queryParams.isDefault()) {\n        // We treat queries that load all data as default queries\n        // Cast is necessary because ref() technically returns Firebase which is actually fb.api.Firebase which inherits\n        // from Query\n        return new (syncTreeGetReferenceConstructor())(query._repo, query._path);\n    }\n    else {\n        return query;\n    }\n}\nfunction syncTreeRemoveTags_(syncTree, queries) {\n    for (let j = 0; j < queries.length; ++j) {\n        const removedQuery = queries[j];\n        if (!removedQuery._queryParams.loadsAllData()) {\n            // We should have a tag for this\n            const removedQueryKey = syncTreeMakeQueryKey_(removedQuery);\n            const removedQueryTag = syncTree.queryToTagMap.get(removedQueryKey);\n            syncTree.queryToTagMap.delete(removedQueryKey);\n            syncTree.tagToQueryMap.delete(removedQueryTag);\n        }\n    }\n}\n/**\n * Static accessor for query tags.\n */\nfunction syncTreeGetNextQueryTag_() {\n    return syncTreeNextQueryTag_++;\n}\n/**\n * For a given new listen, manage the de-duplication of outstanding subscriptions.\n *\n * @returns This method can return events to support synchronous data sources\n */\nfunction syncTreeSetupListener_(syncTree, query, view) {\n    const path = query._path;\n    const tag = syncTreeTagForQuery(syncTree, query);\n    const listener = syncTreeCreateListenerForView_(syncTree, view);\n    const events = syncTree.listenProvider_.startListening(syncTreeQueryForListening_(query), tag, listener.hashFn, listener.onComplete);\n    const subtree = syncTree.syncPointTree_.subtree(path);\n    // The root of this subtree has our query. We're here because we definitely need to send a listen for that, but we\n    // may need to shadow other listens as well.\n    if (tag) {\n        assert(!syncPointHasCompleteView(subtree.value), \"If we're adding a query, it shouldn't be shadowed\");\n    }\n    else {\n        // Shadow everything at or below this location, this is a default listener.\n        const queriesToStop = subtree.fold((relativePath, maybeChildSyncPoint, childMap) => {\n            if (!pathIsEmpty(relativePath) &&\n                maybeChildSyncPoint &&\n                syncPointHasCompleteView(maybeChildSyncPoint)) {\n                return [syncPointGetCompleteView(maybeChildSyncPoint).query];\n            }\n            else {\n                // No default listener here, flatten any deeper queries into an array\n                let queries = [];\n                if (maybeChildSyncPoint) {\n                    queries = queries.concat(syncPointGetQueryViews(maybeChildSyncPoint).map(view => view.query));\n                }\n                each(childMap, (_key, childQueries) => {\n                    queries = queries.concat(childQueries);\n                });\n                return queries;\n            }\n        });\n        for (let i = 0; i < queriesToStop.length; ++i) {\n            const queryToStop = queriesToStop[i];\n            syncTree.listenProvider_.stopListening(syncTreeQueryForListening_(queryToStop), syncTreeTagForQuery(syncTree, queryToStop));\n        }\n    }\n    return events;\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 */\nclass ExistingValueProvider {\n    constructor(node_) {\n        this.node_ = node_;\n    }\n    getImmediateChild(childName) {\n        const child = this.node_.getImmediateChild(childName);\n        return new ExistingValueProvider(child);\n    }\n    node() {\n        return this.node_;\n    }\n}\nclass DeferredValueProvider {\n    constructor(syncTree, path) {\n        this.syncTree_ = syncTree;\n        this.path_ = path;\n    }\n    getImmediateChild(childName) {\n        const childPath = pathChild(this.path_, childName);\n        return new DeferredValueProvider(this.syncTree_, childPath);\n    }\n    node() {\n        return syncTreeCalcCompleteEventCache(this.syncTree_, this.path_);\n    }\n}\n/**\n * Generate placeholders for deferred values.\n */\nconst generateWithValues = function (values) {\n    values = values || {};\n    values['timestamp'] = values['timestamp'] || new Date().getTime();\n    return values;\n};\n/**\n * Value to use when firing local events. When writing server values, fire\n * local events with an approximate value, otherwise return value as-is.\n */\nconst resolveDeferredLeafValue = function (value, existingVal, serverValues) {\n    if (!value || typeof value !== 'object') {\n        return value;\n    }\n    assert('.sv' in value, 'Unexpected leaf node or priority contents');\n    if (typeof value['.sv'] === 'string') {\n        return resolveScalarDeferredValue(value['.sv'], existingVal, serverValues);\n    }\n    else if (typeof value['.sv'] === 'object') {\n        return resolveComplexDeferredValue(value['.sv'], existingVal);\n    }\n    else {\n        assert(false, 'Unexpected server value: ' + JSON.stringify(value, null, 2));\n    }\n};\nconst resolveScalarDeferredValue = function (op, existing, serverValues) {\n    switch (op) {\n        case 'timestamp':\n            return serverValues['timestamp'];\n        default:\n            assert(false, 'Unexpected server value: ' + op);\n    }\n};\nconst resolveComplexDeferredValue = function (op, existing, unused) {\n    if (!op.hasOwnProperty('increment')) {\n        assert(false, 'Unexpected server value: ' + JSON.stringify(op, null, 2));\n    }\n    const delta = op['increment'];\n    if (typeof delta !== 'number') {\n        assert(false, 'Unexpected increment value: ' + delta);\n    }\n    const existingNode = existing.node();\n    assert(existingNode !== null && typeof existingNode !== 'undefined', 'Expected ChildrenNode.EMPTY_NODE for nulls');\n    // Incrementing a non-number sets the value to the incremented amount\n    if (!existingNode.isLeafNode()) {\n        return delta;\n    }\n    const leaf = existingNode;\n    const existingVal = leaf.getValue();\n    if (typeof existingVal !== 'number') {\n        return delta;\n    }\n    // No need to do over/underflow arithmetic here because JS only handles floats under the covers\n    return existingVal + delta;\n};\n/**\n * Recursively replace all deferred values and priorities in the tree with the\n * specified generated replacement values.\n * @param path - path to which write is relative\n * @param node - new data written at path\n * @param syncTree - current data\n */\nconst resolveDeferredValueTree = function (path, node, syncTree, serverValues) {\n    return resolveDeferredValue(node, new DeferredValueProvider(syncTree, path), serverValues);\n};\n/**\n * Recursively replace all deferred values and priorities in the node with the\n * specified generated replacement values.  If there are no server values in the node,\n * it'll be returned as-is.\n */\nconst resolveDeferredValueSnapshot = function (node, existing, serverValues) {\n    return resolveDeferredValue(node, new ExistingValueProvider(existing), serverValues);\n};\nfunction resolveDeferredValue(node, existingVal, serverValues) {\n    const rawPri = node.getPriority().val();\n    const priority = resolveDeferredLeafValue(rawPri, existingVal.getImmediateChild('.priority'), serverValues);\n    let newNode;\n    if (node.isLeafNode()) {\n        const leafNode = node;\n        const value = resolveDeferredLeafValue(leafNode.getValue(), existingVal, serverValues);\n        if (value !== leafNode.getValue() ||\n            priority !== leafNode.getPriority().val()) {\n            return new LeafNode(value, nodeFromJSON(priority));\n        }\n        else {\n            return node;\n        }\n    }\n    else {\n        const childrenNode = node;\n        newNode = childrenNode;\n        if (priority !== childrenNode.getPriority().val()) {\n            newNode = newNode.updatePriority(new LeafNode(priority));\n        }\n        childrenNode.forEachChild(PRIORITY_INDEX, (childName, childNode) => {\n            const newChildNode = resolveDeferredValue(childNode, existingVal.getImmediateChild(childName), serverValues);\n            if (newChildNode !== childNode) {\n                newNode = newNode.updateImmediateChild(childName, newChildNode);\n            }\n        });\n        return newNode;\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 light-weight tree, traversable by path.  Nodes can have both values and children.\n * Nodes are not enumerated (by forEachChild) unless they have a value or non-empty\n * children.\n */\nclass Tree {\n    /**\n     * @param name - Optional name of the node.\n     * @param parent - Optional parent node.\n     * @param node - Optional node to wrap.\n     */\n    constructor(name = '', parent = null, node = { children: {}, childCount: 0 }) {\n        this.name = name;\n        this.parent = parent;\n        this.node = node;\n    }\n}\n/**\n * Returns a sub-Tree for the given path.\n *\n * @param pathObj - Path to look up.\n * @returns Tree for path.\n */\nfunction treeSubTree(tree, pathObj) {\n    // TODO: Require pathObj to be Path?\n    let path = pathObj instanceof Path ? pathObj : new Path(pathObj);\n    let child = tree, next = pathGetFront(path);\n    while (next !== null) {\n        const childNode = safeGet(child.node.children, next) || {\n            children: {},\n            childCount: 0\n        };\n        child = new Tree(next, child, childNode);\n        path = pathPopFront(path);\n        next = pathGetFront(path);\n    }\n    return child;\n}\n/**\n * Returns the data associated with this tree node.\n *\n * @returns The data or null if no data exists.\n */\nfunction treeGetValue(tree) {\n    return tree.node.value;\n}\n/**\n * Sets data to this tree node.\n *\n * @param value - Value to set.\n */\nfunction treeSetValue(tree, value) {\n    tree.node.value = value;\n    treeUpdateParents(tree);\n}\n/**\n * @returns Whether the tree has any children.\n */\nfunction treeHasChildren(tree) {\n    return tree.node.childCount > 0;\n}\n/**\n * @returns Whether the tree is empty (no value or children).\n */\nfunction treeIsEmpty(tree) {\n    return treeGetValue(tree) === undefined && !treeHasChildren(tree);\n}\n/**\n * Calls action for each child of this tree node.\n *\n * @param action - Action to be called for each child.\n */\nfunction treeForEachChild(tree, action) {\n    each(tree.node.children, (child, childTree) => {\n        action(new Tree(child, tree, childTree));\n    });\n}\n/**\n * Does a depth-first traversal of this node's descendants, calling action for each one.\n *\n * @param action - Action to be called for each child.\n * @param includeSelf - Whether to call action on this node as well. Defaults to\n *   false.\n * @param childrenFirst - Whether to call action on children before calling it on\n *   parent.\n */\nfunction treeForEachDescendant(tree, action, includeSelf, childrenFirst) {\n    if (includeSelf && !childrenFirst) {\n        action(tree);\n    }\n    treeForEachChild(tree, child => {\n        treeForEachDescendant(child, action, true, childrenFirst);\n    });\n    if (includeSelf && childrenFirst) {\n        action(tree);\n    }\n}\n/**\n * Calls action on each ancestor node.\n *\n * @param action - Action to be called on each parent; return\n *   true to abort.\n * @param includeSelf - Whether to call action on this node as well.\n * @returns true if the action callback returned true.\n */\nfunction treeForEachAncestor(tree, action, includeSelf) {\n    let node = includeSelf ? tree : tree.parent;\n    while (node !== null) {\n        if (action(node)) {\n            return true;\n        }\n        node = node.parent;\n    }\n    return false;\n}\n/**\n * @returns The path of this tree node, as a Path.\n */\nfunction treeGetPath(tree) {\n    return new Path(tree.parent === null\n        ? tree.name\n        : treeGetPath(tree.parent) + '/' + tree.name);\n}\n/**\n * Adds or removes this child from its parent based on whether it's empty or not.\n */\nfunction treeUpdateParents(tree) {\n    if (tree.parent !== null) {\n        treeUpdateChild(tree.parent, tree.name, tree);\n    }\n}\n/**\n * Adds or removes the passed child to this tree node, depending on whether it's empty.\n *\n * @param childName - The name of the child to update.\n * @param child - The child to update.\n */\nfunction treeUpdateChild(tree, childName, child) {\n    const childEmpty = treeIsEmpty(child);\n    const childExists = contains(tree.node.children, childName);\n    if (childEmpty && childExists) {\n        delete tree.node.children[childName];\n        tree.node.childCount--;\n        treeUpdateParents(tree);\n    }\n    else if (!childEmpty && !childExists) {\n        tree.node.children[childName] = child.node;\n        tree.node.childCount++;\n        treeUpdateParents(tree);\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 * True for invalid Firebase keys\n */\nconst INVALID_KEY_REGEX_ = /[\\[\\].#$\\/\\u0000-\\u001F\\u007F]/;\n/**\n * True for invalid Firebase paths.\n * Allows '/' in paths.\n */\nconst INVALID_PATH_REGEX_ = /[\\[\\].#$\\u0000-\\u001F\\u007F]/;\n/**\n * Maximum number of characters to allow in leaf value\n */\nconst MAX_LEAF_SIZE_ = 10 * 1024 * 1024;\nconst isValidKey = function (key) {\n    return (typeof key === 'string' && key.length !== 0 && !INVALID_KEY_REGEX_.test(key));\n};\nconst isValidPathString = function (pathString) {\n    return (typeof pathString === 'string' &&\n        pathString.length !== 0 &&\n        !INVALID_PATH_REGEX_.test(pathString));\n};\nconst isValidRootPathString = function (pathString) {\n    if (pathString) {\n        // Allow '/.info/' at the beginning.\n        pathString = pathString.replace(/^\\/*\\.info(\\/|$)/, '/');\n    }\n    return isValidPathString(pathString);\n};\nconst isValidPriority = function (priority) {\n    return (priority === null ||\n        typeof priority === 'string' ||\n        (typeof priority === 'number' && !isInvalidJSONNumber(priority)) ||\n        (priority &&\n            typeof priority === 'object' &&\n            // eslint-disable-next-line @typescript-eslint/no-explicit-any\n            contains(priority, '.sv')));\n};\n/**\n * Pre-validate a datum passed as an argument to Firebase function.\n */\nconst validateFirebaseDataArg = function (fnName, value, path, optional) {\n    if (optional && value === undefined) {\n        return;\n    }\n    validateFirebaseData(errorPrefix(fnName, 'value'), value, path);\n};\n/**\n * Validate a data object client-side before sending to server.\n */\nconst validateFirebaseData = function (errorPrefix, data, path_) {\n    const path = path_ instanceof Path ? new ValidationPath(path_, errorPrefix) : path_;\n    if (data === undefined) {\n        throw new Error(errorPrefix + 'contains undefined ' + validationPathToErrorString(path));\n    }\n    if (typeof data === 'function') {\n        throw new Error(errorPrefix +\n            'contains a function ' +\n            validationPathToErrorString(path) +\n            ' with contents = ' +\n            data.toString());\n    }\n    if (isInvalidJSONNumber(data)) {\n        throw new Error(errorPrefix +\n            'contains ' +\n            data.toString() +\n            ' ' +\n            validationPathToErrorString(path));\n    }\n    // Check max leaf size, but try to avoid the utf8 conversion if we can.\n    if (typeof data === 'string' &&\n        data.length > MAX_LEAF_SIZE_ / 3 &&\n        stringLength(data) > MAX_LEAF_SIZE_) {\n        throw new Error(errorPrefix +\n            'contains a string greater than ' +\n            MAX_LEAF_SIZE_ +\n            ' utf8 bytes ' +\n            validationPathToErrorString(path) +\n            \" ('\" +\n            data.substring(0, 50) +\n            \"...')\");\n    }\n    // TODO = Perf = Consider combining the recursive validation of keys into NodeFromJSON\n    // to save extra walking of large objects.\n    if (data && typeof data === 'object') {\n        let hasDotValue = false;\n        let hasActualChild = false;\n        each(data, (key, value) => {\n            if (key === '.value') {\n                hasDotValue = true;\n            }\n            else if (key !== '.priority' && key !== '.sv') {\n                hasActualChild = true;\n                if (!isValidKey(key)) {\n                    throw new Error(errorPrefix +\n                        ' contains an invalid key (' +\n                        key +\n                        ') ' +\n                        validationPathToErrorString(path) +\n                        '.  Keys must be non-empty strings ' +\n                        'and can\\'t contain \".\", \"#\", \"$\", \"/\", \"[\", or \"]\"');\n                }\n            }\n            validationPathPush(path, key);\n            validateFirebaseData(errorPrefix, value, path);\n            validationPathPop(path);\n        });\n        if (hasDotValue && hasActualChild) {\n            throw new Error(errorPrefix +\n                ' contains \".value\" child ' +\n                validationPathToErrorString(path) +\n                ' in addition to actual children.');\n        }\n    }\n};\n/**\n * Pre-validate paths passed in the firebase function.\n */\nconst validateFirebaseMergePaths = function (errorPrefix, mergePaths) {\n    let i, curPath;\n    for (i = 0; i < mergePaths.length; i++) {\n        curPath = mergePaths[i];\n        const keys = pathSlice(curPath);\n        for (let j = 0; j < keys.length; j++) {\n            if (keys[j] === '.priority' && j === keys.length - 1) ;\n            else if (!isValidKey(keys[j])) {\n                throw new Error(errorPrefix +\n                    'contains an invalid key (' +\n                    keys[j] +\n                    ') in path ' +\n                    curPath.toString() +\n                    '. Keys must be non-empty strings ' +\n                    'and can\\'t contain \".\", \"#\", \"$\", \"/\", \"[\", or \"]\"');\n            }\n        }\n    }\n    // Check that update keys are not descendants of each other.\n    // We rely on the property that sorting guarantees that ancestors come\n    // right before descendants.\n    mergePaths.sort(pathCompare);\n    let prevPath = null;\n    for (i = 0; i < mergePaths.length; i++) {\n        curPath = mergePaths[i];\n        if (prevPath !== null && pathContains(prevPath, curPath)) {\n            throw new Error(errorPrefix +\n                'contains a path ' +\n                prevPath.toString() +\n                ' that is ancestor of another path ' +\n                curPath.toString());\n        }\n        prevPath = curPath;\n    }\n};\n/**\n * pre-validate an object passed as an argument to firebase function (\n * must be an object - e.g. for firebase.update()).\n */\nconst validateFirebaseMergeDataArg = function (fnName, data, path, optional) {\n    if (optional && data === undefined) {\n        return;\n    }\n    const errorPrefix$1 = errorPrefix(fnName, 'values');\n    if (!(data && typeof data === 'object') || Array.isArray(data)) {\n        throw new Error(errorPrefix$1 + ' must be an object containing the children to replace.');\n    }\n    const mergePaths = [];\n    each(data, (key, value) => {\n        const curPath = new Path(key);\n        validateFirebaseData(errorPrefix$1, value, pathChild(path, curPath));\n        if (pathGetBack(curPath) === '.priority') {\n            if (!isValidPriority(value)) {\n                throw new Error(errorPrefix$1 +\n                    \"contains an invalid value for '\" +\n                    curPath.toString() +\n                    \"', which must be a valid \" +\n                    'Firebase priority (a string, finite number, server value, or null).');\n            }\n        }\n        mergePaths.push(curPath);\n    });\n    validateFirebaseMergePaths(errorPrefix$1, mergePaths);\n};\nconst validatePriority = function (fnName, priority, optional) {\n    if (optional && priority === undefined) {\n        return;\n    }\n    if (isInvalidJSONNumber(priority)) {\n        throw new Error(errorPrefix(fnName, 'priority') +\n            'is ' +\n            priority.toString() +\n            ', but must be a valid Firebase priority (a string, finite number, ' +\n            'server value, or null).');\n    }\n    // Special case to allow importing data with a .sv.\n    if (!isValidPriority(priority)) {\n        throw new Error(errorPrefix(fnName, 'priority') +\n            'must be a valid Firebase priority ' +\n            '(a string, finite number, server value, or null).');\n    }\n};\nconst validateKey = function (fnName, argumentName, key, optional) {\n    if (optional && key === undefined) {\n        return;\n    }\n    if (!isValidKey(key)) {\n        throw new Error(errorPrefix(fnName, argumentName) +\n            'was an invalid key = \"' +\n            key +\n            '\".  Firebase keys must be non-empty strings and ' +\n            'can\\'t contain \".\", \"#\", \"$\", \"/\", \"[\", or \"]\").');\n    }\n};\n/**\n * @internal\n */\nconst validatePathString = function (fnName, argumentName, pathString, optional) {\n    if (optional && pathString === undefined) {\n        return;\n    }\n    if (!isValidPathString(pathString)) {\n        throw new Error(errorPrefix(fnName, argumentName) +\n            'was an invalid path = \"' +\n            pathString +\n            '\". Paths must be non-empty strings and ' +\n            'can\\'t contain \".\", \"#\", \"$\", \"[\", or \"]\"');\n    }\n};\nconst validateRootPathString = function (fnName, argumentName, pathString, optional) {\n    if (pathString) {\n        // Allow '/.info/' at the beginning.\n        pathString = pathString.replace(/^\\/*\\.info(\\/|$)/, '/');\n    }\n    validatePathString(fnName, argumentName, pathString, optional);\n};\n/**\n * @internal\n */\nconst validateWritablePath = function (fnName, path) {\n    if (pathGetFront(path) === '.info') {\n        throw new Error(fnName + \" failed = Can't modify data under /.info/\");\n    }\n};\nconst validateUrl = function (fnName, parsedUrl) {\n    // TODO = Validate server better.\n    const pathString = parsedUrl.path.toString();\n    if (!(typeof parsedUrl.repoInfo.host === 'string') ||\n        parsedUrl.repoInfo.host.length === 0 ||\n        (!isValidKey(parsedUrl.repoInfo.namespace) &&\n            parsedUrl.repoInfo.host.split(':')[0] !== 'localhost') ||\n        (pathString.length !== 0 && !isValidRootPathString(pathString))) {\n        throw new Error(errorPrefix(fnName, 'url') +\n            'must be a valid firebase URL and ' +\n            'the path can\\'t contain \".\", \"#\", \"$\", \"[\", or \"]\".');\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 event queue serves a few purposes:\n * 1. It ensures we maintain event order in the face of event callbacks doing operations that result in more\n *    events being queued.\n * 2. raiseQueuedEvents() handles being called reentrantly nicely.  That is, if in the course of raising events,\n *    raiseQueuedEvents() is called again, the \"inner\" call will pick up raising events where the \"outer\" call\n *    left off, ensuring that the events are still raised synchronously and in order.\n * 3. You can use raiseEventsAtPath and raiseEventsForChangedPath to ensure only relevant previously-queued\n *    events are raised synchronously.\n *\n * NOTE: This can all go away if/when we move to async events.\n *\n */\nclass EventQueue {\n    constructor() {\n        this.eventLists_ = [];\n        /**\n         * Tracks recursion depth of raiseQueuedEvents_, for debugging purposes.\n         */\n        this.recursionDepth_ = 0;\n    }\n}\n/**\n * @param eventDataList - The new events to queue.\n */\nfunction eventQueueQueueEvents(eventQueue, eventDataList) {\n    // We group events by path, storing them in a single EventList, to make it easier to skip over them quickly.\n    let currList = null;\n    for (let i = 0; i < eventDataList.length; i++) {\n        const data = eventDataList[i];\n        const path = data.getPath();\n        if (currList !== null && !pathEquals(path, currList.path)) {\n            eventQueue.eventLists_.push(currList);\n            currList = null;\n        }\n        if (currList === null) {\n            currList = { events: [], path };\n        }\n        currList.events.push(data);\n    }\n    if (currList) {\n        eventQueue.eventLists_.push(currList);\n    }\n}\n/**\n * Queues the specified events and synchronously raises all events (including previously queued ones)\n * for the specified path.\n *\n * It is assumed that the new events are all for the specified path.\n *\n * @param path - The path to raise events for.\n * @param eventDataList - The new events to raise.\n */\nfunction eventQueueRaiseEventsAtPath(eventQueue, path, eventDataList) {\n    eventQueueQueueEvents(eventQueue, eventDataList);\n    eventQueueRaiseQueuedEventsMatchingPredicate(eventQueue, eventPath => pathEquals(eventPath, path));\n}\n/**\n * Queues the specified events and synchronously raises all events (including previously queued ones) for\n * locations related to the specified change path (i.e. all ancestors and descendants).\n *\n * It is assumed that the new events are all related (ancestor or descendant) to the specified path.\n *\n * @param changedPath - The path to raise events for.\n * @param eventDataList - The events to raise\n */\nfunction eventQueueRaiseEventsForChangedPath(eventQueue, changedPath, eventDataList) {\n    eventQueueQueueEvents(eventQueue, eventDataList);\n    eventQueueRaiseQueuedEventsMatchingPredicate(eventQueue, eventPath => pathContains(eventPath, changedPath) ||\n        pathContains(changedPath, eventPath));\n}\nfunction eventQueueRaiseQueuedEventsMatchingPredicate(eventQueue, predicate) {\n    eventQueue.recursionDepth_++;\n    let sentAll = true;\n    for (let i = 0; i < eventQueue.eventLists_.length; i++) {\n        const eventList = eventQueue.eventLists_[i];\n        if (eventList) {\n            const eventPath = eventList.path;\n            if (predicate(eventPath)) {\n                eventListRaise(eventQueue.eventLists_[i]);\n                eventQueue.eventLists_[i] = null;\n            }\n            else {\n                sentAll = false;\n            }\n        }\n    }\n    if (sentAll) {\n        eventQueue.eventLists_ = [];\n    }\n    eventQueue.recursionDepth_--;\n}\n/**\n * Iterates through the list and raises each event\n */\nfunction eventListRaise(eventList) {\n    for (let i = 0; i < eventList.events.length; i++) {\n        const eventData = eventList.events[i];\n        if (eventData !== null) {\n            eventList.events[i] = null;\n            const eventFn = eventData.getEventRunner();\n            if (logger) {\n                log('event: ' + eventData.toString());\n            }\n            exceptionGuard(eventFn);\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 */\nconst INTERRUPT_REASON = 'repo_interrupt';\n/**\n * If a transaction does not succeed after 25 retries, we abort it. Among other\n * things this ensure that if there's ever a bug causing a mismatch between\n * client / server hashes for some data, we won't retry indefinitely.\n */\nconst MAX_TRANSACTION_RETRIES = 25;\n/**\n * A connection to a single data repository.\n */\nclass Repo {\n    constructor(repoInfo_, forceRestClient_, authTokenProvider_, appCheckProvider_) {\n        this.repoInfo_ = repoInfo_;\n        this.forceRestClient_ = forceRestClient_;\n        this.authTokenProvider_ = authTokenProvider_;\n        this.appCheckProvider_ = appCheckProvider_;\n        this.dataUpdateCount = 0;\n        this.statsListener_ = null;\n        this.eventQueue_ = new EventQueue();\n        this.nextWriteId_ = 1;\n        this.interceptServerDataCallback_ = null;\n        /** A list of data pieces and paths to be set when this client disconnects. */\n        this.onDisconnect_ = newSparseSnapshotTree();\n        /** Stores queues of outstanding transactions for Firebase locations. */\n        this.transactionQueueTree_ = new Tree();\n        // TODO: This should be @private but it's used by test_access.js and internal.js\n        this.persistentConnection_ = null;\n        // This key is intentionally not updated if RepoInfo is later changed or replaced\n        this.key = this.repoInfo_.toURLString();\n    }\n    /**\n     * @returns The URL corresponding to the root of this Firebase.\n     */\n    toString() {\n        return ((this.repoInfo_.secure ? 'https://' : 'http://') + this.repoInfo_.host);\n    }\n}\nfunction repoStart(repo, appId, authOverride) {\n    repo.stats_ = statsManagerGetCollection(repo.repoInfo_);\n    if (repo.forceRestClient_ || beingCrawled()) {\n        repo.server_ = new ReadonlyRestClient(repo.repoInfo_, (pathString, data, isMerge, tag) => {\n            repoOnDataUpdate(repo, pathString, data, isMerge, tag);\n        }, repo.authTokenProvider_, repo.appCheckProvider_);\n        // Minor hack: Fire onConnect immediately, since there's no actual connection.\n        setTimeout(() => repoOnConnectStatus(repo, /* connectStatus= */ true), 0);\n    }\n    else {\n        // Validate authOverride\n        if (typeof authOverride !== 'undefined' && authOverride !== null) {\n            if (typeof authOverride !== 'object') {\n                throw new Error('Only objects are supported for option databaseAuthVariableOverride');\n            }\n            try {\n                stringify(authOverride);\n            }\n            catch (e) {\n                throw new Error('Invalid authOverride provided: ' + e);\n            }\n        }\n        repo.persistentConnection_ = new PersistentConnection(repo.repoInfo_, appId, (pathString, data, isMerge, tag) => {\n            repoOnDataUpdate(repo, pathString, data, isMerge, tag);\n        }, (connectStatus) => {\n            repoOnConnectStatus(repo, connectStatus);\n        }, (updates) => {\n            repoOnServerInfoUpdate(repo, updates);\n        }, repo.authTokenProvider_, repo.appCheckProvider_, authOverride);\n        repo.server_ = repo.persistentConnection_;\n    }\n    repo.authTokenProvider_.addTokenChangeListener(token => {\n        repo.server_.refreshAuthToken(token);\n    });\n    repo.appCheckProvider_.addTokenChangeListener(result => {\n        repo.server_.refreshAppCheckToken(result.token);\n    });\n    // In the case of multiple Repos for the same repoInfo (i.e. there are multiple Firebase.Contexts being used),\n    // we only want to create one StatsReporter.  As such, we'll report stats over the first Repo created.\n    repo.statsReporter_ = statsManagerGetOrCreateReporter(repo.repoInfo_, () => new StatsReporter(repo.stats_, repo.server_));\n    // Used for .info.\n    repo.infoData_ = new SnapshotHolder();\n    repo.infoSyncTree_ = new SyncTree({\n        startListening: (query, tag, currentHashFn, onComplete) => {\n            let infoEvents = [];\n            const node = repo.infoData_.getNode(query._path);\n            // This is possibly a hack, but we have different semantics for .info endpoints. We don't raise null events\n            // on initial data...\n            if (!node.isEmpty()) {\n                infoEvents = syncTreeApplyServerOverwrite(repo.infoSyncTree_, query._path, node);\n                setTimeout(() => {\n                    onComplete('ok');\n                }, 0);\n            }\n            return infoEvents;\n        },\n        stopListening: () => { }\n    });\n    repoUpdateInfo(repo, 'connected', false);\n    repo.serverSyncTree_ = new SyncTree({\n        startListening: (query, tag, currentHashFn, onComplete) => {\n            repo.server_.listen(query, currentHashFn, tag, (status, data) => {\n                const events = onComplete(status, data);\n                eventQueueRaiseEventsForChangedPath(repo.eventQueue_, query._path, events);\n            });\n            // No synchronous events for network-backed sync trees\n            return [];\n        },\n        stopListening: (query, tag) => {\n            repo.server_.unlisten(query, tag);\n        }\n    });\n}\n/**\n * @returns The time in milliseconds, taking the server offset into account if we have one.\n */\nfunction repoServerTime(repo) {\n    const offsetNode = repo.infoData_.getNode(new Path('.info/serverTimeOffset'));\n    const offset = offsetNode.val() || 0;\n    return new Date().getTime() + offset;\n}\n/**\n * Generate ServerValues using some variables from the repo object.\n */\nfunction repoGenerateServerValues(repo) {\n    return generateWithValues({\n        timestamp: repoServerTime(repo)\n    });\n}\n/**\n * Called by realtime when we get new messages from the server.\n */\nfunction repoOnDataUpdate(repo, pathString, data, isMerge, tag) {\n    // For testing.\n    repo.dataUpdateCount++;\n    const path = new Path(pathString);\n    data = repo.interceptServerDataCallback_\n        ? repo.interceptServerDataCallback_(pathString, data)\n        : data;\n    let events = [];\n    if (tag) {\n        if (isMerge) {\n            const taggedChildren = map(data, (raw) => nodeFromJSON(raw));\n            events = syncTreeApplyTaggedQueryMerge(repo.serverSyncTree_, path, taggedChildren, tag);\n        }\n        else {\n            const taggedSnap = nodeFromJSON(data);\n            events = syncTreeApplyTaggedQueryOverwrite(repo.serverSyncTree_, path, taggedSnap, tag);\n        }\n    }\n    else if (isMerge) {\n        const changedChildren = map(data, (raw) => nodeFromJSON(raw));\n        events = syncTreeApplyServerMerge(repo.serverSyncTree_, path, changedChildren);\n    }\n    else {\n        const snap = nodeFromJSON(data);\n        events = syncTreeApplyServerOverwrite(repo.serverSyncTree_, path, snap);\n    }\n    let affectedPath = path;\n    if (events.length > 0) {\n        // Since we have a listener outstanding for each transaction, receiving any events\n        // is a proxy for some change having occurred.\n        affectedPath = repoRerunTransactions(repo, path);\n    }\n    eventQueueRaiseEventsForChangedPath(repo.eventQueue_, affectedPath, events);\n}\nfunction repoOnConnectStatus(repo, connectStatus) {\n    repoUpdateInfo(repo, 'connected', connectStatus);\n    if (connectStatus === false) {\n        repoRunOnDisconnectEvents(repo);\n    }\n}\nfunction repoOnServerInfoUpdate(repo, updates) {\n    each(updates, (key, value) => {\n        repoUpdateInfo(repo, key, value);\n    });\n}\nfunction repoUpdateInfo(repo, pathString, value) {\n    const path = new Path('/.info/' + pathString);\n    const newNode = nodeFromJSON(value);\n    repo.infoData_.updateSnapshot(path, newNode);\n    const events = syncTreeApplyServerOverwrite(repo.infoSyncTree_, path, newNode);\n    eventQueueRaiseEventsForChangedPath(repo.eventQueue_, path, events);\n}\nfunction repoGetNextWriteId(repo) {\n    return repo.nextWriteId_++;\n}\n/**\n * The purpose of `getValue` is to return the latest known value\n * satisfying `query`.\n *\n * This method will first check for in-memory cached values\n * belonging to active listeners. If they are found, such values\n * are considered to be the most up-to-date.\n *\n * If the client is not connected, this method will wait until the\n *  repo has established a connection and then request the value for `query`.\n * If the client is not able to retrieve the query result for another reason,\n * it reports an error.\n *\n * @param query - The query to surface a value for.\n */\nfunction repoGetValue(repo, query, eventRegistration) {\n    // Only active queries are cached. There is no persisted cache.\n    const cached = syncTreeGetServerValue(repo.serverSyncTree_, query);\n    if (cached != null) {\n        return Promise.resolve(cached);\n    }\n    return repo.server_.get(query).then(payload => {\n        const node = nodeFromJSON(payload).withIndex(query._queryParams.getIndex());\n        /**\n         * Below we simulate the actions of an `onlyOnce` `onValue()` event where:\n         * Add an event registration,\n         * Update data at the path,\n         * Raise any events,\n         * Cleanup the SyncTree\n         */\n        syncTreeAddEventRegistration(repo.serverSyncTree_, query, eventRegistration, true);\n        let events;\n        if (query._queryParams.loadsAllData()) {\n            events = syncTreeApplyServerOverwrite(repo.serverSyncTree_, query._path, node);\n        }\n        else {\n            const tag = syncTreeTagForQuery(repo.serverSyncTree_, query);\n            events = syncTreeApplyTaggedQueryOverwrite(repo.serverSyncTree_, query._path, node, tag);\n        }\n        /*\n         * We need to raise events in the scenario where `get()` is called at a parent path, and\n         * while the `get()` is pending, `onValue` is called at a child location. While get() is waiting\n         * for the data, `onValue` will register a new event. Then, get() will come back, and update the syncTree\n         * and its corresponding serverCache, including the child location where `onValue` is called. Then,\n         * `onValue` will receive the event from the server, but look at the syncTree and see that the data received\n         * from the server is already at the SyncPoint, and so the `onValue` callback will never get fired.\n         * Calling `eventQueueRaiseEventsForChangedPath()` is the correct way to propagate the events and\n         * ensure the corresponding child events will get fired.\n         */\n        eventQueueRaiseEventsForChangedPath(repo.eventQueue_, query._path, events);\n        syncTreeRemoveEventRegistration(repo.serverSyncTree_, query, eventRegistration, null, true);\n        return node;\n    }, err => {\n        repoLog(repo, 'get for query ' + stringify(query) + ' failed: ' + err);\n        return Promise.reject(new Error(err));\n    });\n}\nfunction repoSetWithPriority(repo, path, newVal, newPriority, onComplete) {\n    repoLog(repo, 'set', {\n        path: path.toString(),\n        value: newVal,\n        priority: newPriority\n    });\n    // TODO: Optimize this behavior to either (a) store flag to skip resolving where possible and / or\n    // (b) store unresolved paths on JSON parse\n    const serverValues = repoGenerateServerValues(repo);\n    const newNodeUnresolved = nodeFromJSON(newVal, newPriority);\n    const existing = syncTreeCalcCompleteEventCache(repo.serverSyncTree_, path);\n    const newNode = resolveDeferredValueSnapshot(newNodeUnresolved, existing, serverValues);\n    const writeId = repoGetNextWriteId(repo);\n    const events = syncTreeApplyUserOverwrite(repo.serverSyncTree_, path, newNode, writeId, true);\n    eventQueueQueueEvents(repo.eventQueue_, events);\n    repo.server_.put(path.toString(), newNodeUnresolved.val(/*export=*/ true), (status, errorReason) => {\n        const success = status === 'ok';\n        if (!success) {\n            warn('set at ' + path + ' failed: ' + status);\n        }\n        const clearEvents = syncTreeAckUserWrite(repo.serverSyncTree_, writeId, !success);\n        eventQueueRaiseEventsForChangedPath(repo.eventQueue_, path, clearEvents);\n        repoCallOnCompleteCallback(repo, onComplete, status, errorReason);\n    });\n    const affectedPath = repoAbortTransactions(repo, path);\n    repoRerunTransactions(repo, affectedPath);\n    // We queued the events above, so just flush the queue here\n    eventQueueRaiseEventsForChangedPath(repo.eventQueue_, affectedPath, []);\n}\nfunction repoUpdate(repo, path, childrenToMerge, onComplete) {\n    repoLog(repo, 'update', { path: path.toString(), value: childrenToMerge });\n    // Start with our existing data and merge each child into it.\n    let empty = true;\n    const serverValues = repoGenerateServerValues(repo);\n    const changedChildren = {};\n    each(childrenToMerge, (changedKey, changedValue) => {\n        empty = false;\n        changedChildren[changedKey] = resolveDeferredValueTree(pathChild(path, changedKey), nodeFromJSON(changedValue), repo.serverSyncTree_, serverValues);\n    });\n    if (!empty) {\n        const writeId = repoGetNextWriteId(repo);\n        const events = syncTreeApplyUserMerge(repo.serverSyncTree_, path, changedChildren, writeId);\n        eventQueueQueueEvents(repo.eventQueue_, events);\n        repo.server_.merge(path.toString(), childrenToMerge, (status, errorReason) => {\n            const success = status === 'ok';\n            if (!success) {\n                warn('update at ' + path + ' failed: ' + status);\n            }\n            const clearEvents = syncTreeAckUserWrite(repo.serverSyncTree_, writeId, !success);\n            const affectedPath = clearEvents.length > 0 ? repoRerunTransactions(repo, path) : path;\n            eventQueueRaiseEventsForChangedPath(repo.eventQueue_, affectedPath, clearEvents);\n            repoCallOnCompleteCallback(repo, onComplete, status, errorReason);\n        });\n        each(childrenToMerge, (changedPath) => {\n            const affectedPath = repoAbortTransactions(repo, pathChild(path, changedPath));\n            repoRerunTransactions(repo, affectedPath);\n        });\n        // We queued the events above, so just flush the queue here\n        eventQueueRaiseEventsForChangedPath(repo.eventQueue_, path, []);\n    }\n    else {\n        log(\"update() called with empty data.  Don't do anything.\");\n        repoCallOnCompleteCallback(repo, onComplete, 'ok', undefined);\n    }\n}\n/**\n * Applies all of the changes stored up in the onDisconnect_ tree.\n */\nfunction repoRunOnDisconnectEvents(repo) {\n    repoLog(repo, 'onDisconnectEvents');\n    const serverValues = repoGenerateServerValues(repo);\n    const resolvedOnDisconnectTree = newSparseSnapshotTree();\n    sparseSnapshotTreeForEachTree(repo.onDisconnect_, newEmptyPath(), (path, node) => {\n        const resolved = resolveDeferredValueTree(path, node, repo.serverSyncTree_, serverValues);\n        sparseSnapshotTreeRemember(resolvedOnDisconnectTree, path, resolved);\n    });\n    let events = [];\n    sparseSnapshotTreeForEachTree(resolvedOnDisconnectTree, newEmptyPath(), (path, snap) => {\n        events = events.concat(syncTreeApplyServerOverwrite(repo.serverSyncTree_, path, snap));\n        const affectedPath = repoAbortTransactions(repo, path);\n        repoRerunTransactions(repo, affectedPath);\n    });\n    repo.onDisconnect_ = newSparseSnapshotTree();\n    eventQueueRaiseEventsForChangedPath(repo.eventQueue_, newEmptyPath(), events);\n}\nfunction repoOnDisconnectCancel(repo, path, onComplete) {\n    repo.server_.onDisconnectCancel(path.toString(), (status, errorReason) => {\n        if (status === 'ok') {\n            sparseSnapshotTreeForget(repo.onDisconnect_, path);\n        }\n        repoCallOnCompleteCallback(repo, onComplete, status, errorReason);\n    });\n}\nfunction repoOnDisconnectSet(repo, path, value, onComplete) {\n    const newNode = nodeFromJSON(value);\n    repo.server_.onDisconnectPut(path.toString(), newNode.val(/*export=*/ true), (status, errorReason) => {\n        if (status === 'ok') {\n            sparseSnapshotTreeRemember(repo.onDisconnect_, path, newNode);\n        }\n        repoCallOnCompleteCallback(repo, onComplete, status, errorReason);\n    });\n}\nfunction repoOnDisconnectSetWithPriority(repo, path, value, priority, onComplete) {\n    const newNode = nodeFromJSON(value, priority);\n    repo.server_.onDisconnectPut(path.toString(), newNode.val(/*export=*/ true), (status, errorReason) => {\n        if (status === 'ok') {\n            sparseSnapshotTreeRemember(repo.onDisconnect_, path, newNode);\n        }\n        repoCallOnCompleteCallback(repo, onComplete, status, errorReason);\n    });\n}\nfunction repoOnDisconnectUpdate(repo, path, childrenToMerge, onComplete) {\n    if (isEmpty(childrenToMerge)) {\n        log(\"onDisconnect().update() called with empty data.  Don't do anything.\");\n        repoCallOnCompleteCallback(repo, onComplete, 'ok', undefined);\n        return;\n    }\n    repo.server_.onDisconnectMerge(path.toString(), childrenToMerge, (status, errorReason) => {\n        if (status === 'ok') {\n            each(childrenToMerge, (childName, childNode) => {\n                const newChildNode = nodeFromJSON(childNode);\n                sparseSnapshotTreeRemember(repo.onDisconnect_, pathChild(path, childName), newChildNode);\n            });\n        }\n        repoCallOnCompleteCallback(repo, onComplete, status, errorReason);\n    });\n}\nfunction repoAddEventCallbackForQuery(repo, query, eventRegistration) {\n    let events;\n    if (pathGetFront(query._path) === '.info') {\n        events = syncTreeAddEventRegistration(repo.infoSyncTree_, query, eventRegistration);\n    }\n    else {\n        events = syncTreeAddEventRegistration(repo.serverSyncTree_, query, eventRegistration);\n    }\n    eventQueueRaiseEventsAtPath(repo.eventQueue_, query._path, events);\n}\nfunction repoRemoveEventCallbackForQuery(repo, query, eventRegistration) {\n    // These are guaranteed not to raise events, since we're not passing in a cancelError. However, we can future-proof\n    // a little bit by handling the return values anyways.\n    let events;\n    if (pathGetFront(query._path) === '.info') {\n        events = syncTreeRemoveEventRegistration(repo.infoSyncTree_, query, eventRegistration);\n    }\n    else {\n        events = syncTreeRemoveEventRegistration(repo.serverSyncTree_, query, eventRegistration);\n    }\n    eventQueueRaiseEventsAtPath(repo.eventQueue_, query._path, events);\n}\nfunction repoInterrupt(repo) {\n    if (repo.persistentConnection_) {\n        repo.persistentConnection_.interrupt(INTERRUPT_REASON);\n    }\n}\nfunction repoResume(repo) {\n    if (repo.persistentConnection_) {\n        repo.persistentConnection_.resume(INTERRUPT_REASON);\n    }\n}\nfunction repoLog(repo, ...varArgs) {\n    let prefix = '';\n    if (repo.persistentConnection_) {\n        prefix = repo.persistentConnection_.id + ':';\n    }\n    log(prefix, ...varArgs);\n}\nfunction repoCallOnCompleteCallback(repo, callback, status, errorReason) {\n    if (callback) {\n        exceptionGuard(() => {\n            if (status === 'ok') {\n                callback(null);\n            }\n            else {\n                const code = (status || 'error').toUpperCase();\n                let message = code;\n                if (errorReason) {\n                    message += ': ' + errorReason;\n                }\n                const error = new Error(message);\n                // eslint-disable-next-line @typescript-eslint/no-explicit-any\n                error.code = code;\n                callback(error);\n            }\n        });\n    }\n}\n/**\n * Creates a new transaction, adds it to the transactions we're tracking, and\n * sends it to the server if possible.\n *\n * @param path - Path at which to do transaction.\n * @param transactionUpdate - Update callback.\n * @param onComplete - Completion callback.\n * @param unwatcher - Function that will be called when the transaction no longer\n * need data updates for `path`.\n * @param applyLocally - Whether or not to make intermediate results visible\n */\nfunction repoStartTransaction(repo, path, transactionUpdate, onComplete, unwatcher, applyLocally) {\n    repoLog(repo, 'transaction on ' + path);\n    // Initialize transaction.\n    const transaction = {\n        path,\n        update: transactionUpdate,\n        onComplete,\n        // One of TransactionStatus enums.\n        status: null,\n        // Used when combining transactions at different locations to figure out\n        // which one goes first.\n        order: LUIDGenerator(),\n        // Whether to raise local events for this transaction.\n        applyLocally,\n        // Count of how many times we've retried the transaction.\n        retryCount: 0,\n        // Function to call to clean up our .on() listener.\n        unwatcher,\n        // Stores why a transaction was aborted.\n        abortReason: null,\n        currentWriteId: null,\n        currentInputSnapshot: null,\n        currentOutputSnapshotRaw: null,\n        currentOutputSnapshotResolved: null\n    };\n    // Run transaction initially.\n    const currentState = repoGetLatestState(repo, path, undefined);\n    transaction.currentInputSnapshot = currentState;\n    const newVal = transaction.update(currentState.val());\n    if (newVal === undefined) {\n        // Abort transaction.\n        transaction.unwatcher();\n        transaction.currentOutputSnapshotRaw = null;\n        transaction.currentOutputSnapshotResolved = null;\n        if (transaction.onComplete) {\n            transaction.onComplete(null, false, transaction.currentInputSnapshot);\n        }\n    }\n    else {\n        validateFirebaseData('transaction failed: Data returned ', newVal, transaction.path);\n        // Mark as run and add to our queue.\n        transaction.status = 0 /* TransactionStatus.RUN */;\n        const queueNode = treeSubTree(repo.transactionQueueTree_, path);\n        const nodeQueue = treeGetValue(queueNode) || [];\n        nodeQueue.push(transaction);\n        treeSetValue(queueNode, nodeQueue);\n        // Update visibleData and raise events\n        // Note: We intentionally raise events after updating all of our\n        // transaction state, since the user could start new transactions from the\n        // event callbacks.\n        let priorityForNode;\n        if (typeof newVal === 'object' &&\n            newVal !== null &&\n            contains(newVal, '.priority')) {\n            // eslint-disable-next-line @typescript-eslint/no-explicit-any\n            priorityForNode = safeGet(newVal, '.priority');\n            assert(isValidPriority(priorityForNode), 'Invalid priority returned by transaction. ' +\n                'Priority must be a valid string, finite number, server value, or null.');\n        }\n        else {\n            const currentNode = syncTreeCalcCompleteEventCache(repo.serverSyncTree_, path) ||\n                ChildrenNode.EMPTY_NODE;\n            priorityForNode = currentNode.getPriority().val();\n        }\n        const serverValues = repoGenerateServerValues(repo);\n        const newNodeUnresolved = nodeFromJSON(newVal, priorityForNode);\n        const newNode = resolveDeferredValueSnapshot(newNodeUnresolved, currentState, serverValues);\n        transaction.currentOutputSnapshotRaw = newNodeUnresolved;\n        transaction.currentOutputSnapshotResolved = newNode;\n        transaction.currentWriteId = repoGetNextWriteId(repo);\n        const events = syncTreeApplyUserOverwrite(repo.serverSyncTree_, path, newNode, transaction.currentWriteId, transaction.applyLocally);\n        eventQueueRaiseEventsForChangedPath(repo.eventQueue_, path, events);\n        repoSendReadyTransactions(repo, repo.transactionQueueTree_);\n    }\n}\n/**\n * @param excludeSets - A specific set to exclude\n */\nfunction repoGetLatestState(repo, path, excludeSets) {\n    return (syncTreeCalcCompleteEventCache(repo.serverSyncTree_, path, excludeSets) ||\n        ChildrenNode.EMPTY_NODE);\n}\n/**\n * Sends any already-run transactions that aren't waiting for outstanding\n * transactions to complete.\n *\n * Externally it's called with no arguments, but it calls itself recursively\n * with a particular transactionQueueTree node to recurse through the tree.\n *\n * @param node - transactionQueueTree node to start at.\n */\nfunction repoSendReadyTransactions(repo, node = repo.transactionQueueTree_) {\n    // Before recursing, make sure any completed transactions are removed.\n    if (!node) {\n        repoPruneCompletedTransactionsBelowNode(repo, node);\n    }\n    if (treeGetValue(node)) {\n        const queue = repoBuildTransactionQueue(repo, node);\n        assert(queue.length > 0, 'Sending zero length transaction queue');\n        const allRun = queue.every((transaction) => transaction.status === 0 /* TransactionStatus.RUN */);\n        // If they're all run (and not sent), we can send them.  Else, we must wait.\n        if (allRun) {\n            repoSendTransactionQueue(repo, treeGetPath(node), queue);\n        }\n    }\n    else if (treeHasChildren(node)) {\n        treeForEachChild(node, childNode => {\n            repoSendReadyTransactions(repo, childNode);\n        });\n    }\n}\n/**\n * Given a list of run transactions, send them to the server and then handle\n * the result (success or failure).\n *\n * @param path - The location of the queue.\n * @param queue - Queue of transactions under the specified location.\n */\nfunction repoSendTransactionQueue(repo, path, queue) {\n    // Mark transactions as sent and increment retry count!\n    const setsToIgnore = queue.map(txn => {\n        return txn.currentWriteId;\n    });\n    const latestState = repoGetLatestState(repo, path, setsToIgnore);\n    let snapToSend = latestState;\n    const latestHash = latestState.hash();\n    for (let i = 0; i < queue.length; i++) {\n        const txn = queue[i];\n        assert(txn.status === 0 /* TransactionStatus.RUN */, 'tryToSendTransactionQueue_: items in queue should all be run.');\n        txn.status = 1 /* TransactionStatus.SENT */;\n        txn.retryCount++;\n        const relativePath = newRelativePath(path, txn.path);\n        // If we've gotten to this point, the output snapshot must be defined.\n        snapToSend = snapToSend.updateChild(relativePath /** @type {!Node} */, txn.currentOutputSnapshotRaw);\n    }\n    const dataToSend = snapToSend.val(true);\n    const pathToSend = path;\n    // Send the put.\n    repo.server_.put(pathToSend.toString(), dataToSend, (status) => {\n        repoLog(repo, 'transaction put response', {\n            path: pathToSend.toString(),\n            status\n        });\n        let events = [];\n        if (status === 'ok') {\n            // Queue up the callbacks and fire them after cleaning up all of our\n            // transaction state, since the callback could trigger more\n            // transactions or sets.\n            const callbacks = [];\n            for (let i = 0; i < queue.length; i++) {\n                queue[i].status = 2 /* TransactionStatus.COMPLETED */;\n                events = events.concat(syncTreeAckUserWrite(repo.serverSyncTree_, queue[i].currentWriteId));\n                if (queue[i].onComplete) {\n                    // We never unset the output snapshot, and given that this\n                    // transaction is complete, it should be set\n                    callbacks.push(() => queue[i].onComplete(null, true, queue[i].currentOutputSnapshotResolved));\n                }\n                queue[i].unwatcher();\n            }\n            // Now remove the completed transactions.\n            repoPruneCompletedTransactionsBelowNode(repo, treeSubTree(repo.transactionQueueTree_, path));\n            // There may be pending transactions that we can now send.\n            repoSendReadyTransactions(repo, repo.transactionQueueTree_);\n            eventQueueRaiseEventsForChangedPath(repo.eventQueue_, path, events);\n            // Finally, trigger onComplete callbacks.\n            for (let i = 0; i < callbacks.length; i++) {\n                exceptionGuard(callbacks[i]);\n            }\n        }\n        else {\n            // transactions are no longer sent.  Update their status appropriately.\n            if (status === 'datastale') {\n                for (let i = 0; i < queue.length; i++) {\n                    if (queue[i].status === 3 /* TransactionStatus.SENT_NEEDS_ABORT */) {\n                        queue[i].status = 4 /* TransactionStatus.NEEDS_ABORT */;\n                    }\n                    else {\n                        queue[i].status = 0 /* TransactionStatus.RUN */;\n                    }\n                }\n            }\n            else {\n                warn('transaction at ' + pathToSend.toString() + ' failed: ' + status);\n                for (let i = 0; i < queue.length; i++) {\n                    queue[i].status = 4 /* TransactionStatus.NEEDS_ABORT */;\n                    queue[i].abortReason = status;\n                }\n            }\n            repoRerunTransactions(repo, path);\n        }\n    }, latestHash);\n}\n/**\n * Finds all transactions dependent on the data at changedPath and reruns them.\n *\n * Should be called any time cached data changes.\n *\n * Return the highest path that was affected by rerunning transactions. This\n * is the path at which events need to be raised for.\n *\n * @param changedPath - The path in mergedData that changed.\n * @returns The rootmost path that was affected by rerunning transactions.\n */\nfunction repoRerunTransactions(repo, changedPath) {\n    const rootMostTransactionNode = repoGetAncestorTransactionNode(repo, changedPath);\n    const path = treeGetPath(rootMostTransactionNode);\n    const queue = repoBuildTransactionQueue(repo, rootMostTransactionNode);\n    repoRerunTransactionQueue(repo, queue, path);\n    return path;\n}\n/**\n * Does all the work of rerunning transactions (as well as cleans up aborted\n * transactions and whatnot).\n *\n * @param queue - The queue of transactions to run.\n * @param path - The path the queue is for.\n */\nfunction repoRerunTransactionQueue(repo, queue, path) {\n    if (queue.length === 0) {\n        return; // Nothing to do!\n    }\n    // Queue up the callbacks and fire them after cleaning up all of our\n    // transaction state, since the callback could trigger more transactions or\n    // sets.\n    const callbacks = [];\n    let events = [];\n    // Ignore all of the sets we're going to re-run.\n    const txnsToRerun = queue.filter(q => {\n        return q.status === 0 /* TransactionStatus.RUN */;\n    });\n    const setsToIgnore = txnsToRerun.map(q => {\n        return q.currentWriteId;\n    });\n    for (let i = 0; i < queue.length; i++) {\n        const transaction = queue[i];\n        const relativePath = newRelativePath(path, transaction.path);\n        let abortTransaction = false, abortReason;\n        assert(relativePath !== null, 'rerunTransactionsUnderNode_: relativePath should not be null.');\n        if (transaction.status === 4 /* TransactionStatus.NEEDS_ABORT */) {\n            abortTransaction = true;\n            abortReason = transaction.abortReason;\n            events = events.concat(syncTreeAckUserWrite(repo.serverSyncTree_, transaction.currentWriteId, true));\n        }\n        else if (transaction.status === 0 /* TransactionStatus.RUN */) {\n            if (transaction.retryCount >= MAX_TRANSACTION_RETRIES) {\n                abortTransaction = true;\n                abortReason = 'maxretry';\n                events = events.concat(syncTreeAckUserWrite(repo.serverSyncTree_, transaction.currentWriteId, true));\n            }\n            else {\n                // This code reruns a transaction\n                const currentNode = repoGetLatestState(repo, transaction.path, setsToIgnore);\n                transaction.currentInputSnapshot = currentNode;\n                const newData = queue[i].update(currentNode.val());\n                if (newData !== undefined) {\n                    validateFirebaseData('transaction failed: Data returned ', newData, transaction.path);\n                    let newDataNode = nodeFromJSON(newData);\n                    const hasExplicitPriority = typeof newData === 'object' &&\n                        newData != null &&\n                        contains(newData, '.priority');\n                    if (!hasExplicitPriority) {\n                        // Keep the old priority if there wasn't a priority explicitly specified.\n                        newDataNode = newDataNode.updatePriority(currentNode.getPriority());\n                    }\n                    const oldWriteId = transaction.currentWriteId;\n                    const serverValues = repoGenerateServerValues(repo);\n                    const newNodeResolved = resolveDeferredValueSnapshot(newDataNode, currentNode, serverValues);\n                    transaction.currentOutputSnapshotRaw = newDataNode;\n                    transaction.currentOutputSnapshotResolved = newNodeResolved;\n                    transaction.currentWriteId = repoGetNextWriteId(repo);\n                    // Mutates setsToIgnore in place\n                    setsToIgnore.splice(setsToIgnore.indexOf(oldWriteId), 1);\n                    events = events.concat(syncTreeApplyUserOverwrite(repo.serverSyncTree_, transaction.path, newNodeResolved, transaction.currentWriteId, transaction.applyLocally));\n                    events = events.concat(syncTreeAckUserWrite(repo.serverSyncTree_, oldWriteId, true));\n                }\n                else {\n                    abortTransaction = true;\n                    abortReason = 'nodata';\n                    events = events.concat(syncTreeAckUserWrite(repo.serverSyncTree_, transaction.currentWriteId, true));\n                }\n            }\n        }\n        eventQueueRaiseEventsForChangedPath(repo.eventQueue_, path, events);\n        events = [];\n        if (abortTransaction) {\n            // Abort.\n            queue[i].status = 2 /* TransactionStatus.COMPLETED */;\n            // Removing a listener can trigger pruning which can muck with\n            // mergedData/visibleData (as it prunes data). So defer the unwatcher\n            // until we're done.\n            (function (unwatcher) {\n                setTimeout(unwatcher, Math.floor(0));\n            })(queue[i].unwatcher);\n            if (queue[i].onComplete) {\n                if (abortReason === 'nodata') {\n                    callbacks.push(() => queue[i].onComplete(null, false, queue[i].currentInputSnapshot));\n                }\n                else {\n                    callbacks.push(() => queue[i].onComplete(new Error(abortReason), false, null));\n                }\n            }\n        }\n    }\n    // Clean up completed transactions.\n    repoPruneCompletedTransactionsBelowNode(repo, repo.transactionQueueTree_);\n    // Now fire callbacks, now that we're in a good, known state.\n    for (let i = 0; i < callbacks.length; i++) {\n        exceptionGuard(callbacks[i]);\n    }\n    // Try to send the transaction result to the server.\n    repoSendReadyTransactions(repo, repo.transactionQueueTree_);\n}\n/**\n * Returns the rootmost ancestor node of the specified path that has a pending\n * transaction on it, or just returns the node for the given path if there are\n * no pending transactions on any ancestor.\n *\n * @param path - The location to start at.\n * @returns The rootmost node with a transaction.\n */\nfunction repoGetAncestorTransactionNode(repo, path) {\n    let front;\n    // Start at the root and walk deeper into the tree towards path until we\n    // find a node with pending transactions.\n    let transactionNode = repo.transactionQueueTree_;\n    front = pathGetFront(path);\n    while (front !== null && treeGetValue(transactionNode) === undefined) {\n        transactionNode = treeSubTree(transactionNode, front);\n        path = pathPopFront(path);\n        front = pathGetFront(path);\n    }\n    return transactionNode;\n}\n/**\n * Builds the queue of all transactions at or below the specified\n * transactionNode.\n *\n * @param transactionNode\n * @returns The generated queue.\n */\nfunction repoBuildTransactionQueue(repo, transactionNode) {\n    // Walk any child transaction queues and aggregate them into a single queue.\n    const transactionQueue = [];\n    repoAggregateTransactionQueuesForNode(repo, transactionNode, transactionQueue);\n    // Sort them by the order the transactions were created.\n    transactionQueue.sort((a, b) => a.order - b.order);\n    return transactionQueue;\n}\nfunction repoAggregateTransactionQueuesForNode(repo, node, queue) {\n    const nodeQueue = treeGetValue(node);\n    if (nodeQueue) {\n        for (let i = 0; i < nodeQueue.length; i++) {\n            queue.push(nodeQueue[i]);\n        }\n    }\n    treeForEachChild(node, child => {\n        repoAggregateTransactionQueuesForNode(repo, child, queue);\n    });\n}\n/**\n * Remove COMPLETED transactions at or below this node in the transactionQueueTree_.\n */\nfunction repoPruneCompletedTransactionsBelowNode(repo, node) {\n    const queue = treeGetValue(node);\n    if (queue) {\n        let to = 0;\n        for (let from = 0; from < queue.length; from++) {\n            if (queue[from].status !== 2 /* TransactionStatus.COMPLETED */) {\n                queue[to] = queue[from];\n                to++;\n            }\n        }\n        queue.length = to;\n        treeSetValue(node, queue.length > 0 ? queue : undefined);\n    }\n    treeForEachChild(node, childNode => {\n        repoPruneCompletedTransactionsBelowNode(repo, childNode);\n    });\n}\n/**\n * Aborts all transactions on ancestors or descendants of the specified path.\n * Called when doing a set() or update() since we consider them incompatible\n * with transactions.\n *\n * @param path - Path for which we want to abort related transactions.\n */\nfunction repoAbortTransactions(repo, path) {\n    const affectedPath = treeGetPath(repoGetAncestorTransactionNode(repo, path));\n    const transactionNode = treeSubTree(repo.transactionQueueTree_, path);\n    treeForEachAncestor(transactionNode, (node) => {\n        repoAbortTransactionsOnNode(repo, node);\n    });\n    repoAbortTransactionsOnNode(repo, transactionNode);\n    treeForEachDescendant(transactionNode, (node) => {\n        repoAbortTransactionsOnNode(repo, node);\n    });\n    return affectedPath;\n}\n/**\n * Abort transactions stored in this transaction queue node.\n *\n * @param node - Node to abort transactions for.\n */\nfunction repoAbortTransactionsOnNode(repo, node) {\n    const queue = treeGetValue(node);\n    if (queue) {\n        // Queue up the callbacks and fire them after cleaning up all of our\n        // transaction state, since the callback could trigger more transactions\n        // or sets.\n        const callbacks = [];\n        // Go through queue.  Any already-sent transactions must be marked for\n        // abort, while the unsent ones can be immediately aborted and removed.\n        let events = [];\n        let lastSent = -1;\n        for (let i = 0; i < queue.length; i++) {\n            if (queue[i].status === 3 /* TransactionStatus.SENT_NEEDS_ABORT */) ;\n            else if (queue[i].status === 1 /* TransactionStatus.SENT */) {\n                assert(lastSent === i - 1, 'All SENT items should be at beginning of queue.');\n                lastSent = i;\n                // Mark transaction for abort when it comes back.\n                queue[i].status = 3 /* TransactionStatus.SENT_NEEDS_ABORT */;\n                queue[i].abortReason = 'set';\n            }\n            else {\n                assert(queue[i].status === 0 /* TransactionStatus.RUN */, 'Unexpected transaction status in abort');\n                // We can abort it immediately.\n                queue[i].unwatcher();\n                events = events.concat(syncTreeAckUserWrite(repo.serverSyncTree_, queue[i].currentWriteId, true));\n                if (queue[i].onComplete) {\n                    callbacks.push(queue[i].onComplete.bind(null, new Error('set'), false, null));\n                }\n            }\n        }\n        if (lastSent === -1) {\n            // We're not waiting for any sent transactions.  We can clear the queue.\n            treeSetValue(node, undefined);\n        }\n        else {\n            // Remove the transactions we aborted.\n            queue.length = lastSent + 1;\n        }\n        // Now fire the callbacks.\n        eventQueueRaiseEventsForChangedPath(repo.eventQueue_, treeGetPath(node), events);\n        for (let i = 0; i < callbacks.length; i++) {\n            exceptionGuard(callbacks[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 */\nfunction decodePath(pathString) {\n    let pathStringDecoded = '';\n    const pieces = pathString.split('/');\n    for (let i = 0; i < pieces.length; i++) {\n        if (pieces[i].length > 0) {\n            let piece = pieces[i];\n            try {\n                piece = decodeURIComponent(piece.replace(/\\+/g, ' '));\n            }\n            catch (e) { }\n            pathStringDecoded += '/' + piece;\n        }\n    }\n    return pathStringDecoded;\n}\n/**\n * @returns key value hash\n */\nfunction decodeQuery(queryString) {\n    const results = {};\n    if (queryString.charAt(0) === '?') {\n        queryString = queryString.substring(1);\n    }\n    for (const segment of queryString.split('&')) {\n        if (segment.length === 0) {\n            continue;\n        }\n        const kv = segment.split('=');\n        if (kv.length === 2) {\n            results[decodeURIComponent(kv[0])] = decodeURIComponent(kv[1]);\n        }\n        else {\n            warn(`Invalid query segment '${segment}' in query '${queryString}'`);\n        }\n    }\n    return results;\n}\nconst parseRepoInfo = function (dataURL, nodeAdmin) {\n    const parsedUrl = parseDatabaseURL(dataURL), namespace = parsedUrl.namespace;\n    if (parsedUrl.domain === 'firebase.com') {\n        fatal(parsedUrl.host +\n            ' is no longer supported. ' +\n            'Please use <YOUR FIREBASE>.firebaseio.com instead');\n    }\n    // Catch common error of uninitialized namespace value.\n    if ((!namespace || namespace === 'undefined') &&\n        parsedUrl.domain !== 'localhost') {\n        fatal('Cannot parse Firebase url. Please use https://<YOUR FIREBASE>.firebaseio.com');\n    }\n    if (!parsedUrl.secure) {\n        warnIfPageIsSecure();\n    }\n    const webSocketOnly = parsedUrl.scheme === 'ws' || parsedUrl.scheme === 'wss';\n    return {\n        repoInfo: new RepoInfo(parsedUrl.host, parsedUrl.secure, namespace, webSocketOnly, nodeAdmin, \n        /*persistenceKey=*/ '', \n        /*includeNamespaceInQueryParams=*/ namespace !== parsedUrl.subdomain),\n        path: new Path(parsedUrl.pathString)\n    };\n};\nconst parseDatabaseURL = function (dataURL) {\n    // Default to empty strings in the event of a malformed string.\n    let host = '', domain = '', subdomain = '', pathString = '', namespace = '';\n    // Always default to SSL, unless otherwise specified.\n    let secure = true, scheme = 'https', port = 443;\n    // Don't do any validation here. The caller is responsible for validating the result of parsing.\n    if (typeof dataURL === 'string') {\n        // Parse scheme.\n        let colonInd = dataURL.indexOf('//');\n        if (colonInd >= 0) {\n            scheme = dataURL.substring(0, colonInd - 1);\n            dataURL = dataURL.substring(colonInd + 2);\n        }\n        // Parse host, path, and query string.\n        let slashInd = dataURL.indexOf('/');\n        if (slashInd === -1) {\n            slashInd = dataURL.length;\n        }\n        let questionMarkInd = dataURL.indexOf('?');\n        if (questionMarkInd === -1) {\n            questionMarkInd = dataURL.length;\n        }\n        host = dataURL.substring(0, Math.min(slashInd, questionMarkInd));\n        if (slashInd < questionMarkInd) {\n            // For pathString, questionMarkInd will always come after slashInd\n            pathString = decodePath(dataURL.substring(slashInd, questionMarkInd));\n        }\n        const queryParams = decodeQuery(dataURL.substring(Math.min(dataURL.length, questionMarkInd)));\n        // If we have a port, use scheme for determining if it's secure.\n        colonInd = host.indexOf(':');\n        if (colonInd >= 0) {\n            secure = scheme === 'https' || scheme === 'wss';\n            port = parseInt(host.substring(colonInd + 1), 10);\n        }\n        else {\n            colonInd = host.length;\n        }\n        const hostWithoutPort = host.slice(0, colonInd);\n        if (hostWithoutPort.toLowerCase() === 'localhost') {\n            domain = 'localhost';\n        }\n        else if (hostWithoutPort.split('.').length <= 2) {\n            domain = hostWithoutPort;\n        }\n        else {\n            // Interpret the subdomain of a 3 or more component URL as the namespace name.\n            const dotInd = host.indexOf('.');\n            subdomain = host.substring(0, dotInd).toLowerCase();\n            domain = host.substring(dotInd + 1);\n            // Normalize namespaces to lowercase to share storage / connection.\n            namespace = subdomain;\n        }\n        // Always treat the value of the `ns` as the namespace name if it is present.\n        if ('ns' in queryParams) {\n            namespace = queryParams['ns'];\n        }\n    }\n    return {\n        host,\n        port,\n        domain,\n        subdomain,\n        secure,\n        scheme,\n        pathString,\n        namespace\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// Modeled after base64 web-safe chars, but ordered by ASCII.\nconst PUSH_CHARS = '-0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ_abcdefghijklmnopqrstuvwxyz';\n/**\n * Fancy ID generator that creates 20-character string identifiers with the\n * following properties:\n *\n * 1. They're based on timestamp so that they sort *after* any existing ids.\n * 2. They contain 72-bits of random data after the timestamp so that IDs won't\n *    collide with other clients' IDs.\n * 3. They sort *lexicographically* (so the timestamp is converted to characters\n *    that will sort properly).\n * 4. They're monotonically increasing. Even if you generate more than one in\n *    the same timestamp, the latter ones will sort after the former ones. We do\n *    this by using the previous random bits but \"incrementing\" them by 1 (only\n *    in the case of a timestamp collision).\n */\nconst nextPushId = (function () {\n    // Timestamp of last push, used to prevent local collisions if you push twice\n    // in one ms.\n    let lastPushTime = 0;\n    // We generate 72-bits of randomness which get turned into 12 characters and\n    // appended to the timestamp to prevent collisions with other clients. We\n    // store the last characters we generated because in the event of a collision,\n    // we'll use those same characters except \"incremented\" by one.\n    const lastRandChars = [];\n    return function (now) {\n        const duplicateTime = now === lastPushTime;\n        lastPushTime = now;\n        let i;\n        const timeStampChars = new Array(8);\n        for (i = 7; i >= 0; i--) {\n            timeStampChars[i] = PUSH_CHARS.charAt(now % 64);\n            // NOTE: Can't use << here because javascript will convert to int and lose\n            // the upper bits.\n            now = Math.floor(now / 64);\n        }\n        assert(now === 0, 'Cannot push at time == 0');\n        let id = timeStampChars.join('');\n        if (!duplicateTime) {\n            for (i = 0; i < 12; i++) {\n                lastRandChars[i] = Math.floor(Math.random() * 64);\n            }\n        }\n        else {\n            // If the timestamp hasn't changed since last push, use the same random\n            // number, except incremented by 1.\n            for (i = 11; i >= 0 && lastRandChars[i] === 63; i--) {\n                lastRandChars[i] = 0;\n            }\n            lastRandChars[i]++;\n        }\n        for (i = 0; i < 12; i++) {\n            id += PUSH_CHARS.charAt(lastRandChars[i]);\n        }\n        assert(id.length === 20, 'nextPushId: Length should be 20.');\n        return id;\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 * Encapsulates the data needed to raise an event\n */\nclass DataEvent {\n    /**\n     * @param eventType - One of: value, child_added, child_changed, child_moved, child_removed\n     * @param eventRegistration - The function to call to with the event data. User provided\n     * @param snapshot - The data backing the event\n     * @param prevName - Optional, the name of the previous child for child_* events.\n     */\n    constructor(eventType, eventRegistration, snapshot, prevName) {\n        this.eventType = eventType;\n        this.eventRegistration = eventRegistration;\n        this.snapshot = snapshot;\n        this.prevName = prevName;\n    }\n    getPath() {\n        const ref = this.snapshot.ref;\n        if (this.eventType === 'value') {\n            return ref._path;\n        }\n        else {\n            return ref.parent._path;\n        }\n    }\n    getEventType() {\n        return this.eventType;\n    }\n    getEventRunner() {\n        return this.eventRegistration.getEventRunner(this);\n    }\n    toString() {\n        return (this.getPath().toString() +\n            ':' +\n            this.eventType +\n            ':' +\n            stringify(this.snapshot.exportVal()));\n    }\n}\nclass CancelEvent {\n    constructor(eventRegistration, error, path) {\n        this.eventRegistration = eventRegistration;\n        this.error = error;\n        this.path = path;\n    }\n    getPath() {\n        return this.path;\n    }\n    getEventType() {\n        return 'cancel';\n    }\n    getEventRunner() {\n        return this.eventRegistration.getEventRunner(this);\n    }\n    toString() {\n        return this.path.toString() + ':cancel';\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 wrapper class that converts events from the database@exp SDK to the legacy\n * Database SDK. Events are not converted directly as event registration relies\n * on reference comparison of the original user callback (see `matches()`) and\n * relies on equality of the legacy SDK's `context` object.\n */\nclass CallbackContext {\n    constructor(snapshotCallback, cancelCallback) {\n        this.snapshotCallback = snapshotCallback;\n        this.cancelCallback = cancelCallback;\n    }\n    onValue(expDataSnapshot, previousChildName) {\n        this.snapshotCallback.call(null, expDataSnapshot, previousChildName);\n    }\n    onCancel(error) {\n        assert(this.hasCancelCallback, 'Raising a cancel event on a listener with no cancel callback');\n        return this.cancelCallback.call(null, error);\n    }\n    get hasCancelCallback() {\n        return !!this.cancelCallback;\n    }\n    matches(other) {\n        return (this.snapshotCallback === other.snapshotCallback ||\n            (this.snapshotCallback.userCallback !== undefined &&\n                this.snapshotCallback.userCallback ===\n                    other.snapshotCallback.userCallback &&\n                this.snapshotCallback.context === other.snapshotCallback.context));\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 `onDisconnect` class allows you to write or clear data when your client\n * disconnects from the Database server. These updates occur whether your\n * client disconnects cleanly or not, so you can rely on them to clean up data\n * even if a connection is dropped or a client crashes.\n *\n * The `onDisconnect` class is most commonly used to manage presence in\n * applications where it is useful to detect how many clients are connected and\n * when other clients disconnect. See\n * {@link https://firebase.google.com/docs/database/web/offline-capabilities | Enabling Offline Capabilities in JavaScript}\n * for more information.\n *\n * To avoid problems when a connection is dropped before the requests can be\n * transferred to the Database server, these functions should be called before\n * writing any data.\n *\n * Note that `onDisconnect` operations are only triggered once. If you want an\n * operation to occur each time a disconnect occurs, you'll need to re-establish\n * the `onDisconnect` operations each time you reconnect.\n */\nclass OnDisconnect {\n    /** @hideconstructor */\n    constructor(_repo, _path) {\n        this._repo = _repo;\n        this._path = _path;\n    }\n    /**\n     * Cancels all previously queued `onDisconnect()` set or update events for this\n     * location and all children.\n     *\n     * If a write has been queued for this location via a `set()` or `update()` at a\n     * parent location, the write at this location will be canceled, though writes\n     * to sibling locations will still occur.\n     *\n     * @returns Resolves when synchronization to the server is complete.\n     */\n    cancel() {\n        const deferred = new Deferred();\n        repoOnDisconnectCancel(this._repo, this._path, deferred.wrapCallback(() => { }));\n        return deferred.promise;\n    }\n    /**\n     * Ensures the data at this location is deleted when the client is disconnected\n     * (due to closing the browser, navigating to a new page, or network issues).\n     *\n     * @returns Resolves when synchronization to the server is complete.\n     */\n    remove() {\n        validateWritablePath('OnDisconnect.remove', this._path);\n        const deferred = new Deferred();\n        repoOnDisconnectSet(this._repo, this._path, null, deferred.wrapCallback(() => { }));\n        return deferred.promise;\n    }\n    /**\n     * Ensures the data at this location is set to the specified value when the\n     * client is disconnected (due to closing the browser, navigating to a new page,\n     * or network issues).\n     *\n     * `set()` is especially useful for implementing \"presence\" systems, where a\n     * value should be changed or cleared when a user disconnects so that they\n     * appear \"offline\" to other users. See\n     * {@link https://firebase.google.com/docs/database/web/offline-capabilities | Enabling Offline Capabilities in JavaScript}\n     * for more information.\n     *\n     * Note that `onDisconnect` operations are only triggered once. If you want an\n     * operation to occur each time a disconnect occurs, you'll need to re-establish\n     * the `onDisconnect` operations each time.\n     *\n     * @param value - The value to be written to this location on disconnect (can\n     * be an object, array, string, number, boolean, or null).\n     * @returns Resolves when synchronization to the Database is complete.\n     */\n    set(value) {\n        validateWritablePath('OnDisconnect.set', this._path);\n        validateFirebaseDataArg('OnDisconnect.set', value, this._path, false);\n        const deferred = new Deferred();\n        repoOnDisconnectSet(this._repo, this._path, value, deferred.wrapCallback(() => { }));\n        return deferred.promise;\n    }\n    /**\n     * Ensures the data at this location is set to the specified value and priority\n     * when the client is disconnected (due to closing the browser, navigating to a\n     * new page, or network issues).\n     *\n     * @param value - The value to be written to this location on disconnect (can\n     * be an object, array, string, number, boolean, or null).\n     * @param priority - The priority to be written (string, number, or null).\n     * @returns Resolves when synchronization to the Database is complete.\n     */\n    setWithPriority(value, priority) {\n        validateWritablePath('OnDisconnect.setWithPriority', this._path);\n        validateFirebaseDataArg('OnDisconnect.setWithPriority', value, this._path, false);\n        validatePriority('OnDisconnect.setWithPriority', priority, false);\n        const deferred = new Deferred();\n        repoOnDisconnectSetWithPriority(this._repo, this._path, value, priority, deferred.wrapCallback(() => { }));\n        return deferred.promise;\n    }\n    /**\n     * Writes multiple values at this location when the client is disconnected (due\n     * to closing the browser, navigating to a new page, or network issues).\n     *\n     * The `values` argument contains multiple property-value pairs that will be\n     * written to the Database together. Each child property can either be a simple\n     * property (for example, \"name\") or a relative path (for example, \"name/first\")\n     * from the current location to the data to update.\n     *\n     * As opposed to the `set()` method, `update()` can be use to selectively update\n     * only the referenced properties at the current location (instead of replacing\n     * all the child properties at the current location).\n     *\n     * @param values - Object containing multiple values.\n     * @returns Resolves when synchronization to the Database is complete.\n     */\n    update(values) {\n        validateWritablePath('OnDisconnect.update', this._path);\n        validateFirebaseMergeDataArg('OnDisconnect.update', values, this._path, false);\n        const deferred = new Deferred();\n        repoOnDisconnectUpdate(this._repo, this._path, values, deferred.wrapCallback(() => { }));\n        return deferred.promise;\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 * @internal\n */\nclass QueryImpl {\n    /**\n     * @hideconstructor\n     */\n    constructor(_repo, _path, _queryParams, _orderByCalled) {\n        this._repo = _repo;\n        this._path = _path;\n        this._queryParams = _queryParams;\n        this._orderByCalled = _orderByCalled;\n    }\n    get key() {\n        if (pathIsEmpty(this._path)) {\n            return null;\n        }\n        else {\n            return pathGetBack(this._path);\n        }\n    }\n    get ref() {\n        return new ReferenceImpl(this._repo, this._path);\n    }\n    get _queryIdentifier() {\n        const obj = queryParamsGetQueryObject(this._queryParams);\n        const id = ObjectToUniqueKey(obj);\n        return id === '{}' ? 'default' : id;\n    }\n    /**\n     * An object representation of the query parameters used by this Query.\n     */\n    get _queryObject() {\n        return queryParamsGetQueryObject(this._queryParams);\n    }\n    isEqual(other) {\n        other = getModularInstance(other);\n        if (!(other instanceof QueryImpl)) {\n            return false;\n        }\n        const sameRepo = this._repo === other._repo;\n        const samePath = pathEquals(this._path, other._path);\n        const sameQueryIdentifier = this._queryIdentifier === other._queryIdentifier;\n        return sameRepo && samePath && sameQueryIdentifier;\n    }\n    toJSON() {\n        return this.toString();\n    }\n    toString() {\n        return this._repo.toString() + pathToUrlEncodedString(this._path);\n    }\n}\n/**\n * Validates that no other order by call has been made\n */\nfunction validateNoPreviousOrderByCall(query, fnName) {\n    if (query._orderByCalled === true) {\n        throw new Error(fnName + \": You can't combine multiple orderBy calls.\");\n    }\n}\n/**\n * Validates start/end values for queries.\n */\nfunction validateQueryEndpoints(params) {\n    let startNode = null;\n    let endNode = null;\n    if (params.hasStart()) {\n        startNode = params.getIndexStartValue();\n    }\n    if (params.hasEnd()) {\n        endNode = params.getIndexEndValue();\n    }\n    if (params.getIndex() === KEY_INDEX) {\n        const tooManyArgsError = 'Query: When ordering by key, you may only pass one argument to ' +\n            'startAt(), endAt(), or equalTo().';\n        const wrongArgTypeError = 'Query: When ordering by key, the argument passed to startAt(), startAfter(), ' +\n            'endAt(), endBefore(), or equalTo() must be a string.';\n        if (params.hasStart()) {\n            const startName = params.getIndexStartName();\n            if (startName !== MIN_NAME) {\n                throw new Error(tooManyArgsError);\n            }\n            else if (typeof startNode !== 'string') {\n                throw new Error(wrongArgTypeError);\n            }\n        }\n        if (params.hasEnd()) {\n            const endName = params.getIndexEndName();\n            if (endName !== MAX_NAME) {\n                throw new Error(tooManyArgsError);\n            }\n            else if (typeof endNode !== 'string') {\n                throw new Error(wrongArgTypeError);\n            }\n        }\n    }\n    else if (params.getIndex() === PRIORITY_INDEX) {\n        if ((startNode != null && !isValidPriority(startNode)) ||\n            (endNode != null && !isValidPriority(endNode))) {\n            throw new Error('Query: When ordering by priority, the first argument passed to startAt(), ' +\n                'startAfter() endAt(), endBefore(), or equalTo() must be a valid priority value ' +\n                '(null, a number, or a string).');\n        }\n    }\n    else {\n        assert(params.getIndex() instanceof PathIndex ||\n            params.getIndex() === VALUE_INDEX, 'unknown index type.');\n        if ((startNode != null && typeof startNode === 'object') ||\n            (endNode != null && typeof endNode === 'object')) {\n            throw new Error('Query: First argument passed to startAt(), startAfter(), endAt(), endBefore(), or ' +\n                'equalTo() cannot be an object.');\n        }\n    }\n}\n/**\n * Validates that limit* has been called with the correct combination of parameters\n */\nfunction validateLimit(params) {\n    if (params.hasStart() &&\n        params.hasEnd() &&\n        params.hasLimit() &&\n        !params.hasAnchoredLimit()) {\n        throw new Error(\"Query: Can't combine startAt(), startAfter(), endAt(), endBefore(), and limit(). Use \" +\n            'limitToFirst() or limitToLast() instead.');\n    }\n}\n/**\n * @internal\n */\nclass ReferenceImpl extends QueryImpl {\n    /** @hideconstructor */\n    constructor(repo, path) {\n        super(repo, path, new QueryParams(), false);\n    }\n    get parent() {\n        const parentPath = pathParent(this._path);\n        return parentPath === null\n            ? null\n            : new ReferenceImpl(this._repo, parentPath);\n    }\n    get root() {\n        let ref = this;\n        while (ref.parent !== null) {\n            ref = ref.parent;\n        }\n        return ref;\n    }\n}\n/**\n * A `DataSnapshot` contains data from a Database location.\n *\n * Any time you read data from the Database, you receive the data as a\n * `DataSnapshot`. A `DataSnapshot` is passed to the event callbacks you attach\n * with `on()` or `once()`. You can extract the contents of the snapshot as a\n * JavaScript object by calling the `val()` method. Alternatively, you can\n * traverse into the snapshot by calling `child()` to return child snapshots\n * (which you could then call `val()` on).\n *\n * A `DataSnapshot` is an efficiently generated, immutable copy of the data at\n * a Database location. It cannot be modified and will never change (to modify\n * data, you always call the `set()` method on a `Reference` directly).\n */\nclass DataSnapshot {\n    /**\n     * @param _node - A SnapshotNode to wrap.\n     * @param ref - The location this snapshot came from.\n     * @param _index - The iteration order for this snapshot\n     * @hideconstructor\n     */\n    constructor(_node, \n    /**\n     * The location of this DataSnapshot.\n     */\n    ref, _index) {\n        this._node = _node;\n        this.ref = ref;\n        this._index = _index;\n    }\n    /**\n     * Gets the priority value of the data in this `DataSnapshot`.\n     *\n     * Applications need not use priority but can order collections by\n     * ordinary properties (see\n     * {@link https://firebase.google.com/docs/database/web/lists-of-data#sorting_and_filtering_data |Sorting and filtering data}\n     * ).\n     */\n    get priority() {\n        // typecast here because we never return deferred values or internal priorities (MAX_PRIORITY)\n        return this._node.getPriority().val();\n    }\n    /**\n     * The key (last part of the path) of the location of this `DataSnapshot`.\n     *\n     * The last token in a Database location is considered its key. For example,\n     * \"ada\" is the key for the /users/ada/ node. Accessing the key on any\n     * `DataSnapshot` will return the key for the location that generated it.\n     * However, accessing the key on the root URL of a Database will return\n     * `null`.\n     */\n    get key() {\n        return this.ref.key;\n    }\n    /** Returns the number of child properties of this `DataSnapshot`. */\n    get size() {\n        return this._node.numChildren();\n    }\n    /**\n     * Gets another `DataSnapshot` for the location at the specified relative path.\n     *\n     * Passing a relative path to the `child()` method of a DataSnapshot returns\n     * another `DataSnapshot` for the location at the specified relative path. The\n     * relative path can either be a simple child name (for example, \"ada\") or a\n     * deeper, slash-separated path (for example, \"ada/name/first\"). If the child\n     * location has no data, an empty `DataSnapshot` (that is, a `DataSnapshot`\n     * whose value is `null`) is returned.\n     *\n     * @param path - A relative path to the location of child data.\n     */\n    child(path) {\n        const childPath = new Path(path);\n        const childRef = child(this.ref, path);\n        return new DataSnapshot(this._node.getChild(childPath), childRef, PRIORITY_INDEX);\n    }\n    /**\n     * Returns true if this `DataSnapshot` contains any data. It is slightly more\n     * efficient than using `snapshot.val() !== null`.\n     */\n    exists() {\n        return !this._node.isEmpty();\n    }\n    /**\n     * Exports the entire contents of the DataSnapshot as a JavaScript object.\n     *\n     * The `exportVal()` method is similar to `val()`, except priority information\n     * is included (if available), making it suitable for backing up your data.\n     *\n     * @returns The DataSnapshot's contents as a JavaScript value (Object,\n     *   Array, string, number, boolean, or `null`).\n     */\n    // eslint-disable-next-line @typescript-eslint/no-explicit-any\n    exportVal() {\n        return this._node.val(true);\n    }\n    /**\n     * Enumerates the top-level children in the `IteratedDataSnapshot`.\n     *\n     * Because of the way JavaScript objects work, the ordering of data in the\n     * JavaScript object returned by `val()` is not guaranteed to match the\n     * ordering on the server nor the ordering of `onChildAdded()` events. That is\n     * where `forEach()` comes in handy. It guarantees the children of a\n     * `DataSnapshot` will be iterated in their query order.\n     *\n     * If no explicit `orderBy*()` method is used, results are returned\n     * ordered by key (unless priorities are used, in which case, results are\n     * returned by priority).\n     *\n     * @param action - A function that will be called for each child DataSnapshot.\n     * The callback can return true to cancel further enumeration.\n     * @returns true if enumeration was canceled due to your callback returning\n     * true.\n     */\n    forEach(action) {\n        if (this._node.isLeafNode()) {\n            return false;\n        }\n        const childrenNode = this._node;\n        // Sanitize the return value to a boolean. ChildrenNode.forEachChild has a weird return type...\n        return !!childrenNode.forEachChild(this._index, (key, node) => {\n            return action(new DataSnapshot(node, child(this.ref, key), PRIORITY_INDEX));\n        });\n    }\n    /**\n     * Returns true if the specified child path has (non-null) data.\n     *\n     * @param path - A relative path to the location of a potential child.\n     * @returns `true` if data exists at the specified child path; else\n     *  `false`.\n     */\n    hasChild(path) {\n        const childPath = new Path(path);\n        return !this._node.getChild(childPath).isEmpty();\n    }\n    /**\n     * Returns whether or not the `DataSnapshot` has any non-`null` child\n     * properties.\n     *\n     * You can use `hasChildren()` to determine if a `DataSnapshot` has any\n     * children. If it does, you can enumerate them using `forEach()`. If it\n     * doesn't, then either this snapshot contains a primitive value (which can be\n     * retrieved with `val()`) or it is empty (in which case, `val()` will return\n     * `null`).\n     *\n     * @returns true if this snapshot has any children; else false.\n     */\n    hasChildren() {\n        if (this._node.isLeafNode()) {\n            return false;\n        }\n        else {\n            return !this._node.isEmpty();\n        }\n    }\n    /**\n     * Returns a JSON-serializable representation of this object.\n     */\n    toJSON() {\n        return this.exportVal();\n    }\n    /**\n     * Extracts a JavaScript value from a `DataSnapshot`.\n     *\n     * Depending on the data in a `DataSnapshot`, the `val()` method may return a\n     * scalar type (string, number, or boolean), an array, or an object. It may\n     * also return null, indicating that the `DataSnapshot` is empty (contains no\n     * data).\n     *\n     * @returns The DataSnapshot's contents as a JavaScript value (Object,\n     *   Array, string, number, boolean, or `null`).\n     */\n    // eslint-disable-next-line @typescript-eslint/no-explicit-any\n    val() {\n        return this._node.val();\n    }\n}\n/**\n *\n * Returns a `Reference` representing the location in the Database\n * corresponding to the provided path. If no path is provided, the `Reference`\n * will point to the root of the Database.\n *\n * @param db - The database instance to obtain a reference for.\n * @param path - Optional path representing the location the returned\n *   `Reference` will point. If not provided, the returned `Reference` will\n *   point to the root of the Database.\n * @returns If a path is provided, a `Reference`\n *   pointing to the provided path. Otherwise, a `Reference` pointing to the\n *   root of the Database.\n */\nfunction ref(db, path) {\n    db = getModularInstance(db);\n    db._checkNotDeleted('ref');\n    return path !== undefined ? child(db._root, path) : db._root;\n}\n/**\n * Returns a `Reference` representing the location in the Database\n * corresponding to the provided Firebase URL.\n *\n * An exception is thrown if the URL is not a valid Firebase Database URL or it\n * has a different domain than the current `Database` instance.\n *\n * Note that all query parameters (`orderBy`, `limitToLast`, etc.) are ignored\n * and are not applied to the returned `Reference`.\n *\n * @param db - The database instance to obtain a reference for.\n * @param url - The Firebase URL at which the returned `Reference` will\n *   point.\n * @returns A `Reference` pointing to the provided\n *   Firebase URL.\n */\nfunction refFromURL(db, url) {\n    db = getModularInstance(db);\n    db._checkNotDeleted('refFromURL');\n    const parsedURL = parseRepoInfo(url, db._repo.repoInfo_.nodeAdmin);\n    validateUrl('refFromURL', parsedURL);\n    const repoInfo = parsedURL.repoInfo;\n    if (!db._repo.repoInfo_.isCustomHost() &&\n        repoInfo.host !== db._repo.repoInfo_.host) {\n        fatal('refFromURL' +\n            ': Host name does not match the current database: ' +\n            '(found ' +\n            repoInfo.host +\n            ' but expected ' +\n            db._repo.repoInfo_.host +\n            ')');\n    }\n    return ref(db, parsedURL.path.toString());\n}\n/**\n * Gets a `Reference` for the location at the specified relative path.\n *\n * The relative path can either be a simple child name (for example, \"ada\") or\n * a deeper slash-separated path (for example, \"ada/name/first\").\n *\n * @param parent - The parent location.\n * @param path - A relative path from this location to the desired child\n *   location.\n * @returns The specified child location.\n */\nfunction child(parent, path) {\n    parent = getModularInstance(parent);\n    if (pathGetFront(parent._path) === null) {\n        validateRootPathString('child', 'path', path, false);\n    }\n    else {\n        validatePathString('child', 'path', path, false);\n    }\n    return new ReferenceImpl(parent._repo, pathChild(parent._path, path));\n}\n/**\n * Returns an `OnDisconnect` object - see\n * {@link https://firebase.google.com/docs/database/web/offline-capabilities | Enabling Offline Capabilities in JavaScript}\n * for more information on how to use it.\n *\n * @param ref - The reference to add OnDisconnect triggers for.\n */\nfunction onDisconnect(ref) {\n    ref = getModularInstance(ref);\n    return new OnDisconnect(ref._repo, ref._path);\n}\n/**\n * Generates a new child location using a unique key and returns its\n * `Reference`.\n *\n * This is the most common pattern for adding data to a collection of items.\n *\n * If you provide a value to `push()`, the value is written to the\n * generated location. If you don't pass a value, nothing is written to the\n * database and the child remains empty (but you can use the `Reference`\n * elsewhere).\n *\n * The unique keys generated by `push()` are ordered by the current time, so the\n * resulting list of items is chronologically sorted. The keys are also\n * designed to be unguessable (they contain 72 random bits of entropy).\n *\n * See {@link https://firebase.google.com/docs/database/web/lists-of-data#append_to_a_list_of_data | Append to a list of data}.\n * See {@link https://firebase.googleblog.com/2015/02/the-2120-ways-to-ensure-unique_68.html | The 2^120 Ways to Ensure Unique Identifiers}.\n *\n * @param parent - The parent location.\n * @param value - Optional value to be written at the generated location.\n * @returns Combined `Promise` and `Reference`; resolves when write is complete,\n * but can be used immediately as the `Reference` to the child location.\n */\nfunction push(parent, value) {\n    parent = getModularInstance(parent);\n    validateWritablePath('push', parent._path);\n    validateFirebaseDataArg('push', value, parent._path, true);\n    const now = repoServerTime(parent._repo);\n    const name = nextPushId(now);\n    // push() returns a ThennableReference whose promise is fulfilled with a\n    // regular Reference. We use child() to create handles to two different\n    // references. The first is turned into a ThennableReference below by adding\n    // then() and catch() methods and is used as the return value of push(). The\n    // second remains a regular Reference and is used as the fulfilled value of\n    // the first ThennableReference.\n    const thenablePushRef = child(parent, name);\n    const pushRef = child(parent, name);\n    let promise;\n    if (value != null) {\n        promise = set(pushRef, value).then(() => pushRef);\n    }\n    else {\n        promise = Promise.resolve(pushRef);\n    }\n    thenablePushRef.then = promise.then.bind(promise);\n    thenablePushRef.catch = promise.then.bind(promise, undefined);\n    return thenablePushRef;\n}\n/**\n * Removes the data at this Database location.\n *\n * Any data at child locations will also be deleted.\n *\n * The effect of the remove will be visible immediately and the corresponding\n * event 'value' will be triggered. Synchronization of the remove to the\n * Firebase servers will also be started, and the returned Promise will resolve\n * when complete. If provided, the onComplete callback will be called\n * asynchronously after synchronization has finished.\n *\n * @param ref - The location to remove.\n * @returns Resolves when remove on server is complete.\n */\nfunction remove(ref) {\n    validateWritablePath('remove', ref._path);\n    return set(ref, null);\n}\n/**\n * Writes data to this Database location.\n *\n * This will overwrite any data at this location and all child locations.\n *\n * The effect of the write will be visible immediately, and the corresponding\n * events (\"value\", \"child_added\", etc.) will be triggered. Synchronization of\n * the data to the Firebase servers will also be started, and the returned\n * Promise will resolve when complete. If provided, the `onComplete` callback\n * will be called asynchronously after synchronization has finished.\n *\n * Passing `null` for the new value is equivalent to calling `remove()`; namely,\n * all data at this location and all child locations will be deleted.\n *\n * `set()` will remove any priority stored at this location, so if priority is\n * meant to be preserved, you need to use `setWithPriority()` instead.\n *\n * Note that modifying data with `set()` will cancel any pending transactions\n * at that location, so extreme care should be taken if mixing `set()` and\n * `transaction()` to modify the same data.\n *\n * A single `set()` will generate a single \"value\" event at the location where\n * the `set()` was performed.\n *\n * @param ref - The location to write to.\n * @param value - The value to be written (string, number, boolean, object,\n *   array, or null).\n * @returns Resolves when write to server is complete.\n */\nfunction set(ref, value) {\n    ref = getModularInstance(ref);\n    validateWritablePath('set', ref._path);\n    validateFirebaseDataArg('set', value, ref._path, false);\n    const deferred = new Deferred();\n    repoSetWithPriority(ref._repo, ref._path, value, \n    /*priority=*/ null, deferred.wrapCallback(() => { }));\n    return deferred.promise;\n}\n/**\n * Sets a priority for the data at this Database location.\n *\n * Applications need not use priority but can order collections by\n * ordinary properties (see\n * {@link https://firebase.google.com/docs/database/web/lists-of-data#sorting_and_filtering_data | Sorting and filtering data}\n * ).\n *\n * @param ref - The location to write to.\n * @param priority - The priority to be written (string, number, or null).\n * @returns Resolves when write to server is complete.\n */\nfunction setPriority(ref, priority) {\n    ref = getModularInstance(ref);\n    validateWritablePath('setPriority', ref._path);\n    validatePriority('setPriority', priority, false);\n    const deferred = new Deferred();\n    repoSetWithPriority(ref._repo, pathChild(ref._path, '.priority'), priority, null, deferred.wrapCallback(() => { }));\n    return deferred.promise;\n}\n/**\n * Writes data the Database location. Like `set()` but also specifies the\n * priority for that data.\n *\n * Applications need not use priority but can order collections by\n * ordinary properties (see\n * {@link https://firebase.google.com/docs/database/web/lists-of-data#sorting_and_filtering_data | Sorting and filtering data}\n * ).\n *\n * @param ref - The location to write to.\n * @param value - The value to be written (string, number, boolean, object,\n *   array, or null).\n * @param priority - The priority to be written (string, number, or null).\n * @returns Resolves when write to server is complete.\n */\nfunction setWithPriority(ref, value, priority) {\n    validateWritablePath('setWithPriority', ref._path);\n    validateFirebaseDataArg('setWithPriority', value, ref._path, false);\n    validatePriority('setWithPriority', priority, false);\n    if (ref.key === '.length' || ref.key === '.keys') {\n        throw 'setWithPriority failed: ' + ref.key + ' is a read-only object.';\n    }\n    const deferred = new Deferred();\n    repoSetWithPriority(ref._repo, ref._path, value, priority, deferred.wrapCallback(() => { }));\n    return deferred.promise;\n}\n/**\n * Writes multiple values to the Database at once.\n *\n * The `values` argument contains multiple property-value pairs that will be\n * written to the Database together. Each child property can either be a simple\n * property (for example, \"name\") or a relative path (for example,\n * \"name/first\") from the current location to the data to update.\n *\n * As opposed to the `set()` method, `update()` can be use to selectively update\n * only the referenced properties at the current location (instead of replacing\n * all the child properties at the current location).\n *\n * The effect of the write will be visible immediately, and the corresponding\n * events ('value', 'child_added', etc.) will be triggered. Synchronization of\n * the data to the Firebase servers will also be started, and the returned\n * Promise will resolve when complete. If provided, the `onComplete` callback\n * will be called asynchronously after synchronization has finished.\n *\n * A single `update()` will generate a single \"value\" event at the location\n * where the `update()` was performed, regardless of how many children were\n * modified.\n *\n * Note that modifying data with `update()` will cancel any pending\n * transactions at that location, so extreme care should be taken if mixing\n * `update()` and `transaction()` to modify the same data.\n *\n * Passing `null` to `update()` will remove the data at this location.\n *\n * See\n * {@link https://firebase.googleblog.com/2015/09/introducing-multi-location-updates-and_86.html | Introducing multi-location updates and more}.\n *\n * @param ref - The location to write to.\n * @param values - Object containing multiple values.\n * @returns Resolves when update on server is complete.\n */\nfunction update(ref, values) {\n    validateFirebaseMergeDataArg('update', values, ref._path, false);\n    const deferred = new Deferred();\n    repoUpdate(ref._repo, ref._path, values, deferred.wrapCallback(() => { }));\n    return deferred.promise;\n}\n/**\n * Gets the most up-to-date result for this query.\n *\n * @param query - The query to run.\n * @returns A `Promise` which resolves to the resulting DataSnapshot if a value is\n * available, or rejects if the client is unable to return a value (e.g., if the\n * server is unreachable and there is nothing cached).\n */\nfunction get(query) {\n    query = getModularInstance(query);\n    const callbackContext = new CallbackContext(() => { });\n    const container = new ValueEventRegistration(callbackContext);\n    return repoGetValue(query._repo, query, container).then(node => {\n        return new DataSnapshot(node, new ReferenceImpl(query._repo, query._path), query._queryParams.getIndex());\n    });\n}\n/**\n * Represents registration for 'value' events.\n */\nclass ValueEventRegistration {\n    constructor(callbackContext) {\n        this.callbackContext = callbackContext;\n    }\n    respondsTo(eventType) {\n        return eventType === 'value';\n    }\n    createEvent(change, query) {\n        const index = query._queryParams.getIndex();\n        return new DataEvent('value', this, new DataSnapshot(change.snapshotNode, new ReferenceImpl(query._repo, query._path), index));\n    }\n    getEventRunner(eventData) {\n        if (eventData.getEventType() === 'cancel') {\n            return () => this.callbackContext.onCancel(eventData.error);\n        }\n        else {\n            return () => this.callbackContext.onValue(eventData.snapshot, null);\n        }\n    }\n    createCancelEvent(error, path) {\n        if (this.callbackContext.hasCancelCallback) {\n            return new CancelEvent(this, error, path);\n        }\n        else {\n            return null;\n        }\n    }\n    matches(other) {\n        if (!(other instanceof ValueEventRegistration)) {\n            return false;\n        }\n        else if (!other.callbackContext || !this.callbackContext) {\n            // If no callback specified, we consider it to match any callback.\n            return true;\n        }\n        else {\n            return other.callbackContext.matches(this.callbackContext);\n        }\n    }\n    hasAnyCallback() {\n        return this.callbackContext !== null;\n    }\n}\n/**\n * Represents the registration of a child_x event.\n */\nclass ChildEventRegistration {\n    constructor(eventType, callbackContext) {\n        this.eventType = eventType;\n        this.callbackContext = callbackContext;\n    }\n    respondsTo(eventType) {\n        let eventToCheck = eventType === 'children_added' ? 'child_added' : eventType;\n        eventToCheck =\n            eventToCheck === 'children_removed' ? 'child_removed' : eventToCheck;\n        return this.eventType === eventToCheck;\n    }\n    createCancelEvent(error, path) {\n        if (this.callbackContext.hasCancelCallback) {\n            return new CancelEvent(this, error, path);\n        }\n        else {\n            return null;\n        }\n    }\n    createEvent(change, query) {\n        assert(change.childName != null, 'Child events should have a childName.');\n        const childRef = child(new ReferenceImpl(query._repo, query._path), change.childName);\n        const index = query._queryParams.getIndex();\n        return new DataEvent(change.type, this, new DataSnapshot(change.snapshotNode, childRef, index), change.prevName);\n    }\n    getEventRunner(eventData) {\n        if (eventData.getEventType() === 'cancel') {\n            return () => this.callbackContext.onCancel(eventData.error);\n        }\n        else {\n            return () => this.callbackContext.onValue(eventData.snapshot, eventData.prevName);\n        }\n    }\n    matches(other) {\n        if (other instanceof ChildEventRegistration) {\n            return (this.eventType === other.eventType &&\n                (!this.callbackContext ||\n                    !other.callbackContext ||\n                    this.callbackContext.matches(other.callbackContext)));\n        }\n        return false;\n    }\n    hasAnyCallback() {\n        return !!this.callbackContext;\n    }\n}\nfunction addEventListener(query, eventType, callback, cancelCallbackOrListenOptions, options) {\n    let cancelCallback;\n    if (typeof cancelCallbackOrListenOptions === 'object') {\n        cancelCallback = undefined;\n        options = cancelCallbackOrListenOptions;\n    }\n    if (typeof cancelCallbackOrListenOptions === 'function') {\n        cancelCallback = cancelCallbackOrListenOptions;\n    }\n    if (options && options.onlyOnce) {\n        const userCallback = callback;\n        const onceCallback = (dataSnapshot, previousChildName) => {\n            repoRemoveEventCallbackForQuery(query._repo, query, container);\n            userCallback(dataSnapshot, previousChildName);\n        };\n        onceCallback.userCallback = callback.userCallback;\n        onceCallback.context = callback.context;\n        callback = onceCallback;\n    }\n    const callbackContext = new CallbackContext(callback, cancelCallback || undefined);\n    const container = eventType === 'value'\n        ? new ValueEventRegistration(callbackContext)\n        : new ChildEventRegistration(eventType, callbackContext);\n    repoAddEventCallbackForQuery(query._repo, query, container);\n    return () => repoRemoveEventCallbackForQuery(query._repo, query, container);\n}\nfunction onValue(query, callback, cancelCallbackOrListenOptions, options) {\n    return addEventListener(query, 'value', callback, cancelCallbackOrListenOptions, options);\n}\nfunction onChildAdded(query, callback, cancelCallbackOrListenOptions, options) {\n    return addEventListener(query, 'child_added', callback, cancelCallbackOrListenOptions, options);\n}\nfunction onChildChanged(query, callback, cancelCallbackOrListenOptions, options) {\n    return addEventListener(query, 'child_changed', callback, cancelCallbackOrListenOptions, options);\n}\nfunction onChildMoved(query, callback, cancelCallbackOrListenOptions, options) {\n    return addEventListener(query, 'child_moved', callback, cancelCallbackOrListenOptions, options);\n}\nfunction onChildRemoved(query, callback, cancelCallbackOrListenOptions, options) {\n    return addEventListener(query, 'child_removed', callback, cancelCallbackOrListenOptions, options);\n}\n/**\n * Detaches a callback previously attached with the corresponding `on*()` (`onValue`, `onChildAdded`) listener.\n * Note: This is not the recommended way to remove a listener. Instead, please use the returned callback function from\n * the respective `on*` callbacks.\n *\n * Detach a callback previously attached with `on*()`. Calling `off()` on a parent listener\n * will not automatically remove listeners registered on child nodes, `off()`\n * must also be called on any child listeners to remove the callback.\n *\n * If a callback is not specified, all callbacks for the specified eventType\n * will be removed. Similarly, if no eventType is specified, all callbacks\n * for the `Reference` will be removed.\n *\n * Individual listeners can also be removed by invoking their unsubscribe\n * callbacks.\n *\n * @param query - The query that the listener was registered with.\n * @param eventType - One of the following strings: \"value\", \"child_added\",\n * \"child_changed\", \"child_removed\", or \"child_moved.\" If omitted, all callbacks\n * for the `Reference` will be removed.\n * @param callback - The callback function that was passed to `on()` or\n * `undefined` to remove all callbacks.\n */\nfunction off(query, eventType, callback) {\n    let container = null;\n    const expCallback = callback ? new CallbackContext(callback) : null;\n    if (eventType === 'value') {\n        container = new ValueEventRegistration(expCallback);\n    }\n    else if (eventType) {\n        container = new ChildEventRegistration(eventType, expCallback);\n    }\n    repoRemoveEventCallbackForQuery(query._repo, query, container);\n}\n/**\n * A `QueryConstraint` is used to narrow the set of documents returned by a\n * Database query. `QueryConstraint`s are created by invoking {@link endAt},\n * {@link endBefore}, {@link startAt}, {@link startAfter}, {@link\n * limitToFirst}, {@link limitToLast}, {@link orderByChild},\n * {@link orderByChild}, {@link orderByKey} , {@link orderByPriority} ,\n * {@link orderByValue}  or {@link equalTo} and\n * can then be passed to {@link query} to create a new query instance that\n * also contains this `QueryConstraint`.\n */\nclass QueryConstraint {\n}\nclass QueryEndAtConstraint extends QueryConstraint {\n    constructor(_value, _key) {\n        super();\n        this._value = _value;\n        this._key = _key;\n        this.type = 'endAt';\n    }\n    _apply(query) {\n        validateFirebaseDataArg('endAt', this._value, query._path, true);\n        const newParams = queryParamsEndAt(query._queryParams, this._value, this._key);\n        validateLimit(newParams);\n        validateQueryEndpoints(newParams);\n        if (query._queryParams.hasEnd()) {\n            throw new Error('endAt: Starting point was already set (by another call to endAt, ' +\n                'endBefore or equalTo).');\n        }\n        return new QueryImpl(query._repo, query._path, newParams, query._orderByCalled);\n    }\n}\n/**\n * Creates a `QueryConstraint` with the specified ending point.\n *\n * Using `startAt()`, `startAfter()`, `endBefore()`, `endAt()` and `equalTo()`\n * allows you to choose arbitrary starting and ending points for your queries.\n *\n * The ending point is inclusive, so children with exactly the specified value\n * will be included in the query. The optional key argument can be used to\n * further limit the range of the query. If it is specified, then children that\n * have exactly the specified value must also have a key name less than or equal\n * to the specified key.\n *\n * You can read more about `endAt()` in\n * {@link https://firebase.google.com/docs/database/web/lists-of-data#filtering_data | Filtering data}.\n *\n * @param value - The value to end at. The argument type depends on which\n * `orderBy*()` function was used in this query. Specify a value that matches\n * the `orderBy*()` type. When used in combination with `orderByKey()`, the\n * value must be a string.\n * @param key - The child key to end at, among the children with the previously\n * specified priority. This argument is only allowed if ordering by child,\n * value, or priority.\n */\nfunction endAt(value, key) {\n    validateKey('endAt', 'key', key, true);\n    return new QueryEndAtConstraint(value, key);\n}\nclass QueryEndBeforeConstraint extends QueryConstraint {\n    constructor(_value, _key) {\n        super();\n        this._value = _value;\n        this._key = _key;\n        this.type = 'endBefore';\n    }\n    _apply(query) {\n        validateFirebaseDataArg('endBefore', this._value, query._path, false);\n        const newParams = queryParamsEndBefore(query._queryParams, this._value, this._key);\n        validateLimit(newParams);\n        validateQueryEndpoints(newParams);\n        if (query._queryParams.hasEnd()) {\n            throw new Error('endBefore: Starting point was already set (by another call to endAt, ' +\n                'endBefore or equalTo).');\n        }\n        return new QueryImpl(query._repo, query._path, newParams, query._orderByCalled);\n    }\n}\n/**\n * Creates a `QueryConstraint` with the specified ending point (exclusive).\n *\n * Using `startAt()`, `startAfter()`, `endBefore()`, `endAt()` and `equalTo()`\n * allows you to choose arbitrary starting and ending points for your queries.\n *\n * The ending point is exclusive. If only a value is provided, children\n * with a value less than the specified value will be included in the query.\n * If a key is specified, then children must have a value less than or equal\n * to the specified value and a key name less than the specified key.\n *\n * @param value - The value to end before. The argument type depends on which\n * `orderBy*()` function was used in this query. Specify a value that matches\n * the `orderBy*()` type. When used in combination with `orderByKey()`, the\n * value must be a string.\n * @param key - The child key to end before, among the children with the\n * previously specified priority. This argument is only allowed if ordering by\n * child, value, or priority.\n */\nfunction endBefore(value, key) {\n    validateKey('endBefore', 'key', key, true);\n    return new QueryEndBeforeConstraint(value, key);\n}\nclass QueryStartAtConstraint extends QueryConstraint {\n    constructor(_value, _key) {\n        super();\n        this._value = _value;\n        this._key = _key;\n        this.type = 'startAt';\n    }\n    _apply(query) {\n        validateFirebaseDataArg('startAt', this._value, query._path, true);\n        const newParams = queryParamsStartAt(query._queryParams, this._value, this._key);\n        validateLimit(newParams);\n        validateQueryEndpoints(newParams);\n        if (query._queryParams.hasStart()) {\n            throw new Error('startAt: Starting point was already set (by another call to startAt, ' +\n                'startBefore or equalTo).');\n        }\n        return new QueryImpl(query._repo, query._path, newParams, query._orderByCalled);\n    }\n}\n/**\n * Creates a `QueryConstraint` with the specified starting point.\n *\n * Using `startAt()`, `startAfter()`, `endBefore()`, `endAt()` and `equalTo()`\n * allows you to choose arbitrary starting and ending points for your queries.\n *\n * The starting point is inclusive, so children with exactly the specified value\n * will be included in the query. The optional key argument can be used to\n * further limit the range of the query. If it is specified, then children that\n * have exactly the specified value must also have a key name greater than or\n * equal to the specified key.\n *\n * You can read more about `startAt()` in\n * {@link https://firebase.google.com/docs/database/web/lists-of-data#filtering_data | Filtering data}.\n *\n * @param value - The value to start at. The argument type depends on which\n * `orderBy*()` function was used in this query. Specify a value that matches\n * the `orderBy*()` type. When used in combination with `orderByKey()`, the\n * value must be a string.\n * @param key - The child key to start at. This argument is only allowed if\n * ordering by child, value, or priority.\n */\nfunction startAt(value = null, key) {\n    validateKey('startAt', 'key', key, true);\n    return new QueryStartAtConstraint(value, key);\n}\nclass QueryStartAfterConstraint extends QueryConstraint {\n    constructor(_value, _key) {\n        super();\n        this._value = _value;\n        this._key = _key;\n        this.type = 'startAfter';\n    }\n    _apply(query) {\n        validateFirebaseDataArg('startAfter', this._value, query._path, false);\n        const newParams = queryParamsStartAfter(query._queryParams, this._value, this._key);\n        validateLimit(newParams);\n        validateQueryEndpoints(newParams);\n        if (query._queryParams.hasStart()) {\n            throw new Error('startAfter: Starting point was already set (by another call to startAt, ' +\n                'startAfter, or equalTo).');\n        }\n        return new QueryImpl(query._repo, query._path, newParams, query._orderByCalled);\n    }\n}\n/**\n * Creates a `QueryConstraint` with the specified starting point (exclusive).\n *\n * Using `startAt()`, `startAfter()`, `endBefore()`, `endAt()` and `equalTo()`\n * allows you to choose arbitrary starting and ending points for your queries.\n *\n * The starting point is exclusive. If only a value is provided, children\n * with a value greater than the specified value will be included in the query.\n * If a key is specified, then children must have a value greater than or equal\n * to the specified value and a a key name greater than the specified key.\n *\n * @param value - The value to start after. The argument type depends on which\n * `orderBy*()` function was used in this query. Specify a value that matches\n * the `orderBy*()` type. When used in combination with `orderByKey()`, the\n * value must be a string.\n * @param key - The child key to start after. This argument is only allowed if\n * ordering by child, value, or priority.\n */\nfunction startAfter(value, key) {\n    validateKey('startAfter', 'key', key, true);\n    return new QueryStartAfterConstraint(value, key);\n}\nclass QueryLimitToFirstConstraint extends QueryConstraint {\n    constructor(_limit) {\n        super();\n        this._limit = _limit;\n        this.type = 'limitToFirst';\n    }\n    _apply(query) {\n        if (query._queryParams.hasLimit()) {\n            throw new Error('limitToFirst: Limit was already set (by another call to limitToFirst ' +\n                'or limitToLast).');\n        }\n        return new QueryImpl(query._repo, query._path, queryParamsLimitToFirst(query._queryParams, this._limit), query._orderByCalled);\n    }\n}\n/**\n * Creates a new `QueryConstraint` that if limited to the first specific number\n * of children.\n *\n * The `limitToFirst()` method is used to set a maximum number of children to be\n * synced for a given callback. If we set a limit of 100, we will initially only\n * receive up to 100 `child_added` events. If we have fewer than 100 messages\n * stored in our Database, a `child_added` event will fire for each message.\n * However, if we have over 100 messages, we will only receive a `child_added`\n * event for the first 100 ordered messages. As items change, we will receive\n * `child_removed` events for each item that drops out of the active list so\n * that the total number stays at 100.\n *\n * You can read more about `limitToFirst()` in\n * {@link https://firebase.google.com/docs/database/web/lists-of-data#filtering_data | Filtering data}.\n *\n * @param limit - The maximum number of nodes to include in this query.\n */\nfunction limitToFirst(limit) {\n    if (typeof limit !== 'number' || Math.floor(limit) !== limit || limit <= 0) {\n        throw new Error('limitToFirst: First argument must be a positive integer.');\n    }\n    return new QueryLimitToFirstConstraint(limit);\n}\nclass QueryLimitToLastConstraint extends QueryConstraint {\n    constructor(_limit) {\n        super();\n        this._limit = _limit;\n        this.type = 'limitToLast';\n    }\n    _apply(query) {\n        if (query._queryParams.hasLimit()) {\n            throw new Error('limitToLast: Limit was already set (by another call to limitToFirst ' +\n                'or limitToLast).');\n        }\n        return new QueryImpl(query._repo, query._path, queryParamsLimitToLast(query._queryParams, this._limit), query._orderByCalled);\n    }\n}\n/**\n * Creates a new `QueryConstraint` that is limited to return only the last\n * specified number of children.\n *\n * The `limitToLast()` method is used to set a maximum number of children to be\n * synced for a given callback. If we set a limit of 100, we will initially only\n * receive up to 100 `child_added` events. If we have fewer than 100 messages\n * stored in our Database, a `child_added` event will fire for each message.\n * However, if we have over 100 messages, we will only receive a `child_added`\n * event for the last 100 ordered messages. As items change, we will receive\n * `child_removed` events for each item that drops out of the active list so\n * that the total number stays at 100.\n *\n * You can read more about `limitToLast()` in\n * {@link https://firebase.google.com/docs/database/web/lists-of-data#filtering_data | Filtering data}.\n *\n * @param limit - The maximum number of nodes to include in this query.\n */\nfunction limitToLast(limit) {\n    if (typeof limit !== 'number' || Math.floor(limit) !== limit || limit <= 0) {\n        throw new Error('limitToLast: First argument must be a positive integer.');\n    }\n    return new QueryLimitToLastConstraint(limit);\n}\nclass QueryOrderByChildConstraint extends QueryConstraint {\n    constructor(_path) {\n        super();\n        this._path = _path;\n        this.type = 'orderByChild';\n    }\n    _apply(query) {\n        validateNoPreviousOrderByCall(query, 'orderByChild');\n        const parsedPath = new Path(this._path);\n        if (pathIsEmpty(parsedPath)) {\n            throw new Error('orderByChild: cannot pass in empty path. Use orderByValue() instead.');\n        }\n        const index = new PathIndex(parsedPath);\n        const newParams = queryParamsOrderBy(query._queryParams, index);\n        validateQueryEndpoints(newParams);\n        return new QueryImpl(query._repo, query._path, newParams, \n        /*orderByCalled=*/ true);\n    }\n}\n/**\n * Creates a new `QueryConstraint` that orders by the specified child key.\n *\n * Queries can only order by one key at a time. Calling `orderByChild()`\n * multiple times on the same query is an error.\n *\n * Firebase queries allow you to order your data by any child key on the fly.\n * However, if you know in advance what your indexes will be, you can define\n * them via the .indexOn rule in your Security Rules for better performance. See\n * the{@link https://firebase.google.com/docs/database/security/indexing-data}\n * rule for more information.\n *\n * You can read more about `orderByChild()` in\n * {@link https://firebase.google.com/docs/database/web/lists-of-data#sort_data | Sort data}.\n *\n * @param path - The path to order by.\n */\nfunction orderByChild(path) {\n    if (path === '$key') {\n        throw new Error('orderByChild: \"$key\" is invalid.  Use orderByKey() instead.');\n    }\n    else if (path === '$priority') {\n        throw new Error('orderByChild: \"$priority\" is invalid.  Use orderByPriority() instead.');\n    }\n    else if (path === '$value') {\n        throw new Error('orderByChild: \"$value\" is invalid.  Use orderByValue() instead.');\n    }\n    validatePathString('orderByChild', 'path', path, false);\n    return new QueryOrderByChildConstraint(path);\n}\nclass QueryOrderByKeyConstraint extends QueryConstraint {\n    constructor() {\n        super(...arguments);\n        this.type = 'orderByKey';\n    }\n    _apply(query) {\n        validateNoPreviousOrderByCall(query, 'orderByKey');\n        const newParams = queryParamsOrderBy(query._queryParams, KEY_INDEX);\n        validateQueryEndpoints(newParams);\n        return new QueryImpl(query._repo, query._path, newParams, \n        /*orderByCalled=*/ true);\n    }\n}\n/**\n * Creates a new `QueryConstraint` that orders by the key.\n *\n * Sorts the results of a query by their (ascending) key values.\n *\n * You can read more about `orderByKey()` in\n * {@link https://firebase.google.com/docs/database/web/lists-of-data#sort_data | Sort data}.\n */\nfunction orderByKey() {\n    return new QueryOrderByKeyConstraint();\n}\nclass QueryOrderByPriorityConstraint extends QueryConstraint {\n    constructor() {\n        super(...arguments);\n        this.type = 'orderByPriority';\n    }\n    _apply(query) {\n        validateNoPreviousOrderByCall(query, 'orderByPriority');\n        const newParams = queryParamsOrderBy(query._queryParams, PRIORITY_INDEX);\n        validateQueryEndpoints(newParams);\n        return new QueryImpl(query._repo, query._path, newParams, \n        /*orderByCalled=*/ true);\n    }\n}\n/**\n * Creates a new `QueryConstraint` that orders by priority.\n *\n * Applications need not use priority but can order collections by\n * ordinary properties (see\n * {@link https://firebase.google.com/docs/database/web/lists-of-data#sort_data | Sort data}\n * for alternatives to priority.\n */\nfunction orderByPriority() {\n    return new QueryOrderByPriorityConstraint();\n}\nclass QueryOrderByValueConstraint extends QueryConstraint {\n    constructor() {\n        super(...arguments);\n        this.type = 'orderByValue';\n    }\n    _apply(query) {\n        validateNoPreviousOrderByCall(query, 'orderByValue');\n        const newParams = queryParamsOrderBy(query._queryParams, VALUE_INDEX);\n        validateQueryEndpoints(newParams);\n        return new QueryImpl(query._repo, query._path, newParams, \n        /*orderByCalled=*/ true);\n    }\n}\n/**\n * Creates a new `QueryConstraint` that orders by value.\n *\n * If the children of a query are all scalar values (string, number, or\n * boolean), you can order the results by their (ascending) values.\n *\n * You can read more about `orderByValue()` in\n * {@link https://firebase.google.com/docs/database/web/lists-of-data#sort_data | Sort data}.\n */\nfunction orderByValue() {\n    return new QueryOrderByValueConstraint();\n}\nclass QueryEqualToValueConstraint extends QueryConstraint {\n    constructor(_value, _key) {\n        super();\n        this._value = _value;\n        this._key = _key;\n        this.type = 'equalTo';\n    }\n    _apply(query) {\n        validateFirebaseDataArg('equalTo', this._value, query._path, false);\n        if (query._queryParams.hasStart()) {\n            throw new Error('equalTo: Starting point was already set (by another call to startAt/startAfter or ' +\n                'equalTo).');\n        }\n        if (query._queryParams.hasEnd()) {\n            throw new Error('equalTo: Ending point was already set (by another call to endAt/endBefore or ' +\n                'equalTo).');\n        }\n        return new QueryEndAtConstraint(this._value, this._key)._apply(new QueryStartAtConstraint(this._value, this._key)._apply(query));\n    }\n}\n/**\n * Creates a `QueryConstraint` that includes children that match the specified\n * value.\n *\n * Using `startAt()`, `startAfter()`, `endBefore()`, `endAt()` and `equalTo()`\n * allows you to choose arbitrary starting and ending points for your queries.\n *\n * The optional key argument can be used to further limit the range of the\n * query. If it is specified, then children that have exactly the specified\n * value must also have exactly the specified key as their key name. This can be\n * used to filter result sets with many matches for the same value.\n *\n * You can read more about `equalTo()` in\n * {@link https://firebase.google.com/docs/database/web/lists-of-data#filtering_data | Filtering data}.\n *\n * @param value - The value to match for. The argument type depends on which\n * `orderBy*()` function was used in this query. Specify a value that matches\n * the `orderBy*()` type. When used in combination with `orderByKey()`, the\n * value must be a string.\n * @param key - The child key to start at, among the children with the\n * previously specified priority. This argument is only allowed if ordering by\n * child, value, or priority.\n */\nfunction equalTo(value, key) {\n    validateKey('equalTo', 'key', key, true);\n    return new QueryEqualToValueConstraint(value, key);\n}\n/**\n * Creates a new immutable instance of `Query` that is extended to also include\n * additional query constraints.\n *\n * @param query - The Query instance to use as a base for the new constraints.\n * @param queryConstraints - The list of `QueryConstraint`s to apply.\n * @throws if any of the provided query constraints cannot be combined with the\n * existing or new constraints.\n */\nfunction query(query, ...queryConstraints) {\n    let queryImpl = getModularInstance(query);\n    for (const constraint of queryConstraints) {\n        queryImpl = constraint._apply(queryImpl);\n    }\n    return queryImpl;\n}\n/**\n * Define reference constructor in various modules\n *\n * We are doing this here to avoid several circular\n * dependency issues\n */\nsyncPointSetReferenceConstructor(ReferenceImpl);\nsyncTreeSetReferenceConstructor(ReferenceImpl);\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 * This variable is also defined in the firebase Node.js Admin SDK. Before\n * modifying this definition, consult the definition in:\n *\n * https://github.com/firebase/firebase-admin-node\n *\n * and make sure the two are consistent.\n */\nconst FIREBASE_DATABASE_EMULATOR_HOST_VAR = 'FIREBASE_DATABASE_EMULATOR_HOST';\n/**\n * Creates and caches `Repo` instances.\n */\nconst repos = {};\n/**\n * If true, any new `Repo` will be created to use `ReadonlyRestClient` (for testing purposes).\n */\nlet useRestClient = false;\n/**\n * Update an existing `Repo` in place to point to a new host/port.\n */\nfunction repoManagerApplyEmulatorSettings(repo, host, port, tokenProvider) {\n    repo.repoInfo_ = new RepoInfo(`${host}:${port}`, \n    /* secure= */ false, repo.repoInfo_.namespace, repo.repoInfo_.webSocketOnly, repo.repoInfo_.nodeAdmin, repo.repoInfo_.persistenceKey, repo.repoInfo_.includeNamespaceInQueryParams, \n    /*isUsingEmulator=*/ true);\n    if (tokenProvider) {\n        repo.authTokenProvider_ = tokenProvider;\n    }\n}\n/**\n * This function should only ever be called to CREATE a new database instance.\n * @internal\n */\nfunction repoManagerDatabaseFromApp(app, authProvider, appCheckProvider, url, nodeAdmin) {\n    let dbUrl = url || app.options.databaseURL;\n    if (dbUrl === undefined) {\n        if (!app.options.projectId) {\n            fatal(\"Can't determine Firebase Database URL. Be sure to include \" +\n                ' a Project ID when calling firebase.initializeApp().');\n        }\n        log('Using default host for project ', app.options.projectId);\n        dbUrl = `${app.options.projectId}-default-rtdb.firebaseio.com`;\n    }\n    let parsedUrl = parseRepoInfo(dbUrl, nodeAdmin);\n    let repoInfo = parsedUrl.repoInfo;\n    let isEmulator;\n    let dbEmulatorHost = undefined;\n    if (typeof process !== 'undefined' && process.env) {\n        dbEmulatorHost = process.env[FIREBASE_DATABASE_EMULATOR_HOST_VAR];\n    }\n    if (dbEmulatorHost) {\n        isEmulator = true;\n        dbUrl = `http://${dbEmulatorHost}?ns=${repoInfo.namespace}`;\n        parsedUrl = parseRepoInfo(dbUrl, nodeAdmin);\n        repoInfo = parsedUrl.repoInfo;\n    }\n    else {\n        isEmulator = !parsedUrl.repoInfo.secure;\n    }\n    const authTokenProvider = nodeAdmin && isEmulator\n        ? new EmulatorTokenProvider(EmulatorTokenProvider.OWNER)\n        : new FirebaseAuthTokenProvider(app.name, app.options, authProvider);\n    validateUrl('Invalid Firebase Database URL', parsedUrl);\n    if (!pathIsEmpty(parsedUrl.path)) {\n        fatal('Database URL must point to the root of a Firebase Database ' +\n            '(not including a child path).');\n    }\n    const repo = repoManagerCreateRepo(repoInfo, app, authTokenProvider, new AppCheckTokenProvider(app.name, appCheckProvider));\n    return new Database(repo, app);\n}\n/**\n * Remove the repo and make sure it is disconnected.\n *\n */\nfunction repoManagerDeleteRepo(repo, appName) {\n    const appRepos = repos[appName];\n    // This should never happen...\n    if (!appRepos || appRepos[repo.key] !== repo) {\n        fatal(`Database ${appName}(${repo.repoInfo_}) has already been deleted.`);\n    }\n    repoInterrupt(repo);\n    delete appRepos[repo.key];\n}\n/**\n * Ensures a repo doesn't already exist and then creates one using the\n * provided app.\n *\n * @param repoInfo - The metadata about the Repo\n * @returns The Repo object for the specified server / repoName.\n */\nfunction repoManagerCreateRepo(repoInfo, app, authTokenProvider, appCheckProvider) {\n    let appRepos = repos[app.name];\n    if (!appRepos) {\n        appRepos = {};\n        repos[app.name] = appRepos;\n    }\n    let repo = appRepos[repoInfo.toURLString()];\n    if (repo) {\n        fatal('Database initialized multiple times. Please make sure the format of the database URL matches with each database() call.');\n    }\n    repo = new Repo(repoInfo, useRestClient, authTokenProvider, appCheckProvider);\n    appRepos[repoInfo.toURLString()] = repo;\n    return repo;\n}\n/**\n * Forces us to use ReadonlyRestClient instead of PersistentConnection for new Repos.\n */\nfunction repoManagerForceRestClient(forceRestClient) {\n    useRestClient = forceRestClient;\n}\n/**\n * Class representing a Firebase Realtime Database.\n */\nclass Database {\n    /** @hideconstructor */\n    constructor(_repoInternal, \n    /** The {@link @firebase/app#FirebaseApp} associated with this Realtime Database instance. */\n    app) {\n        this._repoInternal = _repoInternal;\n        this.app = app;\n        /** Represents a `Database` instance. */\n        this['type'] = 'database';\n        /** Track if the instance has been used (root or repo accessed) */\n        this._instanceStarted = false;\n    }\n    get _repo() {\n        if (!this._instanceStarted) {\n            repoStart(this._repoInternal, this.app.options.appId, this.app.options['databaseAuthVariableOverride']);\n            this._instanceStarted = true;\n        }\n        return this._repoInternal;\n    }\n    get _root() {\n        if (!this._rootInternal) {\n            this._rootInternal = new ReferenceImpl(this._repo, newEmptyPath());\n        }\n        return this._rootInternal;\n    }\n    _delete() {\n        if (this._rootInternal !== null) {\n            repoManagerDeleteRepo(this._repo, this.app.name);\n            this._repoInternal = null;\n            this._rootInternal = null;\n        }\n        return Promise.resolve();\n    }\n    _checkNotDeleted(apiName) {\n        if (this._rootInternal === null) {\n            fatal('Cannot call ' + apiName + ' on a deleted database.');\n        }\n    }\n}\nfunction checkTransportInit() {\n    if (TransportManager.IS_TRANSPORT_INITIALIZED) {\n        warn('Transport has already been initialized. Please call this function before calling ref or setting up a listener');\n    }\n}\n/**\n * Force the use of websockets instead of longPolling.\n */\nfunction forceWebSockets() {\n    checkTransportInit();\n    BrowserPollConnection.forceDisallow();\n}\n/**\n * Force the use of longPolling instead of websockets. This will be ignored if websocket protocol is used in databaseURL.\n */\nfunction forceLongPolling() {\n    checkTransportInit();\n    WebSocketConnection.forceDisallow();\n    BrowserPollConnection.forceAllow();\n}\n/**\n * Returns the instance of the Realtime Database SDK that is associated with the provided\n * {@link @firebase/app#FirebaseApp}. Initializes a new instance with default settings if\n * no instance exists or if the existing instance uses a custom database URL.\n *\n * @param app - The {@link @firebase/app#FirebaseApp} instance that the returned Realtime\n * Database instance is associated with.\n * @param url - The URL of the Realtime Database instance to connect to. If not\n * provided, the SDK connects to the default instance of the Firebase App.\n * @returns The `Database` instance of the provided app.\n */\nfunction getDatabase(app = getApp(), url) {\n    const db = _getProvider(app, 'database').getImmediate({\n        identifier: url\n    });\n    if (!db._instanceStarted) {\n        const emulator = getDefaultEmulatorHostnameAndPort('database');\n        if (emulator) {\n            connectDatabaseEmulator(db, ...emulator);\n        }\n    }\n    return db;\n}\n/**\n * Modify the provided instance to communicate with the Realtime Database\n * emulator.\n *\n * <p>Note: This method must be called before performing any other operation.\n *\n * @param db - The instance to modify.\n * @param host - The emulator host (ex: localhost)\n * @param port - The emulator port (ex: 8080)\n * @param options.mockUserToken - the mock auth token to use for unit testing Security Rules\n */\nfunction connectDatabaseEmulator(db, host, port, options = {}) {\n    db = getModularInstance(db);\n    db._checkNotDeleted('useEmulator');\n    if (db._instanceStarted) {\n        fatal('Cannot call useEmulator() after instance has already been initialized.');\n    }\n    const repo = db._repoInternal;\n    let tokenProvider = undefined;\n    if (repo.repoInfo_.nodeAdmin) {\n        if (options.mockUserToken) {\n            fatal('mockUserToken is not supported by the Admin SDK. For client access with mock users, please use the \"firebase\" package instead of \"firebase-admin\".');\n        }\n        tokenProvider = new EmulatorTokenProvider(EmulatorTokenProvider.OWNER);\n    }\n    else if (options.mockUserToken) {\n        const token = typeof options.mockUserToken === 'string'\n            ? options.mockUserToken\n            : createMockUserToken(options.mockUserToken, db.app.options.projectId);\n        tokenProvider = new EmulatorTokenProvider(token);\n    }\n    // Modify the repo to apply emulator settings\n    repoManagerApplyEmulatorSettings(repo, host, port, tokenProvider);\n}\n/**\n * Disconnects from the server (all Database operations will be completed\n * offline).\n *\n * The client automatically maintains a persistent connection to the Database\n * server, which will remain active indefinitely and reconnect when\n * disconnected. However, the `goOffline()` and `goOnline()` methods may be used\n * to control the client connection in cases where a persistent connection is\n * undesirable.\n *\n * While offline, the client will no longer receive data updates from the\n * Database. However, all Database operations performed locally will continue to\n * immediately fire events, allowing your application to continue behaving\n * normally. Additionally, each operation performed locally will automatically\n * be queued and retried upon reconnection to the Database server.\n *\n * To reconnect to the Database and begin receiving remote events, see\n * `goOnline()`.\n *\n * @param db - The instance to disconnect.\n */\nfunction goOffline(db) {\n    db = getModularInstance(db);\n    db._checkNotDeleted('goOffline');\n    repoInterrupt(db._repo);\n}\n/**\n * Reconnects to the server and synchronizes the offline Database state\n * with the server state.\n *\n * This method should be used after disabling the active connection with\n * `goOffline()`. Once reconnected, the client will transmit the proper data\n * and fire the appropriate events so that your client \"catches up\"\n * automatically.\n *\n * @param db - The instance to reconnect.\n */\nfunction goOnline(db) {\n    db = getModularInstance(db);\n    db._checkNotDeleted('goOnline');\n    repoResume(db._repo);\n}\nfunction enableLogging(logger, persistent) {\n    enableLogging$1(logger, persistent);\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 */\nfunction registerDatabase(variant) {\n    setSDKVersion(SDK_VERSION$1);\n    _registerComponent(new Component('database', (container, { instanceIdentifier: url }) => {\n        const app = container.getProvider('app').getImmediate();\n        const authProvider = container.getProvider('auth-internal');\n        const appCheckProvider = container.getProvider('app-check-internal');\n        return repoManagerDatabaseFromApp(app, authProvider, appCheckProvider, url);\n    }, \"PUBLIC\" /* ComponentType.PUBLIC */).setMultipleInstances(true));\n    registerVersion(name, version, variant);\n    // BUILD_TARGET will be replaced by values like esm2017, cjs2017, etc during the compilation\n    registerVersion(name, version, 'esm2017');\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 SERVER_TIMESTAMP = {\n    '.sv': 'timestamp'\n};\n/**\n * Returns a placeholder value for auto-populating the current timestamp (time\n * since the Unix epoch, in milliseconds) as determined by the Firebase\n * servers.\n */\nfunction serverTimestamp() {\n    return SERVER_TIMESTAMP;\n}\n/**\n * Returns a placeholder value that can be used to atomically increment the\n * current database value by the provided delta.\n *\n * @param delta - the amount to modify the current value atomically.\n * @returns A placeholder value for modifying data atomically server-side.\n */\nfunction increment(delta) {\n    return {\n        '.sv': {\n            'increment': delta\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 type for the resolve value of {@link runTransaction}.\n */\nclass TransactionResult {\n    /** @hideconstructor */\n    constructor(\n    /** Whether the transaction was successfully committed. */\n    committed, \n    /** The resulting data snapshot. */\n    snapshot) {\n        this.committed = committed;\n        this.snapshot = snapshot;\n    }\n    /** Returns a JSON-serializable representation of this object. */\n    toJSON() {\n        return { committed: this.committed, snapshot: this.snapshot.toJSON() };\n    }\n}\n/**\n * Atomically modifies the data at this location.\n *\n * Atomically modify the data at this location. Unlike a normal `set()`, which\n * just overwrites the data regardless of its previous value, `runTransaction()` is\n * used to modify the existing value to a new value, ensuring there are no\n * conflicts with other clients writing to the same location at the same time.\n *\n * To accomplish this, you pass `runTransaction()` an update function which is\n * used to transform the current value into a new value. If another client\n * writes to the location before your new value is successfully written, your\n * update function will be called again with the new current value, and the\n * write will be retried. This will happen repeatedly until your write succeeds\n * without conflict or you abort the transaction by not returning a value from\n * your update function.\n *\n * Note: Modifying data with `set()` will cancel any pending transactions at\n * that location, so extreme care should be taken if mixing `set()` and\n * `runTransaction()` to update the same data.\n *\n * Note: When using transactions with Security and Firebase Rules in place, be\n * aware that a client needs `.read` access in addition to `.write` access in\n * order to perform a transaction. This is because the client-side nature of\n * transactions requires the client to read the data in order to transactionally\n * update it.\n *\n * @param ref - The location to atomically modify.\n * @param transactionUpdate - A developer-supplied function which will be passed\n * the current data stored at this location (as a JavaScript object). The\n * function should return the new value it would like written (as a JavaScript\n * object). If `undefined` is returned (i.e. you return with no arguments) the\n * transaction will be aborted and the data at this location will not be\n * modified.\n * @param options - An options object to configure transactions.\n * @returns A `Promise` that can optionally be used instead of the `onComplete`\n * callback to handle success and failure.\n */\nfunction runTransaction(ref, \n// eslint-disable-next-line @typescript-eslint/no-explicit-any\ntransactionUpdate, options) {\n    var _a;\n    ref = getModularInstance(ref);\n    validateWritablePath('Reference.transaction', ref._path);\n    if (ref.key === '.length' || ref.key === '.keys') {\n        throw ('Reference.transaction failed: ' + ref.key + ' is a read-only object.');\n    }\n    const applyLocally = (_a = options === null || options === void 0 ? void 0 : options.applyLocally) !== null && _a !== void 0 ? _a : true;\n    const deferred = new Deferred();\n    const promiseComplete = (error, committed, node) => {\n        let dataSnapshot = null;\n        if (error) {\n            deferred.reject(error);\n        }\n        else {\n            dataSnapshot = new DataSnapshot(node, new ReferenceImpl(ref._repo, ref._path), PRIORITY_INDEX);\n            deferred.resolve(new TransactionResult(committed, dataSnapshot));\n        }\n    };\n    // Add a watch to make sure we get server updates.\n    const unwatcher = onValue(ref, () => { });\n    repoStartTransaction(ref._repo, ref._path, transactionUpdate, promiseComplete, unwatcher, applyLocally);\n    return deferred.promise;\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 */\nPersistentConnection;\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nPersistentConnection.prototype.simpleListen = function (pathString, onComplete) {\n    this.sendRequest('q', { p: pathString }, onComplete);\n};\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nPersistentConnection.prototype.echo = function (data, onEcho) {\n    this.sendRequest('echo', { d: data }, onEcho);\n};\n// RealTimeConnection properties that we use in tests.\nConnection;\n/**\n * @internal\n */\nconst hijackHash = function (newHash) {\n    const oldPut = PersistentConnection.prototype.put;\n    PersistentConnection.prototype.put = function (pathString, data, onComplete, hash) {\n        if (hash !== undefined) {\n            hash = newHash();\n        }\n        oldPut.call(this, pathString, data, onComplete, hash);\n    };\n    return function () {\n        PersistentConnection.prototype.put = oldPut;\n    };\n};\nRepoInfo;\n/**\n * Forces the RepoManager to create Repos that use ReadonlyRestClient instead of PersistentConnection.\n * @internal\n */\nconst forceRestClient = function (forceRestClient) {\n    repoManagerForceRestClient(forceRestClient);\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 * Used by console to create a database based on the app,\n * passed database URL and a custom auth implementation.\n * @internal\n * @param app - A valid FirebaseApp-like object\n * @param url - A valid Firebase databaseURL\n * @param version - custom version e.g. firebase-admin version\n * @param customAppCheckImpl - custom app check implementation\n * @param customAuthImpl - custom auth implementation\n */\nfunction _initStandalone({ app, url, version, customAuthImpl, customAppCheckImpl, nodeAdmin = false }) {\n    setSDKVersion(version);\n    /**\n     * ComponentContainer('database-standalone') is just a placeholder that doesn't perform\n     * any actual function.\n     */\n    const componentContainer = new ComponentContainer('database-standalone');\n    const authProvider = new Provider('auth-internal', componentContainer);\n    let appCheckProvider;\n    if (customAppCheckImpl) {\n        appCheckProvider = new Provider('app-check-internal', componentContainer);\n        appCheckProvider.setComponent(new Component('app-check-internal', () => customAppCheckImpl, \"PRIVATE\" /* ComponentType.PRIVATE */));\n    }\n    authProvider.setComponent(new Component('auth-internal', () => customAuthImpl, \"PRIVATE\" /* ComponentType.PRIVATE */));\n    return repoManagerDatabaseFromApp(app, authProvider, appCheckProvider, url, nodeAdmin);\n}\n\n/**\n * Firebase Realtime Database\n *\n * @packageDocumentation\n */\nregisterDatabase();\n\nexport { DataSnapshot, Database, OnDisconnect, QueryConstraint, TransactionResult, QueryImpl as _QueryImpl, QueryParams as _QueryParams, ReferenceImpl as _ReferenceImpl, forceRestClient as _TEST_ACCESS_forceRestClient, hijackHash as _TEST_ACCESS_hijackHash, _initStandalone, repoManagerDatabaseFromApp as _repoManagerDatabaseFromApp, setSDKVersion as _setSDKVersion, validatePathString as _validatePathString, validateWritablePath as _validateWritablePath, child, connectDatabaseEmulator, enableLogging, endAt, endBefore, equalTo, forceLongPolling, forceWebSockets, get, getDatabase, goOffline, goOnline, increment, limitToFirst, limitToLast, off, onChildAdded, onChildChanged, onChildMoved, onChildRemoved, onDisconnect, onValue, orderByChild, orderByKey, orderByPriority, orderByValue, push, query, ref, refFromURL, remove, runTransaction, serverTimestamp, set, setPriority, setWithPriority, startAfter, startAt, update };\n//# sourceMappingURL=index.esm2017.js.map\n","import firebase from '@firebase/app-compat';\nimport { ComponentContainer, Provider, Component } from '@firebase/component';\nimport { _validatePathString, onChildMoved, onChildChanged, onChildRemoved, onChildAdded, onValue, off, get, query, limitToFirst, limitToLast, orderByChild, orderByKey, orderByPriority, orderByValue, startAt, startAfter, endAt, endBefore, equalTo, _ReferenceImpl, _QueryImpl, _QueryParams, child, set, _validateWritablePath, update, setWithPriority, remove, runTransaction, setPriority, push, OnDisconnect as OnDisconnect$1, forceWebSockets, forceLongPolling, connectDatabaseEmulator, refFromURL, ref, goOffline, goOnline, serverTimestamp, increment, _setSDKVersion, _repoManagerDatabaseFromApp, enableLogging } from '@firebase/database';\nimport { errorPrefix, validateArgCount, validateCallback, validateContextObject, Deferred } from '@firebase/util';\nimport { Logger } from '@firebase/logger';\n\nconst name = \"@firebase/database-compat\";\nconst version = \"2.0.1\";\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 */\nconst logClient = new Logger('@firebase/database-compat');\nconst warn = function (msg) {\n    const message = 'FIREBASE WARNING: ' + msg;\n    logClient.warn(message);\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 */\nconst validateBoolean = function (fnName, argumentName, bool, optional) {\n    if (optional && bool === undefined) {\n        return;\n    }\n    if (typeof bool !== 'boolean') {\n        throw new Error(errorPrefix(fnName, argumentName) + 'must be a boolean.');\n    }\n};\nconst validateEventType = function (fnName, eventType, optional) {\n    if (optional && eventType === undefined) {\n        return;\n    }\n    switch (eventType) {\n        case 'value':\n        case 'child_added':\n        case 'child_removed':\n        case 'child_changed':\n        case 'child_moved':\n            break;\n        default:\n            throw new Error(errorPrefix(fnName, 'eventType') +\n                'must be a valid event type = \"value\", \"child_added\", \"child_removed\", ' +\n                '\"child_changed\", or \"child_moved\".');\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 */\nclass OnDisconnect {\n    constructor(_delegate) {\n        this._delegate = _delegate;\n    }\n    cancel(onComplete) {\n        validateArgCount('OnDisconnect.cancel', 0, 1, arguments.length);\n        validateCallback('OnDisconnect.cancel', 'onComplete', onComplete, true);\n        const result = this._delegate.cancel();\n        if (onComplete) {\n            result.then(() => onComplete(null), error => onComplete(error));\n        }\n        return result;\n    }\n    remove(onComplete) {\n        validateArgCount('OnDisconnect.remove', 0, 1, arguments.length);\n        validateCallback('OnDisconnect.remove', 'onComplete', onComplete, true);\n        const result = this._delegate.remove();\n        if (onComplete) {\n            result.then(() => onComplete(null), error => onComplete(error));\n        }\n        return result;\n    }\n    set(value, onComplete) {\n        validateArgCount('OnDisconnect.set', 1, 2, arguments.length);\n        validateCallback('OnDisconnect.set', 'onComplete', onComplete, true);\n        const result = this._delegate.set(value);\n        if (onComplete) {\n            result.then(() => onComplete(null), error => onComplete(error));\n        }\n        return result;\n    }\n    setWithPriority(value, priority, onComplete) {\n        validateArgCount('OnDisconnect.setWithPriority', 2, 3, arguments.length);\n        validateCallback('OnDisconnect.setWithPriority', 'onComplete', onComplete, true);\n        const result = this._delegate.setWithPriority(value, priority);\n        if (onComplete) {\n            result.then(() => onComplete(null), error => onComplete(error));\n        }\n        return result;\n    }\n    update(objectToMerge, onComplete) {\n        validateArgCount('OnDisconnect.update', 1, 2, arguments.length);\n        if (Array.isArray(objectToMerge)) {\n            const newObjectToMerge = {};\n            for (let i = 0; i < objectToMerge.length; ++i) {\n                newObjectToMerge['' + i] = objectToMerge[i];\n            }\n            objectToMerge = newObjectToMerge;\n            warn('Passing an Array to firebase.database.onDisconnect().update() is deprecated. Use set() if you want to overwrite the ' +\n                'existing data, or an Object with integer keys if you really do want to only update some of the children.');\n        }\n        validateCallback('OnDisconnect.update', 'onComplete', onComplete, true);\n        const result = this._delegate.update(objectToMerge);\n        if (onComplete) {\n            result.then(() => onComplete(null), error => onComplete(error));\n        }\n        return result;\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 */\nclass TransactionResult {\n    /**\n     * A type for the resolve value of Firebase.transaction.\n     */\n    constructor(committed, snapshot) {\n        this.committed = committed;\n        this.snapshot = snapshot;\n    }\n    // Do not create public documentation. This is intended to make JSON serialization work but is otherwise unnecessary\n    // for end-users\n    toJSON() {\n        validateArgCount('TransactionResult.toJSON', 0, 1, arguments.length);\n        return { committed: this.committed, snapshot: this.snapshot.toJSON() };\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 * Class representing a firebase data snapshot.  It wraps a SnapshotNode and\n * surfaces the public methods (val, forEach, etc.) we want to expose.\n */\nclass DataSnapshot {\n    constructor(_database, _delegate) {\n        this._database = _database;\n        this._delegate = _delegate;\n    }\n    /**\n     * Retrieves the snapshot contents as JSON.  Returns null if the snapshot is\n     * empty.\n     *\n     * @returns JSON representation of the DataSnapshot contents, or null if empty.\n     */\n    val() {\n        validateArgCount('DataSnapshot.val', 0, 0, arguments.length);\n        return this._delegate.val();\n    }\n    /**\n     * Returns the snapshot contents as JSON, including priorities of node.  Suitable for exporting\n     * the entire node contents.\n     * @returns JSON representation of the DataSnapshot contents, or null if empty.\n     */\n    exportVal() {\n        validateArgCount('DataSnapshot.exportVal', 0, 0, arguments.length);\n        return this._delegate.exportVal();\n    }\n    // Do not create public documentation. This is intended to make JSON serialization work but is otherwise unnecessary\n    // for end-users\n    toJSON() {\n        // Optional spacer argument is unnecessary because we're depending on recursion rather than stringifying the content\n        validateArgCount('DataSnapshot.toJSON', 0, 1, arguments.length);\n        return this._delegate.toJSON();\n    }\n    /**\n     * Returns whether the snapshot contains a non-null value.\n     *\n     * @returns Whether the snapshot contains a non-null value, or is empty.\n     */\n    exists() {\n        validateArgCount('DataSnapshot.exists', 0, 0, arguments.length);\n        return this._delegate.exists();\n    }\n    /**\n     * Returns a DataSnapshot of the specified child node's contents.\n     *\n     * @param path - Path to a child.\n     * @returns DataSnapshot for child node.\n     */\n    child(path) {\n        validateArgCount('DataSnapshot.child', 0, 1, arguments.length);\n        // Ensure the childPath is a string (can be a number)\n        path = String(path);\n        _validatePathString('DataSnapshot.child', 'path', path, false);\n        return new DataSnapshot(this._database, this._delegate.child(path));\n    }\n    /**\n     * Returns whether the snapshot contains a child at the specified path.\n     *\n     * @param path - Path to a child.\n     * @returns Whether the child exists.\n     */\n    hasChild(path) {\n        validateArgCount('DataSnapshot.hasChild', 1, 1, arguments.length);\n        _validatePathString('DataSnapshot.hasChild', 'path', path, false);\n        return this._delegate.hasChild(path);\n    }\n    /**\n     * Returns the priority of the object, or null if no priority was set.\n     *\n     * @returns The priority.\n     */\n    getPriority() {\n        validateArgCount('DataSnapshot.getPriority', 0, 0, arguments.length);\n        return this._delegate.priority;\n    }\n    /**\n     * Iterates through child nodes and calls the specified action for each one.\n     *\n     * @param action - Callback function to be called\n     * for each child.\n     * @returns True if forEach was canceled by action returning true for\n     * one of the child nodes.\n     */\n    forEach(action) {\n        validateArgCount('DataSnapshot.forEach', 1, 1, arguments.length);\n        validateCallback('DataSnapshot.forEach', 'action', action, false);\n        return this._delegate.forEach(expDataSnapshot => action(new DataSnapshot(this._database, expDataSnapshot)));\n    }\n    /**\n     * Returns whether this DataSnapshot has children.\n     * @returns True if the DataSnapshot contains 1 or more child nodes.\n     */\n    hasChildren() {\n        validateArgCount('DataSnapshot.hasChildren', 0, 0, arguments.length);\n        return this._delegate.hasChildren();\n    }\n    get key() {\n        return this._delegate.key;\n    }\n    /**\n     * Returns the number of children for this DataSnapshot.\n     * @returns The number of children that this DataSnapshot contains.\n     */\n    numChildren() {\n        validateArgCount('DataSnapshot.numChildren', 0, 0, arguments.length);\n        return this._delegate.size;\n    }\n    /**\n     * @returns The Firebase reference for the location this snapshot's data came\n     * from.\n     */\n    getRef() {\n        validateArgCount('DataSnapshot.ref', 0, 0, arguments.length);\n        return new Reference(this._database, this._delegate.ref);\n    }\n    get ref() {\n        return this.getRef();\n    }\n}\n/**\n * A Query represents a filter to be applied to a firebase location.  This object purely represents the\n * query expression (and exposes our public API to build the query).  The actual query logic is in ViewBase.js.\n *\n * Since every Firebase reference is a query, Firebase inherits from this object.\n */\nclass Query {\n    constructor(database, _delegate) {\n        this.database = database;\n        this._delegate = _delegate;\n    }\n    on(eventType, callback, cancelCallbackOrContext, context) {\n        var _a;\n        validateArgCount('Query.on', 2, 4, arguments.length);\n        validateCallback('Query.on', 'callback', callback, false);\n        const ret = Query.getCancelAndContextArgs_('Query.on', cancelCallbackOrContext, context);\n        const valueCallback = (expSnapshot, previousChildName) => {\n            callback.call(ret.context, new DataSnapshot(this.database, expSnapshot), previousChildName);\n        };\n        valueCallback.userCallback = callback;\n        valueCallback.context = ret.context;\n        const cancelCallback = (_a = ret.cancel) === null || _a === void 0 ? void 0 : _a.bind(ret.context);\n        switch (eventType) {\n            case 'value':\n                onValue(this._delegate, valueCallback, cancelCallback);\n                return callback;\n            case 'child_added':\n                onChildAdded(this._delegate, valueCallback, cancelCallback);\n                return callback;\n            case 'child_removed':\n                onChildRemoved(this._delegate, valueCallback, cancelCallback);\n                return callback;\n            case 'child_changed':\n                onChildChanged(this._delegate, valueCallback, cancelCallback);\n                return callback;\n            case 'child_moved':\n                onChildMoved(this._delegate, valueCallback, cancelCallback);\n                return callback;\n            default:\n                throw new Error(errorPrefix('Query.on', 'eventType') +\n                    'must be a valid event type = \"value\", \"child_added\", \"child_removed\", ' +\n                    '\"child_changed\", or \"child_moved\".');\n        }\n    }\n    off(eventType, callback, context) {\n        validateArgCount('Query.off', 0, 3, arguments.length);\n        validateEventType('Query.off', eventType, true);\n        validateCallback('Query.off', 'callback', callback, true);\n        validateContextObject('Query.off', 'context', context, true);\n        if (callback) {\n            const valueCallback = () => { };\n            valueCallback.userCallback = callback;\n            valueCallback.context = context;\n            off(this._delegate, eventType, valueCallback);\n        }\n        else {\n            off(this._delegate, eventType);\n        }\n    }\n    /**\n     * Get the server-value for this query, or return a cached value if not connected.\n     */\n    get() {\n        return get(this._delegate).then(expSnapshot => {\n            return new DataSnapshot(this.database, expSnapshot);\n        });\n    }\n    /**\n     * Attaches a listener, waits for the first event, and then removes the listener\n     */\n    once(eventType, callback, failureCallbackOrContext, context) {\n        validateArgCount('Query.once', 1, 4, arguments.length);\n        validateCallback('Query.once', 'callback', callback, true);\n        const ret = Query.getCancelAndContextArgs_('Query.once', failureCallbackOrContext, context);\n        const deferred = new Deferred();\n        const valueCallback = (expSnapshot, previousChildName) => {\n            const result = new DataSnapshot(this.database, expSnapshot);\n            if (callback) {\n                callback.call(ret.context, result, previousChildName);\n            }\n            deferred.resolve(result);\n        };\n        valueCallback.userCallback = callback;\n        valueCallback.context = ret.context;\n        const cancelCallback = (error) => {\n            if (ret.cancel) {\n                ret.cancel.call(ret.context, error);\n            }\n            deferred.reject(error);\n        };\n        switch (eventType) {\n            case 'value':\n                onValue(this._delegate, valueCallback, cancelCallback, {\n                    onlyOnce: true\n                });\n                break;\n            case 'child_added':\n                onChildAdded(this._delegate, valueCallback, cancelCallback, {\n                    onlyOnce: true\n                });\n                break;\n            case 'child_removed':\n                onChildRemoved(this._delegate, valueCallback, cancelCallback, {\n                    onlyOnce: true\n                });\n                break;\n            case 'child_changed':\n                onChildChanged(this._delegate, valueCallback, cancelCallback, {\n                    onlyOnce: true\n                });\n                break;\n            case 'child_moved':\n                onChildMoved(this._delegate, valueCallback, cancelCallback, {\n                    onlyOnce: true\n                });\n                break;\n            default:\n                throw new Error(errorPrefix('Query.once', 'eventType') +\n                    'must be a valid event type = \"value\", \"child_added\", \"child_removed\", ' +\n                    '\"child_changed\", or \"child_moved\".');\n        }\n        return deferred.promise;\n    }\n    /**\n     * Set a limit and anchor it to the start of the window.\n     */\n    limitToFirst(limit) {\n        validateArgCount('Query.limitToFirst', 1, 1, arguments.length);\n        return new Query(this.database, query(this._delegate, limitToFirst(limit)));\n    }\n    /**\n     * Set a limit and anchor it to the end of the window.\n     */\n    limitToLast(limit) {\n        validateArgCount('Query.limitToLast', 1, 1, arguments.length);\n        return new Query(this.database, query(this._delegate, limitToLast(limit)));\n    }\n    /**\n     * Given a child path, return a new query ordered by the specified grandchild path.\n     */\n    orderByChild(path) {\n        validateArgCount('Query.orderByChild', 1, 1, arguments.length);\n        return new Query(this.database, query(this._delegate, orderByChild(path)));\n    }\n    /**\n     * Return a new query ordered by the KeyIndex\n     */\n    orderByKey() {\n        validateArgCount('Query.orderByKey', 0, 0, arguments.length);\n        return new Query(this.database, query(this._delegate, orderByKey()));\n    }\n    /**\n     * Return a new query ordered by the PriorityIndex\n     */\n    orderByPriority() {\n        validateArgCount('Query.orderByPriority', 0, 0, arguments.length);\n        return new Query(this.database, query(this._delegate, orderByPriority()));\n    }\n    /**\n     * Return a new query ordered by the ValueIndex\n     */\n    orderByValue() {\n        validateArgCount('Query.orderByValue', 0, 0, arguments.length);\n        return new Query(this.database, query(this._delegate, orderByValue()));\n    }\n    startAt(value = null, name) {\n        validateArgCount('Query.startAt', 0, 2, arguments.length);\n        return new Query(this.database, query(this._delegate, startAt(value, name)));\n    }\n    startAfter(value = null, name) {\n        validateArgCount('Query.startAfter', 0, 2, arguments.length);\n        return new Query(this.database, query(this._delegate, startAfter(value, name)));\n    }\n    endAt(value = null, name) {\n        validateArgCount('Query.endAt', 0, 2, arguments.length);\n        return new Query(this.database, query(this._delegate, endAt(value, name)));\n    }\n    endBefore(value = null, name) {\n        validateArgCount('Query.endBefore', 0, 2, arguments.length);\n        return new Query(this.database, query(this._delegate, endBefore(value, name)));\n    }\n    /**\n     * Load the selection of children with exactly the specified value, and, optionally,\n     * the specified name.\n     */\n    equalTo(value, name) {\n        validateArgCount('Query.equalTo', 1, 2, arguments.length);\n        return new Query(this.database, query(this._delegate, equalTo(value, name)));\n    }\n    /**\n     * @returns URL for this location.\n     */\n    toString() {\n        validateArgCount('Query.toString', 0, 0, arguments.length);\n        return this._delegate.toString();\n    }\n    // Do not create public documentation. This is intended to make JSON serialization work but is otherwise unnecessary\n    // for end-users.\n    toJSON() {\n        // An optional spacer argument is unnecessary for a string.\n        validateArgCount('Query.toJSON', 0, 1, arguments.length);\n        return this._delegate.toJSON();\n    }\n    /**\n     * Return true if this query and the provided query are equivalent; otherwise, return false.\n     */\n    isEqual(other) {\n        validateArgCount('Query.isEqual', 1, 1, arguments.length);\n        if (!(other instanceof Query)) {\n            const error = 'Query.isEqual failed: First argument must be an instance of firebase.database.Query.';\n            throw new Error(error);\n        }\n        return this._delegate.isEqual(other._delegate);\n    }\n    /**\n     * Helper used by .on and .once to extract the context and or cancel arguments.\n     * @param fnName - The function name (on or once)\n     *\n     */\n    static getCancelAndContextArgs_(fnName, cancelOrContext, context) {\n        const ret = { cancel: undefined, context: undefined };\n        if (cancelOrContext && context) {\n            ret.cancel = cancelOrContext;\n            validateCallback(fnName, 'cancel', ret.cancel, true);\n            ret.context = context;\n            validateContextObject(fnName, 'context', ret.context, true);\n        }\n        else if (cancelOrContext) {\n            // we have either a cancel callback or a context.\n            if (typeof cancelOrContext === 'object' && cancelOrContext !== null) {\n                // it's a context!\n                ret.context = cancelOrContext;\n            }\n            else if (typeof cancelOrContext === 'function') {\n                ret.cancel = cancelOrContext;\n            }\n            else {\n                throw new Error(errorPrefix(fnName, 'cancelOrContext') +\n                    ' must either be a cancel callback or a context object.');\n            }\n        }\n        return ret;\n    }\n    get ref() {\n        return new Reference(this.database, new _ReferenceImpl(this._delegate._repo, this._delegate._path));\n    }\n}\nclass Reference extends Query {\n    /**\n     * Call options:\n     *   new Reference(Repo, Path) or\n     *   new Reference(url: string, string|RepoManager)\n     *\n     * Externally - this is the firebase.database.Reference type.\n     */\n    constructor(database, _delegate) {\n        super(database, new _QueryImpl(_delegate._repo, _delegate._path, new _QueryParams(), false));\n        this.database = database;\n        this._delegate = _delegate;\n    }\n    /** @returns {?string} */\n    getKey() {\n        validateArgCount('Reference.key', 0, 0, arguments.length);\n        return this._delegate.key;\n    }\n    child(pathString) {\n        validateArgCount('Reference.child', 1, 1, arguments.length);\n        if (typeof pathString === 'number') {\n            pathString = String(pathString);\n        }\n        return new Reference(this.database, child(this._delegate, pathString));\n    }\n    /** @returns {?Reference} */\n    getParent() {\n        validateArgCount('Reference.parent', 0, 0, arguments.length);\n        const parent = this._delegate.parent;\n        return parent ? new Reference(this.database, parent) : null;\n    }\n    /** @returns {!Reference} */\n    getRoot() {\n        validateArgCount('Reference.root', 0, 0, arguments.length);\n        return new Reference(this.database, this._delegate.root);\n    }\n    set(newVal, onComplete) {\n        validateArgCount('Reference.set', 1, 2, arguments.length);\n        validateCallback('Reference.set', 'onComplete', onComplete, true);\n        const result = set(this._delegate, newVal);\n        if (onComplete) {\n            result.then(() => onComplete(null), error => onComplete(error));\n        }\n        return result;\n    }\n    update(values, onComplete) {\n        validateArgCount('Reference.update', 1, 2, arguments.length);\n        if (Array.isArray(values)) {\n            const newObjectToMerge = {};\n            for (let i = 0; i < values.length; ++i) {\n                newObjectToMerge['' + i] = values[i];\n            }\n            values = newObjectToMerge;\n            warn('Passing an Array to Firebase.update() is deprecated. ' +\n                'Use set() if you want to overwrite the existing data, or ' +\n                'an Object with integer keys if you really do want to ' +\n                'only update some of the children.');\n        }\n        _validateWritablePath('Reference.update', this._delegate._path);\n        validateCallback('Reference.update', 'onComplete', onComplete, true);\n        const result = update(this._delegate, values);\n        if (onComplete) {\n            result.then(() => onComplete(null), error => onComplete(error));\n        }\n        return result;\n    }\n    setWithPriority(newVal, newPriority, onComplete) {\n        validateArgCount('Reference.setWithPriority', 2, 3, arguments.length);\n        validateCallback('Reference.setWithPriority', 'onComplete', onComplete, true);\n        const result = setWithPriority(this._delegate, newVal, newPriority);\n        if (onComplete) {\n            result.then(() => onComplete(null), error => onComplete(error));\n        }\n        return result;\n    }\n    remove(onComplete) {\n        validateArgCount('Reference.remove', 0, 1, arguments.length);\n        validateCallback('Reference.remove', 'onComplete', onComplete, true);\n        const result = remove(this._delegate);\n        if (onComplete) {\n            result.then(() => onComplete(null), error => onComplete(error));\n        }\n        return result;\n    }\n    transaction(transactionUpdate, onComplete, applyLocally) {\n        validateArgCount('Reference.transaction', 1, 3, arguments.length);\n        validateCallback('Reference.transaction', 'transactionUpdate', transactionUpdate, false);\n        validateCallback('Reference.transaction', 'onComplete', onComplete, true);\n        validateBoolean('Reference.transaction', 'applyLocally', applyLocally, true);\n        const result = runTransaction(this._delegate, transactionUpdate, {\n            applyLocally\n        }).then(transactionResult => new TransactionResult(transactionResult.committed, new DataSnapshot(this.database, transactionResult.snapshot)));\n        if (onComplete) {\n            result.then(transactionResult => onComplete(null, transactionResult.committed, transactionResult.snapshot), error => onComplete(error, false, null));\n        }\n        return result;\n    }\n    setPriority(priority, onComplete) {\n        validateArgCount('Reference.setPriority', 1, 2, arguments.length);\n        validateCallback('Reference.setPriority', 'onComplete', onComplete, true);\n        const result = setPriority(this._delegate, priority);\n        if (onComplete) {\n            result.then(() => onComplete(null), error => onComplete(error));\n        }\n        return result;\n    }\n    push(value, onComplete) {\n        validateArgCount('Reference.push', 0, 2, arguments.length);\n        validateCallback('Reference.push', 'onComplete', onComplete, true);\n        const expPromise = push(this._delegate, value);\n        const promise = expPromise.then(expRef => new Reference(this.database, expRef));\n        if (onComplete) {\n            promise.then(() => onComplete(null), error => onComplete(error));\n        }\n        const result = new Reference(this.database, expPromise);\n        result.then = promise.then.bind(promise);\n        result.catch = promise.catch.bind(promise, undefined);\n        return result;\n    }\n    onDisconnect() {\n        _validateWritablePath('Reference.onDisconnect', this._delegate._path);\n        return new OnDisconnect(new OnDisconnect$1(this._delegate._repo, this._delegate._path));\n    }\n    get key() {\n        return this.getKey();\n    }\n    get parent() {\n        return this.getParent();\n    }\n    get root() {\n        return this.getRoot();\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 * Class representing a firebase database.\n */\nclass Database {\n    /**\n     * The constructor should not be called by users of our public API.\n     */\n    constructor(_delegate, app) {\n        this._delegate = _delegate;\n        this.app = app;\n        this.INTERNAL = {\n            delete: () => this._delegate._delete(),\n            forceWebSockets,\n            forceLongPolling\n        };\n    }\n    /**\n     * Modify this instance to communicate with the Realtime Database emulator.\n     *\n     * <p>Note: This method must be called before performing any other operation.\n     *\n     * @param host - the emulator host (ex: localhost)\n     * @param port - the emulator port (ex: 8080)\n     * @param options.mockUserToken - the mock auth token to use for unit testing Security Rules\n     */\n    useEmulator(host, port, options = {}) {\n        connectDatabaseEmulator(this._delegate, host, port, options);\n    }\n    ref(path) {\n        validateArgCount('database.ref', 0, 1, arguments.length);\n        if (path instanceof Reference) {\n            const childRef = refFromURL(this._delegate, path.toString());\n            return new Reference(this, childRef);\n        }\n        else {\n            const childRef = ref(this._delegate, path);\n            return new Reference(this, childRef);\n        }\n    }\n    /**\n     * Returns a reference to the root or the path specified in url.\n     * We throw a exception if the url is not in the same domain as the\n     * current repo.\n     * @returns Firebase reference.\n     */\n    refFromURL(url) {\n        const apiName = 'database.refFromURL';\n        validateArgCount(apiName, 1, 1, arguments.length);\n        const childRef = refFromURL(this._delegate, url);\n        return new Reference(this, childRef);\n    }\n    // Make individual repo go offline.\n    goOffline() {\n        validateArgCount('database.goOffline', 0, 0, arguments.length);\n        return goOffline(this._delegate);\n    }\n    goOnline() {\n        validateArgCount('database.goOnline', 0, 0, arguments.length);\n        return goOnline(this._delegate);\n    }\n}\nDatabase.ServerValue = {\n    TIMESTAMP: serverTimestamp(),\n    increment: (delta) => increment(delta)\n};\n\n/**\n * Used by console to create a database based on the app,\n * passed database URL and a custom auth implementation.\n *\n * @param app - A valid FirebaseApp-like object\n * @param url - A valid Firebase databaseURL\n * @param version - custom version e.g. firebase-admin version\n * @param customAuthImpl - custom auth implementation\n */\nfunction initStandalone({ app, url, version, customAuthImpl, customAppCheckImpl, namespace, nodeAdmin = false }) {\n    _setSDKVersion(version);\n    const container = new ComponentContainer('database-standalone');\n    /**\n     * ComponentContainer('database-standalone') is just a placeholder that doesn't perform\n     * any actual function.\n     */\n    const authProvider = new Provider('auth-internal', container);\n    authProvider.setComponent(new Component('auth-internal', () => customAuthImpl, \"PRIVATE\" /* ComponentType.PRIVATE */));\n    let appCheckProvider = undefined;\n    if (customAppCheckImpl) {\n        appCheckProvider = new Provider('app-check-internal', container);\n        appCheckProvider.setComponent(new Component('app-check-internal', () => customAppCheckImpl, \"PRIVATE\" /* ComponentType.PRIVATE */));\n    }\n    return {\n        instance: new Database(_repoManagerDatabaseFromApp(app, authProvider, appCheckProvider, url, nodeAdmin), app),\n        namespace\n    };\n}\n\nvar INTERNAL = /*#__PURE__*/Object.freeze({\n  __proto__: null,\n  initStandalone: initStandalone\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 */\nconst ServerValue = Database.ServerValue;\nfunction registerDatabase(instance) {\n    // Register the Database Service with the 'firebase' namespace.\n    instance.INTERNAL.registerComponent(new Component('database-compat', (container, { instanceIdentifier: url }) => {\n        /* Dependencies */\n        // getImmediate for FirebaseApp will always succeed\n        const app = container.getProvider('app-compat').getImmediate();\n        const databaseExp = container\n            .getProvider('database')\n            .getImmediate({ identifier: url });\n        return new Database(databaseExp, app);\n    }, \"PUBLIC\" /* ComponentType.PUBLIC */)\n        .setServiceProps(\n    // firebase.database namespace properties\n    {\n        Reference,\n        Query,\n        Database,\n        DataSnapshot,\n        enableLogging,\n        INTERNAL,\n        ServerValue\n    })\n        .setMultipleInstances(true));\n    instance.registerVersion(name, version);\n}\nregisterDatabase(firebase);\n\nexport { registerDatabase };\n//# sourceMappingURL=index.esm2017.js.map\n","import { exportCsv, remove, replaceWith } from '@slideslive/fuse-kit/utils';\nimport firebase from 'firebase/compat/app';\nimport 'firebase/compat/database';\nimport ApplicationController from 'modules/application_controller';\nimport moment from 'moment-timezone';\n\nexport default class extends ApplicationController {\n  static get targets() {\n    return ['list', 'commentSent', 'commentTemplate', 'email', 'name', 'message'];\n  }\n\n  initialize() {\n    this.props = {\n      exportData: {},\n      firebaseApp: null,\n      messagesRef: null,\n      commentSentTimeout: null,\n    };\n  }\n\n  connect() {\n    if (this.isTurboPreview) {\n      return;\n    }\n\n    this.initFirebase();\n  }\n\n  initFirebase() {\n    this.firebaseApp = firebase.initializeApp(this.firebaseConfig);\n    this.messagesRef = this.firebaseApp.database().ref(`/${this.presentationId}`);\n\n    this.messagesRef.on('child_added', (snapshot) => {\n      const message = snapshot.val();\n\n      if (this.hasListTarget && !message.deletedAt) {\n        const html = this.renderMessageHtml(snapshot.key, message);\n\n        this.listTarget.insertAdjacentHTML('afterbegin', html);\n      }\n\n      if (this.canExport) {\n        this.exportData[snapshot.key] = this.messageDataToObjectForExport(message);\n      }\n    });\n\n    this.messagesRef.on('child_removed', (snapshot) => {\n      if (this.hasListTarget) {\n        const message = this.listTarget.querySelector(`[data-id=\"${snapshot.key}\"]`);\n\n        remove(message);\n      }\n\n      if (this.canExport) {\n        delete this.exportData[snapshot.key];\n      }\n    });\n\n    this.messagesRef.on('child_changed', (snapshot) => {\n      const message = snapshot.val();\n\n      if (this.hasListTarget) {\n        const messageElement = this.listTarget.querySelector(`[data-id=\"${snapshot.key}\"]`);\n\n        if (message.deletedAt) {\n          remove(messageElement);\n        } else {\n          const html = this.renderMessageHtml(snapshot.key, message);\n          replaceWith(messageElement, html);\n        }\n      }\n\n      if (this.canExport) {\n        this.exportData[snapshot.key] = this.messageDataToObjectForExport(message);\n      }\n    });\n  }\n\n  renderMessageHtml(key, data) {\n    const date = moment(data.createdAt).format('LLL');\n    const html = this.commentTemplateTarget.innerHTML;\n    const initials = data.name\n      .split(' ')\n      .slice(0, 2)\n      .map((s) => s[0])\n      .join('');\n\n    return html\n      .replaceAll('{KEY}', key)\n      .replaceAll('{NAME}', data.name)\n      .replaceAll('{INITIALS}', initials)\n      .replaceAll('{MESSAGE}', data.text)\n      .replaceAll('{CREATED_AT}', date);\n  }\n\n  deleteComment(event) {\n    event.preventDefault();\n\n    const messageListItem = event.target.closest('[data-id]');\n    const messageKey = messageListItem.dataset.id;\n    const message = this.messagesRef.child(messageKey);\n\n    message.update({ deletedAt: new Date().toISOString() });\n  }\n\n  sendComment(event) {\n    event.preventDefault();\n\n    this.messagesRef.push(this.createMessageObject());\n    this.resetMessage();\n    this.showCommentSent();\n  }\n\n  createMessageObject() {\n    const now = new Date().toISOString();\n\n    return {\n      createdAt: now,\n      updatedAt: now,\n      name: this.name,\n      email: this.email,\n      // registrationId: this.registrationId,\n      analyticsUserUuid: this.analyticsUserUuid,\n      text: this.messageText,\n    };\n  }\n\n  resetMessage() {\n    this.messageText = '';\n    this.messageTarget.focus();\n  }\n\n  showCommentSent() {\n    if (!this.hasCommentSentTarget) {\n      return;\n    }\n\n    if (this.commentSentTimeout) {\n      clearTimeout(this.commentSentTimeout);\n      this.commentSentTimeout = null;\n    }\n\n    this.commentSentTarget.hidden = false;\n\n    this.commentSentTimeout = setTimeout(() => {\n      this.commentSentTarget.hidden = true;\n    }, 3000);\n  }\n\n  exportCsv(event) {\n    event.preventDefault();\n\n    if (!this.canExport) {\n      return;\n    }\n\n    const rows = [['Analytics user UUID', 'Registration ID', 'E-mail', 'Name', 'Message', 'Created at', 'Deleted at']];\n    const messages = Object.values(this.exportData).sort((a, b) => a.createdAt.localeCompare(b.createdAt));\n\n    for (const data of messages) {\n      rows.push([\n        data.analyticsUserUuid,\n        data.registrationId || '',\n        data.email,\n        data.name,\n        data.text,\n        data.createdAt,\n        data.deletedAt,\n      ]);\n    }\n\n    exportCsv(`qa-${this.presentationId}.csv`, rows);\n  }\n\n  messageDataToObjectForExport(data) {\n    return {\n      analyticsUserUuid: data.analyticsUserUuid,\n      registrationId: data.registrationId,\n      email: data.email,\n      name: data.name,\n      text: data.text,\n      createdAt: data.createdAt,\n      deletedAt: data.deletedAt,\n    };\n  }\n\n  get exportData() {\n    return this.props.exportData;\n  }\n\n  set exportData(value) {\n    this.props.exportData = value;\n  }\n\n  get firebaseApp() {\n    return this.props.firebaseApp;\n  }\n\n  set firebaseApp(value) {\n    this.props.firebaseApp = value;\n  }\n\n  get messagesRef() {\n    return this.props.messagesRef;\n  }\n\n  set messagesRef(value) {\n    this.props.messagesRef = value;\n  }\n\n  get commentSentTimeout() {\n    return this.props.commentSentTimeout;\n  }\n\n  set commentSentTimeout(value) {\n    this.props.commentSentTimeout = value;\n  }\n\n  get name() {\n    return this.nameTarget.value;\n  }\n\n  get email() {\n    return this.emailTarget.value;\n  }\n\n  get messageText() {\n    return this.messageTarget.value;\n  }\n\n  set messageText(value) {\n    this.messageTarget.value = value;\n  }\n\n  get firebaseConfig() {\n    return {\n      apiKey: 'AIzaSyBiWgqO41yQUTFK3WirLgYJH-lrZLMtmCA',\n      databaseURL: 'https://slideslive-qa-default-rtdb.firebaseio.com/',\n    };\n  }\n\n  get presentationId() {\n    return this.element.dataset.presentationId;\n  }\n\n  get analyticsUserUuid() {\n    return gon.analytics_uuid;\n  }\n\n  get canExport() {\n    return this.element.dataset.export === 'true';\n  }\n\n  get canDeleteMessages() {\n    return this.element.dataset.deleteMessages === 'true';\n  }\n}\n","import { isBotUserAgent } from '@slideslive/fuse-kit/utils';\nimport ApplicationController from 'modules/application_controller';\n\nexport default class extends ApplicationController {\n  initialize() {\n    this.props = {\n      value: {},\n      tracked: false,\n    };\n  }\n\n  connect() {\n    this.tryTrack();\n  }\n\n  tryTrack() {\n    if (this.isTurboPreview) return;\n    if (isBotUserAgent()) return;\n\n    if (this.tracked || !this.isAtLeastHalfElementInViewport) {\n      return;\n    }\n\n    const d = Math.floor(50 + Math.random() * 250);\n    setTimeout(() => this.track(), d);\n  }\n\n  track() {\n    if (this.tracked) return;\n    if (isBotUserAgent()) return;\n\n    this.tracked = true;\n\n    const params = {\n      impression_token: this.impressionToken,\n      impression: { source_url: window.location.href, http_referer: document.referrer || '' },\n    };\n\n    fetch(this.impressionUrl, {\n      method: 'POST',\n      mode: 'cors',\n      cache: 'no-cache',\n      credentials: 'omit',\n      headers: {\n        'Content-Type': 'text/plain; charset=utf-8',\n      },\n      redirect: 'follow',\n      referrerPolicy: 'no-referrer',\n      body: JSON.stringify(params),\n    }).catch((error) => {\n      console.warn('IMPRESSION', 'sending impression failed', error);\n    });\n  }\n\n  get tracked() {\n    return this.props.tracked;\n  }\n\n  set tracked(value) {\n    this.props.tracked = value;\n  }\n\n  get isAtLeastHalfElementInViewport() {\n    const rect = this.boxElement.getBoundingClientRect();\n\n    return (\n      rect.top >= 0 &&\n      rect.left >= 0 &&\n      rect.bottom - this.boxElement.offsetHeight / 2 <= (window.innerHeight || document.documentElement.clientHeight) &&\n      rect.right - this.boxElement.offsetWidth / 2 <= (window.innerWidth || document.documentElement.clientWidth)\n    );\n  }\n\n  get impressionUrl() {\n    return this.element.dataset.impressionUrl;\n  }\n\n  get impressionToken() {\n    return this.element.dataset.impressionToken;\n  }\n\n  get isTurboPreview() {\n    return document.documentElement.hasAttribute('data-turbo-preview');\n  }\n\n  get boxElement() {\n    return this.element.parentNode;\n  }\n}\n","import { urlParam } from '@slideslive/fuse-kit/utils';\nimport PlayerBaseController from 'library/player_base_component/player_base_component';\n\nexport default class extends PlayerBaseController {\n  initPlayer() {\n    if (!super.initPlayer()) {\n      return;\n    }\n\n    this.player.on('play', () => {\n      if (this.player.firstPlay) {\n        this.dispatch('firstPlay');\n      }\n    });\n\n    this.player.on('load', (duration, slideCount) => {\n      this.dispatch('load', { detail: { duration, slideCount } });\n    });\n\n    this.player.on('timeChanged', (time, duration) => {\n      this.dispatch('timeChanged', { detail: { time, duration } });\n    });\n\n    this.player.on('currentSlideChanged', (slideIndex, slideCount) => {\n      this.dispatch('currentSlideChanged', { detail: { slideIndex, slideCount } });\n    });\n\n    this.player.on('togglePlaylist', (name, added) => {\n      this.dispatch('togglePlaylist', { detail: { name, added } });\n    });\n\n    this.player.on('toggleBookmark', (added) => {\n      this.dispatch('toggleBookmark', { detail: { added } });\n    });\n  }\n\n  get autoPlay() {\n    return !!urlParam('query');\n  }\n\n  get playerOptions() {\n    const startTime = urlParam('startTime');\n    const startSlide = urlParam('startSlide');\n    const options = {\n      autoPlay: this.autoPlay,\n    };\n\n    if (startTime) {\n      options.startTime = parseInt(startTime, 10);\n    } else if (startSlide) {\n      options.startSlide = parseInt(startSlide, 10);\n    }\n\n    return options;\n  }\n}\n","import ApplicationController from 'modules/application_controller';\n\nexport default class extends ApplicationController {\n  static get targets() {\n    return ['link', 'embed', 'startTime', 'startSlide', 'startTimeCheck', 'startSlideCheck'];\n  }\n\n  initialize() {\n    this.props = {\n      originalShareLink: null,\n    };\n\n    this.originalShareLink = this.linkTarget.value;\n  }\n\n  connect() {\n    this.startTimeTarget.value = this.startTime;\n\n    if (this.hasStartSlideTarget) {\n      this.startSlideTarget.value = this.startSlide + 1;\n    }\n\n    this.updateEmbed();\n  }\n\n  updateStartTime() {\n    if (!this.startTimeCheckTarget.checked) {\n      this.startTime = null;\n      return;\n    }\n\n    const timeParts = this.startTimeTarget.value.split(':');\n    let time = 0;\n\n    if (timeParts.length === 1) {\n      time = parseInt(timeParts[0].trim(), 10);\n    } else {\n      do {\n        const value = parseInt(timeParts.shift(), 10);\n        const exponent = timeParts.length;\n        time += value * 60 ** exponent;\n      } while (timeParts.length);\n    }\n\n    if (Number.isNaN(time) || time < 0) {\n      this.startTime = null;\n      return;\n    }\n\n    this.startTime = time;\n  }\n\n  updateStartSlide() {\n    if (!this.hasStartSlideTarget) return;\n\n    const slide = parseInt(this.startSlideTarget.value, 10) - 1;\n\n    if (Number.isNaN(slide) || slide < 0) {\n      this.startSlide = null;\n      return;\n    }\n\n    this.startSlide = slide;\n  }\n\n  toggleStartTime() {\n    const checked = this.startTimeCheckTarget.checked;\n\n    this.startTimeTarget.disabled = !checked;\n\n    if (checked && this.hasStartSlideTarget) {\n      this.startSlideCheckTarget.checked = false;\n      this.startSlideCheckTarget.dispatchEvent(new Event('change'));\n    }\n  }\n\n  toggleStartSlide() {\n    const checked = this.startSlideCheckTarget.checked;\n\n    this.startSlideTarget.disabled = !checked;\n\n    if (checked) {\n      this.startTimeCheckTarget.checked = false;\n      this.startTimeCheckTarget.dispatchEvent(new Event('change'));\n    }\n  }\n\n  update() {\n    this.updateLink();\n    this.updateEmbed();\n  }\n\n  updateLink() {\n    let link = this.originalShareLink;\n\n    if (this.hasStartTime) {\n      link += `?time=${this.startTime}`;\n    } else if (this.hasStartSlide) {\n      link += `?slide=${this.startSlide}`;\n    }\n\n    this.linkTarget.value = link;\n  }\n\n  updateEmbed() {\n    const options = { ...this.defaultEmbedOptions };\n\n    if (this.hasStartTime) {\n      options.startTime = this.startTime;\n    } else if (this.hasStartSlide) {\n      options.startSlide = this.startSlide;\n    }\n\n    let html = `<div id=\"${this.embedId}\"></div>\\n`;\n    html += `<script src=\"${this.embedSrc}\"></script>\\n`;\n    html += '<script>\\n';\n    html += `  embed = new SlidesLiveEmbed(\"${this.embedId}\", {\\n`;\n\n    Object.keys(options).forEach((key) => {\n      html += `    ${key}: ${JSON.stringify(options[key])},\\n`;\n    });\n\n    html += '  });\\n';\n    html += '</script>';\n\n    this.embedTarget.value = html;\n  }\n\n  get hasStartTime() {\n    return this.startTimeCheckTarget.checked;\n  }\n\n  get startTime() {\n    return parseInt(this.element.dataset.startTime, 10) || 0;\n  }\n\n  set startTime(value) {\n    this.element.dataset.startTime = value;\n    this.update();\n  }\n\n  get hasStartSlide() {\n    return this.hasStartSlideTarget && this.startSlideCheckTarget.checked;\n  }\n\n  get startSlide() {\n    return parseInt(this.element.dataset.startSlide, 10) || 0;\n  }\n\n  set startSlide(value) {\n    this.element.dataset.startSlide = value;\n    this.update();\n  }\n\n  get originalShareLink() {\n    return this.props.originalShareLink;\n  }\n\n  set originalShareLink(value) {\n    this.props.originalShareLink = value;\n  }\n\n  get presentationId() {\n    return this.element.dataset.presentationId;\n  }\n\n  get defaultEmbedOptions() {\n    return {\n      presentationId: `${this.presentationId}`,\n      autoPlay: false,\n      verticalEnabled: true,\n    };\n  }\n\n  get embedSrc() {\n    return 'https://slideslive.com/embed_presentation.js';\n  }\n\n  get embedId() {\n    return `presentation-embed-${this.presentationId}`;\n  }\n}\n","import ApplicationController from 'modules/application_controller';\n\nexport default class extends ApplicationController {\n  static get targets() {\n    return ['advancedButton'];\n  }\n\n  initialize() {\n    this.props = {\n      startTime: 0,\n      startSlide: 0,\n    };\n  }\n\n  updateAdvancedOptionsModalUrlParams() {\n    const urlParams = [`start_time=${this.props.startTime}`, `start_slide=${this.props.startSlide}`].join('&');\n\n    this.advancedButtonTarget.dataset.modalUrlParams = urlParams;\n  }\n\n  set startTime(time) {\n    this.props.startTime = time;\n    this.updateAdvancedOptionsModalUrlParams();\n  }\n\n  set startSlide(slide) {\n    this.props.startSlide = slide;\n    this.updateAdvancedOptionsModalUrlParams();\n  }\n}\n","import { createCookie, readCookie, remove } from '@slideslive/fuse-kit/utils';\nimport ApplicationController from 'modules/application_controller';\n\nexport default class extends ApplicationController {\n  static get targets() {\n    return ['passwordField', 'passwordInput'];\n  }\n\n  initialize() {\n    this.props = {\n      isHidden: false,\n      pausePlayer: true,\n      timeout: null,\n    };\n  }\n\n  connect() {\n    this.isHidden = readCookie(this.cookieName) === 'true';\n\n    if (this.isHidden) {\n      this.remove();\n    }\n  }\n\n  disconnect() {\n    if (this.timeout) {\n      clearTimeout(this.timeout);\n    }\n  }\n\n  onHide() {\n    this.dispatch('resumePlayer');\n    this.timeout = setTimeout(this.remove.bind(this), 300);\n    createCookie(this.cookieName, 'true', 30 * 24 * 60000);\n  }\n\n  startTimeout() {\n    if (this.isHidden) {\n      return;\n    }\n\n    this.timeout = setTimeout(this.show.bind(this), 2 * 60000);\n  }\n\n  requirePassword() {\n    this.passwordInputTarget.disabled = false;\n    this.passwordFieldTarget.hidden = false;\n    this.passwordInputTarget.focus();\n  }\n\n  show() {\n    this.timeout = null;\n    this.dispatch('pausePlayer');\n    this.dispatchOnWindow('open', { prefix: 'modal', detail: { name: this.element.dataset.modalName } });\n  }\n\n  hide() {\n    this.dispatchOnWindow('close', { prefix: 'modal', detail: { name: this.element.dataset.modalName } });\n  }\n\n  remove() {\n    this.timeout = null;\n    remove(this.element);\n  }\n\n  get isHidden() {\n    return this.props.isHidden;\n  }\n\n  set isHidden(isHidden) {\n    this.props.isHidden = isHidden;\n  }\n\n  get pausePlayer() {\n    return this.props.pausePlayer;\n  }\n\n  set pausePlayer(pausePlayer) {\n    this.props.pausePlayer = pausePlayer;\n  }\n\n  get timeout() {\n    return this.props.timeout;\n  }\n\n  set timeout(value) {\n    this.props.timeout = value;\n  }\n\n  get cookieName() {\n    return 'sign-up-interruption-modal-hidden';\n  }\n}\n","import { defer } from '@slideslive/fuse-kit/utils';\nimport ApplicationController from 'modules/application_controller';\n\nexport default class extends ApplicationController {\n  connect() {\n    defer(() => this.dispatch('initialize'));\n  }\n}\n","import { defer, pushDataLayer } from '@slideslive/fuse-kit/utils';\nimport ApplicationController from 'modules/application_controller';\n\nexport default class extends ApplicationController {\n  connect() {\n    pushDataLayer({ sl_user_id: this.userId });\n\n    defer(() => this.dispatch('initialize'));\n  }\n\n  get userId() {\n    return this.element.dataset.userId;\n  }\n}\n","import { defer } from '@slideslive/fuse-kit/utils';\nimport ApplicationController from 'modules/application_controller';\nimport * as PermanentPlayer from 'modules/permanent_player';\n\nexport default class extends ApplicationController {\n  static get targets() {\n    return ['playerTemplate', 'playerWrapper', 'sharingSection', 'signUpInterruptionModal'];\n  }\n\n  initialize() {\n    this.props = {\n      url: null,\n      wasPlaying: false,\n    };\n\n    const url = new URL(window.location);\n    this.url = `${url.origin}${url.pathname}`;\n  }\n\n  connect() {\n    if (this.isTurboPreview) {\n      this.insertPlayer(null);\n\n      return;\n    }\n\n    if (PermanentPlayer.currentPresentationId() === this.presentationId) {\n      this.insertPlayer(PermanentPlayer.currentPlayerElement());\n\n      defer(() => {\n        PermanentPlayer.close();\n      });\n    } else {\n      this.insertPlayer(this.playerTemplateTarget.innerHTML);\n    }\n  }\n\n  disconnect() {\n    if (!this.playerController || !this.playerController.player || this.playerController.player.firstPlay) return;\n    if (this.playerController.player.videoServiceName.toLowerCase() === 'youtube') return;\n\n    this.openInPermanentPlayer();\n  }\n\n  startSignUpInterruptionTimeout() {\n    if (this.signUpInterruptionModalController) {\n      this.signUpInterruptionModalController.startTimeout();\n    }\n  }\n\n  setSharingStartTime(event) {\n    if (!this.sharingSectionController) return;\n\n    this.sharingSectionController.startTime = Math.round(event.detail.time / 1000.0);\n  }\n\n  setSharingShowStartSlide(event) {\n    if (!this.sharingSectionController) return;\n\n    this.sharingSectionController.showStartSlide = event.detail.slideCount > 0;\n  }\n\n  setSharingStartSlide(event) {\n    if (!this.sharingSectionController) return;\n\n    this.sharingSectionController.showStartSlide = event.detail.slideCount > 0;\n    this.sharingSectionController.startSlide = event.detail.slideIndex;\n  }\n\n  openInPermanentPlayer() {\n    const playerWrapper = this.playerWrapperTarget;\n    const playerElement = playerWrapper.firstElementChild;\n    const playerElementController = this.findControllerOnElement(playerElement);\n\n    if (playerElementController) {\n      playerElementController.isPermanent = true;\n    }\n\n    playerWrapper.removeChild(playerElement);\n\n    PermanentPlayer.open({\n      presentationId: this.presentationId,\n      playerElement,\n      url: this.url,\n      title: this.title,\n    });\n  }\n\n  insertPlayer(player) {\n    this.playerWrapperTarget.innerHTML = '';\n\n    if (!player) return;\n\n    if (typeof player === 'string') {\n      this.playerWrapperTarget.insertAdjacentHTML('afterbegin', player);\n    } else {\n      this.playerWrapperTarget.insertAdjacentElement('afterbegin', player);\n    }\n  }\n\n  seekTo(event) {\n    event.preventDefault();\n\n    if (!this.playerController) return;\n\n    const seconds = parseInt(event.target.dataset.seekTo, 10);\n\n    this.playerController.seekTo(seconds);\n  }\n\n  seekSlide(event) {\n    event.preventDefault();\n\n    if (!this.playerController) return;\n\n    const slide = parseInt(event.target.dataset.seekSlide, 10);\n\n    this.playerController.seekSlide(slide);\n  }\n\n  pause() {\n    if (!this.playerController) return;\n\n    this.wasPlaying = this.playerController.player.isPlaying;\n    this.playerController.pause();\n  }\n\n  resume() {\n    if (!this.playerController || !this.wasPlaying) return;\n\n    this.playerController.play();\n    this.wasPlaying = false;\n  }\n\n  get playerController() {\n    if (!this.playerWrapperTarget.firstElementChild) return null;\n\n    return this.findControllerOnElement(this.playerWrapperTarget.firstElementChild);\n  }\n\n  get signUpInterruptionModalController() {\n    if (!this.hasSignUpInterruptionModalTarget) return null;\n\n    return this.findControllerByName('library--presentation-show--sign-up-interruption--modal', {\n      useQuerySelector: false,\n      element: this.signUpInterruptionModalTarget,\n    });\n  }\n\n  get sharingSectionController() {\n    if (!this.hasSharingSectionTarget) return null;\n\n    return this.findControllerOnElement(this.sharingSectionTarget);\n  }\n\n  get presentationId() {\n    return this.element.dataset.id;\n  }\n\n  get title() {\n    return this.element.dataset.title;\n  }\n\n  get url() {\n    return this.props.url;\n  }\n\n  set url(value) {\n    this.props.url = value;\n  }\n\n  get wasPlaying() {\n    return this.props.wasPlaying;\n  }\n\n  set wasPlaying(value) {\n    this.props.wasPlaying = value;\n  }\n}\n","import ApplicationController from 'modules/application_controller';\n\nexport default class extends ApplicationController {\n  static get targets() {\n    return ['server', 'quality720p', 'quality720pLq', 'slidesQuality720p', 'slidesQuality720pLq'];\n  }\n\n  connect() {\n    this.updateOutgoingStreamQuality();\n  }\n\n  updateOutgoingStreamQuality() {\n    const server = this.serverTarget.selectedOptions[0];\n    const quality = server.dataset.outgoingStreamQuality;\n\n    if (!this.hasQuality720pTarget || !this.hasQuality720pLqTarget) {\n      return;\n    }\n\n    if (quality === '1080p') {\n      this.quality720pTarget.checked = false;\n      this.quality720pLqTarget.checked = false;\n\n      if (this.hasSlidesQuality720pTarget) {\n        this.slidesQuality720pTarget.checked = true;\n      }\n\n      if (this.hasSlidesQuality720pLqTarget) {\n        this.slidesQuality720pLqTarget.checked = false;\n      }\n    } else if (quality === '720p') {\n      this.quality720pTarget.checked = true;\n      this.quality720pLqTarget.checked = false;\n\n      if (this.hasSlidesQuality720pTarget) {\n        this.slidesQuality720pTarget.checked = true;\n      }\n\n      if (this.hasSlidesQuality720pLqTarget) {\n        this.slidesQuality720pLqTarget.checked = false;\n      }\n    } else if (quality === '720p-lq') {\n      this.quality720pTarget.checked = false;\n      this.quality720pLqTarget.checked = true;\n\n      if (this.hasSlidesQuality720pTarget) {\n        this.slidesQuality720pTarget.checked = false;\n      }\n\n      if (this.hasSlidesQuality720pLqTarget) {\n        this.slidesQuality720pLqTarget.checked = true;\n      }\n    }\n  }\n}\n","import ApplicationController from 'modules/application_controller';\n\nexport default class extends ApplicationController {\n  static get targets() {\n    return ['availableOnDemandRadio', 'terminateStreamRadio', 'processStreamRecording', 'processStreamRecordingField'];\n  }\n\n  triggerProcessStreamRecordingFields() {\n    if (this.availableOnDemandRadioTarget.checked) {\n      this.processStreamRecordingTarget.checked = false;\n    }\n\n    const show = this.shouldShowProcessStreamRecordingFields;\n\n    for (const field of this.processStreamRecordingFieldTargets) {\n      field.hidden = !show;\n    }\n  }\n\n  get shouldShowProcessStreamRecordingFields() {\n    if (this.availableOnDemandRadioTarget.checked) {\n      return true;\n    }\n\n    if (this.terminateStreamRadioTarget.checked && this.processStreamRecordingTarget.checked) {\n      return true;\n    }\n\n    return false;\n  }\n}\n","import ApplicationController from 'modules/application_controller';\n\nexport default class extends ApplicationController {\n  initialize() {}\n\n  connect() {}\n\n  disconnect() {}\n}\n","import ApplicationController from 'modules/application_controller';\n\nexport default class extends ApplicationController {\n  initReload() {\n    this.dispatch('reload');\n  }\n}\n","import ApplicationController from 'modules/application_controller';\n\nexport default class extends ApplicationController {\n  static get targets() {\n    return ['reloadSpinner'];\n  }\n\n  initialize() {\n    this.props = {\n      reloadTimeout: null,\n      panelTarget: null,\n    };\n  }\n\n  connect() {\n    this.initReloadTimeout();\n  }\n\n  disconnect() {\n    if (this.reloadTimeout) {\n      clearInterval(this.reloadTimeout);\n    }\n  }\n\n  initReloadTimeout() {\n    this.reloadTimeout = setTimeout(this.reload.bind(this), 10000);\n  }\n\n  reload() {\n    if (this.reloadTimeout) {\n      clearTimeout(this.reloadTimeout);\n      this.reloadTimeout = null;\n    }\n\n    if (!this.isVisible) {\n      this.initReloadTimeout();\n      return;\n    }\n\n    this.reloadSpinnerTarget.hidden = false;\n    this.frameTarget.reload();\n  }\n\n  get frameTarget() {\n    return this.element.parentNode;\n  }\n\n  get reloadTimeout() {\n    return this.props.reloadTimeout;\n  }\n\n  set reloadTimeout(value) {\n    this.props.reloadTimeout = value;\n  }\n\n  get isVisible() {\n    return !this.panelTarget.hidden;\n  }\n\n  get panelTarget() {\n    if (!this.props.panelTarget) {\n      this.props.panelTarget = this.element.closest('[role=\"tabpanel\"]');\n    }\n\n    return this.props.panelTarget;\n  }\n}\n","import ApplicationController from 'modules/application_controller';\n\nexport default class extends ApplicationController {\n  static get targets() {\n    return ['reloadSpinner'];\n  }\n\n  initialize() {\n    this.props = {\n      reloadTimeout: null,\n      panelTarget: null,\n    };\n  }\n\n  connect() {\n    this.initReloadTimeout();\n  }\n\n  disconnect() {\n    if (this.reloadTimeout) {\n      clearInterval(this.reloadTimeout);\n    }\n  }\n\n  initReloadTimeout() {\n    this.reloadTimeout = setTimeout(this.reload.bind(this), 10000);\n  }\n\n  reload() {\n    if (this.reloadTimeout) {\n      clearTimeout(this.reloadTimeout);\n      this.reloadTimeout = null;\n    }\n\n    if (!this.isVisible) {\n      this.initReloadTimeout();\n      return;\n    }\n\n    if (this.hasReloadSpinnerTarget) {\n      this.reloadSpinnerTarget.hidden = false;\n    }\n\n    this.frameTarget.reload();\n  }\n\n  get frameTarget() {\n    return this.element.parentNode;\n  }\n\n  get reloadTimeout() {\n    return this.props.reloadTimeout;\n  }\n\n  set reloadTimeout(value) {\n    this.props.reloadTimeout = value;\n  }\n\n  get isVisible() {\n    return !this.panelTarget.hidden;\n  }\n\n  get panelTarget() {\n    if (!this.props.panelTarget) {\n      this.props.panelTarget = this.element.closest('[role=\"tabpanel\"]');\n    }\n\n    return this.props.panelTarget;\n  }\n}\n","import { checkDelayedResult } from '@slideslive/fuse-kit/utils';\nimport ApplicationController from 'modules/application_controller';\n\nexport default class extends ApplicationController {\n  static get targets() {\n    return ['submit', 'spinner', 'result'];\n  }\n\n  restart() {\n    this.submitTarget.disabled = true;\n    this.spinnerTarget.hidden = false;\n    this.resultTarget.textContent = 'Sending.';\n\n    fetch(this.url, {\n      method: 'POST',\n      headers: {\n        'X-CSRF-Token': document.querySelector('meta[name=\"csrf-token\"]').content,\n      },\n    })\n      .then((response) => {\n        this.resultTarget.textContent = 'Scheduled.';\n\n        response.json().then((result) => {\n          if (!result.delayed_result_id) {\n            this.resultTarget.textContent = 'No result ID.';\n            return;\n          }\n\n          checkDelayedResult(\n            result.delayed_result_id,\n            (res) => {\n              this.resultTarget.textContent = res.success ? res.stdout : res.errors;\n            },\n            500,\n          );\n        });\n      })\n      .catch(() => {\n        this.resultTarget.textContent = 'Error.';\n      })\n      .finally(() => {\n        this.submitTarget.disabled = false;\n        this.spinnerTarget.hidden = true;\n      });\n  }\n\n  get url() {\n    return this.submitTarget.dataset.url;\n  }\n}\n","import ApplicationController from 'modules/application_controller';\n\nexport default class extends ApplicationController {\n  static get targets() {\n    return ['servers'];\n  }\n\n  initialize() {\n    this.props = {\n      serversSpinner: null,\n    };\n\n    this.serversSpinner = this.serversTarget.innerHTML;\n  }\n\n  reloadServers() {\n    this.serversTarget.innerHTML = this.serversSpinner;\n    this.serversTarget.reload();\n  }\n\n  get serversSpinner() {\n    return this.props.serversSpinner;\n  }\n\n  set serversSpinner(value) {\n    this.props.serversSpinner = value;\n  }\n}\n","import { formatSize, formatTimeString, getFilesFromDataTransfer } from '@slideslive/fuse-kit/utils';\nimport ApplicationController from 'modules/application_controller';\n\nexport default class extends ApplicationController {\n  static get targets() {\n    return ['fileLabel', 'fileMetadata', 'selectFile', 'removeFile'];\n  }\n\n  initialize() {\n    this.props = {\n      file: null,\n      uploading: false,\n\n      videoDuration: null,\n    };\n  }\n\n  connect() {\n    this._updateDisabledButtons();\n  }\n\n  ignoreDragDrop(event) {\n    event.preventDefault();\n    event.stopPropagation();\n  }\n\n  startDrag(event) {\n    event.dataTransfer.dropEffect = 'copy';\n    this.element.classList.add('dragDropActive');\n  }\n\n  stopDrag() {\n    this.element.classList.remove('dragDropActive');\n  }\n\n  drop(event) {\n    getFilesFromDataTransfer(event.dataTransfer).then((files) => this._setFiles(files));\n  }\n\n  selectFileFromDisk() {\n    const input = document.createElement('input');\n    input.type = 'file';\n    input.accept = '.mp4,video/mp4';\n    input.onchange = () => this._setFiles(Array.from(input.files));\n    input.click();\n  }\n\n  removeFile() {\n    this.props.file = null;\n    this.props.videoDuration = null;\n\n    this._updateDisabledButtons();\n    this._updateFileFields();\n  }\n\n  validate() {\n    return true;\n  }\n\n  fileToUpload(meta) {\n    if (!this.props.file) {\n      return null;\n    }\n\n    return {\n      name: this.props.file.name,\n      type: this.props.file.type,\n      data: this.props.file,\n      meta,\n    };\n  }\n\n  updateUploadingStatus(status) {\n    this.props.uploading = status === 'uploading' || status === 'complete';\n    this._updateDisabledButtons();\n  }\n\n  _setFiles(files) {\n    if (this.props.uploading) {\n      return;\n    }\n\n    const file = files[0];\n    if (!file.name.toLowerCase().endsWith('.mp4') && file.type !== 'video/mp4') {\n      this.removeFile();\n      return;\n    }\n\n    this.props.file = file;\n\n    this._updateDisabledButtons();\n    this._updateFileFields();\n\n    this._loadFileMetadata();\n  }\n\n  _updateDisabledButtons() {\n    if (this.props.uploading) {\n      this.selectFileTarget.disabled = true;\n      this.removeFileTarget.disabled = true;\n    } else {\n      this.selectFileTarget.disabled = false;\n      this.removeFileTarget.disabled = !this.props.file;\n    }\n  }\n\n  _updateFileFields() {\n    if (this.props.file) {\n      this.fileLabelTarget.textContent = this.props.file.name;\n      this.fileMetadataTarget.textContent = this._formatFileMetadataText();\n      this.fileMetadataTarget.hidden = false;\n    } else {\n      this.fileLabelTarget.textContent = this.defaultFileLabel;\n      this.fileMetadataTarget.hidden = true;\n    }\n  }\n\n  _formatFileMetadataText() {\n    if (!this.props.file) {\n      return '';\n    }\n\n    const parts = [];\n\n    if (this.props.videoDuration) {\n      parts.push(formatTimeString(this.props.videoDuration, { useColons: true }));\n    }\n\n    parts.push(formatSize(this.props.file.size));\n\n    return parts.join(' · ');\n  }\n\n  _loadFileMetadata() {\n    const video = document.createElement('video');\n    video.preload = 'metadata';\n    video.onloadedmetadata = () => {\n      window.URL.revokeObjectURL(video.src);\n\n      if (this.props.file) {\n        this.props.videoDuration = video.duration;\n        this._updateFileFields();\n      }\n    };\n\n    video.src = URL.createObjectURL(this.props.file);\n  }\n\n  get defaultFileLabel() {\n    return this.element.dataset.defaultFileLabel;\n  }\n}\n","import { checkDelayedResultWithPromise, formatSize, formatTimeString } from '@slideslive/fuse-kit/utils';\nimport ApplicationController from 'modules/application_controller';\nimport ResumableUpload from 'modules/resumable_upload';\n\nexport default class extends ApplicationController {\n  static get targets() {\n    return [\n      'error',\n      'errorList',\n      'info',\n      'infoList',\n      'success',\n      'successList',\n      'uploadProgress',\n      'progressBar',\n      'speed',\n      'eta',\n      'uploadedBytes',\n      'totalBytes',\n      'hideWhenUploadComplete',\n    ];\n  }\n\n  initialize() {\n    this.upload = null;\n  }\n\n  disconnect() {\n    if (this.upload) {\n      this.stopUpload();\n      this.upload = null;\n    }\n  }\n\n  startUpload({\n    filesToUpload,\n    presentationId,\n    alexEventId,\n    noAlexEvent,\n    uploadToSubmittedEvent,\n    render4kSpeakerVideo,\n    videoInSlides,\n    palpatineTest,\n    title,\n    recordedAt,\n    folderId,\n  }) {\n    this._dispatchInfo('Starting upload&hellip;');\n\n    this.upload = new ResumableUpload({\n      uploadInfoEndpoint: this.uploadInfoEndpoint,\n      uploadInfoData: {\n        upload: {\n          presentation_id: presentationId,\n          alex_event_id: alexEventId,\n          no_alex_event: noAlexEvent,\n          upload_to_submitted_event: uploadToSubmittedEvent,\n          render_4k_speaker_video: render4kSpeakerVideo,\n          videos_in_slides: videoInSlides,\n          palpatine_test: palpatineTest,\n          allow_new_presentation: !presentationId,\n          new_presentation_attributes: {\n            title,\n            recorded_at: recordedAt,\n            folder_id: folderId,\n          },\n        },\n      },\n    });\n\n    this.upload.on('error', ({ error, errorMessage }) => {\n      console.warn(error);\n\n      this._dispatchError(errorMessage);\n      this.upload = null;\n    });\n\n    this.upload.on('totalProgress', (progress) => {\n      this._dispatchInfo('Uploading&hellip;');\n      this._dispatchProgress(progress);\n    });\n\n    this.upload.on('totalComplete', (uploads) => {\n      this._completeUpload({\n        presentationId,\n        alexEventId,\n        noAlexEvent,\n        uploadToSubmittedEvent,\n        render4kSpeakerVideo,\n        videoInSlides,\n        palpatineTest,\n        title,\n        recordedAt,\n        folderId,\n        uploadService: this.upload.service,\n        files: uploads,\n      });\n    });\n\n    this.upload.initialize().then(() => {\n      for (const file of filesToUpload) {\n        try {\n          this.upload.addFile(file.name, file.type, file.data, null, file.meta);\n        } catch (error) {\n          console.warn(error);\n\n          this._dispatchError(`Error when adding file ${file.name} to upload.`);\n          this.upload = null;\n\n          return;\n        }\n      }\n\n      this.upload.startUpload();\n    });\n  }\n\n  stopUpload() {\n    this.upload.abortUpload();\n    this.upload = null;\n  }\n\n  _completeUpload({\n    presentationId,\n    alexEventId,\n    noAlexEvent,\n    uploadToSubmittedEvent,\n    render4kSpeakerVideo,\n    videoInSlides,\n    palpatineTest,\n    title,\n    recordedAt,\n    folderId,\n    uploadService,\n    files,\n  }) {\n    this._dispatchInfo('Completing upload&hellip;');\n\n    const headers = {\n      'Content-Type': 'application/json',\n      Accept: 'application/json',\n    };\n\n    const csrfTokenMetaTag = document.querySelector(\"meta[name='csrf-token']\");\n    if (csrfTokenMetaTag) {\n      headers['X-CSRF-Token'] = csrfTokenMetaTag.content;\n    } else {\n      console.warn('CSRF token meta tag not found!');\n    }\n\n    const data = {\n      upload: {\n        presentation_id: presentationId,\n        alex_event_id: alexEventId,\n        no_alex_event: noAlexEvent,\n        upload_to_submitted_event: uploadToSubmittedEvent,\n        render_4k_speaker_video: render4kSpeakerVideo,\n        videos_in_slides: videoInSlides,\n        palpatine_test: palpatineTest,\n        allow_new_presentation: !presentationId,\n        new_presentation_attributes: {\n          title,\n          recorded_at: recordedAt,\n          folder_id: folderId,\n        },\n        service: uploadService,\n        files,\n      },\n    };\n    const body = JSON.stringify(data);\n\n    fetch(this.uploadCompleteEndpoint, {\n      method: 'POST',\n      cache: 'no-cache',\n      credentials: 'include',\n      headers,\n      redirect: 'follow',\n      referrerPolicy: 'no-referrer',\n      body,\n    })\n      .catch((error) => {\n        console.warn(error);\n        this._dispatchError('Error when completing upload: invalid request.');\n        this.upload = null;\n      })\n      .then((response) => response.json())\n      .catch((error) => {\n        console.warn(error);\n        this._dispatchError('Error when completing upload: invalid JSON.');\n        this.upload = null;\n      })\n      .then((response) => {\n        if (!response) {\n          return { success: false, errors: ['Error when completing upload: no response.'] };\n        }\n\n        if (!response.success) {\n          return { success: false, errors: response.errors };\n        }\n\n        return checkDelayedResultWithPromise(response.delayed_result_id);\n      })\n      .then((result) => {\n        if (result.success) {\n          this._dispatchComplete(result.presentation_id);\n          this.upload = null;\n        } else {\n          this._dispatchError(result.errors.join('\\n'));\n          this.upload = null;\n        }\n      });\n  }\n\n  _dispatchInfo(message) {\n    this.dispatch('info', { detail: { message } });\n  }\n\n  _dispatchError(message) {\n    this.dispatch('error', { detail: { message } });\n  }\n\n  _dispatchProgress(progress) {\n    this.dispatch('progress', { detail: { progress } });\n  }\n\n  _dispatchComplete(presentationId) {\n    this.dispatch('complete', { detail: { presentationId } });\n  }\n\n  showInfo(event) {\n    this._showInfo([event.detail.message]);\n  }\n\n  showError(event) {\n    this._showError([event.detail.message]);\n  }\n\n  showComplete(event) {\n    const { presentationId } = event.detail;\n\n    this.uploadProgressTarget.hidden = true;\n    this._showSuccess([\n      'Upload complete. Your videos will be processed soon.',\n      `In the meantime you can edit the presentation <a class=\"disabled:tw-cursor-not-allowed disabled:tw-opacity-40 focus:tw-outline-none tw-text-current hover:tw-text-current focus:tw-text-current visited:tw-text-current tw-underline hover:tw-no-underline focus:tw-no-underline tw-font-bold\" href=\"https://slideslive.com/${presentationId}/-/edit\">here</a>.`,\n    ]);\n  }\n\n  updateProgress(event) {\n    const progress = event.detail.progress;\n\n    this.progressBarController.percentage = progress.totalProgress;\n    this.speedTarget.textContent = formatSize(progress.totalSpeed, 'B/s');\n    this.etaTarget.textContent = formatTimeString(progress.timeRemaining);\n    this.uploadedBytesTarget.textContent = formatSize(progress.totalUploadedBytes);\n    this.totalBytesTarget.textContent = formatSize(progress.totalBytes);\n\n    this.uploadProgressTarget.hidden = false;\n  }\n\n  _showError(messages) {\n    this.errorListTarget.innerHTML = messages.map((message) => `<li>${message}</li>`).join('');\n    this.errorTarget.hidden = false;\n    this.infoTarget.hidden = true;\n    this.successTarget.hidden = true;\n  }\n\n  _showInfo(messages) {\n    this.infoListTarget.innerHTML = messages.map((message) => `<li>${message}</li>`).join('');\n    this.errorTarget.hidden = true;\n    this.infoTarget.hidden = false;\n    this.successTarget.hidden = true;\n  }\n\n  _showSuccess(messages) {\n    this.successListTarget.innerHTML = messages.map((message) => `<li>${message}</li>`).join('');\n    this.errorTarget.hidden = true;\n    this.infoTarget.hidden = true;\n    this.successTarget.hidden = false;\n  }\n\n  hideUploadProgress() {\n    this.uploadProgressTarget.hidden = true;\n  }\n\n  get createPresentationEndpoint() {\n    return this.element.dataset.createPresentationUrl;\n  }\n\n  get uploadInfoEndpoint() {\n    return this.element.dataset.uploadInfoUrl;\n  }\n\n  get uploadCompleteEndpoint() {\n    return this.element.dataset.uploadCompleteUrl;\n  }\n\n  get progressBarController() {\n    return this.findControllerOnElement(this.progressBarTarget);\n  }\n}\n","import ApplicationController from 'modules/application_controller';\n\nexport default class extends ApplicationController {\n  static get targets() {\n    return [\n      'form',\n      'upload',\n      'alexEvent',\n      'speakerVideo',\n      'slidesVideo',\n      'disableWhenUploading',\n      'hideWhenUploading',\n      'hideWhenUploadComplete',\n      'file',\n    ];\n  }\n\n  startUpload() {\n    if (!this.validate()) {\n      return;\n    }\n\n    const formData = this.formDataObject;\n    const uploadParams = {\n      filesToUpload: this.filesToUpload,\n      presentationId: formData['video_upload[presentation_id]'],\n      alexEventId: formData['video_upload[alex_event_id]'],\n      noAlexEvent: formData['video_upload[no_alex_event]'],\n      uploadToSubmittedEvent: formData['video_upload[upload_to_submitted_event]'],\n      render4kSpeakerVideo: formData['video_upload[render_4k_speaker_video]'],\n      videoInSlides: formData['video_upload[videos_in_slides]'],\n      palpatineTest: formData['video_upload[palpatine_test]'],\n      title: formData['video_upload[title]'],\n      recordedAt: formData['video_upload[recorded_at]'],\n      folderId: formData['video_upload[folder_id]'],\n    };\n\n    this.uploadController.startUpload(uploadParams);\n\n    this.uploadTarget.hidden = false;\n    this.updateUploadingStatus('uploading');\n  }\n\n  stopUpload() {\n    this.uploadController.stopUpload();\n  }\n\n  validate() {\n    let valid = true;\n\n    if (!this.formController.validate()) {\n      valid = false;\n    }\n\n    for (const fileController of this.filesControllers) {\n      if (!fileController.validate()) {\n        valid = false;\n      }\n    }\n\n    return valid;\n  }\n\n  updateUploadingStatus(status) {\n    for (const target of this.disableWhenUploadingTargets) {\n      target.disabled = status === 'uploading' || status === 'complete';\n    }\n\n    for (const target of this.hideWhenUploadingTargets) {\n      target.hidden = status === 'uploading' || status === 'complete';\n    }\n\n    for (const target of this.hideWhenUploadCompleteTargets) {\n      target.hidden = status === 'complete';\n    }\n\n    for (const fileController of this.filesControllers) {\n      fileController.updateUploadingStatus(status);\n    }\n\n    if (status === 'uploading') {\n      this.modalController.preventClose();\n    } else {\n      this.modalController.allowClose();\n    }\n  }\n\n  uploadComplete() {\n    this.updateUploadingStatus('complete');\n  }\n\n  uploadError() {\n    this.updateUploadingStatus('error');\n  }\n\n  get filesToUpload() {\n    const speakerVideoFile = this.speakerVideoFileController.fileToUpload({ name: 'video' });\n    const slidesVideoFile = this.slidesVideoFileController.fileToUpload({ name: 'slides' });\n\n    return [speakerVideoFile, slidesVideoFile].filter((file) => file !== null);\n  }\n\n  get formData() {\n    return new FormData(this.formTarget);\n  }\n\n  get formDataObject() {\n    return Object.fromEntries(this.formData.entries());\n  }\n\n  get formController() {\n    return this.findControllerByName('fuse--form', { useQuerySelector: false, element: this.formTarget });\n  }\n\n  get uploadController() {\n    return this.findControllerOnElement(this.uploadTarget);\n  }\n\n  get filesControllers() {\n    return this.fileTargets.map((fileTarget) => this.findControllerOnElement(fileTarget));\n  }\n\n  get speakerVideoFileController() {\n    return this.findControllerOnElement(this.speakerVideoTarget);\n  }\n\n  get slidesVideoFileController() {\n    return this.findControllerOnElement(this.slidesVideoTarget);\n  }\n\n  get modalController() {\n    return this.findControllerByName('fuse--modal-content-v2', { useQuerySelector: false });\n  }\n}\n","import ApplicationController from 'modules/application_controller';\n\nexport default class extends ApplicationController {\n  static get targets() {\n    return [\n      'form',\n      'upload',\n      'alexEvent',\n      'firstVideo',\n      'secondVideo',\n      'thirdVideo',\n      'disableWhenUploading',\n      'hideWhenUploading',\n      'hideWhenUploadComplete',\n      'file',\n    ];\n  }\n\n  startUpload() {\n    if (!this.validate()) {\n      return;\n    }\n\n    const formData = this.formDataObject;\n    const uploadParams = {\n      filesToUpload: this.filesToUpload,\n      presentationId: formData['video_upload[presentation_id]'],\n      alexEventId: formData['video_upload[alex_event_id]'],\n      noAlexEvent: formData['video_upload[no_alex_event]'],\n      uploadToSubmittedEvent: formData['video_upload[upload_to_submitted_event]'],\n      videoService: formData['video_upload[video_service]'],\n    };\n\n    this.uploadController.startUpload(uploadParams);\n\n    this.uploadTarget.hidden = false;\n    this.updateUploadingStatus('uploading');\n  }\n\n  stopUpload() {\n    this.uploadController.stopUpload();\n  }\n\n  validate() {\n    let valid = true;\n\n    if (!this.formController.validate()) {\n      valid = false;\n    }\n\n    for (const fileController of this.filesControllers) {\n      if (!fileController.validate()) {\n        valid = false;\n      }\n    }\n\n    return valid;\n  }\n\n  updateUploadingStatus(status) {\n    for (const target of this.disableWhenUploadingTargets) {\n      target.disabled = status === 'uploading' || status === 'complete';\n    }\n\n    for (const target of this.hideWhenUploadingTargets) {\n      target.hidden = status === 'uploading' || status === 'complete';\n    }\n\n    for (const target of this.hideWhenUploadCompleteTargets) {\n      target.hidden = status === 'complete';\n    }\n\n    for (const fileController of this.filesControllers) {\n      fileController.updateUploadingStatus(status);\n    }\n\n    if (status === 'uploading') {\n      this.modalController.preventClose();\n    } else {\n      this.modalController.allowClose();\n    }\n  }\n\n  uploadComplete() {\n    this.updateUploadingStatus('complete');\n  }\n\n  uploadError() {\n    this.updateUploadingStatus('error');\n  }\n\n  get filesToUpload() {\n    return this.filesControllers\n      .map((fileController, index) => fileController.fileToUpload({ name: `video_${index + 1}` }))\n      .filter((file) => file !== null);\n  }\n\n  get formData() {\n    return new FormData(this.formTarget);\n  }\n\n  get formDataObject() {\n    return Object.fromEntries(this.formData.entries());\n  }\n\n  get formController() {\n    return this.findControllerByName('fuse--form', { useQuerySelector: false, element: this.formTarget });\n  }\n\n  get uploadController() {\n    return this.findControllerOnElement(this.uploadTarget);\n  }\n\n  get filesControllers() {\n    return this.fileTargets.map((fileTarget) => this.findControllerOnElement(fileTarget));\n  }\n\n  get modalController() {\n    return this.findControllerByName('fuse--modal-content-v2', { useQuerySelector: false });\n  }\n}\n","import ApplicationController from 'modules/application_controller';\n\nexport default class extends ApplicationController {\n  static get targets() {\n    return ['thirdParty', 'email', 'signUp'];\n  }\n\n  showEmail(event) {\n    if (event) event.preventDefault();\n\n    if (this.hasThirdPartyTarget) this.thirdPartyTarget.hidden = true;\n    if (this.hasEmailTarget) this.emailTarget.hidden = false;\n    if (this.hasSignUpTarget) this.signUpTarget.hidden = true;\n  }\n\n  hideEmail(event) {\n    if (event) event.preventDefault();\n\n    if (this.hasThirdPartyTarget) this.thirdPartyTarget.hidden = false;\n    if (this.hasEmailTarget) this.emailTarget.hidden = true;\n    if (this.hasSignUpTarget) this.signUpTarget.hidden = true;\n  }\n\n  showSignUp(event) {\n    if (event) event.preventDefault();\n\n    if (this.hasThirdPartyTarget) this.thirdPartyTarget.hidden = true;\n    if (this.hasEmailTarget) this.emailTarget.hidden = true;\n    if (this.hasSignUpTarget) this.signUpTarget.hidden = false;\n  }\n}\n","import { pushDataLayer } from '@slideslive/fuse-kit/utils';\nimport ApplicationController from 'modules/application_controller';\n\nexport default class extends ApplicationController {\n  initialize() {\n    this.sendGoogleAnalyticEvent();\n  }\n\n  sendGoogleAnalyticEvent() {\n    const event = this.element.dataset.sendGaEvent;\n    if (!event) return;\n\n    pushDataLayer({ event });\n  }\n}\n","import { pushDataLayer } from '@slideslive/fuse-kit/utils';\nimport ApplicationController from 'modules/application_controller';\n\nexport default class extends ApplicationController {\n  static get targets() {\n    return ['turboFrameSearchResult', 'infiniteScrollSearchResult'];\n  }\n\n  initialize() {\n    this.sendGoogleAnalyticSearchEvent();\n  }\n\n  dispatchTypeChangedEvent(event) {\n    event.stopPropagation();\n\n    const searchType = this.searchTypeFromTabChangedEvent(event);\n    this.dispatch('typeChanged', {\n      target: document,\n      prefix: 'search',\n      detail: { type: searchType },\n    });\n  }\n\n  showSearchLoading() {\n    for (const element of this.turboFrameSearchResultTargets) {\n      element.innerHTML = '';\n    }\n\n    for (const element of this.infiniteScrollSearchResultTargets) {\n      const controller = this.findControllerOnElement(element);\n\n      controller.reset();\n      controller.showSkeleton();\n    }\n  }\n\n  sendGoogleAnalyticSearchEvent(event) {\n    const searchEvent = this.element.dataset.searchGaEvent || 'sl_search';\n    const searchQuery = this.element.dataset.searchQuery;\n    const searchType = this.searchTypeFromTabChangedEvent(event);\n\n    pushDataLayer({\n      event: searchEvent,\n      search_type: searchType,\n      search_query: searchQuery,\n    });\n  }\n\n  searchTypeFromTabChangedEvent(event) {\n    if (!event) return this.element.dataset.initialSearchType;\n\n    return event.detail.relatedTarget.dataset.tabName;\n  }\n}\n","import ApplicationController from 'modules/application_controller';\n\nexport default class extends ApplicationController {\n  static get targets() {\n    return ['textarea'];\n  }\n\n  submitEnd() {\n    this.textareaTarget.value = '';\n  }\n}\n","import ApplicationController from 'modules/application_controller';\n\nexport default class extends ApplicationController {\n  static get targets() {\n    return ['updateRoleForm', 'updateRoleSelect', 'updateRoleSpinner', 'deleteButton', 'deleteSpinner'];\n  }\n\n  updateRoleChanged() {\n    this.updateRoleFormTarget.requestSubmit();\n  }\n\n  submitUpdateRoleStart() {\n    this.updateRoleSelectTarget.disabled = true;\n    this.updateRoleSpinnerTarget.hidden = false;\n  }\n\n  submitUpdateRoleEnd() {\n    this.updateRoleSpinnerTarget.hidden = true;\n    this.updateRoleSelectTarget.disabled = false;\n  }\n\n  submitDeleteStart() {\n    this.deleteButtonTarget.disabled = true;\n    this.deleteSpinnerTarget.hidden = false;\n  }\n\n  submitDeleteEnd() {\n    this.deleteSpinnerTarget.hidden = true;\n    this.deleteButtonTarget.disabled = false;\n  }\n}\n","import ApplicationController from 'modules/application_controller';\n\nexport default class extends ApplicationController {\n  static get targets() {\n    return ['thumbnail'];\n  }\n\n  updatePublished(published) {\n    this.thumbnailController.setPublished(published);\n  }\n\n  updatePrivacy({ detail: { privacy } }) {\n    this.thumbnailController.setPrivacy(privacy);\n  }\n\n  updatePrice({ detail: { priceCents, priceCurrency } }) {\n    this.thumbnailController.setPrice(priceCents, priceCurrency);\n  }\n\n  publishedChanged({ target }) {\n    this.updatePublished(target.checked);\n  }\n\n  get thumbnailController() {\n    return this.application.getControllerForElementAndIdentifier(\n      this.thumbnailTarget,\n      'library--presentation-edit--thumbnail',\n    );\n  }\n}\n"],"names":["mapToObject","map","convert","m","acc","key","value","isArray","entry","exportCsv","filename","rows","processRow","row","finalVal","j","innerValue","isVariableDefinedNotNull","result","csvFile","i","blob","link","url","checkDelayedResultWithPromise","urlOrDelayedResultId","checkInterval","resolve","reject","checkDelayedResult","errors","choices_speaker_controller","ChoicesAutocompleteController","data","query","globalClasses","itemSelectText","role","localClasses","addClasses","html","createElementFromHTML","share_popup_controller","ApplicationController","event","target","name","width","height","left","top","opts","charset","divmod","x","y","base45","buffer","res","e","rest","c","d","input","require$$0","decoder","src","srcEnd","position","LEGACY_RECORD_INLINE_ID","RECORD_DEFINITIONS_ID","RECORD_INLINE_ID","BUNDLED_STRINGS_ID","PACKED_REFERENCE_TAG_ID","STOP_CODE","maxArraySize","maxMapSize","currentDecoder","currentStructures","srcString","srcStringStart","srcStringEnd","bundledStrings","referenceMap","currentExtensions","currentExtensionRanges","packedValues","dataView","restoreMapsAsObject","defaultOptions","sequentialMode","inlineObjectReadThreshold","Decoder","options","k","v","rec","safeKey","source","end","r","saveState","clearSource","error","checkedRead","forEach","values","lastPosition","size","defaultDecoder","read","token","majorType","getFloat16","multiplier","mult10","array","object","readBin","string","shortStringInJS","longStringInJS","readFixedString","structure","createStructureReader","length","readJustLength","id","recordDefinition","readBundleExt","loadShared","extension","Tag","packedValue","getPackedValues","validName","readObject","compiledReader","readStringJS","units","byte1","byte2","byte3","byte4","unit","fromCharCode","start","bytes","byte","a","b","f","g","h","l","n","o","f32Array","u8Array","byte0","exponent","abs","tag","dateString","epochSec","fraction","existingStructure","glbl","packedTable","newPackedValues","startingPosition","refEntry","targetProperties","combine","SHARED_DATA_TAG_ID","isLittleEndianMachine","typedArrays","typedArrayTags","registerTypedArray","TypedArray","dvMethod","bytesPerElement","littleEndian","sizeShift","dv","elements","ta","method","bundlePosition","bundleLength","dataPosition","sharedData","updatedStructures","callback","savedSrcEnd","savedPosition","savedSrcStringStart","savedSrcStringEnd","savedSrcString","savedReferenceMap","savedBundledStrings","savedSrc","savedStructures","savedDecoder","savedSequentialMode","textEncoder","extensions","extensionClasses","Buffer","hasNodeBuffer","ByteArrayAllocate","ByteArray","MAX_STRUCTURES","MAX_BUFFER_SIZE","throwOnIterable","targetView","safeEnd","MAX_BUNDLE_SIZE","hasNonLatin","RECORD_SYMBOL","Encoder","sharedStructures","hasSharedUpdate","structures","encodeUtf8","maxBytes","encoder","hasSharedStructures","maxSharedStructures","isSequential","samplingPackedValues","packedObjectMap","sharedValues","sharedPackedObjectMap","recordIdsToRemove","transitionsCount","serializationsSinceTransitionRebuild","encodeOptions","REUSE_BUFFER_MODE","sharedStructuresLength","keys","nextTransition","transition","findRepetitiveStrings","writeArrayHeader","valuesArray","encode","THROW_ON_ITERABLE","writeBundles","makeRoom","serialized","insertIds","returnBuffer","RESET_BUFFER_MODE","threshold","status","type","packedPosition","strLength","extStart","twoByte","headerSize","c1","c2","strPosition","useFloat32","xShifted","referee","idsToInsert","constructor","writeObject","entryValue","extensionClass","isBlob","json","writeBuffer","vals","objectOffset","skipValues","newTransitions","parentRecordId","recordId","newSize","newBuffer","chunkThreshold","continuedChunkThreshold","startEncoding","encodeObjectAsIterable","encodeObjectAsAsyncIterable","iterateProperties","finalIterable","useRecords","writeEntityLength","tryEncode","restartEncoding","restart","encodeIterable","encodedValue","reader","next","asyncValue","lastVersion","structuresCopy","SharedData","saveResults","existingShared","majorValue","version","BlobConstructor","packedStatus","includeKeys","date","seconds","set","regex","arrayBuffer","typedArray","typedArrayEncoder","definitions","offset","nextId","distanceToMove","lastEnd","writeStrings","defaultEncoder","BitMatrix","REGION_SIZE","MIN_DYNAMIC_RANGE","numBetween","min","max","Matrix","bufferSize","binarize","returnInverted","greyscaleWeights","canOverwriteImage","pixelCount","bufferOffset","greyscaleBuffer","greyscalePixels","pixelPosition","horizontalRegionCount","verticalRegionCount","blackPointsCount","blackPointsBuffer","blackPoints","verticalRegion","hortizontalRegion","pixelLumosity","average","averageNeighborBlackPoint","binarized","binarizedBuffer","inverted","invertedBuffer","sum","xRegion","yRegion","lum","BitStream","numBits","bitsLeft","toRead","bitsToNotRead","mask","Mode","ModeByte","decodeNumeric","stream","text","characterCountSize","num","AlphanumericCharacterCodes","decodeAlphanumeric","decodeByte","decodeKanji","decode$2","mode","numericResult","alphanumericResult","byteResult","kanjiResult","GenericGFPoly","field","coefficients","coefficientsLength","firstNonZero","degree","other","smallerCoefficients","largerCoefficients","sumDiff","lengthDiff","addOrSubtractGF","scalar","product","aCoefficients","aLength","bCoefficients","bLength","aCoeff","coefficient","GenericGF","primitive","genBase","runEuclideanAlgorithm","R","rLast","tLast","t","rLastLast","tLastLast","q","denominatorLeadingTerm","dltInverse","degreeDiff","scale","sigmaTildeAtZero","inverse","findErrorLocations","errorLocator","numErrors","errorCount","findErrorMagnitudes","errorEvaluator","errorLocations","s","xiInverse","denominator","decode$1","twoS","outputBytes","poly","syndromeCoefficients","evaluation","syndrome","sigmaOmega","errorMagnitudes","VERSIONS","numBitsDiffering","z","bitCount","pushBit","bit","FORMAT_INFO_TABLE","DATA_MASKS","p","buildFunctionPatternMask","dimension","matrix","readCodewords","formatInfo","dataMask","functionPatternMask","codewords","currentByte","bitsRead","readingUp","columnIndex","columnOffset","readVersion","provisionalVersion","topRightVersionBits","bottomLeftVersionBits","bestDifference","bestVersion","difference","readFormatInformation","topLeftFormatInfoBits","topRightBottomRightFormatInfoBits","bestFormatInfo","bits","getDataBlocks","ecLevel","ecInfo","dataBlocks","totalCodewords","block","shortBlockSize","dataBlock","smallBlockCount","largeBlockCount","decodeMatrix","totalBytes","resultBytes","resultIndex","correctedBytes","decode","squareToQuadrilateral","p1","p2","p3","p4","dx3","dy3","dx1","dx2","dy1","dy2","a13","a23","quadrilateralToSquare","sToQ","times","extract","image","location","qToS","transform","mappingFunction","xValue","yValue","sourcePixel","MAX_FINDERPATTERNS_TO_SEARCH","MIN_QUAD_RATIO","MAX_QUAD_RATIO","distance","reorderFinderPatterns","pattern1","pattern2","pattern3","oneTwoDistance","twoThreeDistance","oneThreeDistance","bottomLeft","topLeft","topRight","computeDimension","moduleSize","countBlackWhiteRun","topDimension","sideDimension","countBlackWhiteRunTowardsPoint","origin","switchPoints","steep","fromX","fromY","toX","toY","dx","dy","xStep","yStep","currentPixel","realX","realY","distances","rise","run","towardsEnd","awayFromEnd","middleValue","scoreBlackWhiteRun","sequence","ratios","averageSize","ratio","scorePattern","point","horizontalRun","verticalRun","topLeftPoint","topLeftBottomRightRun","bottomLeftPoint","bottomLeftTopRightRun","horzError","vertError","diagDownError","diagUpError","ratioError","avgSize","sizeError","recenterLocation","leftX","rightX","topY","bottomY","locate","finderPatternQuads","activeFinderPatternQuads","alignmentPatternQuads","activeAlignmentPatternQuads","lastBit","scans","averageFinderPatternBlocksize","validFinderPattern","averageAlignmentPatternBlocksize","validAlignmentPattern","endX","startX","line","matchingQuads","scoredFinderPatternPositions","quad","lengths","score","finderPatternGroups","otherPoints","otherPoint","bestFinderPatternGroup","alignment","findAlignmentPattern","midTopRight","midTopLeft","midBottomLeft","centeredAlignment","bottomRightFinderPattern","modulesBetweenFinderPatterns","correctionToTopLeft","expectedAlignmentPattern","alignmentPatterns","scan","locations","extracted","decoded","mergeObject","opt","jsQR","providedOptions","tryInvertedFirst","shouldInvert","Z_FIXED$1","Z_BINARY","Z_TEXT","Z_UNKNOWN$1","zero$1","buf","len","STORED_BLOCK","STATIC_TREES","DYN_TREES","MIN_MATCH$1","MAX_MATCH$1","LENGTH_CODES$1","LITERALS$1","L_CODES$1","D_CODES$1","BL_CODES$1","HEAP_SIZE$1","MAX_BITS$1","Buf_size","MAX_BL_BITS","END_BLOCK","REP_3_6","REPZ_3_10","REPZ_11_138","extra_lbits","extra_dbits","extra_blbits","bl_order","DIST_CODE_LEN","static_ltree","static_dtree","_dist_code","_length_code","base_length","base_dist","StaticTreeDesc","static_tree","extra_bits","extra_base","elems","max_length","static_l_desc","static_d_desc","static_bl_desc","TreeDesc","dyn_tree","stat_desc","d_code","dist","put_short","w","send_bits","send_code","tree","bi_reverse","code","bi_flush","gen_bitlen","desc","max_code","stree","has_stree","extra","base","xbits","overflow","gen_codes","bl_count","next_code","tr_static_init","init_block","bi_windup","smaller","depth","_n2","_m2","pqdownheap","compress_block","ltree","dtree","lc","sx","build_tree","node","scan_tree","prevlen","curlen","nextlen","count","max_count","min_count","send_tree","build_bl_tree","max_blindex","send_all_trees","lcodes","dcodes","blcodes","rank","detect_data_type","block_mask","static_init_done","_tr_init$1","_tr_stored_block$1","stored_len","last","_tr_align$1","_tr_flush_block$1","opt_lenb","static_lenb","_tr_tally$1","_tr_init_1","_tr_stored_block_1","_tr_flush_block_1","_tr_tally_1","_tr_align_1","trees","adler32","adler","pos","s1","s2","adler32_1","makeTable","table","crcTable","crc32","crc","crc32_1","messages","constants$2","_tr_init","_tr_stored_block","_tr_flush_block","_tr_tally","_tr_align","Z_NO_FLUSH$2","Z_PARTIAL_FLUSH","Z_FULL_FLUSH$1","Z_FINISH$3","Z_BLOCK$1","Z_OK$3","Z_STREAM_END$3","Z_STREAM_ERROR$2","Z_DATA_ERROR$2","Z_BUF_ERROR$1","Z_DEFAULT_COMPRESSION$1","Z_FILTERED","Z_HUFFMAN_ONLY","Z_RLE","Z_FIXED","Z_DEFAULT_STRATEGY$1","Z_UNKNOWN","Z_DEFLATED$2","MAX_MEM_LEVEL","MAX_WBITS$1","DEF_MEM_LEVEL","LENGTH_CODES","LITERALS","L_CODES","D_CODES","BL_CODES","HEAP_SIZE","MAX_BITS","MIN_MATCH","MAX_MATCH","MIN_LOOKAHEAD","PRESET_DICT","INIT_STATE","GZIP_STATE","EXTRA_STATE","NAME_STATE","COMMENT_STATE","HCRC_STATE","BUSY_STATE","FINISH_STATE","BS_NEED_MORE","BS_BLOCK_DONE","BS_FINISH_STARTED","BS_FINISH_DONE","OS_CODE","err","strm","errorCode","zero","slide_hash","wsize","HASH_ZLIB","prev","HASH","flush_pending","flush_block_only","put_byte","putShortMSB","read_buf","longest_match","cur_match","chain_length","match","best_len","nice_match","limit","_win","wmask","strend","scan_end1","scan_end","fill_window","_w_size","more","str","deflate_stored","flush","min_block","have","used","deflate_fast","hash_head","bflush","deflate_slow","max_insert","deflate_rle","deflate_huff","Config","good_length","max_lazy","nice_length","max_chain","func","configuration_table","lm_init","DeflateState","deflateStateCheck","deflateResetKeep","deflateReset","ret","deflateSetHeader","head","deflateInit2","level","windowBits","memLevel","strategy","wrap","deflateInit","deflate$2","old_flush","header","level_flags","beg","copy","gzhead_extra","val","bstate","deflateEnd","deflateSetDictionary","dictionary","dictLength","tmpDict","avail","deflateInit_1","deflateInit2_1","deflateReset_1","deflateResetKeep_1","deflateSetHeader_1","deflate_2$1","deflateEnd_1","deflateSetDictionary_1","deflateInfo","deflate_1$2","_has","obj","assign","sources","flattenChunks","chunks","chunk","common","STR_APPLY_UIA_OK","_utf8len","string2buf","m_pos","str_len","buf_len","buf2binstring","buf2string","out","utf16buf","c_len","utf8border","strings","ZStream","zstream","toString$1","Z_NO_FLUSH$1","Z_SYNC_FLUSH","Z_FULL_FLUSH","Z_FINISH$2","Z_OK$2","Z_STREAM_END$2","Z_DEFAULT_COMPRESSION","Z_DEFAULT_STRATEGY","Z_DEFLATED$1","Deflate$1","dict","flush_mode","chunkSize","_flush_mode","deflate$1","deflator","deflateRaw$1","gzip$1","Deflate_1$1","deflate_2","deflateRaw_1$1","gzip_1$1","deflate_1$1","BAD$1","TYPE$1","inffast","_in","_out","dmax","whave","wnext","s_window","hold","lcode","dcode","lmask","dmask","here","op","from","from_source","output","state","dolen","dodist","MAXBITS","ENOUGH_LENS$1","ENOUGH_DISTS$1","CODES$1","LENS$1","DISTS$1","lbase","lext","dbase","dext","inflate_table","lens","lens_index","codes","table_index","work","sym","root","curr","drop","huff","incr","fill","low","offs","here_bits","here_op","here_val","inftrees","CODES","LENS","DISTS","Z_FINISH$1","Z_BLOCK","Z_TREES","Z_OK$1","Z_STREAM_END$1","Z_NEED_DICT$1","Z_STREAM_ERROR$1","Z_DATA_ERROR$1","Z_MEM_ERROR$1","Z_BUF_ERROR","Z_DEFLATED","HEAD","FLAGS","TIME","OS","EXLEN","EXTRA","NAME","COMMENT","HCRC","DICTID","DICT","TYPE","TYPEDO","STORED","COPY_","COPY","TABLE","LENLENS","CODELENS","LEN_","LEN","LENEXT","DIST","DISTEXT","MATCH","LIT","CHECK","LENGTH","DONE","BAD","MEM","SYNC","ENOUGH_LENS","ENOUGH_DISTS","MAX_WBITS","DEF_WBITS","zswap32","InflateState","inflateStateCheck","inflateResetKeep","inflateReset","inflateReset2","inflateInit2","inflateInit","virgin","lenfix","distfix","fixedtables","updatewindow","inflate$2","put","last_bits","last_op","last_val","hbuf","order","inf_leave","inflateEnd","inflateGetHeader","inflateSetDictionary","dictid","inflateReset_1","inflateReset2_1","inflateResetKeep_1","inflateInit_1","inflateInit2_1","inflate_2$1","inflateEnd_1","inflateGetHeader_1","inflateSetDictionary_1","inflateInfo","inflate_1$2","GZheader","gzheader","toString","Z_NO_FLUSH","Z_FINISH","Z_OK","Z_STREAM_END","Z_NEED_DICT","Z_STREAM_ERROR","Z_DATA_ERROR","Z_MEM_ERROR","Inflate$1","last_avail_out","next_out_utf8","tail","utf8str","inflate$1","inflator","inflateRaw$1","Inflate_1$1","inflate_2","inflateRaw_1$1","ungzip$1","inflate_1$1","Deflate","deflate","deflateRaw","gzip","Inflate","inflate","inflateRaw","ungzip","Deflate_1","deflate_1","deflateRaw_1","gzip_1","Inflate_1","inflate_1","inflateRaw_1","ungzip_1","constants_1","pako","covid19_cert_tab_component","qrImage","img","canvas","ctx","imageData","decodedQR","decodedBody","decodedData","inflatedData","cborData","jsonData","fire","element","jsonString","info","pair","hourly_rates_tab_component","currency","hourlyRateCurrencyTarget","payout_methods_component","el","paramEls","paramEl","recording_radius_tab_component","defaultLatLng","mapOptions","markerOptions","circleOptions","place","radius","basic_tab_component","colors","color","change_password_modal_component","_b","_a","form_component$4","lat","lng","header_component","remove","subordinate_accounts_component","defer","Sortable","TITLE_LINES","box_with_text_component","shave","bg_component","VimeoPlayerApiLoader","Vimeo","entries","body_component","addListener","removeListener","message","MapShim","getIndex","arr","index","class_1","_i","isBrowser","global$1","requestAnimationFrame$1","trailingTimeout","throttle","delay","leadingCall","trailingCall","lastCallTime","resolvePending","proxy","timeoutCallback","timeStamp","REFRESH_DELAY","transitionKeys","mutationObserverSupported","ResizeObserverController","observer","observers","changesDetected","activeObservers","propertyName","isReflowProperty","defineConfigurable","props","getWindowOf","ownerGlobal","emptyRect","createRectInit","toFloat","getBordersSize","styles","positions","getPaddings","paddings","positions_1","getSVGContentRect","bbox","getHTMLElementContentRect","clientWidth","clientHeight","horizPad","vertPad","isDocumentElement","vertScrollbar","horizScrollbar","isSVGGraphicsElement","getContentRect","createReadOnlyRect","Constr","rect","ResizeObservation","ResizeObserverEntry","rectInit","contentRect","ResizeObserverSPI","controller","callbackCtx","observations","_this","observation","ResizeObserver","box_background_component","player_component$2","Player","fire_empty_component","fire_empty_container_component","setData","cachedData","getData","follow_component$1","pushDataLayer","follow_component","sign_up_component","form_component$3","outlet","response","log_in_modal_component","presentation_show_component$1","permanentPlayerKey","save","presentationId","playerElement","clear","permanentPlayerData","currentPresentationId","currentPlayerElement","exist","open","title","close","permanent_player_component","PermanentPlayer.exist","PermanentPlayer.close","PermanentPlayer.save","PermanentPlayer.clear","PlayerBaseController","host","meta","slide","form_component$2","published","privacy","priceCents","priceCurrency","player_component$1","security_privacy_tab_component","detail","speaker_component","task_content_component","thumbnail_component","cents","price","Money","presentation_edit_component","box_component","box_playlist_loader_component","CONSTANTS","assert","assertion","assertionError","stringToByteArray$1","byteArrayToString","c3","c4","u","base64","webSafe","byteToCharMap","haveByte2","haveByte3","outByte1","outByte2","outByte3","outByte4","charToByteMap","DecodeBase64StringError","base64Encode","utf8Bytes","base64urlEncodeWithoutPadding","base64Decode","deepCopy","deepExtend","dateValue","prop","isValidKey","getGlobal","getDefaultsFromGlobal","getDefaultsFromEnvVariable","define_process_env_default","defaultsJsonString","getDefaultsFromCookie","getDefaults","getDefaultAppConfig","Deferred","createMockUserToken","projectId","project","iat","sub","payload","getUA","isMobileCordova","isWebWorker","isReactNative","isNodeSdk","isIndexedDBAvailable","validateIndexedDBOpenable","preExist","DB_CHECK_NAME","request","ERROR_NAME","FirebaseError","customData","ErrorFactory","service","serviceName","fullCode","template","replaceTemplate","fullMessage","PATTERN","_","jsonEval","stringify","claims","signature","parts","isValidFormat","isAdmin","contains","safeGet","isEmpty","fn","contextObj","deepEqual","aKeys","bKeys","aProp","bProp","isObject","thing","querystring","querystringParams","params","arrayVal","Sha1","W","lengthMinusBlock","inbuf","digest","totalBits","createSubscribe","executor","onNoObservers","ObserverProxy","nextOrObserver","complete","implementsAnyMethods","noop","unsub","methods","validateArgCount","fnName","minCount","maxCount","argCount","argError","errorPrefix","argName","validateCallback","argumentName","optional","validateContextObject","context","stringToByteArray","high","stringLength","getModularInstance","Component","instanceFactory","multipleInstances","DEFAULT_ENTRY_NAME","Provider","container","identifier","normalizedIdentifier","deferred","instance","component","isComponentEager","instanceIdentifier","instanceDeferred","services","normalizedDeferredIdentifier","existingCallbacks","existingInstance","callbacks","normalizeIdentifierForFactory","ComponentContainer","provider","instances","LogLevel","levelStringToEnum","defaultLogLevel","ConsoleMethod","defaultLogHandler","logType","args","now","Logger","setLogLevel","inst","setUserLogHandler","logCallback","customLogLevel","arg","instanceOfAny","constructors","idbProxyableTypes","cursorAdvanceMethods","getIdbProxyableTypes","getCursorAdvanceMethods","cursorRequestMap","transactionDoneMap","transactionStoreNamesMap","transformCache","reverseTransformCache","promisifyRequest","promise","unlisten","success","cacheDonePromiseForTransaction","tx","done","idbProxyTraps","receiver","replaceTraps","wrapFunction","storeNames","unwrap","transformCachableValue","newValue","openDB","blocked","upgrade","blocking","terminated","openPromise","db","readMethods","writeMethods","cachedMethods","getMethod","targetFuncName","useIndex","isWrite","storeName","oldTraps","PlatformLoggerServiceImpl","isVersionServiceProvider","logString","name$q","version$1","logger","name$p","name$o","name$n","name$m","name$l","name$k","name$j","name$i","name$h","name$g","name$f","name$e","name$d","name$c","name$b","name$a","name$9","name$8","name$7","name$6","name$5","name$4","name$3","name$2","name$1","PLATFORM_LOG_STRING","_apps","_serverApps","_components","_addComponent","app","_addOrOverwriteComponent","_registerComponent","componentName","serverApp","_getProvider","heartbeatController","_removeServiceInstance","_isFirebaseApp","_isFirebaseServerApp","_clearComponents","ERRORS","ERROR_FACTORY","FirebaseAppImpl$1","config","FirebaseServerAppImpl","FirebaseAppImpl","serverConfig","automaticDataCollectionEnabled","appImpl","registerVersion","deleteApp","SDK_VERSION","initializeApp","_options","rawConfig","existingApp","newApp","initializeServerApp","_serverAppConfig","appOptions","nameObj","hashCode","hash","nameString","getApp","getApps","cleanupProviders","libraryKeyOrName","variant","library","libraryMismatch","versionMismatch","warning","onLog","logLevel","setLogLevel$1","DB_NAME","DB_VERSION","STORE_NAME","dbPromise","getDbPromise","oldVersion","readHeartbeatsFromIndexedDB","computeKey","idbGetError","writeHeartbeatsToIndexedDB","heartbeatObject","MAX_HEADER_BYTES","STORED_HEARTBEAT_RETENTION_MAX_MILLIS","HeartbeatServiceImpl","HeartbeatStorageImpl","agent","getUTCDateString","singleDateHeartbeat","hbTimestamp","heartbeatsToSend","unsentEntries","extractHeartbeatsForHeader","headerString","heartbeatsCache","maxSize","heartbeatEntry","hb","countBytes","idbHeartbeatObject","heartbeatsObject","existingHeartbeatsObject","registerCoreComponents","_delegate","firebase","_DEFAULT_ENTRY_NAME","createFirebaseNamespaceCore","firebaseAppImpl","apps","namespace","initializeAppCompat","modularAPIs.registerVersion","modularAPIs.setLogLevel","modularAPIs.onLog","modularAPIs.SDK_VERSION","registerComponentCompat","removeApp","useAsService","modularAPIs","modularAPIs._DEFAULT_ENTRY_NAME","modularAPIs.initializeApp","appCompat","componentNameWithoutCompat","modularAPIs._registerComponent","serviceNamespace","appArg","createFirebaseNamespace","extendNamespace","firebase$1","globals","sdkVersion","setSDKVersion","DOMStorageWrapper","domStorage_","storedVal","MemoryStorage","createStoragefor","domStorageName","domStorage","PersistentStorage","SessionStorage","logClient","LUIDGenerator","sha1","sha1Bytes","buildLogMessage_","varArgs","firstLog_","enableLogging$1","logger_","persistent","log","logWrapper","prefix","fatal","warn","warnIfPageIsSecure","isInvalidJSONNumber","executeWhenDOMReady","called","wrappedFn","MIN_NAME","MAX_NAME","nameCompare","aAsInt","tryParseInt","bAsInt","stringCompare","requireKey","ObjectToUniqueKey","splitStringBySize","segsize","dataSegs","each","doubleToIEEE754String","ebits","fbits","bias","ln","hexByteString","hexByte","isChromeExtensionContentScript","isWindowsStoreApp","errorForServerCode","reason","INTEGER_REGEXP_","INTEGER_32_MIN","INTEGER_32_MAX","intVal","exceptionGuard","stack","beingCrawled","setTimeoutNonBlocking","time","timeout","AppCheckTokenProvider","appName_","appCheckProvider","appCheck","forceRefresh","listener","FirebaseAuthTokenProvider","firebaseOptions_","authProvider_","auth","errorMessage","EmulatorTokenProvider","accessToken","PROTOCOL_VERSION","VERSION_PARAM","TRANSPORT_SESSION_PARAM","REFERER_PARAM","FORGE_REF","FORGE_DOMAIN_RE","LAST_SESSION_PARAM","APPLICATION_ID_PARAM","APP_CHECK_TOKEN_PARAM","WEBSOCKET","LONG_POLLING","RepoInfo","secure","webSocketOnly","nodeAdmin","persistenceKey","includeNamespaceInQueryParams","isUsingEmulator","newHost","protocol","repoInfoNeedsQueryParam","repoInfo","repoInfoConnectionURL","connURL","pairs","StatsCollection","amount","collections","reporters","statsManagerGetCollection","hashString","statsManagerGetOrCreateReporter","creatorFunction","PacketReceiver","onMessage_","responseNum","requestNum","toProcess","FIREBASE_LONGPOLL_START_PARAM","FIREBASE_LONGPOLL_CLOSE_COMMAND","FIREBASE_LONGPOLL_COMMAND_CB_NAME","FIREBASE_LONGPOLL_DATA_CB_NAME","FIREBASE_LONGPOLL_ID_PARAM","FIREBASE_LONGPOLL_PW_PARAM","FIREBASE_LONGPOLL_SERIAL_PARAM","FIREBASE_LONGPOLL_CALLBACK_ID_PARAM","FIREBASE_LONGPOLL_SEGMENT_NUM_PARAM","FIREBASE_LONGPOLL_SEGMENTS_IN_PACKET","FIREBASE_LONGPOLL_DATA_PARAM","FIREBASE_LONGPOLL_DISCONN_FRAME_REQUEST_PARAM","MAX_URL_DATA_SIZE","SEG_HEADER_SIZE","MAX_PAYLOAD_SIZE","KEEPALIVE_REQUEST_INTERVAL","LP_CONNECT_TIMEOUT","BrowserPollConnection","connId","applicationId","appCheckToken","authToken","transportSessionId","lastSessionId","onMessage","onDisconnect","FirebaseIFrameScriptHolder","command","arg1","arg2","arg3","arg4","pN","urlParams","connectURL","dataStr","base64data","pw","bytesReceived","commandCB","onMessageCB","urlFn","script","iframeContents","iframe","domain","theURL","curDataString","theSeg","segnum","totalsegs","serial","doNewRequest","keepaliveTimeout","readyStateCB","loadCB","newScript","rstate","WEBSOCKET_MAX_FRAME_SIZE","WEBSOCKET_KEEPALIVE_INTERVAL","WebSocketImpl","WebSocketConnection","isOldAndroid","oldAndroidRegex","oldAndroidMatch","fullMess","jsonMess","frameCount","mess","remainingData","TransportManager","isWebSocketsAvailable","isSkipPollConnection","transports","transport","UPGRADE_TIMEOUT","DELAY_BEFORE_SENDING_EXTRA_REQUESTS","BYTES_SENT_HEALTHY_OVERRIDE","BYTES_RECEIVED_HEALTHY_OVERRIDE","MESSAGE_TYPE","MESSAGE_DATA","CONTROL_SHUTDOWN","CONTROL_RESET","CONTROL_ERROR","CONTROL_PONG","SWITCH_ACK","END_TRANSMISSION","PING","SERVER_HELLO","Connection","repoInfo_","applicationId_","appCheckToken_","authToken_","onReady_","onDisconnect_","onKill_","conn","onMessageReceived","onConnectionLost","healthyTimeoutMS","everConnected","dataMsg","msg","controlData","cmd","parsedData","layer","handshakePayload","handshake","timestamp","ServerActions","pathString","onComplete","stats","EventEmitter","allowedEvents_","eventType","listeners","eventData","et","OnlineMonitor","MAX_PATH_DEPTH","MAX_PATH_LENGTH_BYTES","Path","pathOrString","pieceNum","copyTo","newEmptyPath","pathGetFront","path","pathGetLength","pathPopFront","pathGetBack","pathToUrlEncodedString","pathSlice","begin","pathParent","pieces","pathChild","childPathObj","childPieces","pathIsEmpty","newRelativePath","outerPath","innerPath","outer","inner","pathCompare","right","leftKeys","rightKeys","cmp","pathEquals","pathContains","ValidationPath","errorPrefix_","validationPathCheckValid","validationPathPush","validationPath","child","validationPathPop","validationPathToErrorString","VisibilityMonitor","hidden","visibilityChange","visible","RECONNECT_MIN_DELAY","RECONNECT_MAX_DELAY_DEFAULT","RECONNECT_MAX_DELAY_FOR_ADMINS","RECONNECT_DELAY_MULTIPLIER","RECONNECT_DELAY_RESET_TIMEOUT","SERVER_KILL_INTERRUPT_REASON","INVALID_TOKEN_THRESHOLD","PersistentConnection","onDataUpdate_","onConnectStatus_","onServerInfoUpdate_","authTokenProvider_","appCheckTokenProvider_","authOverride_","action","body","onResponse","curReqNum","outstandingGet","currentHashFn","queryId","listenSpec","get","req","warnings","indexSpec","indexPath","credential","authMethod","requestData","queryObj","errorReason","reqNum","sessionId","online","timeSinceLastConnectAttempt","reconnectDelay","onDataMessage","onReady","canceled","connection","closeFn","sendRequestFn","delta","listen","normalizedPathString","statusCode","explanation","queries","clientName","NamedNode","Index","oldNode","newNode","oldWrapped","newWrapped","__EMPTY_NODE","KeyIndex","indexValue","KEY_INDEX","SortedMapIterator","startKey","comparator","isReverse_","resultGenerator_","LLRBNode","SortedMap","smallest","nl","nr","blackDepth","LLRBEmptyNode","comparator_","root_","rightParent","resultGenerator","NAME_ONLY_COMPARATOR","NAME_COMPARATOR","MAX_NODE$2","setMaxNode$1","priorityHashText","priority","validatePriorityNode","priorityNode","__childrenNodeConstructor","LeafNode","value_","priorityNode_","newPriorityNode","childName","childNode","newChildNode","front","exportFormat","toHash","otherLeaf","otherLeafType","thisLeafType","otherIndex","thisIndex","nodeFromJSON$1","MAX_NODE$1","setNodeFromJSON","setMaxNode","PriorityIndex","aPriority","bPriority","indexCmp","PRIORITY_INDEX","LOG_2","Base12Num","logBase2","bitMask","buildChildSet","childList","keyFn","mapSortFn","buildBalancedTree","namedNode","middle","buildFrom12Array","base12","buildPennant","childTree","attachPennant","pennant","isOne","_defaultIndexMap","fallbackObject","IndexMap","indexes_","indexSet_","indexKey","sortedMap","indexDefinition","existingChildren","sawIndexedValue","iter","newIndex","indexName","newIndexSet","newIndexes","indexedChildren","existingSnap","newChildren","EMPTY_NODE","ChildrenNode","children_","indexMap_","newIndexMap","newPriority","newImmediateChild","numKeys","maxKey","allIntegerKeys","childHash","idx","predecessor","minKey","wrappedNode","startPost","iterator","endPost","MAX_NODE","otherChildrenNode","thisIter","otherIter","thisCurrent","otherCurrent","MaxNode","USE_HINZE","nodeFromJSON","jsonLeaf","children","childrenHavePriority","childSet","sortedChildSet","childData","PathIndex","indexPath_","snap","aChild","bChild","valueNode","ValueIndex","VALUE_INDEX","changeValue","snapshotNode","changeChildAdded","changeChildRemoved","changeChildChanged","oldSnap","changeChildMoved","IndexedFilter","index_","newChild","affectedPath","optChangeAccumulator","oldChild","newSnap","RangedFilter","isWithinStart","isWithinEnd","filtered","self","startName","endName","LimitedFilter","compareRes","childKey","childSnap","changeAccumulator","oldEventCache","newChildNamedNode","windowBoundary","inRange","oldChildSnap","nextChild","compareNext","newEventCache","QueryParams","queryParamsGetNodeFilter","queryParams","queryParamsLimitToFirst","newLimit","newParams","queryParamsLimitToLast","queryParamsStartAt","queryParamsStartAfter","queryParamsEndAt","queryParamsEndBefore","queryParamsOrderBy","queryParamsToRestQueryStringParameters","qs","orderBy","startParam","endParam","queryParamsGetQueryObject","viewFrom","ReadonlyRestClient","listenId","thisListen","queryStringParameters","xhr","SnapshotHolder","newSnapshotNode","newSparseSnapshotTree","sparseSnapshotTreeRemember","sparseSnapshotTree","sparseSnapshotTreeForget","sparseSnapshotTreeForEachTree","prefixPath","sparseSnapshotTreeForEachChild","StatsListener","collection_","newStats","stat","FIRST_STATS_MIN_TIME","FIRST_STATS_MAX_TIME","REPORT_STATS_INTERVAL","StatsReporter","collection","server_","reportedStats","haveStatsToReport","OperationType","newOperationSourceUser","newOperationSourceServer","newOperationSourceServerTaggedQuery","AckUserWrite","affectedTree","revert","ListenComplete","Overwrite","Merge","CacheNode","node_","fullyInitialized_","filtered_","EventGenerator","query_","eventGeneratorGenerateEventsForChanges","eventGenerator","changes","eventCache","eventRegistrations","events","moves","change","eventGeneratorGenerateEventsForType","registrations","filteredChanges","eventGeneratorCompareChanges","materializedChange","eventGeneratorMaterializeSingleChange","registration","aWrapped","bWrapped","newViewCache","serverCache","viewCacheUpdateEventSnap","viewCache","eventSnap","viewCacheUpdateServerSnap","serverSnap","viewCacheGetCompleteEventSnap","viewCacheGetCompleteServerSnap","emptyChildrenSingleton","EmptyChildren","ImmutableTree","childPath","relativePath","predicate","childExistingPathAndValue","toSet","newTree","pathSoFar","accum","pathToFollow","currentRelativePath","CompoundWrite","writeTree_","compoundWriteAddWrite","compoundWrite","rootmost","rootMostPath","subtree","newWriteTree","compoundWriteAddWrites","updates","newWrite","compoundWriteRemoveWrite","compoundWriteHasCompleteWrite","compoundWriteGetCompleteNode","compoundWriteGetCompleteChildren","compoundWriteChildCompoundWrite","shadowingNode","compoundWriteIsEmpty","compoundWriteApply","applySubtreeWrite","writeTree","priorityWrite","writeTreeChildWrites","newWriteTreeRef","writeTreeAddOverwrite","writeId","writeTreeAddMerge","changedChildren","writeTreeGetWrite","record","writeTreeRemoveWrite","writeToRemove","removedWriteWasVisible","removedWriteOverlapsWithOtherWrites","currentWrite","writeTreeRecordContainsPath_","writeTreeResetTree_","writeRecord","writeTreeLayerTree_","writeTreeDefaultFilter_","write","writes","filter","treeRoot","writePath","deepNode","writeTreeCalcCompleteEventCache","treePath","completeServerCache","writeIdsToExclude","includeHiddenWrites","subMerge","layeredCache","merge","mergeAtPath","writeTreeCalcCompleteEventChildren","completeServerChildren","completeChildren","topLevelSet","writeTreeCalcEventCacheAfterServerOverwrite","existingEventSnap","existingServerSnap","childMerge","writeTreeCalcCompleteChild","writeTreeShadowingWrite","writeTreeCalcIndexedSlice","completeServerData","reverse","toIterate","nodes","writeTreeRefCalcCompleteEventCache","writeTreeRef","writeTreeRefCalcCompleteEventChildren","writeTreeRefCalcEventCacheAfterServerOverwrite","writeTreeRefShadowingWrite","writeTreeRefCalcIndexedSlice","writeTreeRefCalcCompleteChild","existingServerCache","writeTreeRefChild","ChildChangeAccumulator","oldChange","oldType","NoCompleteChildSource_","NO_COMPLETE_CHILD_SOURCE","WriteTreeCompleteChildSource","writes_","viewCache_","optCompleteServerCache_","serverNode","newViewProcessor","viewProcessorAssertIndexed","viewProcessor","viewProcessorApplyOperation","oldViewCache","operation","writesCache","completeCache","accumulator","filterServerNode","overwrite","viewProcessorApplyUserOverwrite","viewProcessorApplyServerOverwrite","viewProcessorApplyUserMerge","viewProcessorApplyServerMerge","ackUserWrite","viewProcessorRevertUserWrite","viewProcessorAckUserWrite","viewProcessorListenComplete","viewProcessorMaybeAddValueEvent","isLeafOrEmpty","oldCompleteSnap","viewProcessorGenerateEventCacheAfterServerEvent","changePath","oldEventSnap","completeEventChildren","completeNode","oldEventNode","updatedPriority","childChangePath","newEventChild","eventChildUpdate","changedSnap","oldServerSnap","newServerCache","serverFilter","newServerNode","newEventSnap","viewProcessorCacheHasChild","curViewCache","viewProcessorApplyMerge","viewMergeTree","serverChild","childMergeTree","isUnknownDeepMerge","ackPath","mergePath","serverCachePath","oldServerNode","serverChildren","View","initialViewCache","indexFilter","initialServerCache","initialEventCache","viewGetServerCache","view","viewGetCompleteNode","viewGetCompleteServerCache","cache","viewIsEmpty","viewAddEventRegistration","eventRegistration","viewRemoveEventRegistration","cancelError","cancelEvents","maybeEvent","remaining","existing","viewApplyOperation","viewGenerateEventsForChanges_","viewGetInitialEvents","initialChanges","referenceConstructor$1","SyncPoint","syncPointSetReferenceConstructor","syncPointGetReferenceConstructor","syncPointIsEmpty","syncPoint","syncPointApplyOperation","optCompleteServerCache","syncPointGetView","serverCacheComplete","eventCacheComplete","syncPointAddEventRegistration","syncPointRemoveEventRegistration","removed","hadCompleteView","syncPointHasCompleteView","viewQueryId","syncPointGetQueryViews","syncPointGetCompleteServerCache","syncPointViewForQuery","syncPointGetCompleteView","syncPointViewExistsForQuery","referenceConstructor","syncTreeSetReferenceConstructor","syncTreeGetReferenceConstructor","syncTreeNextQueryTag_","SyncTree","listenProvider_","syncTreeApplyUserOverwrite","syncTree","newData","syncTreeApplyOperationToSyncPoints_","syncTreeApplyUserMerge","changeTree","syncTreeAckUserWrite","syncTreeApplyServerOverwrite","syncTreeApplyServerMerge","syncTreeApplyListenComplete","syncTreeApplyTaggedListenComplete","queryKey","syncTreeQueryKeyForTag_","syncTreeParseQueryKey_","queryPath","syncTreeApplyTaggedOperation_","syncTreeRemoveEventRegistration","skipListenerDedup","maybeSyncPoint","removedAndEvents","removingDefault","covered","parentSyncPoint","newViews","syncTreeCollectDistinctViewsForSubTree_","newQuery","syncTreeCreateListenerForView_","syncTreeQueryForListening_","syncTreeTagForQuery","queryToRemove","tagToRemove","syncTreeMakeQueryKey_","syncTreeRemoveTags_","syncTreeApplyTaggedQueryOverwrite","syncTreeApplyTaggedQueryMerge","syncTreeAddEventRegistration","skipSetupListener","foundAncestorDefaultView","pathToSyncPoint","sp","childSyncPoint","viewAlreadyExists","syncTreeGetNextQueryTag_","syncTreeSetupListener_","syncTreeCalcCompleteEventCache","syncTreeGetServerValue","serverCacheNode","syncTreeApplyOperationHelper_","syncPointTree","syncTreeApplyOperationDescendantsHelper_","childOperation","childServerCache","childWritesCache","splitIndex","maybeChildSyncPoint","childMap","views","_key","childViews","removedQuery","removedQueryKey","removedQueryTag","queriesToStop","childQueries","queryToStop","ExistingValueProvider","DeferredValueProvider","generateWithValues","resolveDeferredLeafValue","existingVal","serverValues","resolveScalarDeferredValue","resolveComplexDeferredValue","unused","existingNode","resolveDeferredValueTree","resolveDeferredValue","resolveDeferredValueSnapshot","rawPri","leafNode","childrenNode","Tree","parent","treeSubTree","pathObj","treeGetValue","treeSetValue","treeUpdateParents","treeHasChildren","treeIsEmpty","treeForEachChild","treeForEachDescendant","includeSelf","childrenFirst","treeForEachAncestor","treeGetPath","treeUpdateChild","childEmpty","childExists","INVALID_KEY_REGEX_","INVALID_PATH_REGEX_","MAX_LEAF_SIZE_","isValidPathString","isValidRootPathString","isValidPriority","validateFirebaseDataArg","validateFirebaseData","path_","hasDotValue","hasActualChild","validateFirebaseMergePaths","mergePaths","curPath","prevPath","validateFirebaseMergeDataArg","errorPrefix$1","validatePriority","validateKey","validatePathString","validateRootPathString","validateWritablePath","validateUrl","parsedUrl","EventQueue","eventQueueQueueEvents","eventQueue","eventDataList","currList","eventQueueRaiseEventsAtPath","eventQueueRaiseQueuedEventsMatchingPredicate","eventPath","eventQueueRaiseEventsForChangedPath","changedPath","sentAll","eventList","eventListRaise","eventFn","INTERRUPT_REASON","MAX_TRANSACTION_RETRIES","Repo","forceRestClient_","appCheckProvider_","repoStart","repo","appId","authOverride","isMerge","repoOnDataUpdate","repoOnConnectStatus","connectStatus","repoOnServerInfoUpdate","infoEvents","repoUpdateInfo","repoServerTime","repoGenerateServerValues","taggedChildren","raw","taggedSnap","repoRerunTransactions","repoRunOnDisconnectEvents","repoGetNextWriteId","repoGetValue","cached","repoLog","repoSetWithPriority","newVal","newNodeUnresolved","clearEvents","repoCallOnCompleteCallback","repoAbortTransactions","repoUpdate","childrenToMerge","empty","changedKey","changedValue","resolvedOnDisconnectTree","resolved","repoOnDisconnectCancel","repoOnDisconnectSet","repoOnDisconnectSetWithPriority","repoOnDisconnectUpdate","repoAddEventCallbackForQuery","repoRemoveEventCallbackForQuery","repoInterrupt","repoResume","repoStartTransaction","transactionUpdate","unwatcher","applyLocally","transaction","currentState","repoGetLatestState","queueNode","nodeQueue","priorityForNode","repoSendReadyTransactions","excludeSets","repoPruneCompletedTransactionsBelowNode","queue","repoBuildTransactionQueue","repoSendTransactionQueue","setsToIgnore","txn","latestState","snapToSend","latestHash","dataToSend","pathToSend","rootMostTransactionNode","repoGetAncestorTransactionNode","repoRerunTransactionQueue","abortTransaction","abortReason","currentNode","newDataNode","oldWriteId","newNodeResolved","transactionNode","transactionQueue","repoAggregateTransactionQueuesForNode","to","repoAbortTransactionsOnNode","lastSent","decodePath","pathStringDecoded","piece","decodeQuery","queryString","results","segment","kv","parseRepoInfo","dataURL","parseDatabaseURL","subdomain","scheme","port","colonInd","slashInd","questionMarkInd","hostWithoutPort","dotInd","PUSH_CHARS","nextPushId","lastPushTime","lastRandChars","duplicateTime","timeStampChars","DataEvent","snapshot","prevName","ref","CancelEvent","CallbackContext","snapshotCallback","cancelCallback","expDataSnapshot","previousChildName","OnDisconnect$1","_repo","_path","QueryImpl","_queryParams","_orderByCalled","ReferenceImpl","sameRepo","samePath","sameQueryIdentifier","validateNoPreviousOrderByCall","validateQueryEndpoints","startNode","endNode","tooManyArgsError","wrongArgTypeError","validateLimit","parentPath","DataSnapshot$1","DataSnapshot","_node","_index","childRef","refFromURL","parsedURL","push","thenablePushRef","pushRef","setPriority","setWithPriority","update","callbackContext","ValueEventRegistration","ChildEventRegistration","eventToCheck","addEventListener","cancelCallbackOrListenOptions","userCallback","onceCallback","dataSnapshot","onValue","onChildAdded","onChildChanged","onChildMoved","onChildRemoved","off","expCallback","QueryConstraint","QueryEndAtConstraint","_value","endAt","QueryEndBeforeConstraint","endBefore","QueryStartAtConstraint","startAt","QueryStartAfterConstraint","startAfter","QueryLimitToFirstConstraint","_limit","limitToFirst","QueryLimitToLastConstraint","limitToLast","QueryOrderByChildConstraint","parsedPath","orderByChild","QueryOrderByKeyConstraint","orderByKey","QueryOrderByPriorityConstraint","orderByPriority","QueryOrderByValueConstraint","orderByValue","QueryEqualToValueConstraint","equalTo","queryConstraints","queryImpl","constraint","FIREBASE_DATABASE_EMULATOR_HOST_VAR","repos","useRestClient","repoManagerApplyEmulatorSettings","tokenProvider","repoManagerDatabaseFromApp","authProvider","dbUrl","isEmulator","dbEmulatorHost","authTokenProvider","repoManagerCreateRepo","Database","repoManagerDeleteRepo","appName","appRepos","Database$1","_repoInternal","apiName","checkTransportInit","forceWebSockets","forceLongPolling","connectDatabaseEmulator","goOffline","goOnline","enableLogging","registerDatabase","SDK_VERSION$1","SERVER_TIMESTAMP","serverTimestamp","increment","TransactionResult$1","committed","runTransaction","promiseComplete","TransactionResult","onEcho","validateBoolean","bool","validateEventType","OnDisconnect","objectToMerge","newObjectToMerge","_database","_validatePathString","Reference","Query","database","cancelCallbackOrContext","valueCallback","expSnapshot","failureCallbackOrContext","cancelOrContext","_ReferenceImpl","_QueryImpl","_QueryParams","_validateWritablePath","transactionResult","expPromise","expRef","initStandalone","customAuthImpl","customAppCheckImpl","_setSDKVersion","_repoManagerDatabaseFromApp","INTERNAL","ServerValue","databaseExp","comments_section_component","messageElement","replaceWith","moment","initials","messageKey","impression_component","isBotUserAgent","player_component","duration","slideCount","slideIndex","added","urlParam","startTime","startSlide","share_modal_component","timeParts","checked","sharing_section_component","modal_component","readCookie","createCookie","isHidden","pausePlayer","password_required_component","success_component","presentation_show_component","PermanentPlayer.currentPresentationId","PermanentPlayer.currentPlayerElement","playerWrapper","playerElementController","PermanentPlayer.open","player","edit_server_modal_component","quality","finish_stream_modal_component","show","form_component$1","live_servers_component","monitoring_tab_component","recording_app_monitoring_tab_component","restart_wowza_transcript_modal_component","stream_tab_component","file_component","getFilesFromDataTransfer","files","file","formatTimeString","formatSize","video","upload_component","filesToUpload","alexEventId","noAlexEvent","uploadToSubmittedEvent","render4kSpeakerVideo","videoInSlides","palpatineTest","recordedAt","folderId","ResumableUpload","progress","uploads","uploadService","headers","csrfTokenMetaTag","upload_exports_modal_component","formData","uploadParams","valid","fileController","speakerVideoFile","slidesVideoFile","fileTarget","upload_videos_to_append_modal_component","log_in_form_component","categories_component","content_component","searchType","searchE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