index.cjs.js 73 KB

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