@nu-art/firebase-frontend 0.400.5

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.
@@ -0,0 +1,24 @@
1
+ /**
2
+ * Created by tacb0ss on 25/08/2018.
3
+ */
4
+ import { Module } from '@nu-art/ts-common';
5
+ import { FirebaseSessionFE } from './auth/FirebaseSessionFE.js';
6
+ import { SwFirebaseSessionFE } from './auth/SwFirebaseSessionFE.js';
7
+ import { FirebaseConfig } from '@nu-art/firebase-shared';
8
+ type ConfigType = {
9
+ [s: string]: FirebaseConfig;
10
+ };
11
+ export declare class ModuleFE_Firebase_Class extends Module<ConfigType> {
12
+ private sessions;
13
+ private swSession?;
14
+ createSwSession(): Promise<SwFirebaseSessionFE>;
15
+ private createLocalSession;
16
+ private fetchLocalConfig;
17
+ createSession(projectId?: string | FirebaseConfig, token?: string): Promise<FirebaseSessionFE>;
18
+ private createSessionWithConfigs;
19
+ private getProjectAuth;
20
+ private initiateSession;
21
+ private checkConfig;
22
+ }
23
+ export declare const ModuleFE_Firebase: ModuleFE_Firebase_Class;
24
+ export {};
@@ -0,0 +1,100 @@
1
+ /*
2
+ * Firebase is a simpler Typescript wrapper to all of firebase services.
3
+ *
4
+ * Copyright (C) 2020 Adam van der Kruk aka TacB0sS
5
+ *
6
+ * Licensed under the Apache License, Version 2.0 (the "License");
7
+ * you may not use this file except in compliance with the License.
8
+ * You may obtain a copy of the License at
9
+ *
10
+ * http://www.apache.org/licenses/LICENSE-2.0
11
+ *
12
+ * Unless required by applicable law or agreed to in writing, software
13
+ * distributed under the License is distributed on an "AS IS" BASIS,
14
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15
+ * See the License for the specific language governing permissions and
16
+ * limitations under the License.
17
+ */
18
+ /**
19
+ * Created by tacb0ss on 25/08/2018.
20
+ */
21
+ import { __stringify, BadImplementationException, ImplementationMissingException, Module } from '@nu-art/ts-common';
22
+ import { FirebaseSessionFE } from './auth/FirebaseSessionFE.js';
23
+ import { SwFirebaseSessionFE } from './auth/SwFirebaseSessionFE.js';
24
+ const localSessionId = 'local';
25
+ export class ModuleFE_Firebase_Class extends Module {
26
+ sessions = {};
27
+ swSession;
28
+ async createSwSession() {
29
+ const swSession = this.swSession;
30
+ if (swSession)
31
+ return swSession;
32
+ const localSession = await this.createLocalSession();
33
+ return this.swSession = new SwFirebaseSessionFE(localSessionId, localSession.app);
34
+ }
35
+ async createLocalSession(token) {
36
+ let session = this.sessions[localSessionId];
37
+ if (session)
38
+ return session;
39
+ let localConfig = this.getProjectAuth(localSessionId);
40
+ if (!localConfig)
41
+ localConfig = await this.fetchLocalConfig();
42
+ this.checkConfig(localConfig, localSessionId);
43
+ // I need to recheck because since it is an async op there might be race conditions
44
+ session = this.sessions[localSessionId];
45
+ if (session)
46
+ return session;
47
+ return this.initiateSession(localSessionId, localConfig, token);
48
+ }
49
+ fetchLocalConfig = async () => {
50
+ try {
51
+ const resp = await fetch('/__/firebase/init.json');
52
+ const config = await resp.json();
53
+ // @ts-ignore
54
+ this.setConfig({ [localSessionId]: config });
55
+ return config;
56
+ }
57
+ catch (e) {
58
+ throw new ImplementationMissingException(`Either specify configs for the 'ModuleBE_Firebase' or use SDK auto-configuration with firebase hosting`, e);
59
+ }
60
+ };
61
+ async createSession(projectId, token) {
62
+ if (!projectId)
63
+ return this.createLocalSession(token);
64
+ if (typeof projectId === 'object')
65
+ return this.createSessionWithConfigs(projectId, token);
66
+ const session = this.sessions[projectId];
67
+ if (session)
68
+ return session;
69
+ this.logInfo(`Creating session for config: ${projectId}`);
70
+ const config = this.getProjectAuth(projectId);
71
+ this.checkConfig(config, projectId);
72
+ return this.initiateSession(projectId, config, token);
73
+ }
74
+ async createSessionWithConfigs(config, token) {
75
+ if (!config || !config.projectId || !config.databaseURL || !config.authDomain || !config.apiKey)
76
+ throw new BadImplementationException(`Config: ${__stringify(config)} is not a credentials pattern`);
77
+ const projectId = config.projectId + (token || '');
78
+ // @ts-ignore
79
+ this.setConfig({ [projectId]: config });
80
+ return this.createSession(projectId, token);
81
+ }
82
+ getProjectAuth(projectId) {
83
+ return this.config?.[projectId];
84
+ }
85
+ async initiateSession(projectId, config, token) {
86
+ const session = new FirebaseSessionFE(projectId, config);
87
+ this.sessions[projectId] = session;
88
+ session.connect();
89
+ if (token)
90
+ await session.signInWithToken(token);
91
+ return session;
92
+ }
93
+ checkConfig(config, projectId) {
94
+ if (!config)
95
+ throw new BadImplementationException('Did you forget to add ModuleBE_Firebase to the main.ts in the modules array?');
96
+ if (!config || !config.projectId || !config.apiKey || !config.authDomain)
97
+ throw new BadImplementationException(`Config for key ${projectId} is not an Admin credentials pattern`);
98
+ }
99
+ }
100
+ export const ModuleFE_Firebase = new ModuleFE_Firebase_Class();
@@ -0,0 +1,52 @@
1
+ import { FirebaseApp } from 'firebase/app';
2
+ import { Database, DataSnapshot } from 'firebase/database';
3
+ import { Logger, Module } from '@nu-art/ts-common';
4
+ import 'firebase/database';
5
+ type FirebaseConfig = {
6
+ apiKey: string;
7
+ authDomain: string;
8
+ databaseURL: string;
9
+ projectId: string;
10
+ appId: string;
11
+ storageBucket?: string;
12
+ messagingSenderId?: string;
13
+ measurementId?: string;
14
+ };
15
+ type EmulatorConfig = {
16
+ hostname: string;
17
+ port: number;
18
+ ssl?: boolean;
19
+ httpsPort?: number;
20
+ };
21
+ type FirebaseListenerConfig = {
22
+ emulatorConfig?: EmulatorConfig;
23
+ firebaseConfig: FirebaseConfig;
24
+ };
25
+ export declare class ModuleFE_FirebaseListener_Class extends Module<FirebaseListenerConfig> {
26
+ app: FirebaseApp;
27
+ database: Database;
28
+ protected init(): void;
29
+ getDatabase(): Database;
30
+ createListener(nodePath: string): RefListenerFE;
31
+ }
32
+ /**
33
+ * Firebase Realtime Database rules need to allow reading the nodes that are being queried.
34
+ * <p>"<b>Permission Denied</b>" errors in dev console imply permission is not allowed in the db's rules.
35
+ */
36
+ export declare class RefListenerFE<Value = any> extends Logger {
37
+ private readonly nodePath;
38
+ private toUnsubscribeFunction?;
39
+ constructor(nodePath: string);
40
+ private getQuery;
41
+ /**
42
+ * Receives initial value and listens henceforth.
43
+ */
44
+ startListening(onValueChangedListener: (snapshot: DataSnapshot) => void): this;
45
+ /**
46
+ * One time get the value.
47
+ */
48
+ get(): Promise<Value>;
49
+ stopListening(): void;
50
+ }
51
+ export declare const ModuleFE_FirebaseListener: ModuleFE_FirebaseListener_Class;
52
+ export {};
@@ -0,0 +1,95 @@
1
+ import { initializeApp } from 'firebase/app';
2
+ import { connectDatabaseEmulator, get, getDatabase, onValue, query, ref } from 'firebase/database';
3
+ import { __stringify, _keys, exists, filterInstances, ImplementationMissingException, Logger, Module } from '@nu-art/ts-common';
4
+ import 'firebase/database';
5
+ const MandatoryFirebaseConfigKeys = ['apiKey', 'authDomain', 'databaseURL', 'projectId', 'appId'];
6
+ export class ModuleFE_FirebaseListener_Class extends Module {
7
+ app;
8
+ database;
9
+ init() {
10
+ if (!this.config.firebaseConfig)
11
+ throw new ImplementationMissingException('Could not initialize firebase listener, did not provide FE firebase config!');
12
+ const configObjectKeys = _keys(this.config.firebaseConfig);
13
+ const missingKeys = filterInstances(MandatoryFirebaseConfigKeys.map(key => configObjectKeys.includes(key) ? undefined : key));
14
+ if (missingKeys.length > 0)
15
+ throw new ImplementationMissingException(`Could not initialize firebase listener, FE firebase config is missing props: ${__stringify(missingKeys)}`);
16
+ this.app = initializeApp(this.config.firebaseConfig);
17
+ }
18
+ getDatabase() {
19
+ if (this.database)
20
+ return this.database;
21
+ const _database = getDatabase(this.app);
22
+ const emulatorConfig = this.config.emulatorConfig;
23
+ if (exists(emulatorConfig)) {
24
+ connectDatabaseEmulator(_database, emulatorConfig.hostname, emulatorConfig.port);
25
+ }
26
+ return this.database = _database;
27
+ }
28
+ createListener(nodePath) {
29
+ this.logDebug(`Creating listener for firebase rtdb node ${nodePath}`);
30
+ return new RefListenerFE(nodePath);
31
+ }
32
+ }
33
+ /**
34
+ * Firebase Realtime Database rules need to allow reading the nodes that are being queried.
35
+ * <p>"<b>Permission Denied</b>" errors in dev console imply permission is not allowed in the db's rules.
36
+ */
37
+ export class RefListenerFE extends Logger {
38
+ nodePath;
39
+ toUnsubscribeFunction;
40
+ constructor(nodePath) {
41
+ super(`RefListenerFE('${nodePath}')`);
42
+ this.nodePath = nodePath;
43
+ }
44
+ getQuery() {
45
+ const db = ModuleFE_FirebaseListener.getDatabase();
46
+ return query(ref(db, this.nodePath));
47
+ }
48
+ /**
49
+ * Receives initial value and listens henceforth.
50
+ */
51
+ startListening(onValueChangedListener) {
52
+ if (this.toUnsubscribeFunction) {
53
+ this.logWarning('RefListener asked to listen mid-listening. Stopping to listen prior to re-listening');
54
+ this.stopListening();
55
+ }
56
+ this.logDebug('Starting to listen...');
57
+ const refQuery = this.getQuery();
58
+ try {
59
+ this.toUnsubscribeFunction = onValue(refQuery, (snapshot) => {
60
+ onValueChangedListener(snapshot);
61
+ }, error => {
62
+ this.logError('Failed receiving value with error', error);
63
+ });
64
+ }
65
+ catch (e) {
66
+ this.logWarning(`Failed listening on node data, check if your rtdb rules permit reading this node '${this.nodePath}'`);
67
+ throw e;
68
+ }
69
+ this.logDebug(`Listening.`);
70
+ return this;
71
+ }
72
+ /**
73
+ * One time get the value.
74
+ */
75
+ async get() {
76
+ try {
77
+ const dataSnapshot = await get(this.getQuery());
78
+ return dataSnapshot.val();
79
+ }
80
+ catch (e) {
81
+ this.logWarning(`Failed getting node data, check if your rtdb rules permit reading this node '${this.nodePath}'`);
82
+ throw e;
83
+ }
84
+ }
85
+ stopListening() {
86
+ if (!this.toUnsubscribeFunction) {
87
+ this.logWarning('RefListener asked to stop listening but unsubscribeFunction does not exist.');
88
+ return;
89
+ }
90
+ this.logInfo('RefListener asked to stop listening');
91
+ this.toUnsubscribeFunction();
92
+ this.toUnsubscribeFunction = undefined;
93
+ }
94
+ }
95
+ export const ModuleFE_FirebaseListener = new ModuleFE_FirebaseListener_Class();
@@ -0,0 +1,34 @@
1
+ import { Logger } from '@nu-art/ts-common';
2
+ import { FirebaseType_CallOptions, FirebaseType_EventNameString } from './types.js';
3
+ import { CustomParams } from 'firebase/analytics';
4
+ import { FirebaseApp } from 'firebase/app';
5
+ /**
6
+ AnalyticsWrapperFE provides a wrapper around the Firebase Analytics library for frontend (FE) use.
7
+ It provides methods for setting user IDs, setting the current screen, enabling or disabling analytics collection,
8
+ setting custom user properties, and logging events.
9
+ */
10
+ export declare class AnalyticsWrapperFE extends Logger {
11
+ private readonly analytics;
12
+ constructor(app: FirebaseApp);
13
+ setUserId(userId: string, options?: FirebaseType_CallOptions): void;
14
+ /**
15
+ * Set the current screen for the user
16
+ * @param screenName
17
+ * @param options
18
+ */
19
+ setCurrentScreen(screenName: string, options?: FirebaseType_CallOptions): void;
20
+ /**
21
+ * Enable or disable analytics collection
22
+ * @param enabled
23
+ */
24
+ setAnalyticsCollectionEnabled(enabled: boolean): void;
25
+ /**
26
+ * Set custom user properties for analytics
27
+ * @param properties
28
+ * @param options
29
+ */
30
+ setUserProperties(properties: CustomParams, options?: FirebaseType_CallOptions): void;
31
+ logEvent(eventName: FirebaseType_EventNameString | string, eventParams?: {
32
+ [key: string]: any;
33
+ }, options?: FirebaseType_CallOptions): void;
34
+ }
@@ -0,0 +1,61 @@
1
+ /*
2
+ * Permissions management system, define access level for each of
3
+ * your server apis, and restrict users by giving them access levels
4
+ *
5
+ * Copyright (C) 2020 Adam van der Kruk aka TacB0sS
6
+ *
7
+ * Licensed under the Apache License, Version 2.0 (the "License");
8
+ * you may not use this file except in compliance with the License.
9
+ * You may obtain a copy of the License at
10
+ *
11
+ * http://www.apache.org/licenses/LICENSE-2.0
12
+ *
13
+ * Unless required by applicable law or agreed to in writing, software
14
+ * distributed under the License is distributed on an "AS IS" BASIS,
15
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16
+ * See the License for the specific language governing permissions and
17
+ * limitations under the License.
18
+ */
19
+ import { Logger } from '@nu-art/ts-common';
20
+ import { getAnalytics, logEvent, setAnalyticsCollectionEnabled, setCurrentScreen, setUserId, setUserProperties, } from 'firebase/analytics';
21
+ /**
22
+ AnalyticsWrapperFE provides a wrapper around the Firebase Analytics library for frontend (FE) use.
23
+ It provides methods for setting user IDs, setting the current screen, enabling or disabling analytics collection,
24
+ setting custom user properties, and logging events.
25
+ */
26
+ export class AnalyticsWrapperFE extends Logger {
27
+ analytics;
28
+ constructor(app) {
29
+ super();
30
+ this.analytics = getAnalytics(app);
31
+ }
32
+ setUserId(userId, options) {
33
+ setUserId(this.analytics, userId, options);
34
+ }
35
+ /**
36
+ * Set the current screen for the user
37
+ * @param screenName
38
+ * @param options
39
+ */
40
+ setCurrentScreen(screenName, options) {
41
+ setCurrentScreen(this.analytics, screenName, options);
42
+ }
43
+ /**
44
+ * Enable or disable analytics collection
45
+ * @param enabled
46
+ */
47
+ setAnalyticsCollectionEnabled(enabled) {
48
+ setAnalyticsCollectionEnabled(this.analytics, enabled);
49
+ }
50
+ /**
51
+ * Set custom user properties for analytics
52
+ * @param properties
53
+ * @param options
54
+ */
55
+ setUserProperties(properties, options) {
56
+ setUserProperties(this.analytics, properties);
57
+ }
58
+ logEvent(eventName, eventParams, options) {
59
+ return logEvent(this.analytics, eventName, eventParams, options);
60
+ }
61
+ }
@@ -0,0 +1,12 @@
1
+ import { Module } from '@nu-art/ts-common';
2
+ declare class FirebaseAnalyticsModule_Class extends Module {
3
+ private analytics?;
4
+ protected init(): void;
5
+ private _init;
6
+ logEvent(eventName: string, eventParams?: {
7
+ [key: string]: any;
8
+ }): void;
9
+ setCurrentScreen(screenName: string): void;
10
+ }
11
+ export declare const FirebaseAnalyticsModule: FirebaseAnalyticsModule_Class;
12
+ export {};
@@ -0,0 +1,41 @@
1
+ /*
2
+ * Firebase is a simpler Typescript wrapper to all of firebase services.
3
+ *
4
+ * Copyright (C) 2020 Adam van der Kruk aka TacB0sS
5
+ *
6
+ * Licensed under the Apache License, Version 2.0 (the "License");
7
+ * you may not use this file except in compliance with the License.
8
+ * You may obtain a copy of the License at
9
+ *
10
+ * http://www.apache.org/licenses/LICENSE-2.0
11
+ *
12
+ * Unless required by applicable law or agreed to in writing, software
13
+ * distributed under the License is distributed on an "AS IS" BASIS,
14
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15
+ * See the License for the specific language governing permissions and
16
+ * limitations under the License.
17
+ */
18
+ import { ImplementationMissingException, Module } from '@nu-art/ts-common';
19
+ import { ModuleFE_Firebase } from '../ModuleFE_Firebase.js';
20
+ class FirebaseAnalyticsModule_Class extends Module {
21
+ analytics;
22
+ init() {
23
+ this.runAsync('Init Analytics', this._init);
24
+ }
25
+ _init = async () => {
26
+ const session = await ModuleFE_Firebase.createSession();
27
+ this.analytics = session.getAnalytics();
28
+ this.analytics.setAnalyticsCollectionEnabled(true);
29
+ };
30
+ logEvent(eventName, eventParams) {
31
+ if (!this.analytics)
32
+ throw new ImplementationMissingException('Missing analytics wrapper');
33
+ return this.analytics.logEvent(eventName, eventParams);
34
+ }
35
+ setCurrentScreen(screenName) {
36
+ if (!this.analytics)
37
+ throw new ImplementationMissingException('Missing analytics wrapper');
38
+ return this.analytics.setCurrentScreen(screenName);
39
+ }
40
+ }
41
+ export const FirebaseAnalyticsModule = new FirebaseAnalyticsModule_Class();
@@ -0,0 +1,4 @@
1
+ import { Analytics, AnalyticsCallOptions, EventNameString } from 'firebase/analytics';
2
+ export type FirebaseType_Analytics = Analytics;
3
+ export type FirebaseType_CallOptions = AnalyticsCallOptions;
4
+ export type FirebaseType_EventNameString = EventNameString;
@@ -0,0 +1,19 @@
1
+ /*
2
+ * Permissions management system, define access level for each of
3
+ * your server apis, and restrict users by giving them access levels
4
+ *
5
+ * Copyright (C) 2020 Adam van der Kruk aka TacB0sS
6
+ *
7
+ * Licensed under the Apache License, Version 2.0 (the "License");
8
+ * you may not use this file except in compliance with the License.
9
+ * You may obtain a copy of the License at
10
+ *
11
+ * http://www.apache.org/licenses/LICENSE-2.0
12
+ *
13
+ * Unless required by applicable law or agreed to in writing, software
14
+ * distributed under the License is distributed on an "AS IS" BASIS,
15
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16
+ * See the License for the specific language governing permissions and
17
+ * limitations under the License.
18
+ */
19
+ export {};
@@ -0,0 +1,41 @@
1
+ /**
2
+ * Created by tacb0ss on 19/09/2018.
3
+ */
4
+ import { Logger } from '@nu-art/ts-common';
5
+ import { MessagingWrapperFE } from '../messaging/MessagingWrapperFE.js';
6
+ import { AnalyticsWrapperFE } from '../analytics/AnalyticsWrapperFE.js';
7
+ import { DatabaseWrapperFE } from '../database/DatabaseWrapperFE.js';
8
+ import { FirebaseApp } from 'firebase/app';
9
+ import { FirebaseConfig } from '@nu-art/firebase-shared';
10
+ export declare class FirebaseSessionFE extends Logger {
11
+ app: FirebaseApp;
12
+ protected config: FirebaseConfig;
13
+ protected sessionName: string;
14
+ protected messaging?: MessagingWrapperFE;
15
+ protected analytics?: AnalyticsWrapperFE;
16
+ protected database?: DatabaseWrapperFE;
17
+ constructor(sessionName: string, config: FirebaseConfig);
18
+ connect(): void;
19
+ /**
20
+ * Returns an instance of the MessagingWrapperFE class if it exists, or creates and returns a new instance if it does not
21
+ */
22
+ getMessaging(): MessagingWrapperFE;
23
+ /**
24
+ * Returns an instance of the AnalyticsWrapperFE class if it exists, or creates and returns a new instance if it does not
25
+ */
26
+ getAnalytics(): AnalyticsWrapperFE;
27
+ /**
28
+ * Returns an instance of the DatabaseWrapperFE class if it exists, or creates and returns a new instance if it does not
29
+ */
30
+ getDatabase(): DatabaseWrapperFE;
31
+ /**
32
+ * Authenticates the user with the given token
33
+ * @param token
34
+ */
35
+ signInWithToken(token: string): Promise<import("firebase/auth").UserCredential>;
36
+ /**
37
+ * Signs out the currently authenticated user
38
+ */
39
+ signOut(): Promise<void>;
40
+ getProjectId(): string;
41
+ }
@@ -0,0 +1,88 @@
1
+ /*
2
+ * Permissions management system, define access level for each of
3
+ * your server apis, and restrict users by giving them access levels
4
+ *
5
+ * Copyright (C) 2020 Adam van der Kruk aka TacB0sS
6
+ *
7
+ * Licensed under the Apache License, Version 2.0 (the "License");
8
+ * you may not use this file except in compliance with the License.
9
+ * You may obtain a copy of the License at
10
+ *
11
+ * http://www.apache.org/licenses/LICENSE-2.0
12
+ *
13
+ * Unless required by applicable law or agreed to in writing, software
14
+ * distributed under the License is distributed on an "AS IS" BASIS,
15
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16
+ * See the License for the specific language governing permissions and
17
+ * limitations under the License.
18
+ */
19
+ /**
20
+ * Created by tacb0ss on 19/09/2018.
21
+ */
22
+ import { Logger, ThisShouldNotHappenException } from '@nu-art/ts-common';
23
+ import { MessagingWrapperFE } from '../messaging/MessagingWrapperFE.js';
24
+ import { AnalyticsWrapperFE } from '../analytics/AnalyticsWrapperFE.js';
25
+ import { DatabaseWrapperFE } from '../database/DatabaseWrapperFE.js';
26
+ import { getAuth, signInWithCustomToken, signOut } from 'firebase/auth';
27
+ import { initializeApp } from 'firebase/app';
28
+ // import auth = firebase.auth;
29
+ export class FirebaseSessionFE extends Logger {
30
+ app;
31
+ config;
32
+ sessionName;
33
+ messaging;
34
+ analytics;
35
+ database;
36
+ constructor(sessionName, config) {
37
+ super(`firebase: ${sessionName}`);
38
+ this.sessionName = sessionName;
39
+ this.config = config;
40
+ }
41
+ connect() {
42
+ this.app = initializeApp(this.config, this.sessionName);
43
+ }
44
+ /**
45
+ * Returns an instance of the MessagingWrapperFE class if it exists, or creates and returns a new instance if it does not
46
+ */
47
+ getMessaging() {
48
+ if (this.messaging)
49
+ return this.messaging;
50
+ return this.messaging = new MessagingWrapperFE(this.app);
51
+ }
52
+ /**
53
+ * Returns an instance of the AnalyticsWrapperFE class if it exists, or creates and returns a new instance if it does not
54
+ */
55
+ getAnalytics() {
56
+ if (this.analytics)
57
+ return this.analytics;
58
+ return this.analytics = new AnalyticsWrapperFE(this.app);
59
+ }
60
+ /**
61
+ * Returns an instance of the DatabaseWrapperFE class if it exists, or creates and returns a new instance if it does not
62
+ */
63
+ getDatabase() {
64
+ if (this.database)
65
+ return this.database;
66
+ return this.database = new DatabaseWrapperFE(this.app);
67
+ }
68
+ /**
69
+ * Authenticates the user with the given token
70
+ * @param token
71
+ */
72
+ async signInWithToken(token) {
73
+ return signInWithCustomToken(getAuth(this.app), token);
74
+ }
75
+ /**
76
+ * Signs out the currently authenticated user
77
+ */
78
+ async signOut() {
79
+ return signOut(getAuth(this.app));
80
+ }
81
+ getProjectId() {
82
+ if (!this.config)
83
+ throw new ThisShouldNotHappenException('Missing config. Probably init not resolved yet!');
84
+ if (!this.config.projectId)
85
+ throw new ThisShouldNotHappenException('Could not deduce project id from session config.. if you need the functionality.. add it to the config!!');
86
+ return this.config.projectId;
87
+ }
88
+ }
@@ -0,0 +1,14 @@
1
+ /**
2
+ * Created by tacb0ss on 19/09/2018.
3
+ */
4
+ import { FirebaseApp } from 'firebase/app';
5
+ import 'firebase/auth';
6
+ import { Logger } from '@nu-art/ts-common';
7
+ import { SwMessagingWrapperFE } from '../messaging/SwMessagingWrapperFE.js';
8
+ export declare class SwFirebaseSessionFE extends Logger {
9
+ app: FirebaseApp;
10
+ protected sessionName: string;
11
+ protected messaging?: SwMessagingWrapperFE;
12
+ constructor(sessionName: string, app: FirebaseApp);
13
+ getMessaging(): SwMessagingWrapperFE;
14
+ }
@@ -0,0 +1,39 @@
1
+ /*
2
+ * Permissions management system, define access level for each of
3
+ * your server apis, and restrict users by giving them access levels
4
+ *
5
+ * Copyright (C) 2020 Adam van der Kruk aka TacB0sS
6
+ *
7
+ * Licensed under the Apache License, Version 2.0 (the "License");
8
+ * you may not use this file except in compliance with the License.
9
+ * You may obtain a copy of the License at
10
+ *
11
+ * http://www.apache.org/licenses/LICENSE-2.0
12
+ *
13
+ * Unless required by applicable law or agreed to in writing, software
14
+ * distributed under the License is distributed on an "AS IS" BASIS,
15
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16
+ * See the License for the specific language governing permissions and
17
+ * limitations under the License.
18
+ */
19
+ // tslint:disable:no-import-side-effect
20
+ import 'firebase/auth';
21
+ import { Logger } from '@nu-art/ts-common';
22
+ // noinspection TypeScriptPreferShortImport
23
+ import { SwMessagingWrapperFE } from '../messaging/SwMessagingWrapperFE.js';
24
+ import { getMessaging } from 'firebase/messaging';
25
+ export class SwFirebaseSessionFE extends Logger {
26
+ app;
27
+ sessionName;
28
+ messaging;
29
+ constructor(sessionName, app) {
30
+ super(`service worker firebase: ${sessionName}`);
31
+ this.sessionName = sessionName;
32
+ this.app = app;
33
+ }
34
+ getMessaging() {
35
+ if (this.messaging)
36
+ return this.messaging;
37
+ return this.messaging = new SwMessagingWrapperFE(getMessaging(this.app));
38
+ }
39
+ }
@@ -0,0 +1,16 @@
1
+ import { Logger, TS_Object } from '@nu-art/ts-common';
2
+ import { FirebaseApp } from 'firebase/app';
3
+ export declare class DatabaseWrapperFE extends Logger {
4
+ private readonly database;
5
+ constructor(app: FirebaseApp);
6
+ get<T>(path: string): Promise<T | null>;
7
+ listen<T>(path: string, callback: (value: T) => void): import("firebase/database").Unsubscribe;
8
+ private getRef;
9
+ set<T>(path: string, value: T): Promise<void>;
10
+ /** @deprecated */
11
+ update<T extends TS_Object>(path: string, value: T): Promise<void>;
12
+ patch<T extends TS_Object>(path: string, value: T): Promise<void>;
13
+ /** @deprecated */
14
+ remove(path: string, assertionRegexp?: string): Promise<void>;
15
+ delete(path: string, assertionRegexp?: string): Promise<void>;
16
+ }
@@ -0,0 +1,81 @@
1
+ /*
2
+ * Firebase is a simpler Typescript wrapper to all of firebase services.
3
+ *
4
+ * Copyright (C) 2020 Adam van der Kruk aka TacB0sS
5
+ *
6
+ * Licensed under the Apache License, Version 2.0 (the "License");
7
+ * you may not use this file except in compliance with the License.
8
+ * You may obtain a copy of the License at
9
+ *
10
+ * http://www.apache.org/licenses/LICENSE-2.0
11
+ *
12
+ * Unless required by applicable law or agreed to in writing, software
13
+ * distributed under the License is distributed on an "AS IS" BASIS,
14
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15
+ * See the License for the specific language governing permissions and
16
+ * limitations under the License.
17
+ */
18
+ import { BadImplementationException, Logger } from '@nu-art/ts-common';
19
+ import { getDatabase, onValue, ref, remove, set, update } from 'firebase/database';
20
+ export class DatabaseWrapperFE extends Logger {
21
+ database;
22
+ constructor(app) {
23
+ super();
24
+ this.database = getDatabase(app);
25
+ }
26
+ async get(path) {
27
+ return new Promise((resolve, reject) => {
28
+ onValue(this.getRef(path), snapshot => {
29
+ resolve(snapshot.val());
30
+ }, (error) => {
31
+ reject(error);
32
+ }, { onlyOnce: true });
33
+ });
34
+ }
35
+ listen(path, callback) {
36
+ return onValue(this.getRef(path), snapshot => {
37
+ callback(!snapshot || snapshot.val());
38
+ }, (error) => {
39
+ throw new BadImplementationException(`Error while getting value from path: ${path}`, error);
40
+ }, { onlyOnce: false });
41
+ }
42
+ getRef = (path) => ref(this.database, path);
43
+ async set(path, value) {
44
+ try {
45
+ await set(this.getRef(path), value);
46
+ }
47
+ catch (e) {
48
+ throw new BadImplementationException(`Error while setting value to path: ${path}`);
49
+ }
50
+ }
51
+ /** @deprecated */
52
+ async update(path, value) {
53
+ this.logWarning('update will be deprecated!! please use patch');
54
+ return this.patch(path, value);
55
+ }
56
+ async patch(path, value) {
57
+ try {
58
+ await update(this.getRef(path), value);
59
+ }
60
+ catch (e) {
61
+ throw new BadImplementationException(`Error while updating value to path: ${path}`);
62
+ }
63
+ }
64
+ /** @deprecated */
65
+ async remove(path, assertionRegexp = '^/.*?/.*') {
66
+ this.logWarning('remove will be deprecated!! please use delete');
67
+ return this.delete(path, assertionRegexp);
68
+ }
69
+ async delete(path, assertionRegexp = '^/.*?/.*') {
70
+ if (!path)
71
+ throw new BadImplementationException(`Falsy value, path: '${path}'`);
72
+ if (!path.match(new RegExp(assertionRegexp)))
73
+ throw new BadImplementationException(`path: '${path}' does not match assertion: '${assertionRegexp}'`);
74
+ try {
75
+ await remove(this.getRef(path));
76
+ }
77
+ catch (e) {
78
+ throw new BadImplementationException(`Error while removing path: ${path}`);
79
+ }
80
+ }
81
+ }
@@ -0,0 +1,2 @@
1
+ import { Database } from 'firebase/database';
2
+ export type FirebaseType_DB = Database;
@@ -0,0 +1,18 @@
1
+ /*
2
+ * Firebase is a simpler Typescript wrapper to all of firebase services.
3
+ *
4
+ * Copyright (C) 2020 Adam van der Kruk aka TacB0sS
5
+ *
6
+ * Licensed under the Apache License, Version 2.0 (the "License");
7
+ * you may not use this file except in compliance with the License.
8
+ * You may obtain a copy of the License at
9
+ *
10
+ * http://www.apache.org/licenses/LICENSE-2.0
11
+ *
12
+ * Unless required by applicable law or agreed to in writing, software
13
+ * distributed under the License is distributed on an "AS IS" BASIS,
14
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15
+ * See the License for the specific language governing permissions and
16
+ * limitations under the License.
17
+ */
18
+ export {};
package/index.d.ts ADDED
@@ -0,0 +1,4 @@
1
+ export * from './auth/FirebaseSessionFE.js';
2
+ export * from './ModuleFE_Firebase.js';
3
+ export * from './analytics/ModuleFE_Analytics.js';
4
+ export * from './messaging/MessagingWrapperFE.js';
package/index.js ADDED
@@ -0,0 +1,22 @@
1
+ /*
2
+ * Permissions management system, define access level for each of
3
+ * your server apis, and restrict users by giving them access levels
4
+ *
5
+ * Copyright (C) 2020 Adam van der Kruk aka TacB0sS
6
+ *
7
+ * Licensed under the Apache License, Version 2.0 (the "License");
8
+ * you may not use this file except in compliance with the License.
9
+ * You may obtain a copy of the License at
10
+ *
11
+ * http://www.apache.org/licenses/LICENSE-2.0
12
+ *
13
+ * Unless required by applicable law or agreed to in writing, software
14
+ * distributed under the License is distributed on an "AS IS" BASIS,
15
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16
+ * See the License for the specific language governing permissions and
17
+ * limitations under the License.
18
+ */
19
+ export * from './auth/FirebaseSessionFE.js';
20
+ export * from './ModuleFE_Firebase.js';
21
+ export * from './analytics/ModuleFE_Analytics.js';
22
+ export * from './messaging/MessagingWrapperFE.js';
@@ -0,0 +1,23 @@
1
+ import { Logger } from '@nu-art/ts-common';
2
+ import { FirebaseType_Unsubscribe } from './types.js';
3
+ import { GetTokenOptions, MessagePayload, NextFn, Observer } from 'firebase/messaging';
4
+ import { FirebaseApp } from 'firebase/app';
5
+ /**
6
+ Firebase Messaging wrapper
7
+ */
8
+ export declare class MessagingWrapperFE extends Logger {
9
+ private readonly messaging;
10
+ private callback?;
11
+ private token?;
12
+ /**
13
+ * Constructor for the MessagingWrapperFE class
14
+ * @param app
15
+ */
16
+ constructor(app: FirebaseApp);
17
+ getToken(options?: GetTokenOptions): Promise<string>;
18
+ /**
19
+ Deletes the current Firebase Messaging token for the client
20
+ */
21
+ deleteToken(): Promise<void>;
22
+ onMessage(callback: NextFn<MessagePayload> | Observer<MessagePayload>): FirebaseType_Unsubscribe | void;
23
+ }
@@ -0,0 +1,55 @@
1
+ /*
2
+ * Firebase is a simpler Typescript wrapper to all of firebase services.
3
+ *
4
+ * Copyright (C) 2020 Adam van der Kruk aka TacB0sS
5
+ *
6
+ * Licensed under the Apache License, Version 2.0 (the "License");
7
+ * you may not use this file except in compliance with the License.
8
+ * You may obtain a copy of the License at
9
+ *
10
+ * http://www.apache.org/licenses/LICENSE-2.0
11
+ *
12
+ * Unless required by applicable law or agreed to in writing, software
13
+ * distributed under the License is distributed on an "AS IS" BASIS,
14
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15
+ * See the License for the specific language governing permissions and
16
+ * limitations under the License.
17
+ */
18
+ import { Logger } from '@nu-art/ts-common';
19
+ import { deleteToken, getMessaging, getToken, onMessage } from 'firebase/messaging';
20
+ /**
21
+ Firebase Messaging wrapper
22
+ */
23
+ export class MessagingWrapperFE extends Logger {
24
+ messaging;
25
+ callback;
26
+ token;
27
+ /**
28
+ * Constructor for the MessagingWrapperFE class
29
+ * @param app
30
+ */
31
+ constructor(app) {
32
+ super();
33
+ this.messaging = getMessaging(app);
34
+ }
35
+ async getToken(options) {
36
+ this.token = await getToken(this.messaging, options);
37
+ if (this.callback)
38
+ this.onMessage(this.callback);
39
+ return this.token;
40
+ }
41
+ /**
42
+ Deletes the current Firebase Messaging token for the client
43
+ */
44
+ async deleteToken() {
45
+ this.logVerbose('Deleting firebase messaging token');
46
+ await deleteToken(this.messaging);
47
+ delete this.token;
48
+ }
49
+ onMessage(callback) {
50
+ this.callback = callback;
51
+ if (!this.token)
52
+ return;
53
+ return onMessage(this.messaging, callback);
54
+ }
55
+ }
@@ -0,0 +1,7 @@
1
+ import { Logger } from '@nu-art/ts-common';
2
+ import { FirebaseType_Messaging } from './types.js';
3
+ export declare class SwMessagingWrapperFE extends Logger {
4
+ private readonly messaging;
5
+ constructor(messaging: FirebaseType_Messaging);
6
+ onBackgroundMessage(callback: (payload: any) => void): void | import("firebase/messaging/sw").Unsubscribe;
7
+ }
@@ -0,0 +1,39 @@
1
+ /*
2
+ * Permissions management system, define access level for each of
3
+ * your server apis, and restrict users by giving them access levels
4
+ *
5
+ * Copyright (C) 2020 Adam van der Kruk aka TacB0sS
6
+ *
7
+ * Licensed under the Apache License, Version 2.0 (the "License");
8
+ * you may not use this file except in compliance with the License.
9
+ * You may obtain a copy of the License at
10
+ *
11
+ * http://www.apache.org/licenses/LICENSE-2.0
12
+ *
13
+ * Unless required by applicable law or agreed to in writing, software
14
+ * distributed under the License is distributed on an "AS IS" BASIS,
15
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16
+ * See the License for the specific language governing permissions and
17
+ * limitations under the License.
18
+ */
19
+ import { Logger } from '@nu-art/ts-common';
20
+ import { onBackgroundMessage } from 'firebase/messaging/sw';
21
+ export class SwMessagingWrapperFE extends Logger {
22
+ messaging;
23
+ constructor(messaging) {
24
+ super();
25
+ this.messaging = messaging;
26
+ }
27
+ onBackgroundMessage(callback) {
28
+ // This means that the bundle is being evaluated in the main thread to register the service worker so there is no need to run the rest
29
+ // Also because it would fail since firebase would initialize the messaging controller as the main thread one instead of the sw one...
30
+ if (!self || !('ServiceWorkerGlobalScope' in self))
31
+ return this.logWarning('Not a service worker context');
32
+ this.logInfo('This is a service worker context');
33
+ return onBackgroundMessage(this.messaging, {
34
+ next: callback,
35
+ error: error => this.logWarning(error),
36
+ complete: () => this.logInfo('Successfully set on background messaging')
37
+ });
38
+ }
39
+ }
@@ -0,0 +1,3 @@
1
+ import { Messaging, Unsubscribe } from 'firebase/messaging';
2
+ export type FirebaseType_Messaging = Messaging;
3
+ export type FirebaseType_Unsubscribe = Unsubscribe;
@@ -0,0 +1,18 @@
1
+ /*
2
+ * Firebase is a simpler Typescript wrapper to all of firebase services.
3
+ *
4
+ * Copyright (C) 2020 Adam van der Kruk aka TacB0sS
5
+ *
6
+ * Licensed under the Apache License, Version 2.0 (the "License");
7
+ * you may not use this file except in compliance with the License.
8
+ * You may obtain a copy of the License at
9
+ *
10
+ * http://www.apache.org/licenses/LICENSE-2.0
11
+ *
12
+ * Unless required by applicable law or agreed to in writing, software
13
+ * distributed under the License is distributed on an "AS IS" BASIS,
14
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15
+ * See the License for the specific language governing permissions and
16
+ * limitations under the License.
17
+ */
18
+ export {};
package/package.json ADDED
@@ -0,0 +1,74 @@
1
+ {
2
+ "name": "@nu-art/firebase-frontend",
3
+ "version": "0.400.5",
4
+ "description": "Storm - Express & Typescript based backend framework Frontend",
5
+ "keywords": [
6
+ "TacB0sS",
7
+ "infra",
8
+ "nu-art",
9
+ "storm",
10
+ "thunderstorm",
11
+ "typescript"
12
+ ],
13
+ "homepage": "https://github.com/nu-art-js/firebase",
14
+ "bugs": {
15
+ "url": "https://github.com/nu-art-js/firebase/issues"
16
+ },
17
+ "repository": {
18
+ "type": "git",
19
+ "url": "git+ssh://git@github.com:nu-art-js/firebase.git"
20
+ },
21
+ "publishConfig": {
22
+ "directory": "dist",
23
+ "linkDirectory": true
24
+ },
25
+ "license": "Apache-2.0",
26
+ "author": "TacB0sS",
27
+ "files": [
28
+ "**/*"
29
+ ],
30
+ "scripts": {
31
+ "build": "tsc",
32
+ "run-tests": "firebase emulators:exec \"npm run test\"",
33
+ "test": "ts-mocha -w -p src/test/tsconfig.json --timeout 0 --inspect=8107 --watch-files '**/*.ts' src/test/firestore-v2/__test.ts",
34
+ "rtv2": "firebase emulators:exec \"npm run test-v2\"",
35
+ "test-v2": "ts-mocha -w -p src/test/tsconfig.json --timeout 0 --inspect=8107 --watch-files '**/*.ts' src/test/firestore-v2/__test.ts"
36
+ },
37
+ "dependencies": {
38
+ "@nu-art/firebase-shared": "0.400.5",
39
+ "@google-cloud/common": "^5.0.2",
40
+ "@google-cloud/firestore": "^7.11.0",
41
+ "@google-cloud/storage": "^7.15.0",
42
+ "@nu-art/ts-common": "0.400.5",
43
+ "express": "^4.18.2",
44
+ "firebase": "^11.9.0",
45
+ "firebase-admin": "13.4.0",
46
+ "firebase-functions": "6.3.2",
47
+ "google-auth-library": "^10.0.0",
48
+ "http-proxy": "1.18.1",
49
+ "url": "0.11.3",
50
+ "ws": "^8.13.0"
51
+ },
52
+ "devDependencies": {
53
+ "@types/compression": "^1.0.1",
54
+ "@types/chai": "^4.3.4",
55
+ "@types/mocha": "^10.0.1",
56
+ "@types/http-proxy": "1.17.14",
57
+ "teeny-request": "~7.2.0",
58
+ "@types/ws": "^8.5.5"
59
+ },
60
+ "unitConfig": {
61
+ "type": "typescript-lib"
62
+ },
63
+ "type": "module",
64
+ "exports": {
65
+ ".": {
66
+ "types": "./index.d.ts",
67
+ "import": "./index.js"
68
+ },
69
+ "./*": {
70
+ "types": "./*.d.ts",
71
+ "import": "./*.js"
72
+ }
73
+ }
74
+ }