diff --git a/.vscode/settings.json b/.vscode/settings.json index 2ac89c5..b8b0fc6 100644 --- a/.vscode/settings.json +++ b/.vscode/settings.json @@ -7,14 +7,7 @@ // Use 'prettier-eslint' instead of 'prettier'. Other settings will only be fallbacks in case they could not be inferred from eslint rules. "editor.codeActionsOnSave": { - // For ESLint - "source.fixAll.eslint": true + "source.fixAll.eslint": "explicit" }, - "cSpell.words": [ - "Mavo", - "appspot", - "firebase", - "firebaseapp", - "firebaseio" - ] + "cSpell.words": ["Mavo", "appspot", "firebase", "firebaseapp", "firebaseio"] } diff --git a/dist/0.4.2/mavo-firebase-firestore.css b/dist/0.4.2/mavo-firebase-firestore.css new file mode 100644 index 0000000..0014e11 --- /dev/null +++ b/dist/0.4.2/mavo-firebase-firestore.css @@ -0,0 +1,4 @@ +.mv-bar.mv-ui button[class*="mv-firebase-auth"]::before { + content: "🔑 "; + filter: brightness(160%) grayscale(100%); +} diff --git a/dist/0.4.2/mavo-firebase-firestore.js b/dist/0.4.2/mavo-firebase-firestore.js new file mode 100644 index 0000000..8ac8d16 --- /dev/null +++ b/dist/0.4.2/mavo-firebase-firestore.js @@ -0,0 +1,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); diff --git a/mavo-firebase-firestore.js b/mavo-firebase-firestore.js index 0ba3c85..8ac8d16 100644 --- a/mavo-firebase-firestore.js +++ b/mavo-firebase-firestore.js @@ -3,7 +3,7 @@ /** * Firebase backend plugin for Mavo. * @author Dmitry Sharabin and contributors - * @version 0.4.1 + * @version 0.4.2 */ (function ($) { "use strict"; diff --git a/package.json b/package.json index ae0aec5..42544db 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "mavo-firebase-firestore", - "version": "0.4.1", + "version": "0.4.2", "description": "Firebase backend plugin for Mavo. Store and sync app data in milliseconds. Store and serve files at Google scale. Authenticate users simply and securely. All the Google Firebase powers are at your fingertips.", "repository": "https://github.com/DmitrySharabin/mavo-firebase-firestore.git", "bugs": {