-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmavo-firebase-firestore.js
676 lines (570 loc) · 20.3 KB
/
mavo-firebase-firestore.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
/*global Mavo, Bliss, firebase*/
/**
* Firebase backend plugin for Mavo.
* @author Dmitry Sharabin and contributors
* @version 0.4.2
*/
(function ($) {
"use strict";
const PROVIDERS = {
"google": {},
"facebook": {},
"twitter": {},
"github": {}
};
Mavo.Plugins.register("firebase-firestore", {
dependencies: [
"https://cdn.jsdelivr.net/gh/DmitrySharabin/mavo-firebase-firestore/mavo-firebase-firestore.css"
],
ready: $.include("https://www.gstatic.com/firebasejs/10.6.0/firebase-app-compat.js").then(() => $.include(firebase?.firestore, "https://www.gstatic.com/firebasejs/10.6.0/firebase-firestore-compat.js")),
hooks: {
"init-start": function (mavo) {
if (mavo.bar?.permissions?.login) {
// Add buttons for auth providers to the Mavo bar
// Show them only if the Firebase backend is used and any auth provider is specified
Object.keys(PROVIDERS).forEach(p => {
const id = `firebase-auth-${p}`;
Mavo.UI.Bar.controls[id] = {
create (custom) {
return custom ?? $.create("button", {
type: "button",
className: `mv-${id}`,
textContent: mavo._(id),
});
},
action () {
mavo.primaryBackend.provider = p;
mavo.primaryBackend.login(false);
},
permission: "login",
condition () {
return Boolean(mavo.primaryBackend?.project) && mavo.primaryBackend?.authProviders?.includes?.(p);
}
};
});
// Hide the Login button if either of auth providers is specified
$.extend(Mavo.UI.Bar.controls.login, {
condition () {
return mavo.primaryBackend?.project? !mavo.primaryBackend?.authProviders?.length : mavo.primaryBackend?.permissions?.login;
}
});
}
}
}
});
const _ = Mavo.Backend.register(
class Firebase extends Mavo.Backend {
id = "Firebase";
constructor (url, o) {
super(url, o);
// Initialization code
this.permissions.on("read");
}
update (url, o) {
super.update(url, o);
this.defaults = {
collection: "mavo-apps",
query: o.query?.trim(),
filename: o.mavo.id,
bucketName: o.bucketname ?? o.mavo.id,
features: {
auth: false,
storage: false,
realtime: false,
"skip-unsaved-data-warning": false,
"offline-persistence": false,
"all-can-write": false,
"all-can-edit": false
},
authProviders: _.getAuthProviders(o.providers ?? "", PROVIDERS),
provider: undefined
};
$.extend(this, this.defaults);
if (this.query === "") {
this.query = "all";
}
// Get the config info from the attribute value
$.extend(this, _.parseSource(this.source, this.defaults));
// If the author provided backend metadata, use them
// since they have higher priority
this.project = o.project ?? this.project;
this.collection = o.collection ?? this.collection;
this.filename = o.filename ?? this.filename;
if (this.query) {
// We are working with a collection of documents
delete this.filename;
}
// The app's Firebase configuration
const config = {
apiKey: this.key,
databaseURL: `https://${this.project}.firebaseio.com`,
projectId: this.project,
authDomain: `${this.project}.firebaseapp.com`,
storageBucket: `${this.project}.appspot.com`
};
// Which backend features should we support?
const template = o.options ?? "";
this.features = _.getOptions(template, this.defaults.features);
// If either of the auth providers is specified, we must enable the auth feature
if (this.authProviders.length) {
this.features.auth = true;
}
// Initialize Cloud Firestore through Firebase
// We want all mavo apps with the same project ID share the same instance of Firebase app
// If there is no previously created Firebase app with the specified project ID, create one
if (!firebase.apps.length) {
this.app = firebase.initializeApp(config);
}
else {
this.app = firebase.apps.find(app => app.options.projectId === this.project)
?? firebase.initializeApp(config, this.project);
}
if (this.features["offline-persistence"]) {
// To allow offline persistence, we MUST enable it foremost and only once
// Offline persistence is supported only by Chrome, Safari, and Firefox web browsers
try {
this.app.firestore().enablePersistence({ synchronizeTabs: true });
}
catch (error) {
if (error.code === "unimplemented") {
// The current browser does not support all of the
// features required to enable persistence
Mavo.warn(this.mavo._("firebase-offline-persistence-unimplemented"));
this.mavo.error(`Firebase Offline Persistence: ${error.message}`);
}
else if (error.code === "failed-precondition") {
// Multiple tabs open, persistence can only be enabled
// in one tab at a a time
Mavo.warn(this.mavo._("firebase-offline-persistence-failed-precondition"));
this.mavo.error(`Firebase Offline Persistence: ${error.message}`);
}
}
}
if (this.features.auth) {
$.include(firebase?.auth, "https://www.gstatic.com/firebasejs/10.6.0/firebase-auth-compat.js").then(() => {
this.permissions.on("login");
// If none of the auth providers is specified, by default Google is used
if (!this.authProviders.length) {
this.provider = "google";
}
const defaultPermissions = ["login"];
// By default, if the authentication feature is on, only signed-in users can edit and save the app's data.
// We want to let authors granularly override the default behavior,
// and we could enable the corresponding permissions
if (this.features["all-can-write"]) {
defaultPermissions.push("save");
}
if (this.features["all-can-edit"]) {
defaultPermissions.push("edit");
}
// Set an authentication state observer and get user data
this.app.auth().onAuthStateChanged(user => {
if (user) {
// User is signed in
this.user = {
username: user.email,
name: user.displayName,
avatar: user.photoURL,
info: user // raw user object
};
// Make the plugin work both with stable and future versions of Mavo.
if (this instanceof EventTarget) {
$.fire(this, "mv-login");
}
else {
// Mavo v0.2.4-
$.fire(o.mavo.element, "mv-login", { backend: this });
}
this.permissions.off("login").on(["edit", "save", "logout"]);
}
else {
// User is signed out
this.user = null;
// Make the plugin work both with stable and future versions of Mavo.
if (this instanceof EventTarget) {
$.fire(this, "mv-logout");
}
else {
// Mavo v0.2.4-
$.fire(o.mavo.element, "mv-logout", { backend: this });
}
this.permissions
.off(["edit", "add", "delete", "save", "logout"])
.on(defaultPermissions);
}
});
});
}
else {
this.permissions.on(["edit", "save"]);
}
this.db = this.app.firestore().collection(this.collection);
if (this.features.realtime) {
this.listenChanges();
}
if (this.features.storage) {
$.include(firebase?.storage, "https://www.gstatic.com/firebasejs/10.6.0/firebase-storage-compat.js").then(() => {
// Get a reference to the storage service, which is used to create references in the storage bucket,
// and create a storage reference from the storage service
this.storageBucketRef = this.app.storage().ref();
});
}
}
async load () {
// Since we support offline persistence, we don't want end-users to think an app is hung when we are offline.
// So we hide the progress indicator after 300ms, and it seems that loading was performed (and it really was).
// I am not sure whether we would face this issue without making other parts of an app offline-ready,
// but in the sake of consistency and future use I add this code here
if (this.features["offline-persistence"] && !navigator.onLine) {
setTimeout(() => this.mavo.inProgress = false, 300);
}
if (this.features.realtime) {
// Do not load the data twice: when the real-time updates feature is enabled, the data will be loaded (and rendered) inside the updatesHandler.
return {};
}
if (!this.filename) {
// We might have a collection of docs.
try {
if (this.query !== "all" && !this.query.startsWith("where(")) {
throw new TypeError(this.mavo._("firebase-query-syntax-error"));
}
const collection = this.query !== "all" ? await eval(`this.db.${this.query}.get()`) : await this.db.get();
const $items = [];
collection.forEach(doc => $items.push({ id: doc.id, data: doc.data() }));
return { $items };
}
catch (error) {
if (this.query) {
if (error instanceof TypeError) {
Mavo.warn(error.message);
}
else {
Mavo.warn(this.mavo._("firebase-query-failed", { collection: this.collection, query: this.query }));
}
}
return null;
}
}
try {
const doc = await this.db.doc(this.filename).get();
return doc.data() ?? {};
}
catch (error) {
Mavo.warn(this.mavo._("firebase-check-security-rules"));
this.mavo.error(`Firebase Load Data: ${error.message}`);
return null;
}
}
/**
* Low-level saving code
* @param {*} serialized Data serialized according to this.format
* @param {*} path Path to store data
* @param {*} o Arbitrary options
*/
async put (serialized, path = this.path, o = {}) {
// Since we support offline persistence, we don't want end-users to think an app is hung when we are offline.
// So we hide the progress indicator after 300ms, and it seems that saving was performed (and it really was)
if (this.features["offline-persistence"] && !navigator.onLine) {
setTimeout(() => this.mavo.inProgress = false, 300);
}
if (o.isFile) {
if (!this.storageBucketRef) {
Mavo.warn(this.mavo._("firebase-enable-storage"));
return Promise.reject(Error(`Firebase Storage: ${this.mavo._("firebase-enable-storage")}`));
}
return this.storageBucketRef
.child(path)
.put(serialized)
.then(snapshot => snapshot.ref.getDownloadURL());
}
if (!this.filename) {
// We have a collection of docs.
const documents = JSON.parse(serialized)?.$items;
if (!documents) {
return null;
}
const ids = [];
for (const document of documents) {
let { id, data } = document;
if (id === undefined) {
data ??= {...document};
try {
// Generate document ID automatically.
const docRef = await this.db.add(data);
ids.push(docRef.id);
}
catch (error) {}
}
else {
if (data === undefined) {
data = {...document};
delete data.id;
}
try {
await this.db.doc(id).set(data);
ids.push(id);
}
catch (error) {}
}
}
// Return IDs of all successfully stored documents.
return Promise.resolve(ids);
}
// We have a document.
return this.db
.doc(this.filename)
.set(JSON.parse(serialized))
.then(() => Promise.resolve())
.catch(error => {
if (this.features.auth) {
Mavo.warn(this.mavo._("firebase-check-security-rules"));
}
else {
Mavo.warn(this.mavo._("firebase-enable-auth"));
Mavo.warn(this.mavo._("firebase-check-security-rules"));
}
this.mavo.error(`Firebase Auth: ${error.message}`);
});
}
/**
* Upload code
* @param {*} file File object to be uploaded
* @param {*} path Relative path to store uploads (e.g. "images")
*/
async upload (file, path) {
path = `${this.bucketName}/${path}`;
try {
const url = await this.put(file, path, {isFile: true});
return url;
}
catch (error) {
if (error.code) {
if (this.features.auth) {
Mavo.warn(this.mavo._("firebase-check-security-rules"));
}
else {
Mavo.warn(this.mavo._("firebase-enable-auth"));
Mavo.warn(this.mavo._("firebase-check-security-rules"));
}
}
this.mavo.error(`${error.message}`);
return null;
}
}
// Takes care of authentication. If passive is true, only checks if
// the user is already logged in, but does not present any login UI
async login (passive) {
return new Promise((resolve, reject) => {
if (passive) {
resolve(this.user);
}
else {
// Apply the default browser preference
firebase.auth().useDeviceLanguage();
this.app
.auth()
.signInWithPopup(_.buildProvider(this.provider))
.then(() => {
if (this.features.realtime && !this.unsubscribe) {
this.listenChanges();
}
})
.catch(error => {
this.mavo.error(`Firebase Auth: ${error.message}`);
reject(error);
});
}
});
}
// Log current user out
logout () {
this.unsubscribe?.();
this.unsubscribe = null;
return this.app
.auth()
.signOut()
.catch(error => {
this.mavo.error(`Firebase Auth: ${error.message}`);
});
}
/**
* A handler for real-time updates of a document/collection
* @param {Object} snapshot A document/collection snapshot
*/
updatesHandler (snapshot, o = {}) {
let data;
if (this.filename) {
data = snapshot.data();
}
else {
const $items = [];
snapshot.forEach(doc => $items.push({ id: doc.id, data: doc.data() }));
data = { $items };
}
if (Mavo.prototype.push) {
// This is how it should be as soon as we can provide conflictPolicy to the push() method through the mv-remotedatachange event.
// Till then, we'll be using the workaround below.
// $.fire(this, "mv-remotedatachange", { data });
// Workaround
this.mavo.push(data, { conflictPolicy: o.skipWarning ? "force" : "ask"});
}
else {
// Backward compatibility for Mavo v0.2.4-
if (!o.skipWarning && this.mavo.unsavedChanges) {
if (!confirm(this.mavo._("remote-data-conflict"))) {
return;
}
}
// When the app's author enables the autosave feature,
// we don't want data loss from race condition with autosave and real-time updates.
// We must save the state of the autosave feature for not to enable it by mistake
const autoSaveState = this.mavo.autoSave;
this.mavo.autoSave = false;
this.mavo.render(data);
this.mavo.autoSave = autoSaveState;
}
}
listenChanges () {
// Stop listening to changes
this.unsubscribe?.();
if (this.filename || this.collection) {
let collection = this.db;
if (this.filename) {
collection = collection.doc(this.filename);
}
else if (this.query && this.query !== "all") {
if (!this.query.startsWith("where(")) {
Mavo.warn(this.mavo._("firebase-query-syntax-error"));
return;
}
collection = eval(`collection.${this.query}`);
}
// Get real-time updates
this.unsubscribe = collection.onSnapshot(
// If the app doesn't have the storage backend or the author wants to skip the warning about unsaved data, we should force the data update.
snapshot => this.updatesHandler(snapshot, { skipWarning: !this.mavo.storage || this.features["skip-unsaved-data-warning"] }),
error => {
if (!this.filename && this.query) {
Mavo.warn(this.mavo._("firebase-query-failed", { collection: this.collection, query: this.query }));
}
this.mavo.error(`Firebase Real-time: ${error.message}`);
}
);
}
else {
this.unsubscribe = null;
}
}
// Mandatory and very important! This determines when the backend is used
// value: The mv-storage/mv-source/mv-init/mv-uploads value
static test (value) {
return /^https:\/\/.*\.firebaseio\.com\/?/.test(value) // Backward compatibility
|| /^firebase:\/\/.*/.test(value);
}
/**
* Parse URL.
* @param {string} source Database URL | URL of a file in Firebase Storage.
* @param {object} defaults Default collection path and filename.
* @returns Project ID, collection path, filename.
*/
static parseSource (source, defaults = {}) {
const ret = {};
if (/^https:\/\/.*\.firebaseio\.com\/?/.test(source)) {
const url = new URL(source);
ret.project = url.hostname.split(".").shift();
source = url.pathname.slice(1);
if (source && !source.includes("/")) {
// Handle the case when only a root collection is provided
source += "/";
}
}
else {
source = source.replace("firebase://", "");
}
if (source.includes("/")) {
const parts = source.split("/").filter(Boolean);
ret.project ??= parts.shift();
// If source without project ID has an odd number of parts,
// the app's author specified only collection.
// Otherwise, we have both: collection and filename.
ret.filename = parts.length % 2 ? defaults.filename : parts.pop();
ret.collection = parts.join("/");
}
else {
ret.project ??= source;
ret.collection = defaults.collection;
ret.filename = defaults.filename;
}
return ret;
}
/**
* Parse the list of options
* @param {String} template The value to parse or an empty string
* @param {Object} defaults Default set of values
*/
static getOptions (template, defaults) {
const ret = defaults;
const all = Object.keys(defaults);
template = template?.trim();
if (template) {
let ids = template.split(/\s+/);
// Drop duplicates (last one wins)
ids = Mavo.Functions.unique(ids.reverse()).reverse();
all.forEach(id =>
ids.includes(id) ? (ret[id] = true) : (ret[id] = false)
);
return ret;
}
// No template, return default set
return ret;
}
/**
* Parse the list of auth providers
* @param {String} template The value to parse or an empty string
* @param {Object} defaults Default set of auth providers
*/
static getAuthProviders (template, defaults) {
const all = Object.keys(defaults);
template = template?.trim();
if (template) {
let ids = template.split(/\s+/);
// Convert all auth providers names to lowercase and drop duplicates
ids = Mavo.Functions.unique(ids.map(id => id.toLowerCase()));
// Drop not supported auth providers
ids = ids.filter(id => all.includes(id));
return ids;
}
// No auth providers provided
return [];
}
/**
* Build an instance of the specified provider object. Fallback to Google
* @param {String} provider An auth provider name
*/
static buildProvider (provider = "google") {
// Make provider name title-cased
provider = provider.charAt(0).toUpperCase() + provider.slice(1);
return eval(`new firebase.auth.${provider}AuthProvider()`);
}
}
);
Mavo.Locale.register("en", {
"firebase-enable-auth": `You might need to enable authorization in your app. To do so, add mv-storage-options="auth" to the Mavo root. Note: Instead of mv-storage, you can also use other backend types: mv-source, mv-init, and mv-uploads.`,
"firebase-enable-storage": `It seems your app does not support uploads. To enable uploads, add mv-storage-options="storage" to the Mavo root. Note: Instead of mv-storage, you can also use other backend types: mv-source, mv-init, and mv-uploads.`,
"firebase-check-security-rules": "Please check the security rules for your app. They might be inappropriately set. For details, see https://plugins.mavo.io/plugin/firebase-firestore#security-rules-examples.",
"firebase-offline-persistence-unimplemented": "The current browser does not support all of the features required to enable offline persistence. This feature is supported only by Chrome, Safari, and Firefox web browsers.",
"firebase-offline-persistence-failed-precondition": "Multiple tabs open, offline persistence can only be enabled in one tab at a time.",
"firebase-query-syntax-error": `The query you provided is malformed. It must start with the “where()” operator. For example, “where("city", ==, "LA")”.`,
"firebase-query-failed": "We couldn't retrieve documents from the “{collection}” collection by performing the following query: {query}. It might be your query is malformed or contains unsupported operators. For the list of all supported query operators, see https://firebase.google.com/docs/firestore/query-data/queries#query_operators.",
"firebase-auth-google": "Google",
"firebase-auth-facebook": "Facebook",
"firebase-auth-twitter": "Twitter",
"firebase-auth-github": "GitHub"
});
// We want to register this localization string for Mavo v0.2.4- only
if (!Mavo.prototype.push) {
Mavo.Locale.register("en", {
"remote-data-conflict": "There is new data but you have unsaved changes. Loading it will overwrite your changes. Load new data?"
});
}
})(Bliss);