index.node.esm.js 73 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131
  1. /**
  2. * @license
  3. * Copyright 2017 Google LLC
  4. *
  5. * Licensed under the Apache License, Version 2.0 (the "License");
  6. * you may not use this file except in compliance with the License.
  7. * You may obtain a copy of the License at
  8. *
  9. * http://www.apache.org/licenses/LICENSE-2.0
  10. *
  11. * Unless required by applicable law or agreed to in writing, software
  12. * distributed under the License is distributed on an "AS IS" BASIS,
  13. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14. * See the License for the specific language governing permissions and
  15. * limitations under the License.
  16. */
  17. /**
  18. * @fileoverview Firebase constants. Some of these (@defines) can be overridden at compile-time.
  19. */
  20. const CONSTANTS = {
  21. /**
  22. * @define {boolean} Whether this is the client Node.js SDK.
  23. */
  24. NODE_CLIENT: false,
  25. /**
  26. * @define {boolean} Whether this is the Admin Node.js SDK.
  27. */
  28. NODE_ADMIN: false,
  29. /**
  30. * Firebase SDK Version
  31. */
  32. SDK_VERSION: '${JSCORE_VERSION}'
  33. };
  34. /**
  35. * @license
  36. * Copyright 2017 Google LLC
  37. *
  38. * Licensed under the Apache License, Version 2.0 (the "License");
  39. * you may not use this file except in compliance with the License.
  40. * You may obtain a copy of the License at
  41. *
  42. * http://www.apache.org/licenses/LICENSE-2.0
  43. *
  44. * Unless required by applicable law or agreed to in writing, software
  45. * distributed under the License is distributed on an "AS IS" BASIS,
  46. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  47. * See the License for the specific language governing permissions and
  48. * limitations under the License.
  49. */
  50. /**
  51. * Throws an error if the provided assertion is falsy
  52. */
  53. const assert = function (assertion, message) {
  54. if (!assertion) {
  55. throw assertionError(message);
  56. }
  57. };
  58. /**
  59. * Returns an Error object suitable for throwing.
  60. */
  61. const assertionError = function (message) {
  62. return new Error('Firebase Database (' +
  63. CONSTANTS.SDK_VERSION +
  64. ') INTERNAL ASSERT FAILED: ' +
  65. message);
  66. };
  67. /**
  68. * @license
  69. * Copyright 2017 Google LLC
  70. *
  71. * Licensed under the Apache License, Version 2.0 (the "License");
  72. * you may not use this file except in compliance with the License.
  73. * You may obtain a copy of the License at
  74. *
  75. * http://www.apache.org/licenses/LICENSE-2.0
  76. *
  77. * Unless required by applicable law or agreed to in writing, software
  78. * distributed under the License is distributed on an "AS IS" BASIS,
  79. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  80. * See the License for the specific language governing permissions and
  81. * limitations under the License.
  82. */
  83. const stringToByteArray$1 = function (str) {
  84. // TODO(user): Use native implementations if/when available
  85. const out = [];
  86. let p = 0;
  87. for (let i = 0; i < str.length; i++) {
  88. let c = str.charCodeAt(i);
  89. if (c < 128) {
  90. out[p++] = c;
  91. }
  92. else if (c < 2048) {
  93. out[p++] = (c >> 6) | 192;
  94. out[p++] = (c & 63) | 128;
  95. }
  96. else if ((c & 0xfc00) === 0xd800 &&
  97. i + 1 < str.length &&
  98. (str.charCodeAt(i + 1) & 0xfc00) === 0xdc00) {
  99. // Surrogate Pair
  100. c = 0x10000 + ((c & 0x03ff) << 10) + (str.charCodeAt(++i) & 0x03ff);
  101. out[p++] = (c >> 18) | 240;
  102. out[p++] = ((c >> 12) & 63) | 128;
  103. out[p++] = ((c >> 6) & 63) | 128;
  104. out[p++] = (c & 63) | 128;
  105. }
  106. else {
  107. out[p++] = (c >> 12) | 224;
  108. out[p++] = ((c >> 6) & 63) | 128;
  109. out[p++] = (c & 63) | 128;
  110. }
  111. }
  112. return out;
  113. };
  114. /**
  115. * Turns an array of numbers into the string given by the concatenation of the
  116. * characters to which the numbers correspond.
  117. * @param bytes Array of numbers representing characters.
  118. * @return Stringification of the array.
  119. */
  120. const byteArrayToString = function (bytes) {
  121. // TODO(user): Use native implementations if/when available
  122. const out = [];
  123. let pos = 0, c = 0;
  124. while (pos < bytes.length) {
  125. const c1 = bytes[pos++];
  126. if (c1 < 128) {
  127. out[c++] = String.fromCharCode(c1);
  128. }
  129. else if (c1 > 191 && c1 < 224) {
  130. const c2 = bytes[pos++];
  131. out[c++] = String.fromCharCode(((c1 & 31) << 6) | (c2 & 63));
  132. }
  133. else if (c1 > 239 && c1 < 365) {
  134. // Surrogate Pair
  135. const c2 = bytes[pos++];
  136. const c3 = bytes[pos++];
  137. const c4 = bytes[pos++];
  138. const u = (((c1 & 7) << 18) | ((c2 & 63) << 12) | ((c3 & 63) << 6) | (c4 & 63)) -
  139. 0x10000;
  140. out[c++] = String.fromCharCode(0xd800 + (u >> 10));
  141. out[c++] = String.fromCharCode(0xdc00 + (u & 1023));
  142. }
  143. else {
  144. const c2 = bytes[pos++];
  145. const c3 = bytes[pos++];
  146. out[c++] = String.fromCharCode(((c1 & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
  147. }
  148. }
  149. return out.join('');
  150. };
  151. // We define it as an object literal instead of a class because a class compiled down to es5 can't
  152. // be treeshaked. https://github.com/rollup/rollup/issues/1691
  153. // Static lookup maps, lazily populated by init_()
  154. const base64 = {
  155. /**
  156. * Maps bytes to characters.
  157. */
  158. byteToCharMap_: null,
  159. /**
  160. * Maps characters to bytes.
  161. */
  162. charToByteMap_: null,
  163. /**
  164. * Maps bytes to websafe characters.
  165. * @private
  166. */
  167. byteToCharMapWebSafe_: null,
  168. /**
  169. * Maps websafe characters to bytes.
  170. * @private
  171. */
  172. charToByteMapWebSafe_: null,
  173. /**
  174. * Our default alphabet, shared between
  175. * ENCODED_VALS and ENCODED_VALS_WEBSAFE
  176. */
  177. ENCODED_VALS_BASE: 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' + 'abcdefghijklmnopqrstuvwxyz' + '0123456789',
  178. /**
  179. * Our default alphabet. Value 64 (=) is special; it means "nothing."
  180. */
  181. get ENCODED_VALS() {
  182. return this.ENCODED_VALS_BASE + '+/=';
  183. },
  184. /**
  185. * Our websafe alphabet.
  186. */
  187. get ENCODED_VALS_WEBSAFE() {
  188. return this.ENCODED_VALS_BASE + '-_.';
  189. },
  190. /**
  191. * Whether this browser supports the atob and btoa functions. This extension
  192. * started at Mozilla but is now implemented by many browsers. We use the
  193. * ASSUME_* variables to avoid pulling in the full useragent detection library
  194. * but still allowing the standard per-browser compilations.
  195. *
  196. */
  197. HAS_NATIVE_SUPPORT: typeof atob === 'function',
  198. /**
  199. * Base64-encode an array of bytes.
  200. *
  201. * @param input An array of bytes (numbers with
  202. * value in [0, 255]) to encode.
  203. * @param webSafe Boolean indicating we should use the
  204. * alternative alphabet.
  205. * @return The base64 encoded string.
  206. */
  207. encodeByteArray(input, webSafe) {
  208. if (!Array.isArray(input)) {
  209. throw Error('encodeByteArray takes an array as a parameter');
  210. }
  211. this.init_();
  212. const byteToCharMap = webSafe
  213. ? this.byteToCharMapWebSafe_
  214. : this.byteToCharMap_;
  215. const output = [];
  216. for (let i = 0; i < input.length; i += 3) {
  217. const byte1 = input[i];
  218. const haveByte2 = i + 1 < input.length;
  219. const byte2 = haveByte2 ? input[i + 1] : 0;
  220. const haveByte3 = i + 2 < input.length;
  221. const byte3 = haveByte3 ? input[i + 2] : 0;
  222. const outByte1 = byte1 >> 2;
  223. const outByte2 = ((byte1 & 0x03) << 4) | (byte2 >> 4);
  224. let outByte3 = ((byte2 & 0x0f) << 2) | (byte3 >> 6);
  225. let outByte4 = byte3 & 0x3f;
  226. if (!haveByte3) {
  227. outByte4 = 64;
  228. if (!haveByte2) {
  229. outByte3 = 64;
  230. }
  231. }
  232. output.push(byteToCharMap[outByte1], byteToCharMap[outByte2], byteToCharMap[outByte3], byteToCharMap[outByte4]);
  233. }
  234. return output.join('');
  235. },
  236. /**
  237. * Base64-encode a string.
  238. *
  239. * @param input A string to encode.
  240. * @param webSafe If true, we should use the
  241. * alternative alphabet.
  242. * @return The base64 encoded string.
  243. */
  244. encodeString(input, webSafe) {
  245. // Shortcut for Mozilla browsers that implement
  246. // a native base64 encoder in the form of "btoa/atob"
  247. if (this.HAS_NATIVE_SUPPORT && !webSafe) {
  248. return btoa(input);
  249. }
  250. return this.encodeByteArray(stringToByteArray$1(input), webSafe);
  251. },
  252. /**
  253. * Base64-decode a string.
  254. *
  255. * @param input to decode.
  256. * @param webSafe True if we should use the
  257. * alternative alphabet.
  258. * @return string representing the decoded value.
  259. */
  260. decodeString(input, webSafe) {
  261. // Shortcut for Mozilla browsers that implement
  262. // a native base64 encoder in the form of "btoa/atob"
  263. if (this.HAS_NATIVE_SUPPORT && !webSafe) {
  264. return atob(input);
  265. }
  266. return byteArrayToString(this.decodeStringToByteArray(input, webSafe));
  267. },
  268. /**
  269. * Base64-decode a string.
  270. *
  271. * In base-64 decoding, groups of four characters are converted into three
  272. * bytes. If the encoder did not apply padding, the input length may not
  273. * be a multiple of 4.
  274. *
  275. * In this case, the last group will have fewer than 4 characters, and
  276. * padding will be inferred. If the group has one or two characters, it decodes
  277. * to one byte. If the group has three characters, it decodes to two bytes.
  278. *
  279. * @param input Input to decode.
  280. * @param webSafe True if we should use the web-safe alphabet.
  281. * @return bytes representing the decoded value.
  282. */
  283. decodeStringToByteArray(input, webSafe) {
  284. this.init_();
  285. const charToByteMap = webSafe
  286. ? this.charToByteMapWebSafe_
  287. : this.charToByteMap_;
  288. const output = [];
  289. for (let i = 0; i < input.length;) {
  290. const byte1 = charToByteMap[input.charAt(i++)];
  291. const haveByte2 = i < input.length;
  292. const byte2 = haveByte2 ? charToByteMap[input.charAt(i)] : 0;
  293. ++i;
  294. const haveByte3 = i < input.length;
  295. const byte3 = haveByte3 ? charToByteMap[input.charAt(i)] : 64;
  296. ++i;
  297. const haveByte4 = i < input.length;
  298. const byte4 = haveByte4 ? charToByteMap[input.charAt(i)] : 64;
  299. ++i;
  300. if (byte1 == null || byte2 == null || byte3 == null || byte4 == null) {
  301. throw new DecodeBase64StringError();
  302. }
  303. const outByte1 = (byte1 << 2) | (byte2 >> 4);
  304. output.push(outByte1);
  305. if (byte3 !== 64) {
  306. const outByte2 = ((byte2 << 4) & 0xf0) | (byte3 >> 2);
  307. output.push(outByte2);
  308. if (byte4 !== 64) {
  309. const outByte3 = ((byte3 << 6) & 0xc0) | byte4;
  310. output.push(outByte3);
  311. }
  312. }
  313. }
  314. return output;
  315. },
  316. /**
  317. * Lazy static initialization function. Called before
  318. * accessing any of the static map variables.
  319. * @private
  320. */
  321. init_() {
  322. if (!this.byteToCharMap_) {
  323. this.byteToCharMap_ = {};
  324. this.charToByteMap_ = {};
  325. this.byteToCharMapWebSafe_ = {};
  326. this.charToByteMapWebSafe_ = {};
  327. // We want quick mappings back and forth, so we precompute two maps.
  328. for (let i = 0; i < this.ENCODED_VALS.length; i++) {
  329. this.byteToCharMap_[i] = this.ENCODED_VALS.charAt(i);
  330. this.charToByteMap_[this.byteToCharMap_[i]] = i;
  331. this.byteToCharMapWebSafe_[i] = this.ENCODED_VALS_WEBSAFE.charAt(i);
  332. this.charToByteMapWebSafe_[this.byteToCharMapWebSafe_[i]] = i;
  333. // Be forgiving when decoding and correctly decode both encodings.
  334. if (i >= this.ENCODED_VALS_BASE.length) {
  335. this.charToByteMap_[this.ENCODED_VALS_WEBSAFE.charAt(i)] = i;
  336. this.charToByteMapWebSafe_[this.ENCODED_VALS.charAt(i)] = i;
  337. }
  338. }
  339. }
  340. }
  341. };
  342. /**
  343. * An error encountered while decoding base64 string.
  344. */
  345. class DecodeBase64StringError extends Error {
  346. constructor() {
  347. super(...arguments);
  348. this.name = 'DecodeBase64StringError';
  349. }
  350. }
  351. /**
  352. * URL-safe base64 encoding
  353. */
  354. const base64Encode = function (str) {
  355. const utf8Bytes = stringToByteArray$1(str);
  356. return base64.encodeByteArray(utf8Bytes, true);
  357. };
  358. /**
  359. * URL-safe base64 encoding (without "." padding in the end).
  360. * e.g. Used in JSON Web Token (JWT) parts.
  361. */
  362. const base64urlEncodeWithoutPadding = function (str) {
  363. // Use base64url encoding and remove padding in the end (dot characters).
  364. return base64Encode(str).replace(/\./g, '');
  365. };
  366. /**
  367. * URL-safe base64 decoding
  368. *
  369. * NOTE: DO NOT use the global atob() function - it does NOT support the
  370. * base64Url variant encoding.
  371. *
  372. * @param str To be decoded
  373. * @return Decoded result, if possible
  374. */
  375. const base64Decode = function (str) {
  376. try {
  377. return base64.decodeString(str, true);
  378. }
  379. catch (e) {
  380. console.error('base64Decode failed: ', e);
  381. }
  382. return null;
  383. };
  384. /**
  385. * @license
  386. * Copyright 2017 Google LLC
  387. *
  388. * Licensed under the Apache License, Version 2.0 (the "License");
  389. * you may not use this file except in compliance with the License.
  390. * You may obtain a copy of the License at
  391. *
  392. * http://www.apache.org/licenses/LICENSE-2.0
  393. *
  394. * Unless required by applicable law or agreed to in writing, software
  395. * distributed under the License is distributed on an "AS IS" BASIS,
  396. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  397. * See the License for the specific language governing permissions and
  398. * limitations under the License.
  399. */
  400. /**
  401. * Do a deep-copy of basic JavaScript Objects or Arrays.
  402. */
  403. function deepCopy(value) {
  404. return deepExtend(undefined, value);
  405. }
  406. /**
  407. * Copy properties from source to target (recursively allows extension
  408. * of Objects and Arrays). Scalar values in the target are over-written.
  409. * If target is undefined, an object of the appropriate type will be created
  410. * (and returned).
  411. *
  412. * We recursively copy all child properties of plain Objects in the source- so
  413. * that namespace- like dictionaries are merged.
  414. *
  415. * Note that the target can be a function, in which case the properties in
  416. * the source Object are copied onto it as static properties of the Function.
  417. *
  418. * Note: we don't merge __proto__ to prevent prototype pollution
  419. */
  420. function deepExtend(target, source) {
  421. if (!(source instanceof Object)) {
  422. return source;
  423. }
  424. switch (source.constructor) {
  425. case Date:
  426. // Treat Dates like scalars; if the target date object had any child
  427. // properties - they will be lost!
  428. const dateValue = source;
  429. return new Date(dateValue.getTime());
  430. case Object:
  431. if (target === undefined) {
  432. target = {};
  433. }
  434. break;
  435. case Array:
  436. // Always copy the array source and overwrite the target.
  437. target = [];
  438. break;
  439. default:
  440. // Not a plain Object - treat it as a scalar.
  441. return source;
  442. }
  443. for (const prop in source) {
  444. // use isValidKey to guard against prototype pollution. See https://snyk.io/vuln/SNYK-JS-LODASH-450202
  445. if (!source.hasOwnProperty(prop) || !isValidKey(prop)) {
  446. continue;
  447. }
  448. target[prop] = deepExtend(target[prop], source[prop]);
  449. }
  450. return target;
  451. }
  452. function isValidKey(key) {
  453. return key !== '__proto__';
  454. }
  455. /**
  456. * @license
  457. * Copyright 2022 Google LLC
  458. *
  459. * Licensed under the Apache License, Version 2.0 (the "License");
  460. * you may not use this file except in compliance with the License.
  461. * You may obtain a copy of the License at
  462. *
  463. * http://www.apache.org/licenses/LICENSE-2.0
  464. *
  465. * Unless required by applicable law or agreed to in writing, software
  466. * distributed under the License is distributed on an "AS IS" BASIS,
  467. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  468. * See the License for the specific language governing permissions and
  469. * limitations under the License.
  470. */
  471. /**
  472. * Polyfill for `globalThis` object.
  473. * @returns the `globalThis` object for the given environment.
  474. * @public
  475. */
  476. function getGlobal() {
  477. if (typeof self !== 'undefined') {
  478. return self;
  479. }
  480. if (typeof window !== 'undefined') {
  481. return window;
  482. }
  483. if (typeof global !== 'undefined') {
  484. return global;
  485. }
  486. throw new Error('Unable to locate global object.');
  487. }
  488. /**
  489. * @license
  490. * Copyright 2022 Google LLC
  491. *
  492. * Licensed under the Apache License, Version 2.0 (the "License");
  493. * you may not use this file except in compliance with the License.
  494. * You may obtain a copy of the License at
  495. *
  496. * http://www.apache.org/licenses/LICENSE-2.0
  497. *
  498. * Unless required by applicable law or agreed to in writing, software
  499. * distributed under the License is distributed on an "AS IS" BASIS,
  500. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  501. * See the License for the specific language governing permissions and
  502. * limitations under the License.
  503. */
  504. const getDefaultsFromGlobal = () => getGlobal().__FIREBASE_DEFAULTS__;
  505. /**
  506. * Attempt to read defaults from a JSON string provided to
  507. * process(.)env(.)__FIREBASE_DEFAULTS__ or a JSON file whose path is in
  508. * process(.)env(.)__FIREBASE_DEFAULTS_PATH__
  509. * The dots are in parens because certain compilers (Vite?) cannot
  510. * handle seeing that variable in comments.
  511. * See https://github.com/firebase/firebase-js-sdk/issues/6838
  512. */
  513. const getDefaultsFromEnvVariable = () => {
  514. if (typeof process === 'undefined' || typeof process.env === 'undefined') {
  515. return;
  516. }
  517. const defaultsJsonString = process.env.__FIREBASE_DEFAULTS__;
  518. if (defaultsJsonString) {
  519. return JSON.parse(defaultsJsonString);
  520. }
  521. };
  522. const getDefaultsFromCookie = () => {
  523. if (typeof document === 'undefined') {
  524. return;
  525. }
  526. let match;
  527. try {
  528. match = document.cookie.match(/__FIREBASE_DEFAULTS__=([^;]+)/);
  529. }
  530. catch (e) {
  531. // Some environments such as Angular Universal SSR have a
  532. // `document` object but error on accessing `document.cookie`.
  533. return;
  534. }
  535. const decoded = match && base64Decode(match[1]);
  536. return decoded && JSON.parse(decoded);
  537. };
  538. /**
  539. * Get the __FIREBASE_DEFAULTS__ object. It checks in order:
  540. * (1) if such an object exists as a property of `globalThis`
  541. * (2) if such an object was provided on a shell environment variable
  542. * (3) if such an object exists in a cookie
  543. * @public
  544. */
  545. const getDefaults = () => {
  546. try {
  547. return (getDefaultsFromGlobal() ||
  548. getDefaultsFromEnvVariable() ||
  549. getDefaultsFromCookie());
  550. }
  551. catch (e) {
  552. /**
  553. * Catch-all for being unable to get __FIREBASE_DEFAULTS__ due
  554. * to any environment case we have not accounted for. Log to
  555. * info instead of swallowing so we can find these unknown cases
  556. * and add paths for them if needed.
  557. */
  558. console.info(`Unable to get __FIREBASE_DEFAULTS__ due to: ${e}`);
  559. return;
  560. }
  561. };
  562. /**
  563. * Returns emulator host stored in the __FIREBASE_DEFAULTS__ object
  564. * for the given product.
  565. * @returns a URL host formatted like `127.0.0.1:9999` or `[::1]:4000` if available
  566. * @public
  567. */
  568. const 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]; };
  569. /**
  570. * Returns emulator hostname and port stored in the __FIREBASE_DEFAULTS__ object
  571. * for the given product.
  572. * @returns a pair of hostname and port like `["::1", 4000]` if available
  573. * @public
  574. */
  575. const getDefaultEmulatorHostnameAndPort = (productName) => {
  576. const host = getDefaultEmulatorHost(productName);
  577. if (!host) {
  578. return undefined;
  579. }
  580. const separatorIndex = host.lastIndexOf(':'); // Finding the last since IPv6 addr also has colons.
  581. if (separatorIndex <= 0 || separatorIndex + 1 === host.length) {
  582. throw new Error(`Invalid host ${host} with no separate hostname and port!`);
  583. }
  584. // eslint-disable-next-line no-restricted-globals
  585. const port = parseInt(host.substring(separatorIndex + 1), 10);
  586. if (host[0] === '[') {
  587. // Bracket-quoted `[ipv6addr]:port` => return "ipv6addr" (without brackets).
  588. return [host.substring(1, separatorIndex - 1), port];
  589. }
  590. else {
  591. return [host.substring(0, separatorIndex), port];
  592. }
  593. };
  594. /**
  595. * Returns Firebase app config stored in the __FIREBASE_DEFAULTS__ object.
  596. * @public
  597. */
  598. const getDefaultAppConfig = () => { var _a; return (_a = getDefaults()) === null || _a === void 0 ? void 0 : _a.config; };
  599. /**
  600. * Returns an experimental setting on the __FIREBASE_DEFAULTS__ object (properties
  601. * prefixed by "_")
  602. * @public
  603. */
  604. const getExperimentalSetting = (name) => { var _a; return (_a = getDefaults()) === null || _a === void 0 ? void 0 : _a[`_${name}`]; };
  605. /**
  606. * @license
  607. * Copyright 2017 Google LLC
  608. *
  609. * Licensed under the Apache License, Version 2.0 (the "License");
  610. * you may not use this file except in compliance with the License.
  611. * You may obtain a copy of the License at
  612. *
  613. * http://www.apache.org/licenses/LICENSE-2.0
  614. *
  615. * Unless required by applicable law or agreed to in writing, software
  616. * distributed under the License is distributed on an "AS IS" BASIS,
  617. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  618. * See the License for the specific language governing permissions and
  619. * limitations under the License.
  620. */
  621. class Deferred {
  622. constructor() {
  623. this.reject = () => { };
  624. this.resolve = () => { };
  625. this.promise = new Promise((resolve, reject) => {
  626. this.resolve = resolve;
  627. this.reject = reject;
  628. });
  629. }
  630. /**
  631. * Our API internals are not promiseified and cannot because our callback APIs have subtle expectations around
  632. * invoking promises inline, which Promises are forbidden to do. This method accepts an optional node-style callback
  633. * and returns a node-style callback which will resolve or reject the Deferred's promise.
  634. */
  635. wrapCallback(callback) {
  636. return (error, value) => {
  637. if (error) {
  638. this.reject(error);
  639. }
  640. else {
  641. this.resolve(value);
  642. }
  643. if (typeof callback === 'function') {
  644. // Attaching noop handler just in case developer wasn't expecting
  645. // promises
  646. this.promise.catch(() => { });
  647. // Some of our callbacks don't expect a value and our own tests
  648. // assert that the parameter length is 1
  649. if (callback.length === 1) {
  650. callback(error);
  651. }
  652. else {
  653. callback(error, value);
  654. }
  655. }
  656. };
  657. }
  658. }
  659. /**
  660. * @license
  661. * Copyright 2021 Google LLC
  662. *
  663. * Licensed under the Apache License, Version 2.0 (the "License");
  664. * you may not use this file except in compliance with the License.
  665. * You may obtain a copy of the License at
  666. *
  667. * http://www.apache.org/licenses/LICENSE-2.0
  668. *
  669. * Unless required by applicable law or agreed to in writing, software
  670. * distributed under the License is distributed on an "AS IS" BASIS,
  671. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  672. * See the License for the specific language governing permissions and
  673. * limitations under the License.
  674. */
  675. function createMockUserToken(token, projectId) {
  676. if (token.uid) {
  677. throw new Error('The "uid" field is no longer supported by mockUserToken. Please use "sub" instead for Firebase Auth User ID.');
  678. }
  679. // Unsecured JWTs use "none" as the algorithm.
  680. const header = {
  681. alg: 'none',
  682. type: 'JWT'
  683. };
  684. const project = projectId || 'demo-project';
  685. const iat = token.iat || 0;
  686. const sub = token.sub || token.user_id;
  687. if (!sub) {
  688. throw new Error("mockUserToken must contain 'sub' or 'user_id' field!");
  689. }
  690. const payload = Object.assign({
  691. // Set all required fields to decent defaults
  692. iss: `https://securetoken.google.com/${project}`, aud: project, iat, exp: iat + 3600, auth_time: iat, sub, user_id: sub, firebase: {
  693. sign_in_provider: 'custom',
  694. identities: {}
  695. } }, token);
  696. // Unsecured JWTs use the empty string as a signature.
  697. const signature = '';
  698. return [
  699. base64urlEncodeWithoutPadding(JSON.stringify(header)),
  700. base64urlEncodeWithoutPadding(JSON.stringify(payload)),
  701. signature
  702. ].join('.');
  703. }
  704. /**
  705. * @license
  706. * Copyright 2017 Google LLC
  707. *
  708. * Licensed under the Apache License, Version 2.0 (the "License");
  709. * you may not use this file except in compliance with the License.
  710. * You may obtain a copy of the License at
  711. *
  712. * http://www.apache.org/licenses/LICENSE-2.0
  713. *
  714. * Unless required by applicable law or agreed to in writing, software
  715. * distributed under the License is distributed on an "AS IS" BASIS,
  716. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  717. * See the License for the specific language governing permissions and
  718. * limitations under the License.
  719. */
  720. /**
  721. * Returns navigator.userAgent string or '' if it's not defined.
  722. * @return user agent string
  723. */
  724. function getUA() {
  725. if (typeof navigator !== 'undefined' &&
  726. typeof navigator['userAgent'] === 'string') {
  727. return navigator['userAgent'];
  728. }
  729. else {
  730. return '';
  731. }
  732. }
  733. /**
  734. * Detect Cordova / PhoneGap / Ionic frameworks on a mobile device.
  735. *
  736. * Deliberately does not rely on checking `file://` URLs (as this fails PhoneGap
  737. * in the Ripple emulator) nor Cordova `onDeviceReady`, which would normally
  738. * wait for a callback.
  739. */
  740. function isMobileCordova() {
  741. return (typeof window !== 'undefined' &&
  742. // @ts-ignore Setting up an broadly applicable index signature for Window
  743. // just to deal with this case would probably be a bad idea.
  744. !!(window['cordova'] || window['phonegap'] || window['PhoneGap']) &&
  745. /ios|iphone|ipod|ipad|android|blackberry|iemobile/i.test(getUA()));
  746. }
  747. /**
  748. * Detect Node.js.
  749. *
  750. * @return true if Node.js environment is detected or specified.
  751. */
  752. // Node detection logic from: https://github.com/iliakan/detect-node/
  753. function isNode() {
  754. var _a;
  755. const forceEnvironment = (_a = getDefaults()) === null || _a === void 0 ? void 0 : _a.forceEnvironment;
  756. if (forceEnvironment === 'node') {
  757. return true;
  758. }
  759. else if (forceEnvironment === 'browser') {
  760. return false;
  761. }
  762. try {
  763. return (Object.prototype.toString.call(global.process) === '[object process]');
  764. }
  765. catch (e) {
  766. return false;
  767. }
  768. }
  769. /**
  770. * Detect Browser Environment
  771. */
  772. function isBrowser() {
  773. return typeof self === 'object' && self.self === self;
  774. }
  775. function isBrowserExtension() {
  776. const runtime = typeof chrome === 'object'
  777. ? chrome.runtime
  778. : typeof browser === 'object'
  779. ? browser.runtime
  780. : undefined;
  781. return typeof runtime === 'object' && runtime.id !== undefined;
  782. }
  783. /**
  784. * Detect React Native.
  785. *
  786. * @return true if ReactNative environment is detected.
  787. */
  788. function isReactNative() {
  789. return (typeof navigator === 'object' && navigator['product'] === 'ReactNative');
  790. }
  791. /** Detects Electron apps. */
  792. function isElectron() {
  793. return getUA().indexOf('Electron/') >= 0;
  794. }
  795. /** Detects Internet Explorer. */
  796. function isIE() {
  797. const ua = getUA();
  798. return ua.indexOf('MSIE ') >= 0 || ua.indexOf('Trident/') >= 0;
  799. }
  800. /** Detects Universal Windows Platform apps. */
  801. function isUWP() {
  802. return getUA().indexOf('MSAppHost/') >= 0;
  803. }
  804. /**
  805. * Detect whether the current SDK build is the Node version.
  806. *
  807. * @return true if it's the Node SDK build.
  808. */
  809. function isNodeSdk() {
  810. return CONSTANTS.NODE_CLIENT === true || CONSTANTS.NODE_ADMIN === true;
  811. }
  812. /** Returns true if we are running in Safari. */
  813. function isSafari() {
  814. return (!isNode() &&
  815. navigator.userAgent.includes('Safari') &&
  816. !navigator.userAgent.includes('Chrome'));
  817. }
  818. /**
  819. * This method checks if indexedDB is supported by current browser/service worker context
  820. * @return true if indexedDB is supported by current browser/service worker context
  821. */
  822. function isIndexedDBAvailable() {
  823. try {
  824. return typeof indexedDB === 'object';
  825. }
  826. catch (e) {
  827. return false;
  828. }
  829. }
  830. /**
  831. * This method validates browser/sw context for indexedDB by opening a dummy indexedDB database and reject
  832. * if errors occur during the database open operation.
  833. *
  834. * @throws exception if current browser/sw context can't run idb.open (ex: Safari iframe, Firefox
  835. * private browsing)
  836. */
  837. function validateIndexedDBOpenable() {
  838. return new Promise((resolve, reject) => {
  839. try {
  840. let preExist = true;
  841. const DB_CHECK_NAME = 'validate-browser-context-for-indexeddb-analytics-module';
  842. const request = self.indexedDB.open(DB_CHECK_NAME);
  843. request.onsuccess = () => {
  844. request.result.close();
  845. // delete database only when it doesn't pre-exist
  846. if (!preExist) {
  847. self.indexedDB.deleteDatabase(DB_CHECK_NAME);
  848. }
  849. resolve(true);
  850. };
  851. request.onupgradeneeded = () => {
  852. preExist = false;
  853. };
  854. request.onerror = () => {
  855. var _a;
  856. reject(((_a = request.error) === null || _a === void 0 ? void 0 : _a.message) || '');
  857. };
  858. }
  859. catch (error) {
  860. reject(error);
  861. }
  862. });
  863. }
  864. /**
  865. *
  866. * This method checks whether cookie is enabled within current browser
  867. * @return true if cookie is enabled within current browser
  868. */
  869. function areCookiesEnabled() {
  870. if (typeof navigator === 'undefined' || !navigator.cookieEnabled) {
  871. return false;
  872. }
  873. return true;
  874. }
  875. /**
  876. * @license
  877. * Copyright 2017 Google LLC
  878. *
  879. * Licensed under the Apache License, Version 2.0 (the "License");
  880. * you may not use this file except in compliance with the License.
  881. * You may obtain a copy of the License at
  882. *
  883. * http://www.apache.org/licenses/LICENSE-2.0
  884. *
  885. * Unless required by applicable law or agreed to in writing, software
  886. * distributed under the License is distributed on an "AS IS" BASIS,
  887. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  888. * See the License for the specific language governing permissions and
  889. * limitations under the License.
  890. */
  891. /**
  892. * @fileoverview Standardized Firebase Error.
  893. *
  894. * Usage:
  895. *
  896. * // Typescript string literals for type-safe codes
  897. * type Err =
  898. * 'unknown' |
  899. * 'object-not-found'
  900. * ;
  901. *
  902. * // Closure enum for type-safe error codes
  903. * // at-enum {string}
  904. * var Err = {
  905. * UNKNOWN: 'unknown',
  906. * OBJECT_NOT_FOUND: 'object-not-found',
  907. * }
  908. *
  909. * let errors: Map<Err, string> = {
  910. * 'generic-error': "Unknown error",
  911. * 'file-not-found': "Could not find file: {$file}",
  912. * };
  913. *
  914. * // Type-safe function - must pass a valid error code as param.
  915. * let error = new ErrorFactory<Err>('service', 'Service', errors);
  916. *
  917. * ...
  918. * throw error.create(Err.GENERIC);
  919. * ...
  920. * throw error.create(Err.FILE_NOT_FOUND, {'file': fileName});
  921. * ...
  922. * // Service: Could not file file: foo.txt (service/file-not-found).
  923. *
  924. * catch (e) {
  925. * assert(e.message === "Could not find file: foo.txt.");
  926. * if ((e as FirebaseError)?.code === 'service/file-not-found') {
  927. * console.log("Could not read file: " + e['file']);
  928. * }
  929. * }
  930. */
  931. const ERROR_NAME = 'FirebaseError';
  932. // Based on code from:
  933. // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error#Custom_Error_Types
  934. class FirebaseError extends Error {
  935. constructor(
  936. /** The error code for this error. */
  937. code, message,
  938. /** Custom data for this error. */
  939. customData) {
  940. super(message);
  941. this.code = code;
  942. this.customData = customData;
  943. /** The custom name for all FirebaseErrors. */
  944. this.name = ERROR_NAME;
  945. // Fix For ES5
  946. // https://github.com/Microsoft/TypeScript-wiki/blob/master/Breaking-Changes.md#extending-built-ins-like-error-array-and-map-may-no-longer-work
  947. Object.setPrototypeOf(this, FirebaseError.prototype);
  948. // Maintains proper stack trace for where our error was thrown.
  949. // Only available on V8.
  950. if (Error.captureStackTrace) {
  951. Error.captureStackTrace(this, ErrorFactory.prototype.create);
  952. }
  953. }
  954. }
  955. class ErrorFactory {
  956. constructor(service, serviceName, errors) {
  957. this.service = service;
  958. this.serviceName = serviceName;
  959. this.errors = errors;
  960. }
  961. create(code, ...data) {
  962. const customData = data[0] || {};
  963. const fullCode = `${this.service}/${code}`;
  964. const template = this.errors[code];
  965. const message = template ? replaceTemplate(template, customData) : 'Error';
  966. // Service Name: Error message (service/code).
  967. const fullMessage = `${this.serviceName}: ${message} (${fullCode}).`;
  968. const error = new FirebaseError(fullCode, fullMessage, customData);
  969. return error;
  970. }
  971. }
  972. function replaceTemplate(template, data) {
  973. return template.replace(PATTERN, (_, key) => {
  974. const value = data[key];
  975. return value != null ? String(value) : `<${key}?>`;
  976. });
  977. }
  978. const PATTERN = /\{\$([^}]+)}/g;
  979. /**
  980. * @license
  981. * Copyright 2017 Google LLC
  982. *
  983. * Licensed under the Apache License, Version 2.0 (the "License");
  984. * you may not use this file except in compliance with the License.
  985. * You may obtain a copy of the License at
  986. *
  987. * http://www.apache.org/licenses/LICENSE-2.0
  988. *
  989. * Unless required by applicable law or agreed to in writing, software
  990. * distributed under the License is distributed on an "AS IS" BASIS,
  991. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  992. * See the License for the specific language governing permissions and
  993. * limitations under the License.
  994. */
  995. /**
  996. * Evaluates a JSON string into a javascript object.
  997. *
  998. * @param {string} str A string containing JSON.
  999. * @return {*} The javascript object representing the specified JSON.
  1000. */
  1001. function jsonEval(str) {
  1002. return JSON.parse(str);
  1003. }
  1004. /**
  1005. * Returns JSON representing a javascript object.
  1006. * @param {*} data Javascript object to be stringified.
  1007. * @return {string} The JSON contents of the object.
  1008. */
  1009. function stringify(data) {
  1010. return JSON.stringify(data);
  1011. }
  1012. /**
  1013. * @license
  1014. * Copyright 2017 Google LLC
  1015. *
  1016. * Licensed under the Apache License, Version 2.0 (the "License");
  1017. * you may not use this file except in compliance with the License.
  1018. * You may obtain a copy of the License at
  1019. *
  1020. * http://www.apache.org/licenses/LICENSE-2.0
  1021. *
  1022. * Unless required by applicable law or agreed to in writing, software
  1023. * distributed under the License is distributed on an "AS IS" BASIS,
  1024. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  1025. * See the License for the specific language governing permissions and
  1026. * limitations under the License.
  1027. */
  1028. /**
  1029. * Decodes a Firebase auth. token into constituent parts.
  1030. *
  1031. * Notes:
  1032. * - May return with invalid / incomplete claims if there's no native base64 decoding support.
  1033. * - Doesn't check if the token is actually valid.
  1034. */
  1035. const decode = function (token) {
  1036. let header = {}, claims = {}, data = {}, signature = '';
  1037. try {
  1038. const parts = token.split('.');
  1039. header = jsonEval(base64Decode(parts[0]) || '');
  1040. claims = jsonEval(base64Decode(parts[1]) || '');
  1041. signature = parts[2];
  1042. data = claims['d'] || {};
  1043. delete claims['d'];
  1044. }
  1045. catch (e) { }
  1046. return {
  1047. header,
  1048. claims,
  1049. data,
  1050. signature
  1051. };
  1052. };
  1053. /**
  1054. * Decodes a Firebase auth. token and checks the validity of its time-based claims. Will return true if the
  1055. * token is within the time window authorized by the 'nbf' (not-before) and 'iat' (issued-at) claims.
  1056. *
  1057. * Notes:
  1058. * - May return a false negative if there's no native base64 decoding support.
  1059. * - Doesn't check if the token is actually valid.
  1060. */
  1061. const isValidTimestamp = function (token) {
  1062. const claims = decode(token).claims;
  1063. const now = Math.floor(new Date().getTime() / 1000);
  1064. let validSince = 0, validUntil = 0;
  1065. if (typeof claims === 'object') {
  1066. if (claims.hasOwnProperty('nbf')) {
  1067. validSince = claims['nbf'];
  1068. }
  1069. else if (claims.hasOwnProperty('iat')) {
  1070. validSince = claims['iat'];
  1071. }
  1072. if (claims.hasOwnProperty('exp')) {
  1073. validUntil = claims['exp'];
  1074. }
  1075. else {
  1076. // token will expire after 24h by default
  1077. validUntil = validSince + 86400;
  1078. }
  1079. }
  1080. return (!!now &&
  1081. !!validSince &&
  1082. !!validUntil &&
  1083. now >= validSince &&
  1084. now <= validUntil);
  1085. };
  1086. /**
  1087. * Decodes a Firebase auth. token and returns its issued at time if valid, null otherwise.
  1088. *
  1089. * Notes:
  1090. * - May return null if there's no native base64 decoding support.
  1091. * - Doesn't check if the token is actually valid.
  1092. */
  1093. const issuedAtTime = function (token) {
  1094. const claims = decode(token).claims;
  1095. if (typeof claims === 'object' && claims.hasOwnProperty('iat')) {
  1096. return claims['iat'];
  1097. }
  1098. return null;
  1099. };
  1100. /**
  1101. * Decodes a Firebase auth. token and checks the validity of its format. Expects a valid issued-at time.
  1102. *
  1103. * Notes:
  1104. * - May return a false negative if there's no native base64 decoding support.
  1105. * - Doesn't check if the token is actually valid.
  1106. */
  1107. const isValidFormat = function (token) {
  1108. const decoded = decode(token), claims = decoded.claims;
  1109. return !!claims && typeof claims === 'object' && claims.hasOwnProperty('iat');
  1110. };
  1111. /**
  1112. * Attempts to peer into an auth token and determine if it's an admin auth token by looking at the claims portion.
  1113. *
  1114. * Notes:
  1115. * - May return a false negative if there's no native base64 decoding support.
  1116. * - Doesn't check if the token is actually valid.
  1117. */
  1118. const isAdmin = function (token) {
  1119. const claims = decode(token).claims;
  1120. return typeof claims === 'object' && claims['admin'] === true;
  1121. };
  1122. /**
  1123. * @license
  1124. * Copyright 2017 Google LLC
  1125. *
  1126. * Licensed under the Apache License, Version 2.0 (the "License");
  1127. * you may not use this file except in compliance with the License.
  1128. * You may obtain a copy of the License at
  1129. *
  1130. * http://www.apache.org/licenses/LICENSE-2.0
  1131. *
  1132. * Unless required by applicable law or agreed to in writing, software
  1133. * distributed under the License is distributed on an "AS IS" BASIS,
  1134. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  1135. * See the License for the specific language governing permissions and
  1136. * limitations under the License.
  1137. */
  1138. function contains(obj, key) {
  1139. return Object.prototype.hasOwnProperty.call(obj, key);
  1140. }
  1141. function safeGet(obj, key) {
  1142. if (Object.prototype.hasOwnProperty.call(obj, key)) {
  1143. return obj[key];
  1144. }
  1145. else {
  1146. return undefined;
  1147. }
  1148. }
  1149. function isEmpty(obj) {
  1150. for (const key in obj) {
  1151. if (Object.prototype.hasOwnProperty.call(obj, key)) {
  1152. return false;
  1153. }
  1154. }
  1155. return true;
  1156. }
  1157. function map(obj, fn, contextObj) {
  1158. const res = {};
  1159. for (const key in obj) {
  1160. if (Object.prototype.hasOwnProperty.call(obj, key)) {
  1161. res[key] = fn.call(contextObj, obj[key], key, obj);
  1162. }
  1163. }
  1164. return res;
  1165. }
  1166. /**
  1167. * Deep equal two objects. Support Arrays and Objects.
  1168. */
  1169. function deepEqual(a, b) {
  1170. if (a === b) {
  1171. return true;
  1172. }
  1173. const aKeys = Object.keys(a);
  1174. const bKeys = Object.keys(b);
  1175. for (const k of aKeys) {
  1176. if (!bKeys.includes(k)) {
  1177. return false;
  1178. }
  1179. const aProp = a[k];
  1180. const bProp = b[k];
  1181. if (isObject(aProp) && isObject(bProp)) {
  1182. if (!deepEqual(aProp, bProp)) {
  1183. return false;
  1184. }
  1185. }
  1186. else if (aProp !== bProp) {
  1187. return false;
  1188. }
  1189. }
  1190. for (const k of bKeys) {
  1191. if (!aKeys.includes(k)) {
  1192. return false;
  1193. }
  1194. }
  1195. return true;
  1196. }
  1197. function isObject(thing) {
  1198. return thing !== null && typeof thing === 'object';
  1199. }
  1200. /**
  1201. * @license
  1202. * Copyright 2022 Google LLC
  1203. *
  1204. * Licensed under the Apache License, Version 2.0 (the "License");
  1205. * you may not use this file except in compliance with the License.
  1206. * You may obtain a copy of the License at
  1207. *
  1208. * http://www.apache.org/licenses/LICENSE-2.0
  1209. *
  1210. * Unless required by applicable law or agreed to in writing, software
  1211. * distributed under the License is distributed on an "AS IS" BASIS,
  1212. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  1213. * See the License for the specific language governing permissions and
  1214. * limitations under the License.
  1215. */
  1216. /**
  1217. * Rejects if the given promise doesn't resolve in timeInMS milliseconds.
  1218. * @internal
  1219. */
  1220. function promiseWithTimeout(promise, timeInMS = 2000) {
  1221. const deferredPromise = new Deferred();
  1222. setTimeout(() => deferredPromise.reject('timeout!'), timeInMS);
  1223. promise.then(deferredPromise.resolve, deferredPromise.reject);
  1224. return deferredPromise.promise;
  1225. }
  1226. /**
  1227. * @license
  1228. * Copyright 2017 Google LLC
  1229. *
  1230. * Licensed under the Apache License, Version 2.0 (the "License");
  1231. * you may not use this file except in compliance with the License.
  1232. * You may obtain a copy of the License at
  1233. *
  1234. * http://www.apache.org/licenses/LICENSE-2.0
  1235. *
  1236. * Unless required by applicable law or agreed to in writing, software
  1237. * distributed under the License is distributed on an "AS IS" BASIS,
  1238. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  1239. * See the License for the specific language governing permissions and
  1240. * limitations under the License.
  1241. */
  1242. /**
  1243. * Returns a querystring-formatted string (e.g. &arg=val&arg2=val2) from a
  1244. * params object (e.g. {arg: 'val', arg2: 'val2'})
  1245. * Note: You must prepend it with ? when adding it to a URL.
  1246. */
  1247. function querystring(querystringParams) {
  1248. const params = [];
  1249. for (const [key, value] of Object.entries(querystringParams)) {
  1250. if (Array.isArray(value)) {
  1251. value.forEach(arrayVal => {
  1252. params.push(encodeURIComponent(key) + '=' + encodeURIComponent(arrayVal));
  1253. });
  1254. }
  1255. else {
  1256. params.push(encodeURIComponent(key) + '=' + encodeURIComponent(value));
  1257. }
  1258. }
  1259. return params.length ? '&' + params.join('&') : '';
  1260. }
  1261. /**
  1262. * Decodes a querystring (e.g. ?arg=val&arg2=val2) into a params object
  1263. * (e.g. {arg: 'val', arg2: 'val2'})
  1264. */
  1265. function querystringDecode(querystring) {
  1266. const obj = {};
  1267. const tokens = querystring.replace(/^\?/, '').split('&');
  1268. tokens.forEach(token => {
  1269. if (token) {
  1270. const [key, value] = token.split('=');
  1271. obj[decodeURIComponent(key)] = decodeURIComponent(value);
  1272. }
  1273. });
  1274. return obj;
  1275. }
  1276. /**
  1277. * Extract the query string part of a URL, including the leading question mark (if present).
  1278. */
  1279. function extractQuerystring(url) {
  1280. const queryStart = url.indexOf('?');
  1281. if (!queryStart) {
  1282. return '';
  1283. }
  1284. const fragmentStart = url.indexOf('#', queryStart);
  1285. return url.substring(queryStart, fragmentStart > 0 ? fragmentStart : undefined);
  1286. }
  1287. /**
  1288. * @license
  1289. * Copyright 2017 Google LLC
  1290. *
  1291. * Licensed under the Apache License, Version 2.0 (the "License");
  1292. * you may not use this file except in compliance with the License.
  1293. * You may obtain a copy of the License at
  1294. *
  1295. * http://www.apache.org/licenses/LICENSE-2.0
  1296. *
  1297. * Unless required by applicable law or agreed to in writing, software
  1298. * distributed under the License is distributed on an "AS IS" BASIS,
  1299. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  1300. * See the License for the specific language governing permissions and
  1301. * limitations under the License.
  1302. */
  1303. /**
  1304. * @fileoverview SHA-1 cryptographic hash.
  1305. * Variable names follow the notation in FIPS PUB 180-3:
  1306. * http://csrc.nist.gov/publications/fips/fips180-3/fips180-3_final.pdf.
  1307. *
  1308. * Usage:
  1309. * var sha1 = new sha1();
  1310. * sha1.update(bytes);
  1311. * var hash = sha1.digest();
  1312. *
  1313. * Performance:
  1314. * Chrome 23: ~400 Mbit/s
  1315. * Firefox 16: ~250 Mbit/s
  1316. *
  1317. */
  1318. /**
  1319. * SHA-1 cryptographic hash constructor.
  1320. *
  1321. * The properties declared here are discussed in the above algorithm document.
  1322. * @constructor
  1323. * @final
  1324. * @struct
  1325. */
  1326. class Sha1 {
  1327. constructor() {
  1328. /**
  1329. * Holds the previous values of accumulated variables a-e in the compress_
  1330. * function.
  1331. * @private
  1332. */
  1333. this.chain_ = [];
  1334. /**
  1335. * A buffer holding the partially computed hash result.
  1336. * @private
  1337. */
  1338. this.buf_ = [];
  1339. /**
  1340. * An array of 80 bytes, each a part of the message to be hashed. Referred to
  1341. * as the message schedule in the docs.
  1342. * @private
  1343. */
  1344. this.W_ = [];
  1345. /**
  1346. * Contains data needed to pad messages less than 64 bytes.
  1347. * @private
  1348. */
  1349. this.pad_ = [];
  1350. /**
  1351. * @private {number}
  1352. */
  1353. this.inbuf_ = 0;
  1354. /**
  1355. * @private {number}
  1356. */
  1357. this.total_ = 0;
  1358. this.blockSize = 512 / 8;
  1359. this.pad_[0] = 128;
  1360. for (let i = 1; i < this.blockSize; ++i) {
  1361. this.pad_[i] = 0;
  1362. }
  1363. this.reset();
  1364. }
  1365. reset() {
  1366. this.chain_[0] = 0x67452301;
  1367. this.chain_[1] = 0xefcdab89;
  1368. this.chain_[2] = 0x98badcfe;
  1369. this.chain_[3] = 0x10325476;
  1370. this.chain_[4] = 0xc3d2e1f0;
  1371. this.inbuf_ = 0;
  1372. this.total_ = 0;
  1373. }
  1374. /**
  1375. * Internal compress helper function.
  1376. * @param buf Block to compress.
  1377. * @param offset Offset of the block in the buffer.
  1378. * @private
  1379. */
  1380. compress_(buf, offset) {
  1381. if (!offset) {
  1382. offset = 0;
  1383. }
  1384. const W = this.W_;
  1385. // get 16 big endian words
  1386. if (typeof buf === 'string') {
  1387. for (let i = 0; i < 16; i++) {
  1388. // TODO(user): [bug 8140122] Recent versions of Safari for Mac OS and iOS
  1389. // have a bug that turns the post-increment ++ operator into pre-increment
  1390. // during JIT compilation. We have code that depends heavily on SHA-1 for
  1391. // correctness and which is affected by this bug, so I've removed all uses
  1392. // of post-increment ++ in which the result value is used. We can revert
  1393. // this change once the Safari bug
  1394. // (https://bugs.webkit.org/show_bug.cgi?id=109036) has been fixed and
  1395. // most clients have been updated.
  1396. W[i] =
  1397. (buf.charCodeAt(offset) << 24) |
  1398. (buf.charCodeAt(offset + 1) << 16) |
  1399. (buf.charCodeAt(offset + 2) << 8) |
  1400. buf.charCodeAt(offset + 3);
  1401. offset += 4;
  1402. }
  1403. }
  1404. else {
  1405. for (let i = 0; i < 16; i++) {
  1406. W[i] =
  1407. (buf[offset] << 24) |
  1408. (buf[offset + 1] << 16) |
  1409. (buf[offset + 2] << 8) |
  1410. buf[offset + 3];
  1411. offset += 4;
  1412. }
  1413. }
  1414. // expand to 80 words
  1415. for (let i = 16; i < 80; i++) {
  1416. const t = W[i - 3] ^ W[i - 8] ^ W[i - 14] ^ W[i - 16];
  1417. W[i] = ((t << 1) | (t >>> 31)) & 0xffffffff;
  1418. }
  1419. let a = this.chain_[0];
  1420. let b = this.chain_[1];
  1421. let c = this.chain_[2];
  1422. let d = this.chain_[3];
  1423. let e = this.chain_[4];
  1424. let f, k;
  1425. // TODO(user): Try to unroll this loop to speed up the computation.
  1426. for (let i = 0; i < 80; i++) {
  1427. if (i < 40) {
  1428. if (i < 20) {
  1429. f = d ^ (b & (c ^ d));
  1430. k = 0x5a827999;
  1431. }
  1432. else {
  1433. f = b ^ c ^ d;
  1434. k = 0x6ed9eba1;
  1435. }
  1436. }
  1437. else {
  1438. if (i < 60) {
  1439. f = (b & c) | (d & (b | c));
  1440. k = 0x8f1bbcdc;
  1441. }
  1442. else {
  1443. f = b ^ c ^ d;
  1444. k = 0xca62c1d6;
  1445. }
  1446. }
  1447. const t = (((a << 5) | (a >>> 27)) + f + e + k + W[i]) & 0xffffffff;
  1448. e = d;
  1449. d = c;
  1450. c = ((b << 30) | (b >>> 2)) & 0xffffffff;
  1451. b = a;
  1452. a = t;
  1453. }
  1454. this.chain_[0] = (this.chain_[0] + a) & 0xffffffff;
  1455. this.chain_[1] = (this.chain_[1] + b) & 0xffffffff;
  1456. this.chain_[2] = (this.chain_[2] + c) & 0xffffffff;
  1457. this.chain_[3] = (this.chain_[3] + d) & 0xffffffff;
  1458. this.chain_[4] = (this.chain_[4] + e) & 0xffffffff;
  1459. }
  1460. update(bytes, length) {
  1461. // TODO(johnlenz): tighten the function signature and remove this check
  1462. if (bytes == null) {
  1463. return;
  1464. }
  1465. if (length === undefined) {
  1466. length = bytes.length;
  1467. }
  1468. const lengthMinusBlock = length - this.blockSize;
  1469. let n = 0;
  1470. // Using local instead of member variables gives ~5% speedup on Firefox 16.
  1471. const buf = this.buf_;
  1472. let inbuf = this.inbuf_;
  1473. // The outer while loop should execute at most twice.
  1474. while (n < length) {
  1475. // When we have no data in the block to top up, we can directly process the
  1476. // input buffer (assuming it contains sufficient data). This gives ~25%
  1477. // speedup on Chrome 23 and ~15% speedup on Firefox 16, but requires that
  1478. // the data is provided in large chunks (or in multiples of 64 bytes).
  1479. if (inbuf === 0) {
  1480. while (n <= lengthMinusBlock) {
  1481. this.compress_(bytes, n);
  1482. n += this.blockSize;
  1483. }
  1484. }
  1485. if (typeof bytes === 'string') {
  1486. while (n < length) {
  1487. buf[inbuf] = bytes.charCodeAt(n);
  1488. ++inbuf;
  1489. ++n;
  1490. if (inbuf === this.blockSize) {
  1491. this.compress_(buf);
  1492. inbuf = 0;
  1493. // Jump to the outer loop so we use the full-block optimization.
  1494. break;
  1495. }
  1496. }
  1497. }
  1498. else {
  1499. while (n < length) {
  1500. buf[inbuf] = bytes[n];
  1501. ++inbuf;
  1502. ++n;
  1503. if (inbuf === this.blockSize) {
  1504. this.compress_(buf);
  1505. inbuf = 0;
  1506. // Jump to the outer loop so we use the full-block optimization.
  1507. break;
  1508. }
  1509. }
  1510. }
  1511. }
  1512. this.inbuf_ = inbuf;
  1513. this.total_ += length;
  1514. }
  1515. /** @override */
  1516. digest() {
  1517. const digest = [];
  1518. let totalBits = this.total_ * 8;
  1519. // Add pad 0x80 0x00*.
  1520. if (this.inbuf_ < 56) {
  1521. this.update(this.pad_, 56 - this.inbuf_);
  1522. }
  1523. else {
  1524. this.update(this.pad_, this.blockSize - (this.inbuf_ - 56));
  1525. }
  1526. // Add # bits.
  1527. for (let i = this.blockSize - 1; i >= 56; i--) {
  1528. this.buf_[i] = totalBits & 255;
  1529. totalBits /= 256; // Don't use bit-shifting here!
  1530. }
  1531. this.compress_(this.buf_);
  1532. let n = 0;
  1533. for (let i = 0; i < 5; i++) {
  1534. for (let j = 24; j >= 0; j -= 8) {
  1535. digest[n] = (this.chain_[i] >> j) & 255;
  1536. ++n;
  1537. }
  1538. }
  1539. return digest;
  1540. }
  1541. }
  1542. /**
  1543. * Helper to make a Subscribe function (just like Promise helps make a
  1544. * Thenable).
  1545. *
  1546. * @param executor Function which can make calls to a single Observer
  1547. * as a proxy.
  1548. * @param onNoObservers Callback when count of Observers goes to zero.
  1549. */
  1550. function createSubscribe(executor, onNoObservers) {
  1551. const proxy = new ObserverProxy(executor, onNoObservers);
  1552. return proxy.subscribe.bind(proxy);
  1553. }
  1554. /**
  1555. * Implement fan-out for any number of Observers attached via a subscribe
  1556. * function.
  1557. */
  1558. class ObserverProxy {
  1559. /**
  1560. * @param executor Function which can make calls to a single Observer
  1561. * as a proxy.
  1562. * @param onNoObservers Callback when count of Observers goes to zero.
  1563. */
  1564. constructor(executor, onNoObservers) {
  1565. this.observers = [];
  1566. this.unsubscribes = [];
  1567. this.observerCount = 0;
  1568. // Micro-task scheduling by calling task.then().
  1569. this.task = Promise.resolve();
  1570. this.finalized = false;
  1571. this.onNoObservers = onNoObservers;
  1572. // Call the executor asynchronously so subscribers that are called
  1573. // synchronously after the creation of the subscribe function
  1574. // can still receive the very first value generated in the executor.
  1575. this.task
  1576. .then(() => {
  1577. executor(this);
  1578. })
  1579. .catch(e => {
  1580. this.error(e);
  1581. });
  1582. }
  1583. next(value) {
  1584. this.forEachObserver((observer) => {
  1585. observer.next(value);
  1586. });
  1587. }
  1588. error(error) {
  1589. this.forEachObserver((observer) => {
  1590. observer.error(error);
  1591. });
  1592. this.close(error);
  1593. }
  1594. complete() {
  1595. this.forEachObserver((observer) => {
  1596. observer.complete();
  1597. });
  1598. this.close();
  1599. }
  1600. /**
  1601. * Subscribe function that can be used to add an Observer to the fan-out list.
  1602. *
  1603. * - We require that no event is sent to a subscriber sychronously to their
  1604. * call to subscribe().
  1605. */
  1606. subscribe(nextOrObserver, error, complete) {
  1607. let observer;
  1608. if (nextOrObserver === undefined &&
  1609. error === undefined &&
  1610. complete === undefined) {
  1611. throw new Error('Missing Observer.');
  1612. }
  1613. // Assemble an Observer object when passed as callback functions.
  1614. if (implementsAnyMethods(nextOrObserver, [
  1615. 'next',
  1616. 'error',
  1617. 'complete'
  1618. ])) {
  1619. observer = nextOrObserver;
  1620. }
  1621. else {
  1622. observer = {
  1623. next: nextOrObserver,
  1624. error,
  1625. complete
  1626. };
  1627. }
  1628. if (observer.next === undefined) {
  1629. observer.next = noop;
  1630. }
  1631. if (observer.error === undefined) {
  1632. observer.error = noop;
  1633. }
  1634. if (observer.complete === undefined) {
  1635. observer.complete = noop;
  1636. }
  1637. const unsub = this.unsubscribeOne.bind(this, this.observers.length);
  1638. // Attempt to subscribe to a terminated Observable - we
  1639. // just respond to the Observer with the final error or complete
  1640. // event.
  1641. if (this.finalized) {
  1642. // eslint-disable-next-line @typescript-eslint/no-floating-promises
  1643. this.task.then(() => {
  1644. try {
  1645. if (this.finalError) {
  1646. observer.error(this.finalError);
  1647. }
  1648. else {
  1649. observer.complete();
  1650. }
  1651. }
  1652. catch (e) {
  1653. // nothing
  1654. }
  1655. return;
  1656. });
  1657. }
  1658. this.observers.push(observer);
  1659. return unsub;
  1660. }
  1661. // Unsubscribe is synchronous - we guarantee that no events are sent to
  1662. // any unsubscribed Observer.
  1663. unsubscribeOne(i) {
  1664. if (this.observers === undefined || this.observers[i] === undefined) {
  1665. return;
  1666. }
  1667. delete this.observers[i];
  1668. this.observerCount -= 1;
  1669. if (this.observerCount === 0 && this.onNoObservers !== undefined) {
  1670. this.onNoObservers(this);
  1671. }
  1672. }
  1673. forEachObserver(fn) {
  1674. if (this.finalized) {
  1675. // Already closed by previous event....just eat the additional values.
  1676. return;
  1677. }
  1678. // Since sendOne calls asynchronously - there is no chance that
  1679. // this.observers will become undefined.
  1680. for (let i = 0; i < this.observers.length; i++) {
  1681. this.sendOne(i, fn);
  1682. }
  1683. }
  1684. // Call the Observer via one of it's callback function. We are careful to
  1685. // confirm that the observe has not been unsubscribed since this asynchronous
  1686. // function had been queued.
  1687. sendOne(i, fn) {
  1688. // Execute the callback asynchronously
  1689. // eslint-disable-next-line @typescript-eslint/no-floating-promises
  1690. this.task.then(() => {
  1691. if (this.observers !== undefined && this.observers[i] !== undefined) {
  1692. try {
  1693. fn(this.observers[i]);
  1694. }
  1695. catch (e) {
  1696. // Ignore exceptions raised in Observers or missing methods of an
  1697. // Observer.
  1698. // Log error to console. b/31404806
  1699. if (typeof console !== 'undefined' && console.error) {
  1700. console.error(e);
  1701. }
  1702. }
  1703. }
  1704. });
  1705. }
  1706. close(err) {
  1707. if (this.finalized) {
  1708. return;
  1709. }
  1710. this.finalized = true;
  1711. if (err !== undefined) {
  1712. this.finalError = err;
  1713. }
  1714. // Proxy is no longer needed - garbage collect references
  1715. // eslint-disable-next-line @typescript-eslint/no-floating-promises
  1716. this.task.then(() => {
  1717. this.observers = undefined;
  1718. this.onNoObservers = undefined;
  1719. });
  1720. }
  1721. }
  1722. /** Turn synchronous function into one called asynchronously. */
  1723. // eslint-disable-next-line @typescript-eslint/ban-types
  1724. function async(fn, onError) {
  1725. return (...args) => {
  1726. Promise.resolve(true)
  1727. .then(() => {
  1728. fn(...args);
  1729. })
  1730. .catch((error) => {
  1731. if (onError) {
  1732. onError(error);
  1733. }
  1734. });
  1735. };
  1736. }
  1737. /**
  1738. * Return true if the object passed in implements any of the named methods.
  1739. */
  1740. function implementsAnyMethods(obj, methods) {
  1741. if (typeof obj !== 'object' || obj === null) {
  1742. return false;
  1743. }
  1744. for (const method of methods) {
  1745. if (method in obj && typeof obj[method] === 'function') {
  1746. return true;
  1747. }
  1748. }
  1749. return false;
  1750. }
  1751. function noop() {
  1752. // do nothing
  1753. }
  1754. /**
  1755. * @license
  1756. * Copyright 2017 Google LLC
  1757. *
  1758. * Licensed under the Apache License, Version 2.0 (the "License");
  1759. * you may not use this file except in compliance with the License.
  1760. * You may obtain a copy of the License at
  1761. *
  1762. * http://www.apache.org/licenses/LICENSE-2.0
  1763. *
  1764. * Unless required by applicable law or agreed to in writing, software
  1765. * distributed under the License is distributed on an "AS IS" BASIS,
  1766. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  1767. * See the License for the specific language governing permissions and
  1768. * limitations under the License.
  1769. */
  1770. /**
  1771. * Check to make sure the appropriate number of arguments are provided for a public function.
  1772. * Throws an error if it fails.
  1773. *
  1774. * @param fnName The function name
  1775. * @param minCount The minimum number of arguments to allow for the function call
  1776. * @param maxCount The maximum number of argument to allow for the function call
  1777. * @param argCount The actual number of arguments provided.
  1778. */
  1779. const validateArgCount = function (fnName, minCount, maxCount, argCount) {
  1780. let argError;
  1781. if (argCount < minCount) {
  1782. argError = 'at least ' + minCount;
  1783. }
  1784. else if (argCount > maxCount) {
  1785. argError = maxCount === 0 ? 'none' : 'no more than ' + maxCount;
  1786. }
  1787. if (argError) {
  1788. const error = fnName +
  1789. ' failed: Was called with ' +
  1790. argCount +
  1791. (argCount === 1 ? ' argument.' : ' arguments.') +
  1792. ' Expects ' +
  1793. argError +
  1794. '.';
  1795. throw new Error(error);
  1796. }
  1797. };
  1798. /**
  1799. * Generates a string to prefix an error message about failed argument validation
  1800. *
  1801. * @param fnName The function name
  1802. * @param argName The name of the argument
  1803. * @return The prefix to add to the error thrown for validation.
  1804. */
  1805. function errorPrefix(fnName, argName) {
  1806. return `${fnName} failed: ${argName} argument `;
  1807. }
  1808. /**
  1809. * @param fnName
  1810. * @param argumentNumber
  1811. * @param namespace
  1812. * @param optional
  1813. */
  1814. function validateNamespace(fnName, namespace, optional) {
  1815. if (optional && !namespace) {
  1816. return;
  1817. }
  1818. if (typeof namespace !== 'string') {
  1819. //TODO: I should do more validation here. We only allow certain chars in namespaces.
  1820. throw new Error(errorPrefix(fnName, 'namespace') + 'must be a valid firebase namespace.');
  1821. }
  1822. }
  1823. function validateCallback(fnName, argumentName,
  1824. // eslint-disable-next-line @typescript-eslint/ban-types
  1825. callback, optional) {
  1826. if (optional && !callback) {
  1827. return;
  1828. }
  1829. if (typeof callback !== 'function') {
  1830. throw new Error(errorPrefix(fnName, argumentName) + 'must be a valid function.');
  1831. }
  1832. }
  1833. function validateContextObject(fnName, argumentName, context, optional) {
  1834. if (optional && !context) {
  1835. return;
  1836. }
  1837. if (typeof context !== 'object' || context === null) {
  1838. throw new Error(errorPrefix(fnName, argumentName) + 'must be a valid context object.');
  1839. }
  1840. }
  1841. /**
  1842. * @license
  1843. * Copyright 2017 Google LLC
  1844. *
  1845. * Licensed under the Apache License, Version 2.0 (the "License");
  1846. * you may not use this file except in compliance with the License.
  1847. * You may obtain a copy of the License at
  1848. *
  1849. * http://www.apache.org/licenses/LICENSE-2.0
  1850. *
  1851. * Unless required by applicable law or agreed to in writing, software
  1852. * distributed under the License is distributed on an "AS IS" BASIS,
  1853. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  1854. * See the License for the specific language governing permissions and
  1855. * limitations under the License.
  1856. */
  1857. // Code originally came from goog.crypt.stringToUtf8ByteArray, but for some reason they
  1858. // automatically replaced '\r\n' with '\n', and they didn't handle surrogate pairs,
  1859. // so it's been modified.
  1860. // Note that not all Unicode characters appear as single characters in JavaScript strings.
  1861. // fromCharCode returns the UTF-16 encoding of a character - so some Unicode characters
  1862. // use 2 characters in Javascript. All 4-byte UTF-8 characters begin with a first
  1863. // character in the range 0xD800 - 0xDBFF (the first character of a so-called surrogate
  1864. // pair).
  1865. // See http://www.ecma-international.org/ecma-262/5.1/#sec-15.1.3
  1866. /**
  1867. * @param {string} str
  1868. * @return {Array}
  1869. */
  1870. const stringToByteArray = function (str) {
  1871. const out = [];
  1872. let p = 0;
  1873. for (let i = 0; i < str.length; i++) {
  1874. let c = str.charCodeAt(i);
  1875. // Is this the lead surrogate in a surrogate pair?
  1876. if (c >= 0xd800 && c <= 0xdbff) {
  1877. const high = c - 0xd800; // the high 10 bits.
  1878. i++;
  1879. assert(i < str.length, 'Surrogate pair missing trail surrogate.');
  1880. const low = str.charCodeAt(i) - 0xdc00; // the low 10 bits.
  1881. c = 0x10000 + (high << 10) + low;
  1882. }
  1883. if (c < 128) {
  1884. out[p++] = c;
  1885. }
  1886. else if (c < 2048) {
  1887. out[p++] = (c >> 6) | 192;
  1888. out[p++] = (c & 63) | 128;
  1889. }
  1890. else if (c < 65536) {
  1891. out[p++] = (c >> 12) | 224;
  1892. out[p++] = ((c >> 6) & 63) | 128;
  1893. out[p++] = (c & 63) | 128;
  1894. }
  1895. else {
  1896. out[p++] = (c >> 18) | 240;
  1897. out[p++] = ((c >> 12) & 63) | 128;
  1898. out[p++] = ((c >> 6) & 63) | 128;
  1899. out[p++] = (c & 63) | 128;
  1900. }
  1901. }
  1902. return out;
  1903. };
  1904. /**
  1905. * Calculate length without actually converting; useful for doing cheaper validation.
  1906. * @param {string} str
  1907. * @return {number}
  1908. */
  1909. const stringLength = function (str) {
  1910. let p = 0;
  1911. for (let i = 0; i < str.length; i++) {
  1912. const c = str.charCodeAt(i);
  1913. if (c < 128) {
  1914. p++;
  1915. }
  1916. else if (c < 2048) {
  1917. p += 2;
  1918. }
  1919. else if (c >= 0xd800 && c <= 0xdbff) {
  1920. // Lead surrogate of a surrogate pair. The pair together will take 4 bytes to represent.
  1921. p += 4;
  1922. i++; // skip trail surrogate.
  1923. }
  1924. else {
  1925. p += 3;
  1926. }
  1927. }
  1928. return p;
  1929. };
  1930. /**
  1931. * @license
  1932. * Copyright 2022 Google LLC
  1933. *
  1934. * Licensed under the Apache License, Version 2.0 (the "License");
  1935. * you may not use this file except in compliance with the License.
  1936. * You may obtain a copy of the License at
  1937. *
  1938. * http://www.apache.org/licenses/LICENSE-2.0
  1939. *
  1940. * Unless required by applicable law or agreed to in writing, software
  1941. * distributed under the License is distributed on an "AS IS" BASIS,
  1942. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  1943. * See the License for the specific language governing permissions and
  1944. * limitations under the License.
  1945. */
  1946. /**
  1947. * Copied from https://stackoverflow.com/a/2117523
  1948. * Generates a new uuid.
  1949. * @public
  1950. */
  1951. const uuidv4 = function () {
  1952. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, c => {
  1953. const r = (Math.random() * 16) | 0, v = c === 'x' ? r : (r & 0x3) | 0x8;
  1954. return v.toString(16);
  1955. });
  1956. };
  1957. /**
  1958. * @license
  1959. * Copyright 2019 Google LLC
  1960. *
  1961. * Licensed under the Apache License, Version 2.0 (the "License");
  1962. * you may not use this file except in compliance with the License.
  1963. * You may obtain a copy of the License at
  1964. *
  1965. * http://www.apache.org/licenses/LICENSE-2.0
  1966. *
  1967. * Unless required by applicable law or agreed to in writing, software
  1968. * distributed under the License is distributed on an "AS IS" BASIS,
  1969. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  1970. * See the License for the specific language governing permissions and
  1971. * limitations under the License.
  1972. */
  1973. /**
  1974. * The amount of milliseconds to exponentially increase.
  1975. */
  1976. const DEFAULT_INTERVAL_MILLIS = 1000;
  1977. /**
  1978. * The factor to backoff by.
  1979. * Should be a number greater than 1.
  1980. */
  1981. const DEFAULT_BACKOFF_FACTOR = 2;
  1982. /**
  1983. * The maximum milliseconds to increase to.
  1984. *
  1985. * <p>Visible for testing
  1986. */
  1987. const MAX_VALUE_MILLIS = 4 * 60 * 60 * 1000; // Four hours, like iOS and Android.
  1988. /**
  1989. * The percentage of backoff time to randomize by.
  1990. * See
  1991. * http://go/safe-client-behavior#step-1-determine-the-appropriate-retry-interval-to-handle-spike-traffic
  1992. * for context.
  1993. *
  1994. * <p>Visible for testing
  1995. */
  1996. const RANDOM_FACTOR = 0.5;
  1997. /**
  1998. * Based on the backoff method from
  1999. * https://github.com/google/closure-library/blob/master/closure/goog/math/exponentialbackoff.js.
  2000. * Extracted here so we don't need to pass metadata and a stateful ExponentialBackoff object around.
  2001. */
  2002. function calculateBackoffMillis(backoffCount, intervalMillis = DEFAULT_INTERVAL_MILLIS, backoffFactor = DEFAULT_BACKOFF_FACTOR) {
  2003. // Calculates an exponentially increasing value.
  2004. // Deviation: calculates value from count and a constant interval, so we only need to save value
  2005. // and count to restore state.
  2006. const currBaseValue = intervalMillis * Math.pow(backoffFactor, backoffCount);
  2007. // A random "fuzz" to avoid waves of retries.
  2008. // Deviation: randomFactor is required.
  2009. const randomWait = Math.round(
  2010. // A fraction of the backoff value to add/subtract.
  2011. // Deviation: changes multiplication order to improve readability.
  2012. RANDOM_FACTOR *
  2013. currBaseValue *
  2014. // A random float (rounded to int by Math.round above) in the range [-1, 1]. Determines
  2015. // if we add or subtract.
  2016. (Math.random() - 0.5) *
  2017. 2);
  2018. // Limits backoff to max to avoid effectively permanent backoff.
  2019. return Math.min(MAX_VALUE_MILLIS, currBaseValue + randomWait);
  2020. }
  2021. /**
  2022. * @license
  2023. * Copyright 2020 Google LLC
  2024. *
  2025. * Licensed under the Apache License, Version 2.0 (the "License");
  2026. * you may not use this file except in compliance with the License.
  2027. * You may obtain a copy of the License at
  2028. *
  2029. * http://www.apache.org/licenses/LICENSE-2.0
  2030. *
  2031. * Unless required by applicable law or agreed to in writing, software
  2032. * distributed under the License is distributed on an "AS IS" BASIS,
  2033. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  2034. * See the License for the specific language governing permissions and
  2035. * limitations under the License.
  2036. */
  2037. /**
  2038. * Provide English ordinal letters after a number
  2039. */
  2040. function ordinal(i) {
  2041. if (!Number.isFinite(i)) {
  2042. return `${i}`;
  2043. }
  2044. return i + indicator(i);
  2045. }
  2046. function indicator(i) {
  2047. i = Math.abs(i);
  2048. const cent = i % 100;
  2049. if (cent >= 10 && cent <= 20) {
  2050. return 'th';
  2051. }
  2052. const dec = i % 10;
  2053. if (dec === 1) {
  2054. return 'st';
  2055. }
  2056. if (dec === 2) {
  2057. return 'nd';
  2058. }
  2059. if (dec === 3) {
  2060. return 'rd';
  2061. }
  2062. return 'th';
  2063. }
  2064. /**
  2065. * @license
  2066. * Copyright 2021 Google LLC
  2067. *
  2068. * Licensed under the Apache License, Version 2.0 (the "License");
  2069. * you may not use this file except in compliance with the License.
  2070. * You may obtain a copy of the License at
  2071. *
  2072. * http://www.apache.org/licenses/LICENSE-2.0
  2073. *
  2074. * Unless required by applicable law or agreed to in writing, software
  2075. * distributed under the License is distributed on an "AS IS" BASIS,
  2076. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  2077. * See the License for the specific language governing permissions and
  2078. * limitations under the License.
  2079. */
  2080. function getModularInstance(service) {
  2081. if (service && service._delegate) {
  2082. return service._delegate;
  2083. }
  2084. else {
  2085. return service;
  2086. }
  2087. }
  2088. /**
  2089. * @license
  2090. * Copyright 2017 Google LLC
  2091. *
  2092. * Licensed under the Apache License, Version 2.0 (the "License");
  2093. * you may not use this file except in compliance with the License.
  2094. * You may obtain a copy of the License at
  2095. *
  2096. * http://www.apache.org/licenses/LICENSE-2.0
  2097. *
  2098. * Unless required by applicable law or agreed to in writing, software
  2099. * distributed under the License is distributed on an "AS IS" BASIS,
  2100. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  2101. * See the License for the specific language governing permissions and
  2102. * limitations under the License.
  2103. */
  2104. // Overriding the constant (we should be the only ones doing this)
  2105. CONSTANTS.NODE_CLIENT = true;
  2106. export { CONSTANTS, DecodeBase64StringError, Deferred, ErrorFactory, FirebaseError, MAX_VALUE_MILLIS, RANDOM_FACTOR, Sha1, areCookiesEnabled, assert, assertionError, async, base64, base64Decode, base64Encode, base64urlEncodeWithoutPadding, calculateBackoffMillis, contains, createMockUserToken, createSubscribe, decode, deepCopy, deepEqual, deepExtend, errorPrefix, extractQuerystring, getDefaultAppConfig, getDefaultEmulatorHost, getDefaultEmulatorHostnameAndPort, getDefaults, getExperimentalSetting, getGlobal, getModularInstance, getUA, isAdmin, isBrowser, isBrowserExtension, isElectron, isEmpty, isIE, isIndexedDBAvailable, isMobileCordova, isNode, isNodeSdk, isReactNative, isSafari, isUWP, isValidFormat, isValidTimestamp, issuedAtTime, jsonEval, map, ordinal, promiseWithTimeout, querystring, querystringDecode, safeGet, stringLength, stringToByteArray, stringify, uuidv4, validateArgCount, validateCallback, validateContextObject, validateIndexedDBOpenable, validateNamespace };
  2107. //# sourceMappingURL=index.node.esm.js.map