@firebase/rules-unit-testing 2.0.2 → 2.0.3-canary.d3336a9cd

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.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,11 @@
1
1
  # @firebase/rules-unit-testing
2
2
 
3
+ ## 2.0.3
4
+
5
+ ### Patch Changes
6
+
7
+ - [`b091b0228`](https://github.com/firebase/firebase-js-sdk/commit/b091b02288fa0d1439dfe945a33325a0495f568d) [#6360](https://github.com/firebase/firebase-js-sdk/pull/6360) (fixes [#6080](https://github.com/firebase/firebase-js-sdk/issues/6080)) - Add Node ESM build to rules-unit-testing.
8
+
3
9
  ## 2.0.2
4
10
 
5
11
  ### Patch Changes
@@ -0,0 +1,19 @@
1
+ /**
2
+ * @license
3
+ * Copyright 2021 Google LLC
4
+ *
5
+ * Licensed under the Apache License, Version 2.0 (the "License");
6
+ * you may not use this file except in compliance with the License.
7
+ * You may obtain a copy of the License at
8
+ *
9
+ * http://www.apache.org/licenses/LICENSE-2.0
10
+ *
11
+ * Unless required by applicable law or agreed to in writing, software
12
+ * distributed under the License is distributed on an "AS IS" BASIS,
13
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ * See the License for the specific language governing permissions and
15
+ * limitations under the License.
16
+ */
17
+ export * from './src/public_types';
18
+ export * from './src/initialize';
19
+ export * from './src/util';
@@ -0,0 +1,607 @@
1
+ import 'firebase/compat/database';
2
+ import 'firebase/compat/firestore';
3
+ import 'firebase/compat/storage';
4
+ import fetch from 'node-fetch';
5
+ import firebase from 'firebase/compat/app';
6
+
7
+ /**
8
+ * @license
9
+ * Copyright 2021 Google LLC
10
+ *
11
+ * Licensed under the Apache License, Version 2.0 (the "License");
12
+ * you may not use this file except in compliance with the License.
13
+ * You may obtain a copy of the License at
14
+ *
15
+ * http://www.apache.org/licenses/LICENSE-2.0
16
+ *
17
+ * Unless required by applicable law or agreed to in writing, software
18
+ * distributed under the License is distributed on an "AS IS" BASIS,
19
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
20
+ * See the License for the specific language governing permissions and
21
+ * limitations under the License.
22
+ */
23
+ /**
24
+ * Return a connectable hostname, replacing wildcard 0.0.0.0 or :: with loopback
25
+ * addresses 127.0.0.1 / ::1 correspondingly. See below for why this is needed:
26
+ * https://github.com/firebase/firebase-tools-ui/issues/286
27
+ *
28
+ * This assumes emulators are running on the same device as fallbackHost (e.g.
29
+ * hub), which should hold if both are started from the same CLI command.
30
+ * @private
31
+ */
32
+ function fixHostname(host, fallbackHost) {
33
+ host = host.replace('[', '').replace(']', ''); // Remove IPv6 brackets
34
+ if (host === '0.0.0.0') {
35
+ host = fallbackHost || '127.0.0.1';
36
+ }
37
+ else if (host === '::') {
38
+ host = fallbackHost || '::1';
39
+ }
40
+ return host;
41
+ }
42
+ /**
43
+ * Create a URL with host, port, and path. Handles IPv6 bracketing correctly.
44
+ * @private
45
+ */
46
+ function makeUrl(hostAndPort, path) {
47
+ if (typeof hostAndPort === 'object') {
48
+ const { host, port } = hostAndPort;
49
+ if (host.includes(':')) {
50
+ hostAndPort = `[${host}]:${port}`;
51
+ }
52
+ else {
53
+ hostAndPort = `${host}:${port}`;
54
+ }
55
+ }
56
+ const url = new URL(`http://${hostAndPort}/`);
57
+ url.pathname = path;
58
+ return url;
59
+ }
60
+
61
+ /**
62
+ * @license
63
+ * Copyright 2021 Google LLC
64
+ *
65
+ * Licensed under the Apache License, Version 2.0 (the "License");
66
+ * you may not use this file except in compliance with the License.
67
+ * You may obtain a copy of the License at
68
+ *
69
+ * http://www.apache.org/licenses/LICENSE-2.0
70
+ *
71
+ * Unless required by applicable law or agreed to in writing, software
72
+ * distributed under the License is distributed on an "AS IS" BASIS,
73
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
74
+ * See the License for the specific language governing permissions and
75
+ * limitations under the License.
76
+ */
77
+ /**
78
+ * Use the Firebase Emulator hub to discover other running emulators.
79
+ *
80
+ * @param hub the host and port where the Emulator Hub is running
81
+ * @private
82
+ */
83
+ async function discoverEmulators(hub, fetch$1 = fetch) {
84
+ const res = await fetch$1(makeUrl(hub, '/emulators'));
85
+ if (!res.ok) {
86
+ throw new Error(`HTTP Error ${res.status} when attempting to reach Emulator Hub at ${res.url}, are you sure it is running?`);
87
+ }
88
+ const emulators = {};
89
+ const data = await res.json();
90
+ if (data.database) {
91
+ emulators.database = {
92
+ host: data.database.host,
93
+ port: data.database.port
94
+ };
95
+ }
96
+ if (data.firestore) {
97
+ emulators.firestore = {
98
+ host: data.firestore.host,
99
+ port: data.firestore.port
100
+ };
101
+ }
102
+ if (data.storage) {
103
+ emulators.storage = {
104
+ host: data.storage.host,
105
+ port: data.storage.port
106
+ };
107
+ }
108
+ if (data.hub) {
109
+ emulators.hub = {
110
+ host: data.hub.host,
111
+ port: data.hub.port
112
+ };
113
+ }
114
+ return emulators;
115
+ }
116
+ /**
117
+ * @private
118
+ */
119
+ function getEmulatorHostAndPort(emulator, conf, discovered) {
120
+ var _a, _b;
121
+ if (conf && ('host' in conf || 'port' in conf)) {
122
+ const { host, port } = conf;
123
+ if (host || port) {
124
+ if (!host || !port) {
125
+ throw new Error(`Invalid configuration ${emulator}.host=${host} and ${emulator}.port=${port}. ` +
126
+ 'If either parameter is supplied, both must be defined.');
127
+ }
128
+ if (discovered && !discovered[emulator]) {
129
+ console.warn(`Warning: config for the ${emulator} emulator is specified, but the Emulator hub ` +
130
+ 'reports it as not running. This may lead to errors such as connection refused.');
131
+ }
132
+ return {
133
+ host: fixHostname(conf.host, (_a = discovered === null || discovered === void 0 ? void 0 : discovered.hub) === null || _a === void 0 ? void 0 : _a.host),
134
+ port: conf.port
135
+ };
136
+ }
137
+ }
138
+ const envVar = EMULATOR_HOST_ENV_VARS[emulator];
139
+ const fallback = (discovered === null || discovered === void 0 ? void 0 : discovered[emulator]) || emulatorFromEnvVar(envVar);
140
+ if (fallback) {
141
+ if (discovered && !discovered[emulator]) {
142
+ console.warn(`Warning: the environment variable ${envVar} is set, but the Emulator hub reports the ` +
143
+ `${emulator} emulator as not running. This may lead to errors such as connection refused.`);
144
+ }
145
+ return {
146
+ host: fixHostname(fallback.host, (_b = discovered === null || discovered === void 0 ? void 0 : discovered.hub) === null || _b === void 0 ? void 0 : _b.host),
147
+ port: fallback.port
148
+ };
149
+ }
150
+ }
151
+ // Visible for testing.
152
+ const EMULATOR_HOST_ENV_VARS = {
153
+ 'database': 'FIREBASE_DATABASE_EMULATOR_HOST',
154
+ 'firestore': 'FIRESTORE_EMULATOR_HOST',
155
+ 'hub': 'FIREBASE_EMULATOR_HUB',
156
+ 'storage': 'FIREBASE_STORAGE_EMULATOR_HOST'
157
+ };
158
+ function emulatorFromEnvVar(envVar) {
159
+ const hostAndPort = process.env[envVar];
160
+ if (!hostAndPort) {
161
+ return undefined;
162
+ }
163
+ let parsed;
164
+ try {
165
+ parsed = new URL(`http://${hostAndPort}`);
166
+ }
167
+ catch (_a) {
168
+ throw new Error(`Invalid format in environment variable ${envVar}=${hostAndPort} (expected host:port)`);
169
+ }
170
+ let host = parsed.hostname;
171
+ const port = Number(parsed.port || '80');
172
+ if (!Number.isInteger(port)) {
173
+ throw new Error(`Invalid port in environment variable ${envVar}=${hostAndPort}`);
174
+ }
175
+ return { host, port };
176
+ }
177
+
178
+ /**
179
+ * @license
180
+ * Copyright 2021 Google LLC
181
+ *
182
+ * Licensed under the Apache License, Version 2.0 (the "License");
183
+ * you may not use this file except in compliance with the License.
184
+ * You may obtain a copy of the License at
185
+ *
186
+ * http://www.apache.org/licenses/LICENSE-2.0
187
+ *
188
+ * Unless required by applicable law or agreed to in writing, software
189
+ * distributed under the License is distributed on an "AS IS" BASIS,
190
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
191
+ * See the License for the specific language governing permissions and
192
+ * limitations under the License.
193
+ */
194
+ /**
195
+ * An implementation of {@code RulesTestEnvironment}. This is private to hide the constructor,
196
+ * which should never be directly called by the developer.
197
+ * @private
198
+ */
199
+ class RulesTestEnvironmentImpl {
200
+ constructor(projectId, emulators) {
201
+ this.projectId = projectId;
202
+ this.emulators = emulators;
203
+ this.contexts = new Set();
204
+ this.destroyed = false;
205
+ }
206
+ authenticatedContext(user_id, tokenOptions) {
207
+ this.checkNotDestroyed();
208
+ return this.createContext(Object.assign(Object.assign({}, tokenOptions), { sub: user_id, user_id: user_id }));
209
+ }
210
+ unauthenticatedContext() {
211
+ this.checkNotDestroyed();
212
+ return this.createContext(/* authToken = */ undefined);
213
+ }
214
+ async withSecurityRulesDisabled(callback) {
215
+ this.checkNotDestroyed();
216
+ // The "owner" token is recognized by the emulators as a special value that bypasses Security
217
+ // Rules. This should only ever be used in withSecurityRulesDisabled.
218
+ // If you're reading this and thinking about doing this in your own app / tests / scripts, think
219
+ // twice. Instead, just use withSecurityRulesDisabled for unit testing OR connect your Firebase
220
+ // Admin SDKs to the emulators for integration testing via environment variables.
221
+ // See: https://firebase.google.com/docs/emulator-suite/connect_firestore#admin_sdks
222
+ const context = this.createContext('owner');
223
+ try {
224
+ await callback(context);
225
+ }
226
+ finally {
227
+ // We eagarly clean up this context to actively prevent misuse outside of the callback, e.g.
228
+ // storing the context in a variable.
229
+ context.cleanup();
230
+ this.contexts.delete(context);
231
+ }
232
+ }
233
+ createContext(authToken) {
234
+ const context = new RulesTestContextImpl(this.projectId, this.emulators, authToken);
235
+ this.contexts.add(context);
236
+ return context;
237
+ }
238
+ clearDatabase() {
239
+ this.checkNotDestroyed();
240
+ return this.withSecurityRulesDisabled(context => {
241
+ return context.database().ref('/').set(null);
242
+ });
243
+ }
244
+ async clearFirestore() {
245
+ this.checkNotDestroyed();
246
+ assertEmulatorRunning(this.emulators, 'firestore');
247
+ const resp = await fetch(makeUrl(this.emulators.firestore, `/emulator/v1/projects/${this.projectId}/databases/(default)/documents`), {
248
+ method: 'DELETE'
249
+ });
250
+ if (!resp.ok) {
251
+ throw new Error(await resp.text());
252
+ }
253
+ }
254
+ clearStorage() {
255
+ this.checkNotDestroyed();
256
+ return this.withSecurityRulesDisabled(async (context) => {
257
+ const { items } = await context.storage().ref().listAll();
258
+ await Promise.all(items.map(item => {
259
+ return item.delete();
260
+ }));
261
+ });
262
+ }
263
+ async cleanup() {
264
+ this.destroyed = true;
265
+ this.contexts.forEach(context => {
266
+ context.envDestroyed = true;
267
+ context.cleanup();
268
+ });
269
+ this.contexts.clear();
270
+ }
271
+ checkNotDestroyed() {
272
+ if (this.destroyed) {
273
+ throw new Error('This RulesTestEnvironment has already been cleaned up. ' +
274
+ '(This may indicate a leak or missing `await` in your test cases. If you do intend to ' +
275
+ 'perform more tests, please call cleanup() later or create another RulesTestEnvironment.)');
276
+ }
277
+ }
278
+ }
279
+ /**
280
+ * An implementation of {@code RulesTestContext}. This is private to hide the constructor,
281
+ * which should never be directly called by the developer.
282
+ * @private
283
+ */
284
+ class RulesTestContextImpl {
285
+ constructor(projectId, emulators, authToken) {
286
+ this.projectId = projectId;
287
+ this.emulators = emulators;
288
+ this.authToken = authToken;
289
+ this.destroyed = false;
290
+ this.envDestroyed = false;
291
+ }
292
+ cleanup() {
293
+ var _a;
294
+ this.destroyed = true;
295
+ (_a = this.app) === null || _a === void 0 ? void 0 : _a.delete();
296
+ this.app = undefined;
297
+ }
298
+ firestore(settings) {
299
+ assertEmulatorRunning(this.emulators, 'firestore');
300
+ const firestore = this.getApp().firestore();
301
+ if (settings) {
302
+ firestore.settings(settings);
303
+ }
304
+ firestore.useEmulator(this.emulators.firestore.host, this.emulators.firestore.port, { mockUserToken: this.authToken });
305
+ return firestore;
306
+ }
307
+ database(databaseURL) {
308
+ assertEmulatorRunning(this.emulators, 'database');
309
+ if (!databaseURL) {
310
+ const url = makeUrl(this.emulators.database, '');
311
+ // Make sure to set the namespace equal to projectId -- otherwise the RTDB SDK will by default
312
+ // use `${projectId}-default-rtdb`, which is treated as a different DB by the RTDB emulator
313
+ // (and thus WON'T apply any rules set for the `projectId` DB during initialization).
314
+ url.searchParams.append('ns', this.projectId);
315
+ databaseURL = url.toString();
316
+ }
317
+ const database = this.getApp().database(databaseURL);
318
+ database.useEmulator(this.emulators.database.host, this.emulators.database.port, { mockUserToken: this.authToken });
319
+ return database;
320
+ }
321
+ storage(bucketUrl = `gs://${this.projectId}`) {
322
+ assertEmulatorRunning(this.emulators, 'storage');
323
+ const storage = this.getApp().storage(bucketUrl);
324
+ storage.useEmulator(this.emulators.storage.host, this.emulators.storage.port, { mockUserToken: this.authToken });
325
+ return storage;
326
+ }
327
+ getApp() {
328
+ if (this.envDestroyed) {
329
+ throw new Error('This RulesTestContext is no longer valid because its RulesTestEnvironment has been ' +
330
+ 'cleaned up. (This may indicate a leak or missing `await` in your test cases.)');
331
+ }
332
+ if (this.destroyed) {
333
+ throw new Error('This RulesTestContext is no longer valid. When using withSecurityRulesDisabled, ' +
334
+ 'make sure to perform all operations on the context within the callback function and ' +
335
+ 'return a Promise that resolves when the operations are done.');
336
+ }
337
+ if (!this.app) {
338
+ this.app = firebase.initializeApp({ projectId: this.projectId }, `_Firebase_RulesUnitTesting_${Date.now()}_${Math.random()}`);
339
+ }
340
+ return this.app;
341
+ }
342
+ }
343
+ function assertEmulatorRunning(emulators, emulator) {
344
+ if (!emulators[emulator]) {
345
+ if (emulators.hub) {
346
+ throw new Error(`The ${emulator} emulator is not running (according to Emulator hub). To force ` +
347
+ 'connecting anyway, please specify its host and port in initializeTestEnvironment({...}).');
348
+ }
349
+ else {
350
+ throw new Error(`The host and port of the ${emulator} emulator must be specified. (You may wrap the test ` +
351
+ "script with `firebase emulators:exec './your-test-script'` to enable automatic " +
352
+ `discovery, or specify manually via initializeTestEnvironment({${emulator}: {host, port}}).`);
353
+ }
354
+ }
355
+ }
356
+
357
+ /**
358
+ * @license
359
+ * Copyright 2021 Google LLC
360
+ *
361
+ * Licensed under the Apache License, Version 2.0 (the "License");
362
+ * you may not use this file except in compliance with the License.
363
+ * You may obtain a copy of the License at
364
+ *
365
+ * http://www.apache.org/licenses/LICENSE-2.0
366
+ *
367
+ * Unless required by applicable law or agreed to in writing, software
368
+ * distributed under the License is distributed on an "AS IS" BASIS,
369
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
370
+ * See the License for the specific language governing permissions and
371
+ * limitations under the License.
372
+ */
373
+ /**
374
+ * @private
375
+ */
376
+ async function loadDatabaseRules(hostAndPort, databaseName, rules) {
377
+ const url = makeUrl(hostAndPort, '/.settings/rules.json');
378
+ url.searchParams.append('ns', databaseName);
379
+ const resp = await fetch(url, {
380
+ method: 'PUT',
381
+ headers: { Authorization: 'Bearer owner' },
382
+ body: rules
383
+ });
384
+ if (!resp.ok) {
385
+ throw new Error(await resp.text());
386
+ }
387
+ }
388
+ /**
389
+ * @private
390
+ */
391
+ async function loadFirestoreRules(hostAndPort, projectId, rules) {
392
+ const resp = await fetch(makeUrl(hostAndPort, `/emulator/v1/projects/${projectId}:securityRules`), {
393
+ method: 'PUT',
394
+ body: JSON.stringify({
395
+ rules: {
396
+ files: [{ content: rules }]
397
+ }
398
+ })
399
+ });
400
+ if (!resp.ok) {
401
+ throw new Error(await resp.text());
402
+ }
403
+ }
404
+ /**
405
+ * @private
406
+ */
407
+ async function loadStorageRules(hostAndPort, rules) {
408
+ const resp = await fetch(makeUrl(hostAndPort, '/internal/setRules'), {
409
+ method: 'PUT',
410
+ headers: {
411
+ 'Content-Type': 'application/json'
412
+ },
413
+ body: JSON.stringify({
414
+ rules: {
415
+ files: [{ name: 'storage.rules', content: rules }]
416
+ }
417
+ })
418
+ });
419
+ if (!resp.ok) {
420
+ throw new Error(await resp.text());
421
+ }
422
+ }
423
+
424
+ /**
425
+ * @license
426
+ * Copyright 2021 Google LLC
427
+ *
428
+ * Licensed under the Apache License, Version 2.0 (the "License");
429
+ * you may not use this file except in compliance with the License.
430
+ * You may obtain a copy of the License at
431
+ *
432
+ * http://www.apache.org/licenses/LICENSE-2.0
433
+ *
434
+ * Unless required by applicable law or agreed to in writing, software
435
+ * distributed under the License is distributed on an "AS IS" BASIS,
436
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
437
+ * See the License for the specific language governing permissions and
438
+ * limitations under the License.
439
+ */
440
+ /**
441
+ * Initializes a test environment for rules unit testing. Call this function first for test setup.
442
+ *
443
+ * Requires emulators to be running. This function tries to discover those emulators via environment
444
+ * variables or through the Firebase Emulator hub if hosts and ports are unspecified. It is strongly
445
+ * recommended to specify security rules for emulators used for testing. See minimal example below.
446
+ *
447
+ * @param config - the configuration for emulators. Most fields are optional if they can be discovered
448
+ * @returns a promise that resolves with an environment ready for testing, or rejects on error.
449
+ * @public
450
+ * @example
451
+ * ```javascript
452
+ * const testEnv = await initializeTestEnvironment({
453
+ * firestore: {
454
+ * rules: fs.readFileSync("/path/to/firestore.rules", "utf8"), // Load rules from file
455
+ * // host and port can be omitted if they can be discovered from the hub.
456
+ * },
457
+ * // ...
458
+ * });
459
+ * ```
460
+ */
461
+ async function initializeTestEnvironment(config) {
462
+ var _a, _b, _c;
463
+ const projectId = config.projectId || process.env.GCLOUD_PROJECT;
464
+ if (!projectId) {
465
+ throw new Error('Missing projectId option or env var GCLOUD_PROJECT! Please specify the projectId either ' +
466
+ 'way.\n(A demo-* projectId is strongly recommended for unit tests, such as "demo-test".)');
467
+ }
468
+ const hub = getEmulatorHostAndPort('hub', config.hub);
469
+ let discovered = hub ? Object.assign(Object.assign({}, (await discoverEmulators(hub))), { hub }) : undefined;
470
+ const emulators = {};
471
+ if (hub) {
472
+ emulators.hub = hub;
473
+ }
474
+ for (const emulator of SUPPORTED_EMULATORS) {
475
+ const hostAndPort = getEmulatorHostAndPort(emulator, config[emulator], discovered);
476
+ if (hostAndPort) {
477
+ emulators[emulator] = hostAndPort;
478
+ }
479
+ }
480
+ if ((_a = config.database) === null || _a === void 0 ? void 0 : _a.rules) {
481
+ assertEmulatorRunning(emulators, 'database');
482
+ await loadDatabaseRules(emulators.database, projectId, config.database.rules);
483
+ }
484
+ if ((_b = config.firestore) === null || _b === void 0 ? void 0 : _b.rules) {
485
+ assertEmulatorRunning(emulators, 'firestore');
486
+ await loadFirestoreRules(emulators.firestore, projectId, config.firestore.rules);
487
+ }
488
+ if ((_c = config.storage) === null || _c === void 0 ? void 0 : _c.rules) {
489
+ assertEmulatorRunning(emulators, 'storage');
490
+ await loadStorageRules(emulators.storage, config.storage.rules);
491
+ }
492
+ return new RulesTestEnvironmentImpl(projectId, emulators);
493
+ }
494
+ const SUPPORTED_EMULATORS = ['database', 'firestore', 'storage'];
495
+
496
+ /**
497
+ * @license
498
+ * Copyright 2021 Google LLC
499
+ *
500
+ * Licensed under the Apache License, Version 2.0 (the "License");
501
+ * you may not use this file except in compliance with the License.
502
+ * You may obtain a copy of the License at
503
+ *
504
+ * http://www.apache.org/licenses/LICENSE-2.0
505
+ *
506
+ * Unless required by applicable law or agreed to in writing, software
507
+ * distributed under the License is distributed on an "AS IS" BASIS,
508
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
509
+ * See the License for the specific language governing permissions and
510
+ * limitations under the License.
511
+ */
512
+ async function withFunctionTriggersDisabled(fnOrHub, maybeFn) {
513
+ let hub;
514
+ if (typeof fnOrHub === 'function') {
515
+ maybeFn = fnOrHub;
516
+ hub = getEmulatorHostAndPort('hub');
517
+ }
518
+ else {
519
+ hub = getEmulatorHostAndPort('hub', fnOrHub);
520
+ if (!maybeFn) {
521
+ throw new Error('The callback function must be specified!');
522
+ }
523
+ }
524
+ if (!hub) {
525
+ throw new Error('Please specify the Emulator Hub host and port via arguments or set the environment ' +
526
+ `varible ${EMULATOR_HOST_ENV_VARS.hub}!`);
527
+ }
528
+ hub.host = fixHostname(hub.host);
529
+ makeUrl(hub, '/functions/disableBackgroundTriggers');
530
+ // Disable background triggers
531
+ const disableRes = await fetch(makeUrl(hub, '/functions/disableBackgroundTriggers'), {
532
+ method: 'PUT'
533
+ });
534
+ if (!disableRes.ok) {
535
+ throw new Error(`HTTP Error ${disableRes.status} when disabling functions triggers, are you using firebase-tools 8.13.0 or higher?`);
536
+ }
537
+ // Run the user's function
538
+ let result = undefined;
539
+ try {
540
+ result = await maybeFn();
541
+ }
542
+ finally {
543
+ // Re-enable background triggers
544
+ const enableRes = await fetch(makeUrl(hub, '/functions/enableBackgroundTriggers'), {
545
+ method: 'PUT'
546
+ });
547
+ if (!enableRes.ok) {
548
+ throw new Error(`HTTP Error ${enableRes.status} when enabling functions triggers, are you using firebase-tools 8.13.0 or higher?`);
549
+ }
550
+ }
551
+ // Return the user's function result
552
+ return result;
553
+ }
554
+ /**
555
+ * Assert the promise to be rejected with a "permission denied" error.
556
+ *
557
+ * Useful to assert a certain request to be denied by Security Rules. See example below.
558
+ * This function recognizes permission-denied errors from Database, Firestore, and Storage JS SDKs.
559
+ *
560
+ * @param pr - the promise to be asserted
561
+ * @returns a Promise that is fulfilled if pr is rejected with "permission denied". If pr is
562
+ * rejected with any other error or resolved, the returned promise rejects.
563
+ * @public
564
+ * @example
565
+ * ```javascript
566
+ * const unauthed = testEnv.unauthenticatedContext();
567
+ * await assertFails(get(doc(unauthed.firestore(), '/private/doc'), { ... });
568
+ * ```
569
+ */
570
+ function assertFails(pr) {
571
+ return pr.then(() => {
572
+ return Promise.reject(new Error('Expected request to fail, but it succeeded.'));
573
+ }, (err) => {
574
+ var _a, _b;
575
+ const errCode = ((_a = err === null || err === void 0 ? void 0 : err.code) === null || _a === void 0 ? void 0 : _a.toLowerCase()) || '';
576
+ const errMessage = ((_b = err === null || err === void 0 ? void 0 : err.message) === null || _b === void 0 ? void 0 : _b.toLowerCase()) || '';
577
+ const isPermissionDenied = errCode === 'permission-denied' ||
578
+ errCode === 'permission_denied' ||
579
+ errMessage.indexOf('permission_denied') >= 0 ||
580
+ errMessage.indexOf('permission denied') >= 0 ||
581
+ // Storage permission errors contain message: (storage/unauthorized)
582
+ errMessage.indexOf('unauthorized') >= 0;
583
+ if (!isPermissionDenied) {
584
+ return Promise.reject(new Error(`Expected PERMISSION_DENIED but got unexpected error: ${err}`));
585
+ }
586
+ return err;
587
+ });
588
+ }
589
+ /**
590
+ * Assert the promise to be successful.
591
+ *
592
+ * This is a no-op function returning the passed promise as-is, but can be used for documentational
593
+ * purposes in test code to emphasize that a certain request should succeed (e.g. allowed by rules).
594
+ *
595
+ * @public
596
+ * @example
597
+ * ```javascript
598
+ * const alice = testEnv.authenticatedContext('alice');
599
+ * await assertSucceeds(get(doc(alice.firestore(), '/doc/readable/by/alice'), { ... });
600
+ * ```
601
+ */
602
+ function assertSucceeds(pr) {
603
+ return pr;
604
+ }
605
+
606
+ export { assertFails, assertSucceeds, initializeTestEnvironment, withFunctionTriggersDisabled };
607
+ //# sourceMappingURL=index.esm.js.map