@firebase/util 1.10.1 → 1.10.2-canary.ffbf5a60a

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