UNPKG

11.9 kBJavaScriptView Raw
1'use strict';
2
3Object.defineProperty(exports, '__esModule', { value: true });
4
5var firebase = require('firebase');
6var request = require('request');
7var util = require('@firebase/util');
8var logger = require('@firebase/logger');
9var component = require('@firebase/component');
10
11/*! *****************************************************************************
12Copyright (c) Microsoft Corporation.
13
14Permission to use, copy, modify, and/or distribute this software for any
15purpose with or without fee is hereby granted.
16
17THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
18REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
19AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
20INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
21LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
22OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
23PERFORMANCE OF THIS SOFTWARE.
24***************************************************************************** */
25
26function __awaiter(thisArg, _arguments, P, generator) {
27 function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
28 return new (P || (P = Promise))(function (resolve, reject) {
29 function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
30 function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
31 function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
32 step((generator = generator.apply(thisArg, _arguments || [])).next());
33 });
34}
35
36function __generator(thisArg, body) {
37 var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
38 return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
39 function verb(n) { return function (v) { return step([n, v]); }; }
40 function step(op) {
41 if (f) throw new TypeError("Generator is already executing.");
42 while (_) try {
43 if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
44 if (y = 0, t) op = [op[0] & 2, t.value];
45 switch (op[0]) {
46 case 0: case 1: t = op; break;
47 case 4: _.label++; return { value: op[1], done: false };
48 case 5: _.label++; y = op[1]; op = [0]; continue;
49 case 7: op = _.ops.pop(); _.trys.pop(); continue;
50 default:
51 if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
52 if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
53 if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
54 if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
55 if (t[2]) _.ops.pop();
56 _.trys.pop(); continue;
57 }
58 op = body.call(thisArg, _);
59 } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
60 if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
61 }
62}
63
64/**
65 * @license
66 * Copyright 2018 Google LLC
67 *
68 * Licensed under the Apache License, Version 2.0 (the "License");
69 * you may not use this file except in compliance with the License.
70 * You may obtain a copy of the License at
71 *
72 * http://www.apache.org/licenses/LICENSE-2.0
73 *
74 * Unless required by applicable law or agreed to in writing, software
75 * distributed under the License is distributed on an "AS IS" BASIS,
76 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
77 * See the License for the specific language governing permissions and
78 * limitations under the License.
79 */
80/** If this environment variable is set, use it for the database emulator's address. */
81var DATABASE_ADDRESS_ENV = 'FIREBASE_DATABASE_EMULATOR_ADDRESS';
82/** The default address for the local database emulator. */
83var DATABASE_ADDRESS_DEFAULT = 'localhost:9000';
84/** The actual address for the database emulator */
85var DATABASE_ADDRESS = process.env[DATABASE_ADDRESS_ENV] || DATABASE_ADDRESS_DEFAULT;
86/** If any of environment variable is set, use it for the Firestore emulator. */
87var FIRESTORE_ADDRESS_ENVS = [
88 'FIRESTORE_EMULATOR_HOST',
89 'FIREBASE_FIRESTORE_EMULATOR_ADDRESS'
90];
91/** The default address for the local Firestore emulator. */
92var FIRESTORE_ADDRESS_DEFAULT = 'localhost:8080';
93/** The actual address for the Firestore emulator */
94var FIRESTORE_ADDRESS = FIRESTORE_ADDRESS_ENVS.reduce(function (addr, name) { return process.env[name] || addr; }, FIRESTORE_ADDRESS_DEFAULT);
95/** Passing this in tells the emulator to treat you as an admin. */
96var ADMIN_TOKEN = 'owner';
97/** Create an unsecured JWT for the given auth payload. See https://tools.ietf.org/html/rfc7519#section-6. */
98function createUnsecuredJwt(auth) {
99 // Unsecured JWTs use "none" as the algorithm.
100 var header = {
101 alg: 'none',
102 kid: 'fakekid'
103 };
104 // Ensure that the auth payload has a value for 'iat'.
105 auth.iat = auth.iat || 0;
106 // Use `uid` field as a backup when `sub` is missing.
107 auth.sub = auth.sub || auth.uid;
108 if (!auth.sub) {
109 throw new Error("auth must be an object with a 'sub' or 'uid' field");
110 }
111 // Unsecured JWTs use the empty string as a signature.
112 var signature = '';
113 return [
114 util.base64.encodeString(JSON.stringify(header), /*webSafe=*/ false),
115 util.base64.encodeString(JSON.stringify(auth), /*webSafe=*/ false),
116 signature
117 ].join('.');
118}
119function apps() {
120 return firebase.apps;
121}
122/** Construct an App authenticated with options.auth. */
123function initializeTestApp(options) {
124 return initializeApp(options.auth ? createUnsecuredJwt(options.auth) : undefined, options.databaseName, options.projectId);
125}
126/** Construct an App authenticated as an admin user. */
127function initializeAdminApp(options) {
128 return initializeApp(ADMIN_TOKEN, options.databaseName, options.projectId);
129}
130function initializeApp(accessToken, databaseName, projectId) {
131 var _this = this;
132 var appOptions = {};
133 if (databaseName) {
134 appOptions['databaseURL'] = "http://" + DATABASE_ADDRESS + "?ns=" + databaseName;
135 }
136 if (projectId) {
137 appOptions['projectId'] = projectId;
138 }
139 var appName = 'app-' + new Date().getTime() + '-' + Math.random();
140 var app = firebase.initializeApp(appOptions, appName);
141 if (accessToken) {
142 var mockAuthComponent = new component.Component('auth-internal', function () {
143 return ({
144 getToken: function () { return __awaiter(_this, void 0, void 0, function () { return __generator(this, function (_a) {
145 return [2 /*return*/, ({ accessToken: accessToken })];
146 }); }); },
147 getUid: function () { return null; },
148 addAuthTokenListener: function (listener) {
149 // Call listener once immediately with predefined accessToken.
150 listener(accessToken);
151 },
152 removeAuthTokenListener: function () { }
153 });
154 }, "PRIVATE" /* PRIVATE */);
155 app._addOrOverwriteComponent(mockAuthComponent);
156 }
157 if (databaseName) {
158 // Toggle network connectivity to force a reauthentication attempt.
159 // This mitigates a minor race condition where the client can send the
160 // first database request before authenticating.
161 app.database().goOffline();
162 app.database().goOnline();
163 }
164 if (projectId) {
165 app.firestore().settings({
166 host: FIRESTORE_ADDRESS,
167 ssl: false
168 });
169 }
170 /**
171 Mute warnings for the previously-created database and whatever other
172 objects were just created.
173 */
174 logger.setLogLevel(logger.LogLevel.ERROR);
175 return app;
176}
177function loadDatabaseRules(options) {
178 if (!options.databaseName) {
179 throw Error('databaseName not specified');
180 }
181 if (!options.rules) {
182 throw Error('must provide rules to loadDatabaseRules');
183 }
184 return new Promise(function (resolve, reject) {
185 request.put({
186 uri: "http://" + DATABASE_ADDRESS + "/.settings/rules.json?ns=" + options.databaseName,
187 headers: { Authorization: 'Bearer owner' },
188 body: options.rules
189 }, function (err, resp, body) {
190 if (err) {
191 reject(err);
192 }
193 else if (resp.statusCode !== 200) {
194 reject(JSON.parse(body).error);
195 }
196 else {
197 resolve();
198 }
199 });
200 });
201}
202function loadFirestoreRules(options) {
203 if (!options.projectId) {
204 throw new Error('projectId not specified');
205 }
206 if (!options.rules) {
207 throw new Error('must provide rules to loadFirestoreRules');
208 }
209 return new Promise(function (resolve, reject) {
210 request.put({
211 uri: "http://" + FIRESTORE_ADDRESS + "/emulator/v1/projects/" + options.projectId + ":securityRules",
212 body: JSON.stringify({
213 rules: {
214 files: [{ content: options.rules }]
215 }
216 })
217 }, function (err, resp, body) {
218 if (err) {
219 reject(err);
220 }
221 else if (resp.statusCode !== 200) {
222 console.log('body', body);
223 reject(JSON.parse(body).error);
224 }
225 else {
226 resolve();
227 }
228 });
229 });
230}
231function clearFirestoreData(options) {
232 if (!options.projectId) {
233 throw new Error('projectId not specified');
234 }
235 return new Promise(function (resolve, reject) {
236 request.delete({
237 uri: "http://" + FIRESTORE_ADDRESS + "/emulator/v1/projects/" + options.projectId + "/databases/(default)/documents",
238 body: JSON.stringify({
239 database: "projects/" + options.projectId + "/databases/(default)"
240 })
241 }, function (err, resp, body) {
242 if (err) {
243 reject(err);
244 }
245 else if (resp.statusCode !== 200) {
246 console.log('body', body);
247 reject(JSON.parse(body).error);
248 }
249 else {
250 resolve();
251 }
252 });
253 });
254}
255function assertFails(pr) {
256 return pr.then(function (v) {
257 return Promise.reject(new Error('Expected request to fail, but it succeeded.'));
258 }, function (err) { return err; });
259}
260function assertSucceeds(pr) {
261 return pr;
262}
263
264Object.defineProperty(exports, 'database', {
265 enumerable: true,
266 get: function () {
267 return firebase.database;
268 }
269});
270Object.defineProperty(exports, 'firestore', {
271 enumerable: true,
272 get: function () {
273 return firebase.firestore;
274 }
275});
276exports.apps = apps;
277exports.assertFails = assertFails;
278exports.assertSucceeds = assertSucceeds;
279exports.clearFirestoreData = clearFirestoreData;
280exports.initializeAdminApp = initializeAdminApp;
281exports.initializeTestApp = initializeTestApp;
282exports.loadDatabaseRules = loadDatabaseRules;
283exports.loadFirestoreRules = loadFirestoreRules;
284//# sourceMappingURL=index.cjs.js.map