diff --git a/packages/analytics/__tests__/analytics.test.ts b/packages/analytics/__tests__/analytics.test.ts index 61dc819059..0f360c813f 100644 --- a/packages/analytics/__tests__/analytics.test.ts +++ b/packages/analytics/__tests__/analytics.test.ts @@ -1,9 +1,9 @@ import { jest, afterAll, beforeAll, describe, expect, it, xit, beforeEach } from '@jest/globals'; // @ts-ignore test -import FirebaseModule from '../../app/lib/internal/FirebaseModule'; +import FirebaseModule from '@react-native-firebase/app/lib/internal/FirebaseModule'; -import { +import analytics, { firebase, getAnalytics, initializeAnalytics, @@ -65,7 +65,7 @@ import { import { createCheckV9Deprecation, CheckV9DeprecationFunction, -} from '../../app/lib/common/unitTestUtils'; +} from '@react-native-firebase/app/lib/common/unitTestUtils'; describe('Analytics', function () { describe('namespace', function () { @@ -707,6 +707,49 @@ describe('Analytics', function () { ); }); }); + + describe('TypeScript migration maintains existing `analytics()` exports', function () { + it('`analytics()` is properly exposed to end user', function () { + expect(analytics().logAddToCart).toBeDefined(); + expect(analytics().logAddPaymentInfo).toBeDefined(); + expect(analytics().logAddShippingInfo).toBeDefined(); + expect(analytics().logAddToWishlist).toBeDefined(); + expect(analytics().logAppOpen).toBeDefined(); + expect(analytics().logBeginCheckout).toBeDefined(); + expect(analytics().logCampaignDetails).toBeDefined(); + expect(analytics().logEarnVirtualCurrency).toBeDefined(); + expect(analytics().logEvent).toBeDefined(); + expect(analytics().logGenerateLead).toBeDefined(); + expect(analytics().logJoinGroup).toBeDefined(); + expect(analytics().logLevelEnd).toBeDefined(); + expect(analytics().logLevelStart).toBeDefined(); + expect(analytics().logLevelUp).toBeDefined(); + expect(analytics().logLogin).toBeDefined(); + expect(analytics().logPostScore).toBeDefined(); + expect(analytics().logSelectContent).toBeDefined(); + expect(analytics().logSetCheckoutOption).toBeDefined(); + expect(analytics().logShare).toBeDefined(); + expect(analytics().logSignUp).toBeDefined(); + expect(analytics().logSpendVirtualCurrency).toBeDefined(); + expect(analytics().logTutorialBegin).toBeDefined(); + expect(analytics().logTutorialComplete).toBeDefined(); + expect(analytics().logUnlockAchievement).toBeDefined(); + expect(analytics().logViewItem).toBeDefined(); + expect(analytics().logViewItemList).toBeDefined(); + expect(analytics().resetAnalyticsData).toBeDefined(); + expect(analytics().logViewCart).toBeDefined(); + expect(analytics().setAnalyticsCollectionEnabled).toBeDefined(); + expect(analytics().logSelectPromotion).toBeDefined(); + expect(analytics().logScreenView).toBeDefined(); + expect(analytics().logViewPromotion).toBeDefined(); + expect(analytics().setSessionTimeoutDuration).toBeDefined(); + expect(analytics().setUserId).toBeDefined(); + expect(analytics().setUserProperties).toBeDefined(); + expect(analytics().logViewSearchResults).toBeDefined(); + expect(analytics().setUserProperty).toBeDefined(); + expect(analytics().setConsent).toBeDefined(); + }); + }); }); describe('modular', function () { diff --git a/packages/analytics/index.d.ts b/packages/analytics/index.d.ts new file mode 100644 index 0000000000..11aece60c4 --- /dev/null +++ b/packages/analytics/index.d.ts @@ -0,0 +1 @@ +export * from './lib/index'; diff --git a/packages/analytics/lib/index.d.ts b/packages/analytics/lib/index.d.ts deleted file mode 100644 index 2267bd9813..0000000000 --- a/packages/analytics/lib/index.d.ts +++ /dev/null @@ -1,1903 +0,0 @@ -/* - * Copyright (c) 2016-present Invertase Limited & Contributors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this library except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -import { ReactNativeFirebase } from '@react-native-firebase/app'; - -/** - * Firebase Analytics package for React Native. - * - * #### Example: Access the firebase export from the `analytics` package: - * - * ```js - * import { firebase } from '@react-native-firebase/analytics'; - * - * // firebase.analytics().X - * ``` - * - * #### Example: Using the default export from the `analytics` package: - * - * ```js - * import analytics from '@react-native-firebase/analytics'; - * - * // analytics().X - * ``` - * - * #### Example: Using the default export from the `app` package: - * - * ```js - * import firebase from '@react-native-firebase/app'; - * import '@react-native-firebase/analytics'; - * - * // firebase.analytics().X - * ``` - * - * @firebase analytics - */ -export namespace FirebaseAnalyticsTypes { - import FirebaseModule = ReactNativeFirebase.FirebaseModule; - - export interface Item { - /** - * The item's brand. - */ - item_brand?: string; - /** - * An item ID. - */ - item_id?: string; - /** - * An item name. - */ - item_name?: string; - /** - * First class item category. - */ - item_category?: string; - /** - * Second class item category. - */ - item_category2?: string; - /** - * Third class item category. - */ - item_category3?: string; - /** - * Fourth class item category. - */ - item_category4?: string; - /** - * Fifth class item category. - */ - item_category5?: string; - /** - * The ID of the list in which the item was presented to the user. - */ - item_list_id?: string; - /** - * The name of the list in which the item was presented to the user. - */ - item_list_name?: string; - /** - * The Google [Place ID](https://developers.google.com/places/place-id) that corresponds to the associated item (String). Alternatively, you can supply your own custom Location ID. - */ - location_id?: string; - /** - * The Item variant. - */ - item_variant?: string; - /** - * The Item quantity. - */ - quantity?: number; - /** - * The Item price. - * Note that firebase analytics will display this as an integer with trailing zeros, due to some firebase-internal conversion. - * See https://github.com/invertase/react-native-firebase/issues/4578#issuecomment-771703420 for more information - */ - price?: number; - /** - * The affiliation of the item. - */ - affiliation?: string; - /** - * The coupon associated with the item. - */ - coupon?: string; - /** - * The creative name associated with the item. - */ - creative_name?: string; - /** - * The creative slot associated with the item. - */ - creative_slot?: string; - /** - * The discount applied to the item. - */ - discount?: Currency; - /** - * The index of the item. - */ - index?: number; - /** - * The promotion ID associated with the item. - */ - promotion_id?: string; - /** - * The promotion name associated with the item. - */ - promotion_name?: string; - /** - * Custom event parameters. The parameter names can be up to 40 characters long and must start with an alphabetic character and contain only alphanumeric characters and underscores. String parameter values can be up to 100 characters long. - * The "firebase_", "google_" and "ga_" prefixes are reserved and should not be used for parameter names. - */ - [key: string]: string | number; - } - - export interface AddPaymentInfoEventParameters { - items?: Item[]; - /** - * Purchase currency in 3 letter [ISO_4217](https://en.wikipedia.org/wiki/ISO_4217#Active_codes) format. E.g. `USD`. - */ - currency?: string; - value?: number; - /** - * Coupon code for a purchasable item. - */ - coupon?: string; - /** - * The chosen method of payment - */ - payment_type?: string; - } - - export interface AddShippingInfoEventParameters { - items?: Item[]; - /** - * Purchase currency in 3 letter [ISO_4217](https://en.wikipedia.org/wiki/ISO_4217#Active_codes) format. E.g. `USD`. - */ - currency?: string; - value?: number; - /** - * Coupon code for a purchasable item. - */ - coupon?: string; - /** - * The shipping tier (e.g. Ground, Air, Next-day) selected for delivery of the purchased item - */ - shipping_tier?: string; - } - - export interface AddToCartEventParameters { - items?: Item[]; - /** - * Purchase currency in 3 letter [ISO_4217](https://en.wikipedia.org/wiki/ISO_4217#Active_codes) format. E.g. `USD`. - */ - currency?: string; - /** - * value of item - */ - value?: number; - } - - export interface AddToWishlistEventParameters { - items?: Item[]; - /** - * Purchase currency in 3 letter [ISO_4217](https://en.wikipedia.org/wiki/ISO_4217#Active_codes) format. E.g. `USD`. - */ - currency?: string; - value?: number; - } - - export interface BeginCheckoutEventParameters { - /** - * Purchase currency in 3 letter [ISO_4217](https://en.wikipedia.org/wiki/ISO_4217#Active_codes) format. E.g. `USD`. - */ - //TODO if value is a param, so must currency: https://firebase.google.com/docs/reference/android/com/google/firebase/analytics/FirebaseAnalytics.Event#public-static-final-string-add_to_wishlist - currency?: string; - value?: number; - /** - * Coupon code for a purchasable item. - */ - coupon?: string; - - items?: Item[]; - /** - * Custom event parameters. - */ - [key: string]: any; - } - - export interface CampaignDetailsEventParameters { - /** - * Used to identify a search engine, newsletter, or other source. - */ - source: string; - /** - * Used to identify a medium such as email or cost-per-click (cpc). - */ - medium: string; - /** - * Used for keyword analysis to identify a specific product promotion or strategic campaign. - */ - campaign: string; - /** - * Used with paid search to supply the keywords for ads. - */ - term?: string; - /** - * Used for A/B testing and content-targeted ads to differentiate ads or links that point to the same URL. - */ - content?: string; - /** - * A campaign detail click ID. - */ - aclid?: string; - cp1?: string; - } - - // - // Unsupported in "Enhanced Ecommerce reports": - // https://firebase.google.com/docs/reference/android/com/google/firebase/analytics/FirebaseAnalytics.Event#public-static-final-string-checkout_progress - // - // export interface CheckoutProgressEventParameters { - // checkout_step: string; - // checkout_options: string; - // } - - export interface EarnVirtualCurrencyEventParameters { - /** - * Name of virtual currency type. E.g. `gems`. - */ - virtual_currency_name: string; - /** - * A context-specific numeric value which is accumulated automatically for each event type. Values - * can include revenue, distance, time and points. - */ - value: number; - } - - export interface GenerateLeadEventParameters { - /** - * Purchase currency in 3 letter [ISO_4217](https://en.wikipedia.org/wiki/ISO_4217#Active_codes) format. E.g. `USD`. - */ - currency?: string; - /** - * A context-specific numeric value which is accumulated automatically for each event type. Values - * can include revenue, distance, time and points. When a value is set, the accompanying `currency` - * parameter should also be defined. - */ - value?: number; - } - - export interface JoinGroupEventParameters { - /** - * Group/clan/guild id. - */ - group_id: string; - } - - export interface LevelEndEventParameters { - /** - * Level in game. - */ - level: number; - /** - * The result of an operation. - */ - success?: string; - } - - export interface LevelStartEventParameters { - /** - * Level in game. - */ - level: number; - } - - export interface LevelUpEventParameters { - /** - * Level in game. - */ - level: number; - /** - * Character used in game. - */ - character?: string; - } - - export interface LoginEventParameters { - /** - * The login method. E.g. `facebook.com`. - */ - method: string; - } - - export interface PostScoreEventParameters { - /** - * Score in game. - */ - score: number; - /** - * Level in game. - */ - level?: number; - /** - * Character used in game. - */ - character?: string; - } - - export interface PurchaseEventParameters { - /** - * A product affiliation to designate a supplying company or brick and mortar store location - */ - affiliation?: string; - /** - * Coupon code for a purchasable item. - */ - coupon?: string; - /** - * Purchase currency in 3 letter [ISO_4217](https://en.wikipedia.org/wiki/ISO_4217#Active_codes) format. E.g. `USD`. - */ - currency?: string; - - items?: Item[]; - /** - * Shipping cost. - */ - shipping?: number; - /** - * Tax amount. - */ - tax?: number; - /** - * A context-specific numeric value which is accumulated automatically for each event type. Values - * can include revenue, distance, time and points. When a value is set, the accompanying `currency` - * parameter should also be defined. - */ - value?: number; - /** - * A single ID for a ecommerce group transaction. - */ - transaction_id?: string; - /** - * Custom event parameters. - */ - [key: string]: any; - } - - export interface ScreenViewParameters { - /** - * Screen name the user is currently viewing. - */ - screen_name?: string; - /** - * Current class associated with the view the user is currently viewing. - */ - screen_class?: string; - - /** - * Custom event parameters. - */ - [key: string]: any; - } - - export interface RefundEventParameters { - /** - * A product affiliation to designate a supplying company or brick and mortar store location - */ - affiliation?: string; - /** - * Coupon code for a purchasable item. - */ - coupon?: string; - /** - * Purchase currency in 3 letter [ISO_4217](https://en.wikipedia.org/wiki/ISO_4217#Active_codes) format. E.g. `USD`. - */ - currency?: string; - - items?: Item[]; - /** - * Shipping cost. - */ - shipping?: number; - /** - * Tax amount. - */ - tax?: number; - /** - * A context-specific numeric value which is accumulated automatically for each event type. Values - * can include revenue, distance, time and points. When a value is set, the accompanying `currency` - * parameter should also be defined. - */ - value?: number; - /** - * A single ID for a ecommerce group transaction. - */ - transaction_id?: string; - } - - export interface RemoveFromCartEventParameters { - items?: Item[]; - /** - * A context-specific numeric value which is accumulated automatically for each event type. Values - * can include revenue, distance, time and points. When a value is set, the accompanying `currency` - * parameter should also be defined. - */ - value?: number; - /** - * Purchase currency in 3 letter [ISO_4217](https://en.wikipedia.org/wiki/ISO_4217#Active_codes) format. E.g. `USD`. - x */ - currency?: string; - } - - export interface SearchEventParameters { - search_term: string; - /** - * Number of nights staying at hotel. - */ - number_of_nights?: number; - /** - * Number of rooms for travel events. - */ - number_of_rooms?: number; - /** - * Number of passengers traveling. - */ - number_of_passengers?: number; - /** - * Flight or Travel origin. E.g. `Mountain View, CA`. - */ - origin?: string; - /** - * Flight or Travel destination. E.g. `Mountain View, CA`. - */ - destination?: string; - /** - * The departure date, check-in date, or rental start date for the item (String). The parameter expects a date formatted as YYYY-MM-DD. - */ - start_date?: string; - /** - * The arrival date, check-out date, or rental end date for the item (String). The parameter expects a date formatted as YYYY-MM-DD. - */ - end_date?: string; - /** - * Travel class. E.g. `business`. - */ - travel_class?: string; - } - - export interface SelectContentEventParameters { - content_type: string; - /** - * An item ID. - */ - item_id: string; - } - - export interface SelectItemEventParameters { - items?: Item[]; - content_type: string; - /** - * The ID of the list in which the item was presented to the user - */ - item_list_id: string; - /** - * The name of the list in which the item was presented to the user - */ - item_list_name: string; - } - - export interface SetCheckoutOptionEventParameters { - checkout_step?: EventParams['checkout_step']; - checkout_option?: EventParams['checkout_option']; - - [key: string]: any; - } - - export interface SelectPromotionEventParameters { - /** - * The name of a creative used in a promotional spot - */ - creative_name: string; - /** - * The name of a creative slot - */ - creative_slot: string; - items?: Item[]; - /** - * The location associated with the event. Preferred to be the Google Place ID that corresponds to the associated item but could be overridden to a custom location ID string - */ - location_id: string; - /** - * The ID of a product promotion - */ - promotion_id: string; - /** - * The name of a product promotion - */ - promotion_name: string; - } - - export interface ShareEventParameters { - /** - * Type of content selected. - */ - content_type: string; - /** - * An item ID. - */ - item_id: string; - /** - * A particular approach used in an operation; for example, "facebook" or "email" in the context of a sign_up or login event. - */ - method: string; - } - - export interface SignUpEventParameters { - /** - * A particular approach used in an operation; for example, "facebook" or "email" in the context of a sign_up or login event. - */ - method: string; - } - - export interface SpendVirtualCurrencyEventParameters { - /** - * An item name. - */ - item_name: string; - /** - * Name of virtual currency type. E.g. `gems`. - */ - virtual_currency_name: string; - /** - * A context-specific numeric value which is accumulated automatically for each event type. Values - * can include revenue, distance, time and points. When a value is set, the accompanying `currency` - * parameter should also be defined. - */ - value: number; - } - - export interface UnlockAchievementEventParameters { - /** - * Game achievement ID (String). - */ - achievement_id: string; - } - - export interface ViewCartEventParameters { - items?: Item[]; - /** - * Purchase currency in 3 letter [ISO_4217](https://en.wikipedia.org/wiki/ISO_4217#Active_codes) format. E.g. `USD`. - */ - currency?: string; - /** - * A context-specific numeric value which is accumulated automatically for each event type. Values - * can include revenue, distance, time and points. When a value is set, the accompanying `currency` - * parameter should also be defined. - */ - value?: number; - } - - export interface ViewItemEventParameters { - items?: Item[]; - /** - * Purchase currency in 3 letter [ISO_4217](https://en.wikipedia.org/wiki/ISO_4217#Active_codes) format. E.g. `USD`. - */ - currency?: string; - /** - * A context-specific numeric value which is accumulated automatically for each event type. Values - * can include revenue, distance, time and points. When a value is set, the accompanying `currency` - * parameter should also be defined. - */ - value?: number; - } - - export interface ViewSearchResultsParameters { - /** - * The search string/keywords used. - */ - search_term: string; - } - - export interface ViewItemListEventParameters { - items?: Item[]; - /** - * The ID of the list in which the item was presented to the user - */ - item_list_id?: string; - /** - * The name of the list in which the item was presented to the user - */ - item_list_name?: string; - } - - export interface ViewPromotionEventParameters { - items?: Item[]; - /** - * The location associated with the event. Preferred to be the Google Place ID that corresponds to the associated item but could be overridden to a custom location ID string - */ - location_id?: string; - /** - * The name of a creative used in a promotional spot - */ - creative_name?: string; - /** - * The name of a creative slot - */ - creative_slot?: string; - /** - * The ID of a product promotion - */ - promotion_id?: string; - /** - * The name of a product promotion - */ - promotion_name?: string; - } - - export interface AddShippingInfoParameters { - items?: Item[]; - /** - * Purchase currency in 3 letter [ISO_4217](https://en.wikipedia.org/wiki/ISO_4217#Active_codes) format. E.g. `USD`. - */ - currency?: string; - /** - * A context-specific numeric value which is accumulated automatically for each event type. Values - * can include revenue, distance, time and points. When a value is set, the accompanying `currency` - * parameter should also be defined. - */ - value?: number; - /** - * Coupon code for a purchasable item. - */ - coupon?: string; - /** - * The shipping tier (e.g. Ground, Air, Next-day) selected for delivery of the purchased item - */ - shipping_tier?: string; - } - - /** - * Unsupported in "Enhanced Ecommerce reports": - * https://firebase.google.com/docs/reference/android/com/google/firebase/analytics/FirebaseAnalytics.Event#public-static-final-string-view_search_results - */ - // export interface ViewSearchResults { - // /** - // * The search string/keywords used. - // */ - // search_term: string; - // } - - // eslint-disable-next-line @typescript-eslint/no-empty-object-type - export interface Statics {} - - /** - * Analytics instance initialization options. Web only. - */ - export interface AnalyticsSettings { - config?: GtagConfigParams | EventParams; - } - - /** - * Additional options that can be passed to Analytics method calls such as logEvent. Web only. - */ - export interface AnalyticsCallOptions { - /** - * If true, this config or event call applies globally to all Google Analytics properties on the page. Web only. - */ - global: boolean; - } - - /** - * A set of common Google Analytics config settings recognized by gtag.js. Web only. - */ - export interface GtagConfigParams { - /** - * Whether or not a page view should be sent. - * If set to true (default), a page view is automatically sent upon initialization - * of analytics. - * See {@link https://developers.google.com/analytics/devguides/collection/ga4/page-view | Page views } - */ - send_page_view?: boolean; - /** - * The title of the page. - * See {@link https://developers.google.com/analytics/devguides/collection/ga4/page-view | Page views } - */ - page_title?: string; - /** - * The URL of the page. - * See {@link https://developers.google.com/analytics/devguides/collection/ga4/page-view | Page views } - */ - page_location?: string; - /** - * Defaults to `auto`. - * See {@link https://developers.google.com/analytics/devguides/collection/ga4/cookies-user-id | Cookies and user identification } - */ - cookie_domain?: string; - /** - * Defaults to 63072000 (two years, in seconds). - * See {@link https://developers.google.com/analytics/devguides/collection/ga4/cookies-user-id | Cookies and user identification } - */ - cookie_expires?: number; - /** - * Defaults to `_ga`. - * See {@link https://developers.google.com/analytics/devguides/collection/ga4/cookies-user-id | Cookies and user identification } - */ - cookie_prefix?: string; - /** - * If set to true, will update cookies on each page load. - * Defaults to true. - * See {@link https://developers.google.com/analytics/devguides/collection/ga4/cookies-user-id | Cookies and user identification } - */ - cookie_update?: boolean; - /** - * Appends additional flags to the cookie when set. - * See {@link https://developers.google.com/analytics/devguides/collection/ga4/cookies-user-id | Cookies and user identification } - */ - cookie_flags?: string; - /** - * If set to false, disables all advertising features with `gtag.js`. - * See {@link https://developers.google.com/analytics/devguides/collection/ga4/display-features | Disable advertising features } - */ - allow_google_signals?: boolean; - /** - * If set to false, disables all advertising personalization with `gtag.js`. - * See {@link https://developers.google.com/analytics/devguides/collection/ga4/display-features | Disable advertising features } - */ - allow_ad_personalization_signals?: boolean; - - [key: string]: unknown; - } - - /** - * Standard gtag.js event parameters. For more information, see the GA4 reference documentation. Web only. - */ - export interface EventParams { - checkout_option?: string; - checkout_step?: number; - item_id?: string; - content_type?: string; - coupon?: string; - currency?: string; - description?: string; - fatal?: boolean; - items?: Item[]; - method?: string; - number?: string; - promotions?: Promotion[]; - screen_name?: string; - /** - * Firebase-specific. Use to log a `screen_name` to Firebase Analytics. - */ - firebase_screen?: string; - /** - * Firebase-specific. Use to log a `screen_class` to Firebase Analytics. - */ - firebase_screen_class?: string; - search_term?: string; - shipping?: Currency; - tax?: Currency; - transaction_id?: string; - value?: number; - event_label?: string; - event_category?: string; - shipping_tier?: string; - item_list_id?: string; - item_list_name?: string; - promotion_id?: string; - promotion_name?: string; - payment_type?: string; - affiliation?: string; - page_title?: string; - page_location?: string; - page_path?: string; - - [key: string]: unknown; - } - - /** - * Consent status settings for each consent type. - * For more information, see - * {@link https://developers.google.com/tag-platform/tag-manager/templates/consent-apis - * | the GA4 reference documentation for consent state and consent types}. - */ - export interface ConsentSettings { - /** Enables storage, such as cookies, related to advertising */ - ad_storage?: boolean; - /** Sets consent for sending user data to Google for online advertising purposes */ - ad_user_data?: boolean; - /** Sets consent for personalized advertising */ - ad_personalization?: boolean; - /** Enables storage, such as cookies, related to analytics (for example, visit duration) */ - analytics_storage?: boolean; - /** - * Enables storage that supports the functionality of the website or app such as language settings - */ - functionality_storage?: boolean; - /** Enables storage related to personalization such as video recommendations */ - personalization_storage?: boolean; - /** - * Enables storage related to security such as authentication functionality, fraud prevention, - * and other user protection. - */ - security_storage?: ConsentStatusString; - - [key: string]: unknown; - } - - /** - * Specifies custom options for your Firebase Analytics instance. - * You must set these before initializing `firebase.analytics()`. - */ - export interface SettingsOptions { - /** Sets custom name for `gtag` function. */ - gtagName?: string; - /** Sets custom name for `dataLayer` array used by `gtag.js`. */ - dataLayerName?: string; - } - - /** - * The Firebase Analytics service interface. - * - * > This module is available for the default app only. - * - * #### Example - * - * Get the Analytics service for the default app: - * - * ```js - * const defaultAppAnalytics = firebase.analytics(); - * ``` - */ - export class Module extends FirebaseModule { - /** - * Log a custom event with optional params. Note that there are various limits that applied - * to event parameters (total parameter count, etc), but analytics applies the limits during - * cloud processing, the errors will not be seen as Promise rejections when you call logEvent. - * While integrating this API in your app you are strongly encouraged to enable - * [DebugView](https://firebase.google.com/docs/analytics/debugview) - - * any errors in your events will show up in the firebase web console with links to relevant documentation - * - * #### Example - * - * ```js - * await firebase.analytics().logEvent('product_view', { - * id: '1234', - * }); - * ``` - * - * > 100 characters is the maximum length for param key names. - * - * @param name Event name must not conflict with any Reserved Events. - * @param params Parameters to be sent and displayed with the event. - * @param options Additional options that can be passed. Web only. - */ - logEvent( - name: string, - params?: { [key: string]: any }, - options?: AnalyticsCallOptions, - ): Promise; - - /** - * If true, allows the device to collect analytical data and send it to - * Firebase. Useful for GDPR. - * - * #### Example - * - * ```js - * // Disable collection - * await firebase.analytics().setAnalyticsCollectionEnabled(false); - * ``` - * - * @param enabled A boolean value representing whether Analytics collection is enabled or disabled. Analytics collection is enabled by default. - */ - setAnalyticsCollectionEnabled(enabled: boolean): Promise; - - /** - * Sets the duration of inactivity that terminates the current session. - * - * #### Example - * - * ```js - * // 20 minutes - * await firebase.analytics().setMinimumSessionDuration(900000); - * ``` - * - * @param milliseconds The default value is 1800000 (30 minutes). - */ - setSessionTimeoutDuration(milliseconds?: number): Promise; - - /** - * Retrieve the app instance id of the application. - * - * #### Example - * - * ```js - * const appInstanceId = await firebase.analytics().getAppInstanceId(); - * ``` - * - * @returns Returns the app instance id or null on android if FirebaseAnalytics.ConsentType.ANALYTICS_STORAGE has been set to FirebaseAnalytics.ConsentStatus.DENIED and null on iOS if ConsentType.analyticsStorage has been set to ConsentStatus.denied. - */ - getAppInstanceId(): Promise; - - /** - * Retrieves the session id from the client. - * On iOS, Firebase SDK may return an error that is handled internally and may take many minutes to return a valid value. Check native debug logs for more details. - * - * #### Example - * - * ```js - * const sessionId = await firebase.analytics().getSessionId(); - * ``` - * - * @returns Returns the session id or null if session is expired, null on android if FirebaseAnalytics.ConsentType.ANALYTICS_STORAGE has been set to FirebaseAnalytics.ConsentStatus.DENIED and null on iOS if ConsentType.analyticsStorage has been set to ConsentStatus.denied. - */ - getSessionId(): Promise; - - /** - * Gives a user a unique identification. - * - * #### Example - * - * ```js - * // Set User - * await firebase.analytics().setUserId('123456789'); - * // Remove User - * await firebase.analytics().setUserId(null); - * ``` - * - * @param id Set to null to remove a previously assigned ID from analytics - * events - */ - setUserId(id: string | null): Promise; - - /** - * Sets a key/value pair of data on the current user. Each Firebase project can have up to 25 uniquely named (case-sensitive) user properties. - * - * #### Example - * - * ```js - * await firebase.analytics().setUserProperty('account_type', 'gold'); - * ``` - * - * @param name A user property identifier. - * @param value Set to null to remove a previously assigned ID from analytics events. - */ - setUserProperty(name: string, value: string | null): Promise; - - /** - * Sets multiple key/value pairs of data on the current user. Each Firebase project can have up to 25 uniquely named (case-sensitive) user properties. - * - * #### Example - * - * ```js - * await firebase.analytics().setUserProperties({ - * account_type: 'gold', - * account_name: 'Gold Badge', - * }); - * ``` - * - * > When you set user properties, be sure to never include personally identifiable information such as names, social security numbers, or email addresses, even in hashed form. - * - * @react-native-firebase - * @param properties Set a property value to null to remove it. - * @param options Additional options that can be passed. Web only. - */ - setUserProperties( - properties: { [key: string]: string | null }, - options?: AnalyticsCallOptions, - ): Promise; - - /** - * Clears all analytics data for this instance from the device and resets the app instance ID. - * - * #### Example - * - * ```js - * await firebase.analytics().resetAnalyticsData(); - * ``` - */ - resetAnalyticsData(): Promise; - - /** - * E-Commerce Purchase event. This event signifies that an item(s) was purchased by a user. Note: This is different from the in-app purchase event, which is reported - * automatically for Google Play-based apps. - * - * If you supply the `value` parameter, you must also supply the `currency` parameter so that revenue metrics can be computed accurately. - * - * Logged event name: `purchase` - * - * #### Example - * - * ```js - * await firebase.analytics().logPurchase({ - * value: 100, - * currency: 'usd', - * items: [{ - * item_brand: 'cool-shirt-brand', - * item_id: '23456', - * item_name: 'orange t-shirt', - * item_category: 'round necked t-shirts', - * }] - * }); - * ``` - */ - logPurchase(params: PurchaseEventParameters): Promise; - - /** - * Sets or clears the screen name and class the user is currently viewing - * - * #### Example - * - * ```js - * await firebase.analytics().logScreenView({ - * screen_class: 'ProductScreen', - * screen_name: 'ProductScreen', - * }); - * ``` - * - */ - logScreenView(params: ScreenViewParameters): Promise; - - /** - * Add Payment Info event. This event signifies that a user has submitted their payment information to your app. - * - * If you supply the `value` parameter, you must also supply the `currency` parameter so that revenue metrics can be computed accurately. - * - * Logged event name: `add_payment_info` - * - * #### Example - * - * ```js - * await firebase.analytics().logAddPaymentInfo({ - * value: 100, - * currency: 'usd', - * items: [{ - * item_brand: 'cool-shirt-brand', - * item_id: '23456', - * item_name: 'orange t-shirt', - * item_category: 'round necked t-shirts', - * }] - * }); - * ``` - */ - logAddPaymentInfo(params: AddPaymentInfoEventParameters): Promise; - - /** - * E-Commerce Add To Cart event. - * - * If you supply the `value` parameter, you must also supply the `currency` parameter so that revenue metrics can be computed accurately. - * - * Logged event name: `add_to_cart` - * - * #### Example - * - * ```js - * await firebase.analytics().logAddToCart({ - * value: 100, - * currency: 'usd', - * items: [{ - * item_brand: 'cool-shirt-brand', - * item_id: '23456', - * item_name: 'orange t-shirt', - * item_category: 'round necked t-shirts', - * }] - * }); - * ``` - * - * @param params See {@link analytics.AddToCartEventParameters}. - */ - logAddToCart(params: AddToCartEventParameters): Promise; - - /** - * E-Commerce Add To Wishlist event. This event signifies that an item was added to a wishlist. - * Use this event to identify popular gift items in your app. - * - * If you supply the `value` parameter, you must also supply the `currency` parameter so that revenue metrics can be computed accurately. - * - * Logged event name: `add_to_wishlist` - * - * #### Example - * - * ```js - * await firebase.analytics().logAddToWishlist({ - * value: 100, - * currency: 'usd', - * items: [{ - * item_brand: 'cool-shirt-brand', - * item_id: '23456', - * item_name: 'orange t-shirt', - * item_category: 'round necked t-shirts', - * }] - * }); - * ``` - * - * @param params See {@link analytics.AddToWishlistEventParameters}. - */ - logAddToWishlist(params: AddToWishlistEventParameters): Promise; - - /** - * E-Commerce Add Shipping Info event. This event signifies that a user has submitted their shipping information. - * Use this event to identify popular gift items in your app. - * - * If you supply the `value` parameter, you must also supply the `currency` parameter so that revenue metrics can be computed accurately. - * - * Logged event name: `add_shipping_info` - * - * #### Example - * - * ```js - * await firebase.analytics().logAddShippingInfo({ - * value: 100, - * currency: 'usd', - * items: [{ - * item_brand: 'cool-shirt-brand', - * item_id: '23456', - * item_name: 'orange t-shirt', - * item_category: 'round necked t-shirts', - * }] - * }); - * ``` - * - * @param params See {@link analytics.AddShippingInfoParameters}. - */ - logAddShippingInfo(params: AddShippingInfoParameters): Promise; - - /** - * App Open event. By logging this event when an App is moved to the foreground, developers can - * understand how often users leave and return during the course of a Session. Although Sessions - * are automatically reported, this event can provide further clarification around the continuous - * engagement of app-users. - * - * Logged event name: `app_open` - * - * #### Example - * - * ```js - * await firebase.analytics().logAppOpen(); - * ``` - */ - logAppOpen(): Promise; - - /** - * E-Commerce Begin Checkout event. This event signifies that a user has begun the process of - * checking out. - * - * If you supply the `value` parameter, you must also supply the `currency` parameter so that revenue metrics can be computed accurately. - * - * Logged event name: `begin_checkout` - * - * #### Example - * - * ```js - * await firebase.analytics().logBeginCheckout({ - * value: 100, - * currency: 'usd', - * items: [{ - * item_brand: 'cool-shirt-brand', - * item_id: '23456', - * item_name: 'orange t-shirt', - * item_category: 'round necked t-shirts', - * }] - * }); - * ``` - * - * @param params See {@link analytics.BeginCheckoutEventParameters}. - */ - logBeginCheckout(params?: BeginCheckoutEventParameters): Promise; - - /** - * Log this event to supply the referral details of a re-engagement campaign. - * - * Logged event name: `campaign_details` - * - * #### Example - * - * ```js - * await firebase.analytics().logCampaignDetails({ - * source: 'email', - * medium: 'cta_button', - * campaign: 'newsletter', - * }); - * ``` - * - * @param params See {@link analytics.CampaignDetailsEventParameters}. - */ - logCampaignDetails(params: CampaignDetailsEventParameters): Promise; - - /** - * View Promotion event. This event signifies that a promotion was shown to a user. - * - * Logged event name: `view_promotion` - * - * #### Example - * - * ```js - * await firebase.analytics().logViewPromotion({ - * creative_name: 'the promotion', - * creative_slot: 'evening', - * location_id: 'london', - * promotion_id: '230593', - * promotion_name: 'london evening event', - * }); - * ``` - * - * @param params See {@link analytics.ViewPromotionEventParameters}. - */ - logViewPromotion(params: ViewPromotionEventParameters): Promise; - - /** - * Earn Virtual Currency event. This event tracks the awarding of virtual currency in your app. Log this along with - * {@link analytics.logSpendVirtualCurrency} to better understand your virtual economy. - * - * Logged event name: `earn_virtual_currency` - * - * #### Example - * - * ```js - * await firebase.analytics().logEarnVirtualCurrency({ - * virtual_currency_name: 'coins', - * value: 100, - * }); - * ``` - * - * @param params See {@link analytics.EarnVirtualCurrencyEventParameters}. - */ - logEarnVirtualCurrency(params: EarnVirtualCurrencyEventParameters): Promise; - - /** - * Generate Lead event. Log this event when a lead has been generated in the app to understand - * the efficacy of your install and re-engagement campaigns. - * - * If you supply the `value` parameter, you must also supply the `currency` parameter so that revenue metrics can be computed accurately. - * - * Logged event name: `generate_lead` - * - * #### Example - * - * ```js - * await firebase.analytics().logGenerateLead({ - * currency: 'USD', - * value: 123, - * }); - * ``` - * - * @param params See {@link analytics.GenerateLeadEventParameters}. - */ - logGenerateLead(params?: GenerateLeadEventParameters): Promise; - - /** - * Join Group event. Log this event when a user joins a group such as a guild, team or family. - * Use this event to analyze how popular certain groups or social features are in your app - * - * Logged event name: `join_group` - * - * #### Example - * - * ```js - * await firebase.analytics().logJoinGroup({ - * group_id: '12345', - * }); - * ``` - * - * @param params See {@link analytics.JoinGroupEventParameters}. - */ - logJoinGroup(params: JoinGroupEventParameters): Promise; - - /** - * Level End event. - * - * Logged event name: `level_end` - * - * #### Example - * - * ```js - * await firebase.analytics().logLevelEnd({ - * level: 12, - * success: 'true' - * }); - * ``` - * - * @param params See {@link analytics.LevelEndEventParameters}. - */ - logLevelEnd(params: LevelEndEventParameters): Promise; - - /** - * Level Start event. - * - * Logged event name: `level_start` - * - * #### Example - * - * ```js - * await firebase.analytics().logLevelStart({ - * level: 12, - * }); - * ``` - * - * @param params See {@link analytics.LevelStartEventParameters}. - */ - logLevelStart(params: LevelStartEventParameters): Promise; - - /** - * Level Up event. This event signifies that a player has leveled up in your gaming app. - * It can help you gauge the level distribution of your userbase and help you identify certain levels that are difficult to pass. - * - * Logged event name: `level_up` - * - * #### Example - * - * ```js - * await firebase.analytics().logLevelUp({ - * level: 12, - * character: 'Snake', - * }); - * ``` - * - * @param params See {@link analytics.LevelUpEventParameters}. - */ - logLevelUp(params: LevelUpEventParameters): Promise; - - /** - * Login event. Apps with a login feature can report this event to signify that a user has logged in. - * - * Logged event name: `login` - * - * #### Example - * - * ```js - * await firebase.analytics().logLogin({ - * method: 'facebook.com', - * }); - * ``` - * - * @param params See {@link analytics.LoginEventParameters}. - */ - logLogin(params: LoginEventParameters): Promise; - - /** - * Post Score event. Log this event when the user posts a score in your gaming app. This event can - * help you understand how users are actually performing in your game and it can help you correlate - * high scores with certain audiences or behaviors. - * - * Logged event name: `post_score` - * - * #### Example - * - * ```js - * await firebase.analytics().logPostScore({ - * score: 567334, - * level: 3, - * character: 'Pete', - * }); - * ``` - * - * @param params See {@link analytics.PostScoreEventParameters}. - */ - logPostScore(params: PostScoreEventParameters): Promise; - - /** - * Remove from cart event. - * - * Logged event name: `remove_from_cart` - * - * #### Example - * - * ```js - * await firebase.analytics().logRemoveFromCart({ - * value: 100, - * currency: 'usd', - * items: [{ - * item_brand: 'cool-shirt-brand', - * item_id: '23456', - * item_name: 'orange t-shirt', - * item_category: 'round necked t-shirts', - * }] - * }); - * ``` - * - * @param params See {@link analytics.RemoveFromCartEventParameters}. - */ - logRemoveFromCart(params: RemoveFromCartEventParameters): Promise; - - /** - * E-Commerce Refund event. This event signifies that a refund was issued. - * - * Logged event name: `remove_from_cart` - * - * #### Example - * - * ```js - * await firebase.analytics().logRefund({ - * value: 100, - * currency: 'usd', - * items: [{ - * item_brand: 'cool-shirt-brand', - * item_id: '23456', - * item_name: 'orange t-shirt', - * item_category: 'round necked t-shirts', - * }] - * }); - * ``` - * - * @param params See {@link analytics.RefundEventParameters}. - */ - logRefund(params: RefundEventParameters): Promise; - - /** - * Search event. Apps that support search features can use this event to contextualize search - * operations by supplying the appropriate, corresponding parameters. This event can help you - * identify the most popular content in your app. - * - * Logged event name: `search` - * - * #### Example - * - * ```js - * await firebase.analytics().logSearch({ - * search_term: 't-shirts', - * }); - * ``` - * - * @param params See {@link analytics.SearchEventParameters}. - */ - logSearch(params: SearchEventParameters): Promise; - - /** - * Select Content event. This general purpose event signifies that a user has selected some - * content of a certain type in an app. The content can be any object in your app. This event - * can help you identify popular content and categories of content in your app. - * - * Logged event name: `select_content` - * - * #### Example - * - * ```js - * await firebase.analytics().logSelectContent({ - * content_type: 'clothing', - * item_id: 'abcd', - * }); - * ``` - * - * @param params See {@link analytics.SelectContentEventParameters}. - */ - logSelectContent(params: SelectContentEventParameters): Promise; - - /** - * Select Item event. This event signifies that an item was selected by a user from a list. - * Use the appropriate parameters to contextualize the event. - * Use this event to discover the most popular items selected. - * - * Logged event name: `select_item` - * - * #### Example - * - * ```js - * await firebase.analytics().logSelectItem({ - * item_list_id: '54690834', - * item_list_name: 't-shirts', - * items: [{ - * item_brand: 'cool-shirt-brand', - * item_id: '23456', - * item_name: 'orange t-shirt', - * item_category: 'round necked t-shirts', - * }] - * }); - * ``` - * - * @param params See {@link analytics.SelectItemEventParameters}. - */ - logSelectItem(params: SelectItemEventParameters): Promise; - - /** - * Set checkout option event. - * - * Logged event name: `set_checkout_option` - * - * #### Example - * - * ```js - * await firebase.analytics().logSetCheckoutOption({ - * checkout_step: 2, - * checkout_option: 'false', - * }); - * ``` - * - * @param params See {@link analytics.SetCheckoutOptionEventParameters}. - */ - logSetCheckoutOption(params: any): Promise; - - /** - * Share event. Apps with social features can log the Share event to identify the most viral content. - * - * Logged event name: `share` - * - * #### Example - * - * ```js - * await firebase.analytics().logShare({ - * content_type: 't-shirts', - * item_id: '12345', - * method: 'twitter.com', - * }); - * ``` - * - * @param params See {@link analytics.ShareEventParameters}. - */ - logShare(params: ShareEventParameters): Promise; - - /** - * Sign Up event. This event indicates that a user has signed up for an account in your app. - * The parameter signifies the method by which the user signed up. Use this event to understand - * the different behaviors between logged in and logged out users. - * - * Logged event name: `sign_up` - * - * #### Example - * - * ```js - * await firebase.analytics().logSignUp({ - * method: 'facebook.com', - * }); - * ``` - * - * @param params See {@link analytics.SignUpEventParameters}. - */ - logSignUp(params: SignUpEventParameters): Promise; - - /** - * Spend Virtual Currency event. This event tracks the sale of virtual goods in your app and can - * help you identify which virtual goods are the most popular objects of purchase. - * - * Logged event name: `spend_virtual_currency` - * - * #### Example - * - * ```js - * await firebase.analytics().logSpendVirtualCurrency({ - * item_name: 'battle_pass', - * virtual_currency_name: 'coins', - * value: 100, - * }); - * ``` - * - * @param params See {@link analytics.SpendVirtualCurrencyEventParameters}. - */ - logSpendVirtualCurrency(params: SpendVirtualCurrencyEventParameters): Promise; - - /** - * Tutorial Begin event. This event signifies the start of the on-boarding process in your app. - * Use this in a funnel with {@link analytics#logTutorialComplete} to understand how many users - * complete this process and move on to the full app experience. - * - * Logged event name: `tutorial_begin` - * - * #### Example - * - * ```js - * await firebase.analytics().logTutorialBegin(); - * ``` - */ - logTutorialBegin(): Promise; - - /** - * Tutorial End event. Use this event to signify the user's completion of your app's on-boarding process. - * Add this to a funnel with {@link analytics#logTutorialBegin} to understand how many users - * complete this process and move on to the full app experience. - * - * Logged event name: `tutorial_complete` - * - * #### Example - * - * ```js - * await firebase.analytics().logTutorialComplete(); - * ``` - */ - logTutorialComplete(): Promise; - - /** - * Select promotion event. This event signifies that a user has selected a promotion offer. Use the - * appropriate parameters to contextualize the event, such as the item(s) for which the promotion applies. - * - * Logged event name: `select_promotion` - * - * #### Example - * - * ```js - * await firebase.analytics().logSelectPromotion({ - * creative_name: 'the promotion', - * creative_slot: 'evening', - * location_id: 'london', - * promotion_id: '230593', - * promotion_name: 'london evening event', - * }); - * ``` - * @param params See {@link analytics.SelectPromotionEventParameters}. - */ - logSelectPromotion(params: SelectPromotionEventParameters): Promise; - - /** - * Unlock Achievement event. Log this event when the user has unlocked an achievement in your game. - * Since achievements generally represent the breadth of a gaming experience, this event can help - * you understand how many users are experiencing all that your game has to offer. - * - * Logged event name: `unlock_achievement` - * - * #### Example - * - * ```js - * await firebase.analytics().logUnlockAchievement({ - * achievement_id: '12345', - * }); - * ``` - * - * @param params See {@link analytics.UnlockAchievementEventParameters}. - */ - logUnlockAchievement(params: UnlockAchievementEventParameters): Promise; - - /** - * View Item event. This event signifies that some content was shown to the user. This content - * may be a product, a screen or just a simple image or text. Use the appropriate parameters - * to contextualize the event. Use this event to discover the most popular items viewed in your app. - * - * If you supply the `value` parameter, you must also supply the `currency` parameter so that revenue metrics can be computed accurately. - * - * Logged event name: `view_item` - * - * #### Example - * - * ```js - * await firebase.analytics().logViewItem({ - * value: 100, - * currency: 'usd', - * items: [{ - * item_brand: 'cool-shirt-brand', - * item_id: '23456', - * item_name: 'orange t-shirt', - * item_category: 'round necked t-shirts', - * }] - * }); - * ``` - * - * @param params See {@link analytics.ViewItemEventParameters}. - */ - logViewItem(params: ViewItemEventParameters): Promise; - - /** - * E-commerce View Cart event. This event signifies that a user has viewed their cart. Use this to analyze your purchase funnel. - * - * If you supply the `value` parameter, you must also supply the `currency` parameter so that revenue metrics can be computed accurately. - * - * Logged event name: `view_cart` - * - * #### Example - * - * ```js - * await firebase.analytics().logViewCart({ - * value: 100, - * currency: 'usd', - * items: [{ - * item_brand: 'cool-shirt-brand', - * item_id: '23456', - * item_name: 'orange t-shirt', - * item_category: 'round necked t-shirts', - * }] - * }); - * ``` - * - * @param params See {@link analytics.ViewCartEventParameters}. - */ - logViewCart(params: ViewCartEventParameters): Promise; - - /** - * View Item List event. Log this event when the user has been presented with a list of items of a certain category. - * - * Logged event name: `view_item_list` - * - * #### Example - * - * ```js - * await firebase.analytics().logViewItemList({ - * item_list_name: 't-shirts', - * }); - * ``` - * - * @param params See {@link analytics.ViewItemListEventParameters}. - */ - logViewItemList(params: ViewItemListEventParameters): Promise; - - /** - * View Search Results event. Log this event when the user has been presented with the results of a search. - * - * Logged event name: `view_search_results` - * - * #### Example - * - * ```js - * await firebase.analytics().logViewSearchResults({ - * search_term: 'clothing', - * }); - * ``` - * - * @param params See {@link analytics.ViewSearchResultsParameters}. - */ - logViewSearchResults(params: ViewSearchResultsParameters): Promise; - - /** - * Adds parameters that will be set on every event logged from the SDK, including automatic ones. - * - * #### Example - * - * ```js - * await firebase.analytics().setDefaultEventParameters({ - * userId: '1234', - * }); - * ``` - * - * - * @param params Parameters to be added to the map of parameters added to every event. - * They will be added to the map of default event parameters, replacing any existing - * parameter with the same name. Valid parameter values are String, long, and double. - * Setting a key's value to null will clear that parameter. Passing in a null bundle - * will clear all parameters. - */ - setDefaultEventParameters(params?: { [key: string]: any }): Promise; - - /** - * Start privacy-sensitive on-device conversion management. - * This is iOS-only. - * This is a no-op if you do not include '$RNFirebaseAnalyticsGoogleAppMeasurementOnDeviceConversion = true' in your Podfile. - * - * @platform ios - * @param emailAddress email address, properly formatted complete with domain name e.g, 'user@example.com' - */ - initiateOnDeviceConversionMeasurementWithEmailAddress(emailAddress: string): Promise; - - /** - * Start privacy-sensitive on-device conversion management. - * This is iOS-only. - * This is a no-op if you do not include '$RNFirebaseAnalyticsGoogleAppMeasurementOnDeviceConversion = true' in your Podfile. - * You need to pass the sha256-hashed of normalized email address to this function. See [this link](https://firebase.google.com/docs/tutorials/ads-ios-on-device-measurement/step-3#use-hashed-credentials) for more information. - * - * @platform ios - * @param hashedEmailAddress sha256-hashed of normalized email address, properly formatted complete with domain name e.g, 'user@example.com' - */ - initiateOnDeviceConversionMeasurementWithHashedEmailAddress( - hashedEmailAddress: string, - ): Promise; - - /** - * Start privacy-sensitive on-device conversion management. - * This is iOS-only. - * This is a no-op if you do not include '$RNFirebaseAnalyticsGoogleAppMeasurementOnDeviceConversion = true' in your Podfile. - * - * @platform ios - * @param phoneNumber phone number in E.164 format - that is a leading + sign, then up to 15 digits, no dashes or spaces. - */ - initiateOnDeviceConversionMeasurementWithPhoneNumber(phoneNumber: string): Promise; - - /** - * Start privacy-sensitive on-device conversion management. - * This is iOS-only. - * This is a no-op if you do not include '$RNFirebaseAnalyticsGoogleAppMeasurementOnDeviceConversion = true' in your Podfile. - * You need to pass the sha256-hashed of phone number in E.164 format. See [this link](https://firebase.google.com/docs/tutorials/ads-ios-on-device-measurement/step-3#use-hashed-credentials) for more information. - * - * @platform ios - * @param hashedPhoneNumber sha256-hashed of normalized phone number in E.164 format - that is a leading + sign, then up to 15 digits, no dashes or spaces. - */ - initiateOnDeviceConversionMeasurementWithHashedPhoneNumber( - hashedPhoneNumber: string, - ): Promise; - - /** - * For Consent Mode! - * - * #### Example - * - * ```js - * // Disable consent - * await firebase.analytics().setConsent({ - * ad_personalization: false, - * analytics_storage: false, - * ad_storage: false, - * ad_user_data: false, - * }); - * ``` - * - * Sets the applicable end user consent state (e.g., for device identifiers) for this app on this device. - * Use the consent map to specify individual consent type values. - * Settings are persisted across app sessions. - * @param consentSettings Consent status settings for each consent type. - */ - setConsent(consentSettings: ConsentSettings): Promise; - } - - /** - * Any custom event name string not in the standard list of recommended event names. - */ - export declare type CustomEventName = T extends EventNameString ? never : T; - /** - * Type for standard Google Analytics event names. logEvent also accepts any custom string and interprets it as a custom event name. - * See https://firebase.google.com/docs/reference/js/analytics.md#eventnamestring - */ - export declare type EventNameString = - | 'add_payment_info' - | 'add_shipping_info' - | 'add_to_cart' - | 'add_to_wishlist' - | 'begin_checkout' - | 'checkout_progress' - | 'exception' - | 'generate_lead' - | 'login' - | 'page_view' - | 'purchase' - | 'refund' - | 'remove_from_cart' - | 'screen_view' - | 'search' - | 'select_content' - | 'select_item' - | 'select_promotion' - | 'set_checkout_option' - | 'share' - | 'sign_up' - | 'timing_complete' - | 'view_cart' - | 'view_item' - | 'view_item_list' - | 'view_promotion' - | 'view_search_results'; -} - -declare const defaultExport: ReactNativeFirebase.FirebaseModuleWithStatics< - FirebaseAnalyticsTypes.Module, - FirebaseAnalyticsTypes.Statics ->; - -export const firebase: ReactNativeFirebase.Module & { - analytics: typeof defaultExport; - app( - name?: string, - ): ReactNativeFirebase.FirebaseApp & { analytics(): FirebaseAnalyticsTypes.Module }; -}; - -export * from './modular'; - -export default defaultExport; - -/** - * Attach namespace to `firebase.` and `FirebaseApp.`. - */ -declare module '@react-native-firebase/app' { - namespace ReactNativeFirebase { - import FirebaseModuleWithStatics = ReactNativeFirebase.FirebaseModuleWithStatics; - - interface Module { - analytics: FirebaseModuleWithStatics< - FirebaseAnalyticsTypes.Module, - FirebaseAnalyticsTypes.Statics - >; - } - - interface FirebaseApp { - analytics(): FirebaseAnalyticsTypes.Module; - } - } -} diff --git a/packages/analytics/lib/index.ts b/packages/analytics/lib/index.ts new file mode 100644 index 0000000000..a2eeeddc5c --- /dev/null +++ b/packages/analytics/lib/index.ts @@ -0,0 +1,6 @@ +import defaultExport from './namespaced'; + +export * from './modular'; +export * from './namespaced'; + +export default defaultExport; diff --git a/packages/analytics/lib/modular/index.js b/packages/analytics/lib/modular.ts similarity index 59% rename from packages/analytics/lib/modular/index.js rename to packages/analytics/lib/modular.ts index 90e0138551..de3a67d25d 100644 --- a/packages/analytics/lib/modular/index.js +++ b/packages/analytics/lib/modular.ts @@ -1,54 +1,57 @@ -import { MODULAR_DEPRECATION_ARG } from '../../../app/lib/common'; +import { MODULAR_DEPRECATION_ARG } from '@react-native-firebase/app/lib/common'; +import type { FirebaseAnalyticsModule } from './namespaced'; import { getApp } from '@react-native-firebase/app'; import { Platform } from 'react-native'; - -/** - * @typedef {import('@firebase/app').FirebaseApp} FirebaseApp - * @typedef {import("..").FirebaseAnalyticsTypes.Module} FirebaseAnalytics - * @typedef {import("..").FirebaseAnalyticsTypes.AnalyticsCallOptions} AnalyticsCallOptions - * @typedef {import("..").FirebaseAnalyticsTypes.EventParams} EventParams - * @typedef {import("..").FirebaseAnalyticsTypes.AddPaymentInfoEventParameters} AddPaymentInfoEventParameters - * @typedef {import("..").FirebaseAnalyticsTypes.ScreenViewParameters} ScreenViewParameters - * @typedef {import("..").FirebaseAnalyticsTypes.AddShippingInfoParameters} AddShippingInfoParameters - * @typedef {import("..").FirebaseAnalyticsTypes.AddToCartEventParameters} AddToCartEventParameters - * @typedef {import("..").FirebaseAnalyticsTypes.AddToWishlistEventParameters} AddToWishlistEventParameters - * @typedef {import("..").FirebaseAnalyticsTypes.BeginCheckoutEventParameters} BeginCheckoutEventParameters - * @typedef {import("..").FirebaseAnalyticsTypes.CampaignDetailsEventParameters} CampaignDetailsEventParameters - * @typedef {import("..").FirebaseAnalyticsTypes.EarnVirtualCurrencyEventParameters} EarnVirtualCurrencyEventParameters - * @typedef {import("..").FirebaseAnalyticsTypes.GenerateLeadEventParameters} GenerateLeadEventParameters - * @typedef {import("..").FirebaseAnalyticsTypes.JoinGroupEventParameters} JoinGroupEventParameters - * @typedef {import("..").FirebaseAnalyticsTypes.LevelEndEventParameters} LevelEndEventParameters - * @typedef {import("..").FirebaseAnalyticsTypes.LevelStartEventParameters} LevelStartEventParameters - * @typedef {import("..").FirebaseAnalyticsTypes.LevelUpEventParameters} LevelUpEventParameters - * @typedef {import("..").FirebaseAnalyticsTypes.LoginEventParameters} LoginEventParameters - * @typedef {import("..").FirebaseAnalyticsTypes.PostScoreEventParameters} PostScoreEventParameters - * @typedef {import("..").FirebaseAnalyticsTypes.SelectContentEventParameters} SelectContentEventParameters - * @typedef {import("..").FirebaseAnalyticsTypes.PurchaseEventParameters} PurchaseEventParameters - * @typedef {import("..").FirebaseAnalyticsTypes.RefundEventParameters} RefundEventParameters - * @typedef {import("..").FirebaseAnalyticsTypes.RemoveFromCartEventParameters} RemoveFromCartEventParameters - * @typedef {import("..").FirebaseAnalyticsTypes.SearchEventParameters} SearchEventParameters - * @typedef {import("..").FirebaseAnalyticsTypes.SelectItemEventParameters} SelectItemEventParameters - * @typedef {import("..").FirebaseAnalyticsTypes.SetCheckoutOptionEventParameters} SetCheckoutOptionEventParameters - * @typedef {import("..").FirebaseAnalyticsTypes.SelectPromotionEventParameters} SelectPromotionEventParameters - * @typedef {import("..").FirebaseAnalyticsTypes.ShareEventParameters} ShareEventParameters - * @typedef {import("..").FirebaseAnalyticsTypes.SignUpEventParameters} SignUpEventParameters - * @typedef {import("..").FirebaseAnalyticsTypes.SpendVirtualCurrencyEventParameters} SpendVirtualCurrencyEventParameters - * @typedef {import("..").FirebaseAnalyticsTypes.UnlockAchievementEventParameters} UnlockAchievementEventParameters - * @typedef {import("..").FirebaseAnalyticsTypes.ViewCartEventParameters} ViewCartEventParameters - * @typedef {import("..").FirebaseAnalyticsTypes.ViewItemEventParameters} ViewItemEventParameters - * @typedef {import("..").FirebaseAnalyticsTypes.ViewItemListEventParameters} ViewItemListEventParameters - * @typedef {import("..").FirebaseAnalyticsTypes.ViewPromotionEventParameters} ViewPromotionEventParameters - * @typedef {import("..").FirebaseAnalyticsTypes.ViewSearchResultsParameters} ViewSearchResultsParameters - * @typedef {import("..").FirebaseAnalyticsTypes.ConsentSettings} ConsentSettings - * @typedef {import("..").FirebaseAnalyticsTypes.SettingsOptions} SettingsOptions - */ +import type { ReactNativeFirebase } from '@react-native-firebase/app'; +import type { + AnalyticsSettings, + AnalyticsCallOptions, + ConsentSettings, + AddPaymentInfoEventParameters, + ScreenViewParameters, + AddShippingInfoParameters, + AddToCartEventParameters, + AddToWishlistEventParameters, + BeginCheckoutEventParameters, + CampaignDetailsEventParameters, + EarnVirtualCurrencyEventParameters, + GenerateLeadEventParameters, + JoinGroupEventParameters, + LevelEndEventParameters, + LevelStartEventParameters, + LevelUpEventParameters, + LoginEventParameters, + PostScoreEventParameters, + SelectContentEventParameters, + PurchaseEventParameters, + RefundEventParameters, + RemoveFromCartEventParameters, + SearchEventParameters, + SelectItemEventParameters, + SetCheckoutOptionEventParameters, + SelectPromotionEventParameters, + ShareEventParameters, + SignUpEventParameters, + SpendVirtualCurrencyEventParameters, + UnlockAchievementEventParameters, + ViewCartEventParameters, + ViewItemEventParameters, + ViewItemListEventParameters, + ViewPromotionEventParameters, + ViewSearchResultsParameters, + SettingsOptions, +} from './types/analytics'; + +declare module '@react-native-firebase/app' { + function getApp( + name?: string, + ): ReactNativeFirebase.FirebaseApp & { analytics(): FirebaseAnalyticsModule }; +} /** * Returns an Analytics instance for the given app. - * @param {FirebaseApp} [app] - FirebaseApp. Optional. - * @returns {FirebaseAnalytics} */ -export function getAnalytics(app) { +export function getAnalytics(app?: ReactNativeFirebase.FirebaseApp): FirebaseAnalyticsModule { if (app) { return getApp(app.name).analytics(); } @@ -57,297 +60,294 @@ export function getAnalytics(app) { /** * Returns an Analytics instance for the given app. - * @param {FirebaseApp} app - FirebaseApp. - * @param {object} [options] - AnalyticsSettings. Web only. - * @returns {FirebaseAnalytics} */ -// eslint-disable-next-line -export function initializeAnalytics(app, options) { +export function initializeAnalytics( + app: ReactNativeFirebase.FirebaseApp, + _options?: AnalyticsSettings, +): FirebaseAnalyticsModule { return getApp(app.name).analytics(); } /** * Retrieves a unique Google Analytics identifier for the web client. - * - * @param {FirebaseAnalytics} analytics - Instance of analytics (web - only) - * @returns {Promise} */ -export async function getGoogleAnalyticsClientId(analytics) { +export async function getGoogleAnalyticsClientId( + analytics: FirebaseAnalyticsModule, +): Promise { if (Platform.OS === 'android' || Platform.OS === 'ios') { throw new Error('getGoogleAnalyticsClientId is web-only.'); } else { - return getAppInstanceId(analytics); + const instanceId = await getAppInstanceId(analytics); + return instanceId || ''; } } /** * Log a custom event with optional params. - * @param {FirebaseAnalytics} analytics - Analytics instance. - * @param {string} name - Event name must not conflict with any Reserved Events. - * @param {object} [params={}] - Parameters to be sent and displayed with the event. - * @param {AnalyticsCallOptions} [options={}] - Additional options that can be passed. Web only. - * @returns {Promise} */ -export function logEvent(analytics, name, params = {}, options = {}) { +export function logEvent( + analytics: FirebaseAnalyticsModule, + name: string, + params: { [key: string]: any } = {}, + options: AnalyticsCallOptions = { global: false }, +): Promise { + // @ts-ignore - MODULAR_DEPRECATION_ARG is filtered out internally return analytics.logEvent.call(analytics, name, params, options, MODULAR_DEPRECATION_ARG); } /** * If true, allows the device to collect analytical data and send it to Firebase. Useful for GDPR. - * @param {FirebaseAnalytics} analytics - Analytics instance. - * @param {boolean} enabled - A boolean value representing whether Analytics collection is enabled or disabled. - * @returns {Promise} */ -export function setAnalyticsCollectionEnabled(analytics, enabled) { +export function setAnalyticsCollectionEnabled( + analytics: FirebaseAnalyticsModule, + enabled: boolean, +): Promise { + // @ts-ignore - MODULAR_DEPRECATION_ARG is filtered out internally return analytics.setAnalyticsCollectionEnabled.call(analytics, enabled, MODULAR_DEPRECATION_ARG); } /** * Sets the duration of inactivity that terminates the current session. - * @param {FirebaseAnalytics} analytics - Analytics instance. - * @param {number} [milliseconds=1800000] - The default value is 1800000 (30 minutes). - * @returns {Promise} */ -export function setSessionTimeoutDuration(analytics, milliseconds = 1800000) { +export function setSessionTimeoutDuration( + analytics: FirebaseAnalyticsModule, + milliseconds: number = 1800000, +): Promise { // This doesn't exist on firebase-js-sdk, but probably should keep this for android & iOS + // @ts-ignore - MODULAR_DEPRECATION_ARG is filtered out internally return analytics.setSessionTimeoutDuration.call(analytics, milliseconds, MODULAR_DEPRECATION_ARG); } /** * Retrieve the app instance id of the application. - * @param {FirebaseAnalytics} analytics - Analytics instance. - * @returns {Promise} Returns the app instance id or null on android if FirebaseAnalytics.ConsentType.ANALYTICS_STORAGE has been set to FirebaseAnalytics.ConsentStatus.DENIED and null on iOS if ConsentType.analyticsStorage has been set to ConsentStatus.denied. */ -export function getAppInstanceId(analytics) { +export function getAppInstanceId(analytics: FirebaseAnalyticsModule): Promise { // This doesn't exist on firebase-js-sdk, but probably should keep this for android & iOS + // @ts-ignore - MODULAR_DEPRECATION_ARG is filtered out internally return analytics.getAppInstanceId.call(analytics, MODULAR_DEPRECATION_ARG); } /** * Retrieves the session id from the client. * On iOS, Firebase SDK may return an error that is handled internally and may take many minutes to return a valid value. Check native debug logs for more details. - * @param {FirebaseAnalytics} analytics - Analytics instance. - * @returns {Promise} Returns the session id or null if session is expired, null on android if FirebaseAnalytics.ConsentType.ANALYTICS_STORAGE has been set to FirebaseAnalytics.ConsentStatus.DENIED and null on iOS if ConsentType.analyticsStorage has been set to ConsentStatus.denied. */ -export function getSessionId(analytics) { +export function getSessionId(analytics: FirebaseAnalyticsModule): Promise { // This doesn't exist on firebase-js-sdk, but probably should keep this for android & iOS + // @ts-ignore - MODULAR_DEPRECATION_ARG is filtered out internally return analytics.getSessionId.call(analytics, MODULAR_DEPRECATION_ARG); } /** * Gives a user a unique identification. - * @param {FirebaseAnalytics} analytics - Analytics instance. - * @param {string|null} id - Set to null to remove a previously assigned ID from analytics events. - * @returns {Promise} */ -export function setUserId(analytics, id) { +export function setUserId(analytics: FirebaseAnalyticsModule, id: string | null): Promise { + // @ts-ignore - MODULAR_DEPRECATION_ARG is filtered out internally return analytics.setUserId.call(analytics, id, MODULAR_DEPRECATION_ARG); } /** * Sets a key/value pair of data on the current user. Each Firebase project can have up to 25 uniquely named (case-sensitive) user properties. - * @param {FirebaseAnalytics} analytics - Analytics instance. - * @param {string} name - A user property identifier. - * @param {string|null} value - Set to null to remove a previously assigned ID from analytics events. - * @returns {Promise} */ -export function setUserProperty(analytics, name, value) { +export function setUserProperty( + analytics: FirebaseAnalyticsModule, + name: string, + value: string | null, +): Promise { // This doesn't exist on firebase-js-sdk, but probably should keep this for android & iOS + // @ts-ignore - MODULAR_DEPRECATION_ARG is filtered out internally return analytics.setUserProperty.call(analytics, name, value, MODULAR_DEPRECATION_ARG); } /** * Sets multiple key/value pairs of data on the current user. Each Firebase project can have up to 25 uniquely named (case-sensitive) user properties. - * @param {FirebaseAnalytics} analytics - Analytics instance. - * @param {object} properties - Set a property value to null to remove it. - * @param {AnalyticsCallOptions} [options={}] - Additional options that can be passed. Web only. - * @returns {Promise} */ -export function setUserProperties(analytics, properties, options = {}) { +export function setUserProperties( + analytics: FirebaseAnalyticsModule, + properties: { [key: string]: string | null }, + options: AnalyticsCallOptions = { global: false }, +): Promise { + // @ts-ignore - MODULAR_DEPRECATION_ARG is filtered out internally return analytics.setUserProperties.call(analytics, properties, options, MODULAR_DEPRECATION_ARG); } /** * Clears all analytics data for this instance from the device and resets the app instance ID. - * @param {FirebaseAnalytics} analytics - Analytics instance. - * @returns {Promise} */ -export function resetAnalyticsData(analytics) { +export function resetAnalyticsData(analytics: FirebaseAnalyticsModule): Promise { // This doesn't exist on firebase-js-sdk, but probably should keep this for android & iOS + // @ts-ignore - MODULAR_DEPRECATION_ARG is filtered out internally return analytics.resetAnalyticsData.call(analytics, MODULAR_DEPRECATION_ARG); } /** * E-Commerce Purchase event. This event signifies that an item(s) was purchased by a user. Note: This is different from the in-app purchase event, which is reported automatically for Google Play-based apps. - * @param {FirebaseAnalytics} analytics - Analytics instance. - * @param {AddPaymentInfoEventParameters} params - Event parameters. - * @returns {Promise} */ -export function logAddPaymentInfo(analytics, params) { +export function logAddPaymentInfo( + analytics: FirebaseAnalyticsModule, + params: AddPaymentInfoEventParameters, +): Promise { // This is deprecated for both namespaced and modular. return analytics.logAddPaymentInfo(params); } /** * Sets or clears the screen name and class the user is currently viewing. - * @param {FirebaseAnalytics} analytics - Analytics instance. - * @param {ScreenViewParameters} params - Event parameters. - * @returns {Promise} */ -export function logScreenView(analytics, params) { +export function logScreenView( + analytics: FirebaseAnalyticsModule, + params: ScreenViewParameters, +): Promise { // This is deprecated for both namespaced and modular. return analytics.logScreenView(params); } /** * Add Payment Info event. This event signifies that a user has submitted their payment information to your app. - * @param {FirebaseAnalytics} analytics - Analytics instance. - * @param {AddShippingInfoParameters} params - Event parameters. - * @returns {Promise} */ -export function logAddShippingInfo(analytics, params) { +export function logAddShippingInfo( + analytics: FirebaseAnalyticsModule, + params: AddShippingInfoParameters, +): Promise { // This is deprecated for both namespaced and modular. return analytics.logAddShippingInfo(params); } /** * E-Commerce Add To Cart event. - * @param {FirebaseAnalytics} analytics - Analytics instance. - * @param {AddToCartEventParameters} params - Event parameters. - * @returns {Promise} */ -export function logAddToCart(analytics, params) { +export function logAddToCart( + analytics: FirebaseAnalyticsModule, + params: AddToCartEventParameters, +): Promise { // This is deprecated for both namespaced and modular. return analytics.logAddToCart(params); } /** * E-Commerce Add To Wishlist event. This event signifies that an item was added to a wishlist. - * @param {FirebaseAnalytics} analytics - Analytics instance. - * @param {AddToWishlistEventParameters} params - Event parameters. - * @returns {Promise} */ -export function logAddToWishlist(analytics, params) { +export function logAddToWishlist( + analytics: FirebaseAnalyticsModule, + params: AddToWishlistEventParameters, +): Promise { // This is deprecated for both namespaced and modular. return analytics.logAddToWishlist(params); } /** * App Open event. By logging this event when an App is moved to the foreground, developers can understand how often users leave and return during the course of a Session. - * @param {FirebaseAnalytics} analytics - Analytics instance. - * @returns {Promise} */ -export function logAppOpen(analytics) { +export function logAppOpen(analytics: FirebaseAnalyticsModule): Promise { // This is deprecated for both namespaced and modular. return analytics.logAppOpen(); } /** * E-Commerce Begin Checkout event. This event signifies that a user has begun the process of checking out. - * @param {FirebaseAnalytics} analytics - Analytics instance. - * @param {BeginCheckoutEventParameters} params - Event parameters. - * @returns {Promise} */ -export function logBeginCheckout(analytics, params) { +export function logBeginCheckout( + analytics: FirebaseAnalyticsModule, + params: BeginCheckoutEventParameters, +): Promise { // This is deprecated for both namespaced and modular. return analytics.logBeginCheckout(params); } /** * Log this event to supply the referral details of a re-engagement campaign. - * @param {FirebaseAnalytics} analytics - Analytics instance. - * @param {CampaignDetailsEventParameters} params - Event parameters. - * @returns {Promise} */ -export function logCampaignDetails(analytics, params) { +export function logCampaignDetails( + analytics: FirebaseAnalyticsModule, + params: CampaignDetailsEventParameters, +): Promise { // This is deprecated for both namespaced and modular. return analytics.logCampaignDetails(params); } /** * Earn Virtual Currency event. This event tracks the awarding of virtual currency in your app. - * @param {FirebaseAnalytics} analytics - Analytics instance. - * @param {EarnVirtualCurrencyEventParameters} params - Event parameters. - * @returns {Promise} */ -export function logEarnVirtualCurrency(analytics, params) { +export function logEarnVirtualCurrency( + analytics: FirebaseAnalyticsModule, + params: EarnVirtualCurrencyEventParameters, +): Promise { // This is deprecated for both namespaced and modular. return analytics.logEarnVirtualCurrency(params); } /** * Generate Lead event. Log this event when a lead has been generated in the app. - * @param {FirebaseAnalytics} analytics - Analytics instance. - * @param {GenerateLeadEventParameters} params - Event parameters. - * @returns {Promise} */ -export function logGenerateLead(analytics, params) { +export function logGenerateLead( + analytics: FirebaseAnalyticsModule, + params: GenerateLeadEventParameters, +): Promise { // This is deprecated for both namespaced and modular. return analytics.logGenerateLead(params); } /** * Join Group event. Log this event when a user joins a group such as a guild, team or family. - * @param {FirebaseAnalytics} analytics - Analytics instance. - * @param {JoinGroupEventParameters} params - Event parameters. - * @returns {Promise} */ -export function logJoinGroup(analytics, params) { +export function logJoinGroup( + analytics: FirebaseAnalyticsModule, + params: JoinGroupEventParameters, +): Promise { // This is deprecated for both namespaced and modular. return analytics.logJoinGroup(params); } /** * Level End event. - * @param {FirebaseAnalytics} analytics - Analytics instance. - * @param {LevelEndEventParameters} params - Event parameters. - * @returns {Promise} */ -export function logLevelEnd(analytics, params) { +export function logLevelEnd( + analytics: FirebaseAnalyticsModule, + params: LevelEndEventParameters, +): Promise { // This is deprecated for both namespaced and modular. return analytics.logLevelEnd(params); } /** * Level Start event. - * @param {FirebaseAnalytics} analytics - Analytics instance. - * @param {LevelStartEventParameters} params - Event parameters. - * @returns {Promise} */ -export function logLevelStart(analytics, params) { +export function logLevelStart( + analytics: FirebaseAnalyticsModule, + params: LevelStartEventParameters, +): Promise { // This is deprecated for both namespaced and modular. return analytics.logLevelStart(params); } /** * Level Up event. This event signifies that a player has leveled up in your gaming app. - * @param {FirebaseAnalytics} analytics - Analytics instance. - * @param {LevelUpEventParameters} params - Event parameters. - * @returns {Promise} */ -export function logLevelUp(analytics, params) { +export function logLevelUp( + analytics: FirebaseAnalyticsModule, + params: LevelUpEventParameters, +): Promise { // This is deprecated for both namespaced and modular. return analytics.logLevelUp(params); } /** * Login event. Apps with a login feature can report this event to signify that a user has logged in. - * @param {FirebaseAnalytics} analytics - Analytics instance. - * @param {LoginEventParameters} params - Event parameters. - * @returns {Promise} */ -export function logLogin(analytics, params) { +export function logLogin( + analytics: FirebaseAnalyticsModule, + params: LoginEventParameters, +): Promise { // This is deprecated for both namespaced and modular. return analytics.logLogin(params); } /** * Post Score event. Log this event when the user posts a score in your gaming app. - * @param {FirebaseAnalytics} analytics - Analytics instance. - * @param {PostScoreEventParameters} params - Event parameters. - * @returns {Promise} */ -export function logPostScore(analytics, params) { +export function logPostScore( + analytics: FirebaseAnalyticsModule, + params: PostScoreEventParameters, +): Promise { // This is deprecated for both namespaced and modular. return analytics.logPostScore(params); } @@ -358,7 +358,10 @@ export function logPostScore(analytics, params) { * @param {SelectContentEventParameters} params - Event parameters. * @returns {Promise} */ -export function logSelectContent(analytics, params) { +export function logSelectContent( + analytics: FirebaseAnalyticsModule, + params: SelectContentEventParameters, +): Promise { // This is deprecated for both namespaced and modular. return analytics.logSelectContent(params); } @@ -369,7 +372,10 @@ export function logSelectContent(analytics, params) { * @param {PurchaseEventParameters} params - Event parameters. * @returns {Promise} */ -export function logPurchase(analytics, params) { +export function logPurchase( + analytics: FirebaseAnalyticsModule, + params: PurchaseEventParameters, +): Promise { // This is deprecated for both namespaced and modular. return analytics.logPurchase(params); } @@ -380,7 +386,10 @@ export function logPurchase(analytics, params) { * @param {RefundEventParameters} params - Event parameters. * @returns {Promise} */ -export function logRefund(analytics, params) { +export function logRefund( + analytics: FirebaseAnalyticsModule, + params: RefundEventParameters, +): Promise { // This is deprecated for both namespaced and modular. return analytics.logRefund(params); } @@ -391,7 +400,10 @@ export function logRefund(analytics, params) { * @param {RemoveFromCartEventParameters} params - Event parameters. * @returns {Promise} */ -export function logRemoveFromCart(analytics, params) { +export function logRemoveFromCart( + analytics: FirebaseAnalyticsModule, + params: RemoveFromCartEventParameters, +): Promise { // This is deprecated for both namespaced and modular. return analytics.logRemoveFromCart(params); } @@ -402,7 +414,10 @@ export function logRemoveFromCart(analytics, params) { * @param {SearchEventParameters} params - Event parameters. * @returns {Promise} */ -export function logSearch(analytics, params) { +export function logSearch( + analytics: FirebaseAnalyticsModule, + params: SearchEventParameters, +): Promise { // This is deprecated for both namespaced and modular. return analytics.logSearch(params); } @@ -413,7 +428,10 @@ export function logSearch(analytics, params) { * @param {SelectItemEventParameters} params - Event parameters. * @returns {Promise} */ -export function logSelectItem(analytics, params) { +export function logSelectItem( + analytics: FirebaseAnalyticsModule, + params: SelectItemEventParameters, +): Promise { // This is deprecated for both namespaced and modular. return analytics.logSelectItem(params); } @@ -424,7 +442,10 @@ export function logSelectItem(analytics, params) { * @param {SetCheckoutOptionEventParameters} params - Event parameters. * @returns {Promise} */ -export function logSetCheckoutOption(analytics, params) { +export function logSetCheckoutOption( + analytics: FirebaseAnalyticsModule, + params: SetCheckoutOptionEventParameters, +): Promise { // This is deprecated for both namespaced and modular. return analytics.logSetCheckoutOption(params); } @@ -435,7 +456,10 @@ export function logSetCheckoutOption(analytics, params) { * @param {SelectPromotionEventParameters} params - Event parameters. * @returns {Promise} */ -export function logSelectPromotion(analytics, params) { +export function logSelectPromotion( + analytics: FirebaseAnalyticsModule, + params: SelectPromotionEventParameters, +): Promise { // This is deprecated for both namespaced and modular. return analytics.logSelectPromotion(params); } @@ -446,7 +470,10 @@ export function logSelectPromotion(analytics, params) { * @param {ShareEventParameters} params - Event parameters. * @returns {Promise} */ -export function logShare(analytics, params) { +export function logShare( + analytics: FirebaseAnalyticsModule, + params: ShareEventParameters, +): Promise { // This is deprecated for both namespaced and modular. return analytics.logShare(params); } @@ -457,7 +484,10 @@ export function logShare(analytics, params) { * @param {SignUpEventParameters} params - Event parameters. * @returns {Promise} */ -export function logSignUp(analytics, params) { +export function logSignUp( + analytics: FirebaseAnalyticsModule, + params: SignUpEventParameters, +): Promise { // This is deprecated for both namespaced and modular. return analytics.logSignUp(params); } @@ -468,7 +498,10 @@ export function logSignUp(analytics, params) { * @param {SpendVirtualCurrencyEventParameters} params - Event parameters. * @returns {Promise} */ -export function logSpendVirtualCurrency(analytics, params) { +export function logSpendVirtualCurrency( + analytics: FirebaseAnalyticsModule, + params: SpendVirtualCurrencyEventParameters, +): Promise { // This is deprecated for both namespaced and modular. return analytics.logSpendVirtualCurrency(params); } @@ -478,7 +511,7 @@ export function logSpendVirtualCurrency(analytics, params) { * @param {FirebaseAnalytics} analytics - Analytics instance. * @returns {Promise} */ -export function logTutorialBegin(analytics) { +export function logTutorialBegin(analytics: FirebaseAnalyticsModule): Promise { // This is deprecated for both namespaced and modular. return analytics.logTutorialBegin(); } @@ -488,7 +521,7 @@ export function logTutorialBegin(analytics) { * @param {FirebaseAnalytics} analytics - Analytics instance. * @returns {Promise} */ -export function logTutorialComplete(analytics) { +export function logTutorialComplete(analytics: FirebaseAnalyticsModule): Promise { // This is deprecated for both namespaced and modular. return analytics.logTutorialComplete(); } @@ -499,7 +532,10 @@ export function logTutorialComplete(analytics) { * @param {UnlockAchievementEventParameters} params - Event parameters. * @returns {Promise} */ -export function logUnlockAchievement(analytics, params) { +export function logUnlockAchievement( + analytics: FirebaseAnalyticsModule, + params: UnlockAchievementEventParameters, +): Promise { // This is deprecated for both namespaced and modular. return analytics.logUnlockAchievement(params); } @@ -510,7 +546,10 @@ export function logUnlockAchievement(analytics, params) { * @param {ViewCartEventParameters} params - Event parameters. * @returns {Promise} */ -export function logViewCart(analytics, params) { +export function logViewCart( + analytics: FirebaseAnalyticsModule, + params: ViewCartEventParameters, +): Promise { // This is deprecated for both namespaced and modular. return analytics.logViewCart(params); } @@ -521,7 +560,10 @@ export function logViewCart(analytics, params) { * @param {ViewItemEventParameters} params - Event parameters. * @returns {Promise} */ -export function logViewItem(analytics, params) { +export function logViewItem( + analytics: FirebaseAnalyticsModule, + params: ViewItemEventParameters, +): Promise { // This is deprecated for both namespaced and modular. return analytics.logViewItem(params); } @@ -532,7 +574,10 @@ export function logViewItem(analytics, params) { * @param {ViewItemListEventParameters} params - Event parameters. * @returns {Promise} */ -export function logViewItemList(analytics, params) { +export function logViewItemList( + analytics: FirebaseAnalyticsModule, + params: ViewItemListEventParameters, +): Promise { // This is deprecated for both namespaced and modular. return analytics.logViewItemList(params); } @@ -543,7 +588,10 @@ export function logViewItemList(analytics, params) { * @param {ViewPromotionEventParameters} params - Event parameters. * @returns {Promise} */ -export function logViewPromotion(analytics, params) { +export function logViewPromotion( + analytics: FirebaseAnalyticsModule, + params: ViewPromotionEventParameters, +): Promise { // This is deprecated for both namespaced and modular. return analytics.logViewPromotion(params); } @@ -554,7 +602,10 @@ export function logViewPromotion(analytics, params) { * @param {ViewSearchResultsParameters} params - Event parameters. * @returns {Promise} */ -export function logViewSearchResults(analytics, params) { +export function logViewSearchResults( + analytics: FirebaseAnalyticsModule, + params: ViewSearchResultsParameters, +): Promise { // This is deprecated for both namespaced and modular. return analytics.logViewSearchResults(params); } @@ -565,7 +616,11 @@ export function logViewSearchResults(analytics, params) { * @param {object} [params={}] - Parameters to be added to the map of parameters added to every event. * @returns {Promise} */ -export function setDefaultEventParameters(analytics, params = {}) { +export function setDefaultEventParameters( + analytics: FirebaseAnalyticsModule, + params: { [key: string]: any } = {}, +): Promise { + // @ts-ignore - MODULAR_DEPRECATION_ARG is filtered out internally return analytics.setDefaultEventParameters.call(analytics, params, MODULAR_DEPRECATION_ARG); } @@ -576,10 +631,14 @@ export function setDefaultEventParameters(analytics, params = {}) { * @param {string} emailAddress - Email address, properly formatted complete with domain name e.g, 'user@example.com'. * @returns {Promise} */ -export function initiateOnDeviceConversionMeasurementWithEmailAddress(analytics, emailAddress) { +export function initiateOnDeviceConversionMeasurementWithEmailAddress( + analytics: FirebaseAnalyticsModule, + emailAddress: string, +): Promise { return analytics.initiateOnDeviceConversionMeasurementWithEmailAddress.call( analytics, emailAddress, + // @ts-ignore - MODULAR_DEPRECATION_ARG is filtered out internally MODULAR_DEPRECATION_ARG, ); } @@ -594,12 +653,13 @@ export function initiateOnDeviceConversionMeasurementWithEmailAddress(analytics, * @link https://firebase.google.com/docs/tutorials/ads-ios-on-device-measurement/step-3#use-hashed-credentials */ export function initiateOnDeviceConversionMeasurementWithHashedEmailAddress( - analytics, - hashedEmailAddress, -) { + analytics: FirebaseAnalyticsModule, + hashedEmailAddress: string, +): Promise { return analytics.initiateOnDeviceConversionMeasurementWithHashedEmailAddress.call( analytics, hashedEmailAddress, + // @ts-ignore - MODULAR_DEPRECATION_ARG is filtered out internally MODULAR_DEPRECATION_ARG, ); } @@ -611,10 +671,14 @@ export function initiateOnDeviceConversionMeasurementWithHashedEmailAddress( * @param {string} phoneNumber - Phone number in E.164 format - that is a leading + sign, then up to 15 digits, no dashes or spaces. * @returns {Promise} */ -export function initiateOnDeviceConversionMeasurementWithPhoneNumber(analytics, phoneNumber) { +export function initiateOnDeviceConversionMeasurementWithPhoneNumber( + analytics: FirebaseAnalyticsModule, + phoneNumber: string, +): Promise { return analytics.initiateOnDeviceConversionMeasurementWithPhoneNumber.call( analytics, phoneNumber, + // @ts-ignore - MODULAR_DEPRECATION_ARG is filtered out internally MODULAR_DEPRECATION_ARG, ); } @@ -629,12 +693,13 @@ export function initiateOnDeviceConversionMeasurementWithPhoneNumber(analytics, * @link https://firebase.google.com/docs/tutorials/ads-ios-on-device-measurement/step-3#use-hashed-credentials */ export function initiateOnDeviceConversionMeasurementWithHashedPhoneNumber( - analytics, - hashedPhoneNumber, -) { + analytics: FirebaseAnalyticsModule, + hashedPhoneNumber: string, +): Promise { return analytics.initiateOnDeviceConversionMeasurementWithHashedPhoneNumber.call( analytics, hashedPhoneNumber, + // @ts-ignore - MODULAR_DEPRECATION_ARG is filtered out internally MODULAR_DEPRECATION_ARG, ); } @@ -647,7 +712,7 @@ export function initiateOnDeviceConversionMeasurementWithHashedPhoneNumber( * 4. Checks if the current browser context is valid for using IndexedDB.open(). * @returns {Promise} */ -export function isSupported() { +export function isSupported(): Promise { return Promise.resolve(true); } @@ -657,7 +722,11 @@ export function isSupported() { * @param {ConsentSettings} consentSettings - See ConsentSettings. * @returns {Promise} */ -export function setConsent(analytics, consentSettings) { +export function setConsent( + analytics: FirebaseAnalyticsModule, + consentSettings: ConsentSettings, +): Promise { + // @ts-ignore - MODULAR_DEPRECATION_ARG is filtered out internally return analytics.setConsent.call(analytics, consentSettings, MODULAR_DEPRECATION_ARG); } @@ -667,7 +736,6 @@ export function setConsent(analytics, consentSettings) { * @param {SettingsOptions} options - See SettingsOptions. * @returns {void} */ -// eslint-disable-next-line -export function settings(options) { +export function settings(_options: SettingsOptions): void { // Returns nothing until Web implemented. } diff --git a/packages/analytics/lib/modular/index.d.ts b/packages/analytics/lib/modular/index.d.ts deleted file mode 100644 index 83a66da8fb..0000000000 --- a/packages/analytics/lib/modular/index.d.ts +++ /dev/null @@ -1,1267 +0,0 @@ -import { ReactNativeFirebase } from '@react-native-firebase/app'; -import { FirebaseAnalyticsTypes } from '..'; -import Analytics = FirebaseAnalyticsTypes.Module; -import AnalyticsCallOptions = FirebaseAnalyticsTypes.AnalyticsCallOptions; -import EventParams = FirebaseAnalyticsTypes.EventParams; -import FirebaseApp = ReactNativeFirebase.FirebaseApp; - -/** - * Returns an Analytics instance for the given app. - * - * @param app - FirebaseApp. Optional. - */ -export declare function getAnalytics(app?: FirebaseApp): Analytics; - -/** - * Returns an Analytics instance for the given app. - * - * @param app - FirebaseApp. - * @param options - `AnalyticsSettings`. Web only. - */ -export declare function initializeAnalytics( - app: FirebaseApp, - options?: FirebaseAnalyticsTypes.AnalyticsSettings, -): Analytics; - -/** - * Retrieves a unique Google Analytics identifier for the web client. - * - * @param analyticsInstance - Instance of analytics (web - only) - * - */ -export declare function getGoogleAnalyticsClientId(analyticsInstance: Analytics): Promise; - -/** - * Log a custom event with optional params. Note that there are various limits that applied - * to event parameters (total parameter count, etc), but analytics applies the limits during - * cloud processing, the errors will not be seen as Promise rejections when you call logEvent. - * While integrating this API in your app you are strongly encouraged to enable - * [DebugView](https://firebase.google.com/docs/analytics/debugview) - - * any errors in your events will show up in the firebase web console with links to relevant documentation - * - * @param analytics Analytics instance. - * @param name Event name must not conflict with any Reserved Events. - * @param params Parameters to be sent and displayed with the event. - * @param options Additional options that can be passed. Web only. - */ -export declare function logEvent( - analytics: Analytics, - name: 'add_payment_info', - params?: { - coupon?: EventParams['coupon']; - currency?: EventParams['currency']; - items?: EventParams['items']; - payment_type?: EventParams['payment_type']; - value?: EventParams['value']; - [key: string]: any; - }, - options?: AnalyticsCallOptions, -): Promise; - -/** - * Log a custom event with optional params. Note that there are various limits that applied - * to event parameters (total parameter count, etc), but analytics applies the limits during - * cloud processing, the errors will not be seen as Promise rejections when you call logEvent. - * While integrating this API in your app you are strongly encouraged to enable - * [DebugView](https://firebase.google.com/docs/analytics/debugview) - - * any errors in your events will show up in the firebase web console with links to relevant documentation - * - * @param analytics Analytics instance. - * @param name Event name must not conflict with any Reserved Events. - * @param params Parameters to be sent and displayed with the event. - * @param options Additional options that can be passed. Web only. - */ -export declare function logEvent( - analytics: Analytics, - name: 'purchase' | 'refund', - params?: { - value?: EventParams['value']; - currency?: EventParams['currency']; - transaction_id: EventParams['transaction_id']; - tax?: EventParams['tax']; - shipping?: EventParams['shipping']; - items?: EventParams['items']; - coupon?: EventParams['coupon']; - affiliation?: EventParams['affiliation']; - [key: string]: any; - }, - options?: AnalyticsCallOptions, -): Promise; - -/** - * Log a custom event with optional params. Note that there are various limits that applied - * to event parameters (total parameter count, etc), but analytics applies the limits during - * cloud processing, the errors will not be seen as Promise rejections when you call logEvent. - * While integrating this API in your app you are strongly encouraged to enable - * [DebugView](https://firebase.google.com/docs/analytics/debugview) - - * any errors in your events will show up in the firebase web console with links to relevant documentation - * - * @param analytics Analytics instance. - * @param name Event name must not conflict with any Reserved Events. - * @param params Parameters to be sent and displayed with the event. - * @param options Additional options that can be passed. Web only. - */ -export declare function logEvent( - analytics: Analytics, - name: 'screen_view', - params?: { - firebase_screen: EventParams['firebase_screen']; - firebase_screen_class: EventParams['firebase_screen_class']; - [key: string]: any; - }, - options?: AnalyticsCallOptions, -): Promise; - -/** - * Log a custom event with optional params. Note that there are various limits that applied - * to event parameters (total parameter count, etc), but analytics applies the limits during - * cloud processing, the errors will not be seen as Promise rejections when you call logEvent. - * While integrating this API in your app you are strongly encouraged to enable - * [DebugView](https://firebase.google.com/docs/analytics/debugview) - - * any errors in your events will show up in the firebase web console with links to relevant documentation - * - * @param analytics Analytics instance. - * @param name Event name must not conflict with any Reserved Events. - * @param params Parameters to be sent and displayed with the event. - * @param options Additional options that can be passed. Web only. - */ -export declare function logEvent( - analytics: Analytics, - name: 'search' | 'view_search_results', - params?: { - search_term?: EventParams['search_term']; - [key: string]: any; - }, - options?: AnalyticsCallOptions, -): Promise; - -/** - * Log a custom event with optional params. Note that there are various limits that applied - * to event parameters (total parameter count, etc), but analytics applies the limits during - * cloud processing, the errors will not be seen as Promise rejections when you call logEvent. - * While integrating this API in your app you are strongly encouraged to enable - * [DebugView](https://firebase.google.com/docs/analytics/debugview) - - * any errors in your events will show up in the firebase web console with links to relevant documentation - * - * @param analytics Analytics instance. - * @param name Event name must not conflict with any Reserved Events. - * @param params Parameters to be sent and displayed with the event. - * @param options Additional options that can be passed. Web only. - */ -export declare function logEvent( - analytics: Analytics, - name: 'select_content', - params?: { - content_type?: EventParams['content_type']; - item_id?: EventParams['item_id']; - [key: string]: any; - }, - options?: AnalyticsCallOptions, -): Promise; - -/** - * Log a custom event with optional params. Note that there are various limits that applied - * to event parameters (total parameter count, etc), but analytics applies the limits during - * cloud processing, the errors will not be seen as Promise rejections when you call logEvent. - * While integrating this API in your app you are strongly encouraged to enable - * [DebugView](https://firebase.google.com/docs/analytics/debugview) - - * any errors in your events will show up in the firebase web console with links to relevant documentation - * - * @param analytics Analytics instance. - * @param name Event name must not conflict with any Reserved Events. - * @param params Parameters to be sent and displayed with the event. - * @param options Additional options that can be passed. Web only. - */ -export declare function logEvent( - analytics: Analytics, - name: 'select_item', - params?: { - items?: EventParams['items']; - item_list_name?: EventParams['item_list_name']; - item_list_id?: EventParams['item_list_id']; - [key: string]: any; - }, - options?: AnalyticsCallOptions, -): Promise; - -/** - * Log a custom event with optional params. Note that there are various limits that applied - * to event parameters (total parameter count, etc), but analytics applies the limits during - * cloud processing, the errors will not be seen as Promise rejections when you call logEvent. - * While integrating this API in your app you are strongly encouraged to enable - * [DebugView](https://firebase.google.com/docs/analytics/debugview) - - * any errors in your events will show up in the firebase web console with links to relevant documentation - * - * @param analytics Analytics instance. - * @param name Event name must not conflict with any Reserved Events. - * @param params Parameters to be sent and displayed with the event. - * @param options Additional options that can be passed. Web only. - */ -export declare function logEvent( - analytics: Analytics, - name: 'select_promotion' | 'view_promotion', - params?: { - items?: EventParams['items']; - promotion_id?: EventParams['promotion_id']; - promotion_name?: EventParams['promotion_name']; - [key: string]: any; - }, - options?: AnalyticsCallOptions, -): Promise; - -/** - * Log a custom event with optional params. Note that there are various limits that applied - * to event parameters (total parameter count, etc), but analytics applies the limits during - * cloud processing, the errors will not be seen as Promise rejections when you call logEvent. - * While integrating this API in your app you are strongly encouraged to enable - * [DebugView](https://firebase.google.com/docs/analytics/debugview) - - * any errors in your events will show up in the firebase web console with links to relevant documentation - * - * @param analytics Analytics instance. - * @param name Event name must not conflict with any Reserved Events. - * @param params Parameters to be sent and displayed with the event. - * @param options Additional options that can be passed. Web only. - */ -export declare function logEvent( - analytics: Analytics, - name: 'set_checkout_option', - params?: { - checkout_step?: EventParams['checkout_step']; - checkout_option?: EventParams['checkout_option']; - [key: string]: any; - }, - options?: AnalyticsCallOptions, -): Promise; - -/** - * Log a custom event with optional params. Note that there are various limits that applied - * to event parameters (total parameter count, etc), but analytics applies the limits during - * cloud processing, the errors will not be seen as Promise rejections when you call logEvent. - * While integrating this API in your app you are strongly encouraged to enable - * [DebugView](https://firebase.google.com/docs/analytics/debugview) - - * any errors in your events will show up in the firebase web console with links to relevant documentation - * - * @param analytics Analytics instance. - * @param name Event name must not conflict with any Reserved Events. - * @param params Parameters to be sent and displayed with the event. - * @param options Additional options that can be passed. Web only. - */ -export declare function logEvent( - analytics: Analytics, - name: 'share', - params?: { - method?: EventParams['method']; - content_type?: EventParams['content_type']; - item_id?: EventParams['item_id']; - [key: string]: any; - }, - options?: AnalyticsCallOptions, -): Promise; - -/** - * Log a custom event with optional params. Note that there are various limits that applied - * to event parameters (total parameter count, etc), but analytics applies the limits during - * cloud processing, the errors will not be seen as Promise rejections when you call logEvent. - * While integrating this API in your app you are strongly encouraged to enable - * [DebugView](https://firebase.google.com/docs/analytics/debugview) - - * any errors in your events will show up in the firebase web console with links to relevant documentation - * - * @param analytics Analytics instance. - * @param name Event name must not conflict with any Reserved Events. - * @param params Parameters to be sent and displayed with the event. - * @param options Additional options that can be passed. Web only. - */ -export declare function logEvent( - analytics: Analytics, - name: 'sign_up', - params?: { - method?: EventParams['method']; - [key: string]: any; - }, - options?: AnalyticsCallOptions, -): Promise; - -/** - * Log a custom event with optional params. Note that there are various limits that applied - * to event parameters (total parameter count, etc), but analytics applies the limits during - * cloud processing, the errors will not be seen as Promise rejections when you call logEvent. - * While integrating this API in your app you are strongly encouraged to enable - * [DebugView](https://firebase.google.com/docs/analytics/debugview) - - * any errors in your events will show up in the firebase web console with links to relevant documentation - * - * @param analytics Analytics instance. - * @param name Event name must not conflict with any Reserved Events. - * @param params Parameters to be sent and displayed with the event. - * @param options Additional options that can be passed. Web only. - */ -export declare function logEvent( - analytics: Analytics, - name: 'timing_complete', - params?: { - name: string; - value: number; - event_category?: string; - event_label?: string; - [key: string]: any; - }, - options?: AnalyticsCallOptions, -): Promise; - -/** - * Log a custom event with optional params. Note that there are various limits that applied - * to event parameters (total parameter count, etc), but analytics applies the limits during - * cloud processing, the errors will not be seen as Promise rejections when you call logEvent. - * While integrating this API in your app you are strongly encouraged to enable - * [DebugView](https://firebase.google.com/docs/analytics/debugview) - - * any errors in your events will show up in the firebase web console with links to relevant documentation - * - * @param analytics Analytics instance. - * @param name Event name must not conflict with any Reserved Events. - * @param params Parameters to be sent and displayed with the event. - * @param options Additional options that can be passed. Web only. - */ -export declare function logEvent( - analytics: Analytics, - name: 'add_shipping_info', - params?: { - coupon?: EventParams['coupon']; - currency?: EventParams['currency']; - items?: EventParams['items']; - shipping_tier?: EventParams['shipping_tier']; - value?: EventParams['value']; - [key: string]: any; - }, - options?: AnalyticsCallOptions, -): Promise; - -/** - * Log a custom event with optional params. Note that there are various limits that applied - * to event parameters (total parameter count, etc), but analytics applies the limits during - * cloud processing, the errors will not be seen as Promise rejections when you call logEvent. - * While integrating this API in your app you are strongly encouraged to enable - * [DebugView](https://firebase.google.com/docs/analytics/debugview) - - * any errors in your events will show up in the firebase web console with links to relevant documentation - * - * @param analytics Analytics instance. - * @param name Event name must not conflict with any Reserved Events. - * @param params Parameters to be sent and displayed with the event. - * @param options Additional options that can be passed. Web only. - */ -export declare function logEvent( - analytics: Analytics, - name: 'view_cart' | 'view_item', - params?: { - currency?: EventParams['currency']; - items?: EventParams['items']; - value?: EventParams['value']; - [key: string]: any; - }, - options?: AnalyticsCallOptions, -): Promise; - -/** - * Log a custom event with optional params. Note that there are various limits that applied - * to event parameters (total parameter count, etc), but analytics applies the limits during - * cloud processing, the errors will not be seen as Promise rejections when you call logEvent. - * While integrating this API in your app you are strongly encouraged to enable - * [DebugView](https://firebase.google.com/docs/analytics/debugview) - - * any errors in your events will show up in the firebase web console with links to relevant documentation - * - * @param analytics Analytics instance. - * @param name Event name must not conflict with any Reserved Events. - * @param params Parameters to be sent and displayed with the event. - * @param options Additional options that can be passed. Web only. - */ -export declare function logEvent( - analytics: Analytics, - name: 'view_item_list', - params?: { - items?: EventParams['items']; - item_list_name?: EventParams['item_list_name']; - item_list_id?: EventParams['item_list_id']; - [key: string]: any; - }, - options?: AnalyticsCallOptions, -): Promise; - -/** - * Log a custom event with optional params. Note that there are various limits that applied - * to event parameters (total parameter count, etc), but analytics applies the limits during - * cloud processing, the errors will not be seen as Promise rejections when you call logEvent. - * While integrating this API in your app you are strongly encouraged to enable - * [DebugView](https://firebase.google.com/docs/analytics/debugview) - - * any errors in your events will show up in the firebase web console with links to relevant documentation - * - * @param analytics Analytics instance. - * @param name Event name must not conflict with any Reserved Events. - * @param params Parameters to be sent and displayed with the event. - * @param options Additional options that can be passed. Web only. - */ -export declare function logEvent( - analytics: Analytics, - name: FirebaseAnalyticsTypes.CustomEventName, - params?: { - [key: string]: any; - }, - options?: AnalyticsCallOptions, -): Promise; - -/** - * Log a custom event with optional params. Note that there are various limits that applied - * to event parameters (total parameter count, etc), but analytics applies the limits during - * cloud processing, the errors will not be seen as Promise rejections when you call logEvent. - * While integrating this API in your app you are strongly encouraged to enable - * [DebugView](https://firebase.google.com/docs/analytics/debugview) - - * any errors in your events will show up in the firebase web console with links to relevant documentation - * - * @param analytics Analytics instance. - * @param name Event name must not conflict with any Reserved Events. - * @param params Parameters to be sent and displayed with the event. - * @param options Additional options that can be passed. Web only. - */ -export declare function logEvent( - analytics: Analytics, - name: 'add_to_cart' | 'add_to_wishlist' | 'remove_from_cart', - params?: { - currency?: EventParams['currency']; - value?: EventParams['value']; - items?: EventParams['items']; - [key: string]: any; - }, - options?: AnalyticsCallOptions, -): Promise; - -/** - * Log a custom event with optional params. Note that there are various limits that applied - * to event parameters (total parameter count, etc), but analytics applies the limits during - * cloud processing, the errors will not be seen as Promise rejections when you call logEvent. - * While integrating this API in your app you are strongly encouraged to enable - * [DebugView](https://firebase.google.com/docs/analytics/debugview) - - * any errors in your events will show up in the firebase web console with links to relevant documentation - * - * @param analytics Analytics instance. - * @param name Event name must not conflict with any Reserved Events. - * @param params Parameters to be sent and displayed with the event. - * @param options Additional options that can be passed. Web only. - */ -export declare function logEvent( - analytics: Analytics, - name: 'begin_checkout', - params?: { - currency?: EventParams['currency']; - coupon?: EventParams['coupon']; - value?: EventParams['value']; - items?: EventParams['items']; - [key: string]: any; - }, - options?: AnalyticsCallOptions, -): Promise; - -/** - * Log a custom event with optional params. Note that there are various limits that applied - * to event parameters (total parameter count, etc), but analytics applies the limits during - * cloud processing, the errors will not be seen as Promise rejections when you call logEvent. - * While integrating this API in your app you are strongly encouraged to enable - * [DebugView](https://firebase.google.com/docs/analytics/debugview) - - * any errors in your events will show up in the firebase web console with links to relevant documentation - * - * @param analytics Analytics instance. - * @param name Event name must not conflict with any Reserved Events. - * @param params Parameters to be sent and displayed with the event. - * @param options Additional options that can be passed. Web only. - */ -export declare function logEvent( - analytics: Analytics, - name: 'checkout_progress', - params?: { - currency?: EventParams['currency']; - coupon?: EventParams['coupon']; - value?: EventParams['value']; - items?: EventParams['items']; - checkout_step?: EventParams['checkout_step']; - checkout_option?: EventParams['checkout_option']; - [key: string]: any; - }, - options?: AnalyticsCallOptions, -): Promise; - -/** - * Log a custom event with optional params. Note that there are various limits that applied - * to event parameters (total parameter count, etc), but analytics applies the limits during - * cloud processing, the errors will not be seen as Promise rejections when you call logEvent. - * While integrating this API in your app you are strongly encouraged to enable - * [DebugView](https://firebase.google.com/docs/analytics/debugview) - - * any errors in your events will show up in the firebase web console with links to relevant documentation - * - * @param analytics Analytics instance. - * @param name Event name must not conflict with any Reserved Events. - * @param params Parameters to be sent and displayed with the event. - * @param options Additional options that can be passed. Web only. - */ -export declare function logEvent( - analytics: Analytics, - name: 'exception', - params?: { - description?: EventParams['description']; - fatal?: EventParams['fatal']; - [key: string]: any; - }, - options?: AnalyticsCallOptions, -): Promise; - -/** - * Log a custom event with optional params. Note that there are various limits that applied - * to event parameters (total parameter count, etc), but analytics applies the limits during - * cloud processing, the errors will not be seen as Promise rejections when you call logEvent. - * While integrating this API in your app you are strongly encouraged to enable - * [DebugView](https://firebase.google.com/docs/analytics/debugview) - - * any errors in your events will show up in the firebase web console with links to relevant documentation - * - * @param analytics Analytics instance. - * @param name Event name must not conflict with any Reserved Events. - * @param params Parameters to be sent and displayed with the event. - * @param options Additional options that can be passed. Web only. - */ -export declare function logEvent( - analytics: Analytics, - name: 'generate_lead', - params?: { - value?: EventParams['value']; - currency?: EventParams['currency']; - [key: string]: any; - }, - options?: AnalyticsCallOptions, -): Promise; - -/** - * Log a custom event with optional params. Note that there are various limits that applied - * to event parameters (total parameter count, etc), but analytics applies the limits during - * cloud processing, the errors will not be seen as Promise rejections when you call logEvent. - * While integrating this API in your app you are strongly encouraged to enable - * [DebugView](https://firebase.google.com/docs/analytics/debugview) - - * any errors in your events will show up in the firebase web console with links to relevant documentation - * - * @param analytics Analytics instance. - * @param name Event name must not conflict with any Reserved Events. - * @param params Parameters to be sent and displayed with the event. - * @param options Additional options that can be passed. Web only. - */ -export declare function logEvent( - analytics: Analytics, - name: 'login', - params?: { - method?: EventParams['method']; - [key: string]: any; - }, - options?: AnalyticsCallOptions, -): Promise; - -/** - * Log a custom event with optional params. Note that there are various limits that applied - * to event parameters (total parameter count, etc), but analytics applies the limits during - * cloud processing, the errors will not be seen as Promise rejections when you call logEvent. - * While integrating this API in your app you are strongly encouraged to enable - * [DebugView](https://firebase.google.com/docs/analytics/debugview) - - * any errors in your events will show up in the firebase web console with links to relevant documentation - * - * @param analytics Analytics instance. - * @param name Event name must not conflict with any Reserved Events. - * @param params Parameters to be sent and displayed with the event. - * @param options Additional options that can be passed. Web only. - */ -export declare function logEvent( - analytics: Analytics, - name: 'page_view', - params?: { - page_title?: string; - page_location?: string; - page_path?: string; - [key: string]: any; - }, - options?: AnalyticsCallOptions, -): Promise; - -/** - * If true, allows the device to collect analytical data and send it to - * Firebase. Useful for GDPR. - */ -export declare function setAnalyticsCollectionEnabled( - analyticsInstance: Analytics, - enabled: boolean, -): Promise; - -/** - * Sets the duration of inactivity that terminates the current session. - * - * @param analytics Analytics instance. - * @param milliseconds The default value is 1800000 (30 minutes). - */ -export declare function setSessionTimeoutDuration( - analytics: Analytics, - milliseconds: number, -): Promise; - -/** - * Retrieve the app instance id of the application. - * - * @param analytics Analytics instance. - * @returns Returns the app instance id or null on android if FirebaseAnalytics.ConsentType.ANALYTICS_STORAGE has been set to FirebaseAnalytics.ConsentStatus.DENIED and null on iOS if ConsentType.analyticsStorage has been set to ConsentStatus.denied. - */ -export function getAppInstanceId(analytics: Analytics): Promise; - -/** - * Gives a user a unique identification. - * - * @param analytics Analytics instance. - * @param id Set to null to remove a previously assigned ID from analytics events - * @param options Additional options that can be passed to Analytics method calls such as logEvent, etc. - */ -export function setUserId( - analytics: Analytics, - id: string | null, - options?: AnalyticsCallOptions, -): Promise; - -/** - * Sets a key/value pair of data on the current user. Each Firebase project can have up to 25 uniquely named (case-sensitive) user properties. - * - * @param analytics Analytics instance. - * @param name A user property identifier. - * @param value Set to null to remove a previously assigned ID from analytics events. - */ -export function setUserProperty( - analytics: Analytics, - name: string, - value: string | null, -): Promise; - -/** - * Sets multiple key/value pairs of data on the current user. Each Firebase project can have up to 25 uniquely named (case-sensitive) user properties. - * - * > When you set user properties, be sure to never include personally identifiable information such as names, social security numbers, or email addresses, even in hashed form. - * - * @param analytics Analytics instance. - * @param properties Set a property value to null to remove it. - * @param options `AnalyticsCallOptions`. Additional options that can be passed. Web only. - */ -export function setUserProperties( - analytics: Analytics, - properties: { [key: string]: any }, - options?: AnalyticsCallOptions, -): Promise; - -/** - * Clears all analytics data for this instance from the device and resets the app instance ID. - * - * @param analytics Analytics instance. - */ -export function resetAnalyticsData(analytics: Analytics): Promise; - -/** - * E-Commerce Purchase event. This event signifies that an item(s) was purchased by a user. Note: This is different from the in-app purchase event, which is reported - * automatically for Google Play-based apps. - * - * If you supply the `value` parameter, you must also supply the `currency` parameter so that revenue metrics can be computed accurately. - * - * Logged event name: `purchase` - * - * @param analytics Analytics instance. - * @param object See {@link analytics.AddPaymentInfoEventParameters}. - */ -export function logAddPaymentInfo( - analytics: Analytics, - object: FirebaseAnalyticsTypes.AddPaymentInfoEventParameters, -): Promise; - -/** - * Sets or clears the screen name and class the user is currently viewing - * - * @param analytics Analytics instance. - * @param params See {@link analytics.ScreenViewParameters}. - */ -export function logScreenView( - analytics: Analytics, - params: FirebaseAnalyticsTypes.ScreenViewParameters, -): Promise; - -/** - * Add Payment Info event. This event signifies that a user has submitted their payment information to your app. - * - * If you supply the `value` parameter, you must also supply the `currency` parameter so that revenue metrics can be computed accurately. - * - * Logged event name: `add_payment_info` - * - * @param analytics Analytics instance. - * @param params See {@link analytics.AddShippingInfoParameters}. - */ -export function logAddShippingInfo( - analytics: Analytics, - params: FirebaseAnalyticsTypes.AddShippingInfoParameters, -): Promise; - -/** - * E-Commerce Add To Cart event. - * - * If you supply the `value` parameter, you must also supply the `currency` parameter so that revenue metrics can be computed accurately. - * - * Logged event name: `add_to_cart` - * - * @param analytics Analytics instance. - * @param params See {@link analytics.AddToCartEventParameters}. - */ -export function logAddToCart( - analytics: Analytics, - params: FirebaseAnalyticsTypes.AddToCartEventParameters, -): Promise; - -/** - * E-Commerce Add To Wishlist event. This event signifies that an item was added to a wishlist. - * Use this event to identify popular gift items in your app. - * - * If you supply the `value` parameter, you must also supply the `currency` parameter so that revenue metrics can be computed accurately. - * - * Logged event name: `add_to_wishlist - * - * @param analytics Analytics instance. - * @param params See {@link analytics.AddToWishlistEventParameters}. - */ -export function logAddToWishlist( - analytics, - params: FirebaseAnalyticsTypes.AddToWishlistEventParameters, -): Promise; - -/** - * App Open event. By logging this event when an App is moved to the foreground, developers can - * understand how often users leave and return during the course of a Session. Although Sessions - * are automatically reported, this event can provide further clarification around the continuous - * engagement of app-users. - * - * @param analytics Analytics instance. - */ -export function logAppOpen(analytics: Analytics): Promise; - -/** - * E-Commerce Begin Checkout event. This event signifies that a user has begun the process of - * checking out. - * - * If you supply the `value` parameter, you must also supply the `currency` parameter so that revenue metrics can be computed accurately. - * - * Logged event name: `begin_checkout` - * - * @param analytics Analytics instance. - * @param params See {@link analytics.BeginCheckoutEventParameters}. - */ -export function logBeginCheckout( - analytics: Analytics, - params: FirebaseAnalyticsTypes.BeginCheckoutEventParameters, -): Promise; - -/** - * Log this event to supply the referral details of a re-engagement campaign. - * - * Logged event name: `campaign_details` - * - * @param analytics Analytics instance. - * @param params See {@link analytics.CampaignDetailsEventParameters}. - */ -export function logCampaignDetails( - analytics: Analytics, - params: FirebaseAnalyticsTypes.CampaignDetailsEventParameters, -): Promise; - -/** - * Earn Virtual Currency event. This event tracks the awarding of virtual currency in your app. Log this along with - * {@link analytics.logSpendVirtualCurrency} to better understand your virtual economy. - * - * Logged event name: `earn_virtual_currency` - * - * @param analytics Analytics instance. - * @param params See {@link analytics.EarnVirtualCurrencyEventParameters}. - */ -export function logEarnVirtualCurrency( - analytics: Analytics, - params: FirebaseAnalyticsTypes.EarnVirtualCurrencyEventParameters, -): Promise; - -/** - * Generate Lead event. Log this event when a lead has been generated in the app to understand - * the efficacy of your install and re-engagement campaigns. - * - * If you supply the `value` parameter, you must also supply the `currency` parameter so that revenue metrics can be computed accurately. - * - * Logged event name: `generate_lead` - * - * @param analytics Analytics instance. - * @param params See {@link analytics.GenerateLeadEventParameters}. - */ -export function logGenerateLead( - analytics: Analytics, - params: FirebaseAnalyticsTypes.GenerateLeadEventParameters, -): Promise; - -/** - * Join Group event. Log this event when a user joins a group such as a guild, team or family. - * Use this event to analyze how popular certain groups or social features are in your app - * - * Logged event name: `join_group` - * - * @param analytics Analytics instance. - * @param params See {@link analytics.JoinGroupEventParameters}. - */ -export function logJoinGroup( - analytics: Analytics, - params: FirebaseAnalyticsTypes.JoinGroupEventParameters, -): Promise; - -/** - * Level End event. - * - * Logged event name: `level_end` - * - * @param analytics Analytics instance. - * @param params See {@link analytics.LevelEndEventParameters}. - */ -export function logLevelEnd( - analytics: Analytics, - params: FirebaseAnalyticsTypes.LevelEndEventParameters, -): Promise; - -/** - * Level Start event. - * - * Logged event name: `level_start` - * - * @param analytics Analytics instance. - * @param params See {@link analytics.LevelStartEventParameters}. - */ -export function logLevelStart( - analytics: Analytics, - params: FirebaseAnalyticsTypes.LevelStartEventParameters, -): Promise; - -/** - * Level Up event. This event signifies that a player has leveled up in your gaming app. - * It can help you gauge the level distribution of your userbase and help you identify certain levels that are difficult to pass. - * - * Logged event name: `level_up` - * - * @param analytics Analytics instance. - * @param params See {@link analytics.LevelUpEventParameters}. - */ -export function logLevelUp( - analytics: Analytics, - params: FirebaseAnalyticsTypes.LevelUpEventParameters, -): Promise; - -/** - * Login event. Apps with a login feature can report this event to signify that a user has logged in. - * - * Logged event name: `login` - * - * @param analytics Analytics instance. - * @param params See {@link analytics.LoginEventParameters}. - */ -export function logLogin( - analytics: Analytics, - params: FirebaseAnalyticsTypes.LoginEventParameters, -): Promise; - -/** - * Post Score event. Log this event when the user posts a score in your gaming app. This event can - * help you understand how users are actually performing in your game and it can help you correlate - * high scores with certain audiences or behaviors. - * - * Logged event name: `post_score` - * - * @param analytics Analytics instance. - * @param params See {@link analytics.PostScoreEventParameters}. - */ -export function logPostScore( - analytics: Analytics, - params: FirebaseAnalyticsTypes.PostScoreEventParameters, -): Promise; - -/** - * Select Content event. This general purpose event signifies that a user has selected some - * content of a certain type in an app. The content can be any object in your app. This event - * can help you identify popular content and categories of content in your app. - * - * Logged event name: `select_content` - * - * @param analytics Analytics instance. - * @param params See {@link analytics.SelectContentEventParameters}. - */ -export function logSelectContent( - analytics: Analytics, - params: FirebaseAnalyticsTypes.SelectContentEventParameters, -): Promise; - -/** - * E-Commerce Purchase event. This event signifies that an item(s) was purchased by a user. Note: This is different from the in-app purchase event, which is reported - * automatically for Google Play-based apps. - * - * If you supply the `value` parameter, you must also supply the `currency` parameter so that revenue metrics can be computed accurately. - * - * Logged event name: `purchase` - * - * @param analytics Analytics instance. - * @param params See {@link analytics.PurchaseEventParameters}. - */ -export function logPurchase( - analytics: Analytics, - params: FirebaseAnalyticsTypes.PurchaseEventParameters, -): Promise; - -/** - * E-Commerce Refund event. This event signifies that a refund was issued. - * - * Logged event name: `remove_from_cart` - * - * @param analytics Analytics instance. - * @param params See {@link analytics.RefundEventParameters}. - */ -export function logRefund( - analytics: Analytics, - params: FirebaseAnalyticsTypes.RefundEventParameters, -): Promise; - -/** - * Remove from cart event. - * - * Logged event name: `remove_from_cart` - * - * @param analytics Analytics instance. - * @param params See {@link analytics.RemoveFromCartEventParameters}. - */ -export function logRemoveFromCart( - analytics: Analytics, - params: FirebaseAnalyticsTypes.RemoveFromCartEventParameters, -): Promise; - -/** - * Search event. Apps that support search features can use this event to contextualize search - * operations by supplying the appropriate, corresponding parameters. This event can help you - * identify the most popular content in your app. - * - * Logged event name: `search` - * - * @param analytics Analytics instance. - * @param params See {@link analytics.SearchEventParameters}. - */ -export function logSearch( - analytics: Analytics, - params: FirebaseAnalyticsTypes.SearchEventParameters, -): Promise; - -/** - * Select Item event. This event signifies that an item was selected by a user from a list. - * Use the appropriate parameters to contextualize the event. - * Use this event to discover the most popular items selected. - * - * Logged event name: `select_item` - * - * @param analytics Analytics instance. - * @param params See {@link analytics.SelectItemEventParameters}. - */ -export function logSelectItem( - analytics: Analytics, - params: FirebaseAnalyticsTypes.SelectItemEventParameters, -): Promise; - -/** - * Set checkout option event. - * - * Logged event name: `set_checkout_option` - * - * @param analytics Analytics instance. - * @param params See {@link analytics.SetCheckoutOptionEventParameters}. - */ -export function logSetCheckoutOption( - analytics: Analytics, - params: FirebaseAnalyticsTypes.SetCheckoutOptionEventParameters, -): Promise; - -/** - * Select promotion event. This event signifies that a user has selected a promotion offer. Use the - * appropriate parameters to contextualize the event, such as the item(s) for which the promotion applies. - * - * Logged event name: `select_promotion` - * - * @param analytics Analytics instance. - * @param params See {@link analytics.SelectPromotionEventParameters}. - */ -export function logSelectPromotion( - analytics: Analytics, - params: FirebaseAnalyticsTypes.SelectPromotionEventParameters, -): Promise; - -/** - * Share event. Apps with social features can log the Share event to identify the most viral content. - * - * Logged event name: `share` - * - * @param analytics Analytics instance. - * @param params See {@link analytics.ShareEventParameters}. - */ -export function logShare( - analytics: Analytics, - params: FirebaseAnalyticsTypes.ShareEventParameters, -): Promise; - -/** - * Sign Up event. This event indicates that a user has signed up for an account in your app. - * The parameter signifies the method by which the user signed up. Use this event to understand - * the different behaviors between logged in and logged out users. - * - * Logged event name: `sign_up` - * - * @param analytics Analytics instance. - * @param params See {@link analytics.SignUpEventParameters}. - */ -export function logSignUp( - analytics: Analytics, - params: FirebaseAnalyticsTypes.SignUpEventParameters, -): Promise; - -/** - * Spend Virtual Currency event. This event tracks the sale of virtual goods in your app and can - * help you identify which virtual goods are the most popular objects of purchase. - * - * Logged event name: `spend_virtual_currency` - * - * @param analytics Analytics instance. - * @param params See {@link analytics.SpendVirtualCurrencyEventParameters}. - */ -export function logSpendVirtualCurrency( - analytics: Analytics, - params: FirebaseAnalyticsTypes.SpendVirtualCurrencyEventParameters, -): Promise; - -/** - * Tutorial Begin event. This event signifies the start of the on-boarding process in your app. - * Use this in a funnel with {@link analytics#logTutorialComplete} to understand how many users - * complete this process and move on to the full app experience. - * - * Logged event name: `tutorial_begin` - * - * @param analytics Analytics instance. - */ -export function logTutorialBegin(analytics: Analytics): Promise; - -/** - * Tutorial End event. Use this event to signify the user's completion of your app's on-boarding process. - * Add this to a funnel with {@link analytics#logTutorialBegin} to understand how many users - * complete this process and move on to the full app experience. - * - * Logged event name: `tutorial_complete` - * - * @param analytics Analytics instance. - */ -export function logTutorialComplete(analytics: Analytics): Promise; - -/** - * Unlock Achievement event. Log this event when the user has unlocked an achievement in your game. - * Since achievements generally represent the breadth of a gaming experience, this event can help - * you understand how many users are experiencing all that your game has to offer. - * - * Logged event name: `unlock_achievement` - * - * @param analytics Analytics instance. - * @param params See {@link analytics.UnlockAchievementEventParameters}. - */ -export function logUnlockAchievement( - analytics: Analytics, - params: FirebaseAnalyticsTypes.UnlockAchievementEventParameters, -): Promise; - -/** - * E-commerce View Cart event. This event signifies that a user has viewed their cart. Use this to analyze your purchase funnel. - * - * If you supply the `value` parameter, you must also supply the `currency` parameter so that revenue metrics can be computed accurately. - * - * Logged event name: `view_cart` - * - * @param analytics Analytics instance. - * @param params See {@link analytics.ViewCartEventParameters}. - */ -export function logViewCart( - analytics: Analytics, - params: FirebaseAnalyticsTypes.ViewCartEventParameters, -): Promise; - -/** - * View Item event. This event signifies that some content was shown to the user. This content - * may be a product, a screen or just a simple image or text. Use the appropriate parameters - * to contextualize the event. Use this event to discover the most popular items viewed in your app. - * - * If you supply the `value` parameter, you must also supply the `currency` parameter so that revenue metrics can be computed accurately. - * - * Logged event name: `view_item` - * - * @param analytics Analytics instance. - * @param params See {@link analytics.ViewItemEventParameters}. - */ -export function logViewItem( - analytics: Analytics, - params: FirebaseAnalyticsTypes.ViewItemEventParameters, -): Promise; - -/** - * View Item List event. Log this event when the user has been presented with a list of items of a certain category. - * - * Logged event name: `view_item_list` - * - * @param analytics Analytics instance. - * @param params See {@link analytics.ViewItemListEventParameters}. - */ -export function logViewItemList( - analytics: Analytics, - params: FirebaseAnalyticsTypes.ViewItemListEventParameters, -): Promise; - -/** - * View Promotion event. This event signifies that a promotion was shown to a user. - * - * Logged event name: `view_promotion` - * - * @param analytics Analytics instance. - * @param params See {@link analytics.ViewPromotionEventParameters}. - */ -export function logViewPromotion( - analytics: Analytics, - params: FirebaseAnalyticsTypes.ViewPromotionEventParameters, -): Promise; - -/** - * View Search Results event. Log this event when the user has been presented with the results of a search. - * - * Logged event name: `view_search_results` - * - * @param analytics Analytics instance. - * @param params See {@link analytics.ViewSearchResultsParameters}. - */ -export function logViewSearchResults( - analytics: Analytics, - params: FirebaseAnalyticsTypes.ViewSearchResultsParameters, -): Promise; - -/** - * Adds parameters that will be set on every event logged from the SDK, including automatic ones. - * - * They will be added to the map of default event parameters, replacing any existing - * parameter with the same name. Valid parameter values are String, long, and double. - * Setting a key's value to null will clear that parameter. Passing in a null bundle - * will clear all parameters. - * For Web, the values passed persist on the current page and are passed with all - * subsequent events. - * - * @platform ios - * @param analytics Analytics instance. - * @param params Parameters to be added to the map of parameters added to every event. - */ -export function setDefaultEventParameters( - analytics: Analytics, - params: { [p: string]: any }, -): Promise; - -/** - * Start privacy-sensitive on-device conversion management. - * This is iOS-only. - * This is a no-op if you do not include '$RNFirebaseAnalyticsGoogleAppMeasurementOnDeviceConversion = true' in your Podfile. - * - * @platform ios - * @param analytics Analytics instance. - * @param emailAddress email address, properly formatted complete with domain name e.g, 'user@example.com' - */ -export function initiateOnDeviceConversionMeasurementWithEmailAddress( - analytics: Analytics, - emailAddress: string, -): Promise; - -/** - * Start privacy-sensitive on-device conversion management. - * This is iOS-only. - * This is a no-op if you do not include '$RNFirebaseAnalyticsGoogleAppMeasurementOnDeviceConversion = true' in your Podfile. - * You need to pass the sha256-hashed of normalized email address to this function. See [this link](https://firebase.google.com/docs/tutorials/ads-ios-on-device-measurement/step-3#use-hashed-credentials) for more information. - * - * @platform ios - * @param analytics Analytics instance. - * @param hashedEmailAddress sha256-hashed of normalized email address, properly formatted complete with domain name e.g, 'user@example.com' - */ -export function initiateOnDeviceConversionMeasurementWithHashedEmailAddress( - analytics: Analytics, - hashedEmailAddress: string, -): Promise; - -/** - * Start privacy-sensitive on-device conversion management. - * This is iOS-only. - * This is a no-op if you do not include '$RNFirebaseAnalyticsGoogleAppMeasurementOnDeviceConversion = true' in your Podfile. - * - * @platform ios - * @param analytics Analytics instance. - * @param phoneNumber phone number in E.164 format - that is a leading + sign, then up to 15 digits, no dashes or spaces. - */ -export function initiateOnDeviceConversionMeasurementWithPhoneNumber( - analytics: Analytics, - phoneNumber: string, -): Promise; - -/** - * Start privacy-sensitive on-device conversion management. - * This is iOS-only. - * This is a no-op if you do not include '$RNFirebaseAnalyticsGoogleAppMeasurementOnDeviceConversion = true' in your Podfile. - * You need to pass the sha256-hashed of phone number in E.164 format. See [this link](https://firebase.google.com/docs/tutorials/ads-ios-on-device-measurement/step-3#use-hashed-credentials) for more information. - * - * @platform ios - * @param analytics Analytics instance. - * @param hashedPhoneNumber sha256-hashed of normalized phone number in E.164 format - that is a leading + sign, then up to 15 digits, no dashes or spaces. - */ -export function initiateOnDeviceConversionMeasurementWithHashedPhoneNumber( - analytics: Analytics, - hashedPhoneNumber: string, -): Promise; - -/** - * Checks four different things. - * 1. Checks if it's not a browser extension environment. - * 2. Checks if cookies are enabled in current browser. - * 3. Checks if IndexedDB is supported by the browser environment. - * 4. Checks if the current browser context is valid for using IndexedDB.open(). - * - * @returns {Promise} - */ -export function isSupported(): Promise; - -/** - * Sets the applicable end user consent state for this app. - * references once Firebase Analytics is initialized. - * @param analytics Analytics instance. - * @param consentSettings See {@link analytics.ConsentSettings}. - * @returns {Promise} - */ -export function setConsent( - analytics: Analytics, - consentSettings: FirebaseAnalyticsTypes.ConsentSettings, -): Promise; - -/** - * Configures Firebase Analytics to use custom gtag or dataLayer names. - * Intended to be used if gtag.js script has been installed on this page - * independently of Firebase Analytics, and is using non-default names for - * either the gtag function or for dataLayer. Must be called before calling - * `getAnalytics()` or it won't have any effect. Web only. - * @param options See {@link analytics.SettingsOptions}. - * @returns {void} - */ -export function settings(options: FirebaseAnalyticsTypes.SettingsOptions): void; - -/** - * Retrieves the session id from the client. - * On iOS, Firebase SDK may return an error that is handled internally and may take many minutes to return a valid value. Check native debug logs for more details. - * - * Returns the session id or null if session is expired, null on android if FirebaseAnalytics.ConsentType.ANALYTICS_STORAGE has been set to FirebaseAnalytics.ConsentStatus.DENIED and null on iOS if ConsentType.analyticsStorage has been set to ConsentStatus.denied. - * @param {Analytics} instance. - * @returns {Promise} - */ -export function getSessionId(analytics: Analytics): Promise; diff --git a/packages/analytics/lib/index.js b/packages/analytics/lib/namespaced.ts similarity index 77% rename from packages/analytics/lib/index.js rename to packages/analytics/lib/namespaced.ts index 581af582f3..e33c0bc34f 100644 --- a/packages/analytics/lib/index.js +++ b/packages/analytics/lib/namespaced.ts @@ -14,7 +14,7 @@ * limitations under the License. * */ - +import { ReactNativeFirebase } from '@react-native-firebase/app'; import { isAlphaNumericUnderscore, isE164PhoneNumber, @@ -32,15 +32,54 @@ import { FirebaseModule, getFirebaseRoot, } from '@react-native-firebase/app/lib/internal'; + +// Internal types are now available through module declarations in app package import { setReactNativeModule } from '@react-native-firebase/app/lib/internal/nativeModule'; import { isBoolean } from '@react-native-firebase/app/lib/common'; import { validateStruct, validateCompound } from './struct'; -import fallBackModule from './web/RNFBAnalyticsModule'; -import version from './version'; +import { RNFBAnalyticsModule } from './web/RNFBAnalyticsModule'; +import { version } from './version'; import * as structs from './structs'; - -const ReservedEventNames = [ +import { + Statics, + AnalyticsCallOptions, + ConsentSettings, + AddPaymentInfoEventParameters, + ScreenViewParameters, + AddShippingInfoParameters, + AddToCartEventParameters, + AddToWishlistEventParameters, + BeginCheckoutEventParameters, + CampaignDetailsEventParameters, + EarnVirtualCurrencyEventParameters, + GenerateLeadEventParameters, + JoinGroupEventParameters, + LevelEndEventParameters, + LevelStartEventParameters, + LevelUpEventParameters, + LoginEventParameters, + PostScoreEventParameters, + SelectContentEventParameters, + PurchaseEventParameters, + RefundEventParameters, + RemoveFromCartEventParameters, + SearchEventParameters, + SelectItemEventParameters, + SetCheckoutOptionEventParameters, + SelectPromotionEventParameters, + ShareEventParameters, + SignUpEventParameters, + SpendVirtualCurrencyEventParameters, + UnlockAchievementEventParameters, + ViewCartEventParameters, + ViewItemEventParameters, + ViewItemListEventParameters, + ViewPromotionEventParameters, + ViewSearchResultsParameters, +} from './types/analytics'; + +const ReservedEventNames: readonly string[] = [ 'ad_activeview', 'ad_click', 'ad_exposure', @@ -73,16 +112,20 @@ const ReservedEventNames = [ 'session_start', 'session_start_with_rollout', 'user_engagement', -]; +] as const; -const statics = {}; +const statics: Statics = {}; const namespace = 'analytics'; const nativeModuleName = 'RNFBAnalyticsModule'; class FirebaseAnalyticsModule extends FirebaseModule { - logEvent(name, params = {}, options = {}) { + logEvent( + name: string, + params: { [key: string]: any } = {}, + options: AnalyticsCallOptions = { global: false }, + ): Promise { if (!isString(name)) { throw new Error("firebase.analytics().logEvent(*) 'name' expected a string value."); } @@ -92,7 +135,7 @@ class FirebaseAnalyticsModule extends FirebaseModule { } // check name is not a reserved event name - if (isOneOf(name, ReservedEventNames)) { + if (isOneOf(name, ReservedEventNames as any[])) { throw new Error( `firebase.analytics().logEvent(*) 'name' the event name '${name}' is reserved and can not be used.`, ); @@ -120,7 +163,7 @@ class FirebaseAnalyticsModule extends FirebaseModule { return this.native.logEvent(name, params); } - setAnalyticsCollectionEnabled(enabled) { + setAnalyticsCollectionEnabled(enabled: boolean): Promise { if (!isBoolean(enabled)) { throw new Error( "firebase.analytics().setAnalyticsCollectionEnabled(*) 'enabled' expected a boolean value.", @@ -130,7 +173,7 @@ class FirebaseAnalyticsModule extends FirebaseModule { return this.native.setAnalyticsCollectionEnabled(enabled); } - setSessionTimeoutDuration(milliseconds = 1800000) { + setSessionTimeoutDuration(milliseconds: number = 1800000): Promise { if (!isNumber(milliseconds)) { throw new Error( "firebase.analytics().setSessionTimeoutDuration(*) 'milliseconds' expected a number value.", @@ -146,15 +189,15 @@ class FirebaseAnalyticsModule extends FirebaseModule { return this.native.setSessionTimeoutDuration(milliseconds); } - getAppInstanceId() { + getAppInstanceId(): Promise { return this.native.getAppInstanceId(); } - getSessionId() { + getSessionId(): Promise { return this.native.getSessionId(); } - setUserId(id) { + setUserId(id: string | null): Promise { if (!isNull(id) && !isString(id)) { throw new Error("firebase.analytics().setUserId(*) 'id' expected a string value."); } @@ -162,7 +205,7 @@ class FirebaseAnalyticsModule extends FirebaseModule { return this.native.setUserId(id); } - setUserProperty(name, value) { + setUserProperty(name: string, value: string | null): Promise { if (!isString(name)) { throw new Error("firebase.analytics().setUserProperty(*) 'name' expected a string value."); } @@ -176,7 +219,10 @@ class FirebaseAnalyticsModule extends FirebaseModule { return this.native.setUserProperty(name, value); } - setUserProperties(properties, options = {}) { + setUserProperties( + properties: { [key: string]: string | null }, + options: AnalyticsCallOptions = { global: false }, + ): Promise { if (!isObject(properties)) { throw new Error( "firebase.analytics().setUserProperties(*) 'properties' expected an object of key/value pairs.", @@ -197,7 +243,9 @@ class FirebaseAnalyticsModule extends FirebaseModule { const entries = Object.entries(properties); for (let i = 0; i < entries.length; i++) { - const [key, value] = entries[i]; + const entry = entries[i]; + if (!entry) continue; + const [key, value] = entry; if (!isNull(value) && !isString(value)) { throw new Error( `firebase.analytics().setUserProperties(*) 'properties' value for parameter '${key}' is invalid, expected a string.`, @@ -208,11 +256,11 @@ class FirebaseAnalyticsModule extends FirebaseModule { return this.native.setUserProperties(properties); } - resetAnalyticsData() { + resetAnalyticsData(): Promise { return this.native.resetAnalyticsData(); } - setConsent(consentSettings) { + setConsent(consentSettings: ConsentSettings): Promise { if (!isObject(consentSettings)) { throw new Error( 'firebase.analytics().setConsent(*): The supplied arg must be an object of key/values.', @@ -221,7 +269,9 @@ class FirebaseAnalyticsModule extends FirebaseModule { const entries = Object.entries(consentSettings); for (let i = 0; i < entries.length; i++) { - const [key, value] = entries[i]; + const entry = entries[i]; + if (!entry) continue; + const [key, value] = entry; if (!isBoolean(value)) { throw new Error( `firebase.analytics().setConsent(*) 'consentSettings' value for parameter '${key}' is invalid, expected a boolean.`, @@ -235,7 +285,7 @@ class FirebaseAnalyticsModule extends FirebaseModule { /** ------------------- * EVENTS * -------------------- */ - logAddPaymentInfo(object = {}) { + logAddPaymentInfo(object: AddPaymentInfoEventParameters): Promise { if (!isObject(object)) { throw new Error( 'firebase.analytics().logAddPaymentInfo(*): The supplied arg must be an object of key/values.', @@ -250,7 +300,7 @@ class FirebaseAnalyticsModule extends FirebaseModule { ); } - logScreenView(object) { + logScreenView(object: ScreenViewParameters): Promise { if (!isObject(object)) { throw new Error( 'firebase.analytics().logScreenView(*): The supplied arg must be an object of key/values.', @@ -263,7 +313,7 @@ class FirebaseAnalyticsModule extends FirebaseModule { ); } - logAddShippingInfo(object = {}) { + logAddShippingInfo(object: AddShippingInfoParameters = {}): Promise { if (!isObject(object)) { throw new Error( 'firebase.analytics().logAddShippingInfo(*): The supplied arg must be an object of key/values.', @@ -282,7 +332,7 @@ class FirebaseAnalyticsModule extends FirebaseModule { ); } - logAddToCart(object = {}) { + logAddToCart(object: AddToCartEventParameters = {}): Promise { if (!isObject(object)) { throw new Error( 'firebase.analytics().logAddToCart(*): The supplied arg must be an object of key/values.', @@ -297,7 +347,7 @@ class FirebaseAnalyticsModule extends FirebaseModule { ); } - logAddToWishlist(object = {}) { + logAddToWishlist(object: AddToWishlistEventParameters = {}): Promise { if (!isObject(object)) { throw new Error( 'firebase.analytics().logAddToWishlist(*): The supplied arg must be an object of key/values.', @@ -312,11 +362,11 @@ class FirebaseAnalyticsModule extends FirebaseModule { ); } - logAppOpen() { + logAppOpen(): Promise { return this.logEvent('app_open'); } - logBeginCheckout(object = {}) { + logBeginCheckout(object: BeginCheckoutEventParameters = {}): Promise { if (!isObject(object)) { throw new Error( 'firebase.analytics().logBeginCheckout(*): The supplied arg must be an object of key/values.', @@ -331,7 +381,7 @@ class FirebaseAnalyticsModule extends FirebaseModule { ); } - logCampaignDetails(object) { + logCampaignDetails(object: CampaignDetailsEventParameters): Promise { if (!isObject(object)) { throw new Error( 'firebase.analytics().logCampaignDetails(*): The supplied arg must be an object of key/values.', @@ -348,7 +398,7 @@ class FirebaseAnalyticsModule extends FirebaseModule { ); } - logEarnVirtualCurrency(object) { + logEarnVirtualCurrency(object: EarnVirtualCurrencyEventParameters): Promise { if (!isObject(object)) { throw new Error( 'firebase.analytics().logEarnVirtualCurrency(*): The supplied arg must be an object of key/values.', @@ -365,7 +415,7 @@ class FirebaseAnalyticsModule extends FirebaseModule { ); } - logGenerateLead(object = {}) { + logGenerateLead(object: GenerateLeadEventParameters = {}): Promise { if (!isObject(object)) { throw new Error( 'firebase.analytics().logGenerateLead(*): The supplied arg must be an object of key/values.', @@ -380,7 +430,7 @@ class FirebaseAnalyticsModule extends FirebaseModule { ); } - logJoinGroup(object) { + logJoinGroup(object: JoinGroupEventParameters): Promise { if (!isObject(object)) { throw new Error( 'firebase.analytics().logJoinGroup(*): The supplied arg must be an object of key/values.', @@ -393,7 +443,7 @@ class FirebaseAnalyticsModule extends FirebaseModule { ); } - logLevelEnd(object) { + logLevelEnd(object: LevelEndEventParameters): Promise { if (!isObject(object)) { throw new Error( 'firebase.analytics().logLevelEnd(*): The supplied arg must be an object of key/values.', @@ -406,7 +456,7 @@ class FirebaseAnalyticsModule extends FirebaseModule { ); } - logLevelStart(object) { + logLevelStart(object: LevelStartEventParameters): Promise { if (!isObject(object)) { throw new Error( 'firebase.analytics().logLevelStart(*): The supplied arg must be an object of key/values.', @@ -419,7 +469,7 @@ class FirebaseAnalyticsModule extends FirebaseModule { ); } - logLevelUp(object) { + logLevelUp(object: LevelUpEventParameters): Promise { if (!isObject(object)) { throw new Error( 'firebase.analytics().logLevelUp(*): The supplied arg must be an object of key/values.', @@ -432,7 +482,7 @@ class FirebaseAnalyticsModule extends FirebaseModule { ); } - logLogin(object) { + logLogin(object: LoginEventParameters): Promise { if (!isObject(object)) { throw new Error( 'firebase.analytics().logLogin(*): The supplied arg must be an object of key/values.', @@ -445,7 +495,7 @@ class FirebaseAnalyticsModule extends FirebaseModule { ); } - logPostScore(object) { + logPostScore(object: PostScoreEventParameters): Promise { if (!isObject(object)) { throw new Error( 'firebase.analytics().logPostScore(*): The supplied arg must be an object of key/values.', @@ -458,7 +508,7 @@ class FirebaseAnalyticsModule extends FirebaseModule { ); } - logSelectContent(object) { + logSelectContent(object: SelectContentEventParameters): Promise { if (!isObject(object)) { throw new Error( 'firebase.analytics().logSelectContent(*): The supplied arg must be an object of key/values.', @@ -471,7 +521,7 @@ class FirebaseAnalyticsModule extends FirebaseModule { ); } - logPurchase(object = {}) { + logPurchase(object: PurchaseEventParameters = {}): Promise { if (!isObject(object)) { throw new Error( 'firebase.analytics().logPurchase(*): The supplied arg must be an object of key/values.', @@ -486,7 +536,7 @@ class FirebaseAnalyticsModule extends FirebaseModule { ); } - logRefund(object = {}) { + logRefund(object: RefundEventParameters = {}): Promise { if (!isObject(object)) { throw new Error( 'firebase.analytics().logRefund(*): The supplied arg must be an object of key/values.', @@ -501,7 +551,7 @@ class FirebaseAnalyticsModule extends FirebaseModule { ); } - logRemoveFromCart(object = {}) { + logRemoveFromCart(object: RemoveFromCartEventParameters = {}): Promise { if (!isObject(object)) { throw new Error( 'firebase.analytics().logRemoveFromCart(*): The supplied arg must be an object of key/values.', @@ -516,7 +566,7 @@ class FirebaseAnalyticsModule extends FirebaseModule { ); } - logSearch(object) { + logSearch(object: SearchEventParameters): Promise { if (!isObject(object)) { throw new Error( 'firebase.analytics().logSearch(*): The supplied arg must be an object of key/values.', @@ -529,7 +579,7 @@ class FirebaseAnalyticsModule extends FirebaseModule { ); } - logSelectItem(object = {}) { + logSelectItem(object: SelectItemEventParameters): Promise { if (!isObject(object)) { throw new Error( 'firebase.analytics().logSelectItem(*): The supplied arg must be an object of key/values.', @@ -542,7 +592,7 @@ class FirebaseAnalyticsModule extends FirebaseModule { ); } - logSetCheckoutOption(object) { + logSetCheckoutOption(object: SetCheckoutOptionEventParameters): Promise { if (!isObject(object)) { throw new Error( 'firebase.analytics().logSetCheckoutOption(*): The supplied arg must be an object of key/values.', @@ -559,7 +609,7 @@ class FirebaseAnalyticsModule extends FirebaseModule { ); } - logSelectPromotion(object) { + logSelectPromotion(object: SelectPromotionEventParameters): Promise { if (!isObject(object)) { throw new Error( 'firebase.analytics().logSelectPromotion(*): The supplied arg must be an object of key/values.', @@ -576,7 +626,7 @@ class FirebaseAnalyticsModule extends FirebaseModule { ); } - logShare(object) { + logShare(object: ShareEventParameters): Promise { if (!isObject(object)) { throw new Error( 'firebase.analytics().logShare(*): The supplied arg must be an object of key/values.', @@ -589,7 +639,7 @@ class FirebaseAnalyticsModule extends FirebaseModule { ); } - logSignUp(object) { + logSignUp(object: SignUpEventParameters): Promise { if (!isObject(object)) { throw new Error( 'firebase.analytics().logSignUp(*): The supplied arg must be an object of key/values.', @@ -602,7 +652,7 @@ class FirebaseAnalyticsModule extends FirebaseModule { ); } - logSpendVirtualCurrency(object) { + logSpendVirtualCurrency(object: SpendVirtualCurrencyEventParameters): Promise { if (!isObject(object)) { throw new Error( 'firebase.analytics().logSpendVirtualCurrency(*): The supplied arg must be an object of key/values.', @@ -619,15 +669,15 @@ class FirebaseAnalyticsModule extends FirebaseModule { ); } - logTutorialBegin() { + logTutorialBegin(): Promise { return this.logEvent('tutorial_begin'); } - logTutorialComplete() { + logTutorialComplete(): Promise { return this.logEvent('tutorial_complete'); } - logUnlockAchievement(object) { + logUnlockAchievement(object: UnlockAchievementEventParameters): Promise { if (!isObject(object)) { throw new Error( 'firebase.analytics().logUnlockAchievement(*): The supplied arg must be an object of key/values.', @@ -644,7 +694,7 @@ class FirebaseAnalyticsModule extends FirebaseModule { ); } - logViewCart(object = {}) { + logViewCart(object: ViewCartEventParameters = {}): Promise { if (!isObject(object)) { throw new Error( 'firebase.analytics().logViewCart(*): The supplied arg must be an object of key/values.', @@ -659,7 +709,7 @@ class FirebaseAnalyticsModule extends FirebaseModule { ); } - logViewItem(object = {}) { + logViewItem(object: ViewItemEventParameters = {}): Promise { if (!isObject(object)) { throw new Error( 'firebase.analytics().logViewItem(*): The supplied arg must be an object of key/values.', @@ -673,7 +723,7 @@ class FirebaseAnalyticsModule extends FirebaseModule { ); } - logViewItemList(object = {}) { + logViewItemList(object: ViewItemListEventParameters = {}): Promise { if (!isObject(object)) { throw new Error( 'firebase.analytics().logViewItemList(*): The supplied arg must be an object of key/values.', @@ -686,7 +736,7 @@ class FirebaseAnalyticsModule extends FirebaseModule { ); } - logViewPromotion(object = {}) { + logViewPromotion(object: ViewPromotionEventParameters = {}): Promise { if (!isObject(object)) { throw new Error( 'firebase.analytics().logViewPromotion(*): The supplied arg must be an object of key/values.', @@ -702,7 +752,7 @@ class FirebaseAnalyticsModule extends FirebaseModule { * Unsupported in "Enhanced Ecommerce reports": * https://firebase.google.com/docs/reference/android/com/google/firebase/analytics/FirebaseAnalytics.Event#public-static-final-string-view_search_results */ - logViewSearchResults(object) { + logViewSearchResults(object: ViewSearchResultsParameters): Promise { if (!isObject(object)) { throw new Error( 'firebase.analytics().logViewSearchResults(*): The supplied arg must be an object of key/values.', @@ -719,7 +769,7 @@ class FirebaseAnalyticsModule extends FirebaseModule { ); } - setDefaultEventParameters(params) { + setDefaultEventParameters(params?: { [key: string]: any }): Promise { if (!isObject(params) && !isNull(params) && !isUndefined(params)) { throw new Error( "firebase.analytics().setDefaultEventParameters(*) 'params' expected an object value when it is defined.", @@ -729,7 +779,7 @@ class FirebaseAnalyticsModule extends FirebaseModule { return this.native.setDefaultEventParameters(params); } - initiateOnDeviceConversionMeasurementWithEmailAddress(emailAddress) { + initiateOnDeviceConversionMeasurementWithEmailAddress(emailAddress: string): Promise { if (!isString(emailAddress)) { throw new Error( "firebase.analytics().initiateOnDeviceConversionMeasurementWithEmailAddress(*) 'emailAddress' expected a string value.", @@ -737,13 +787,15 @@ class FirebaseAnalyticsModule extends FirebaseModule { } if (!isIOS) { - return; + return Promise.resolve(); } return this.native.initiateOnDeviceConversionMeasurementWithEmailAddress(emailAddress); } - initiateOnDeviceConversionMeasurementWithHashedEmailAddress(hashedEmailAddress) { + initiateOnDeviceConversionMeasurementWithHashedEmailAddress( + hashedEmailAddress: string, + ): Promise { if (!isString(hashedEmailAddress)) { throw new Error( "firebase.analytics().initiateOnDeviceConversionMeasurementWithHashedEmailAddress(*) 'hashedEmailAddress' expected a string value.", @@ -751,7 +803,7 @@ class FirebaseAnalyticsModule extends FirebaseModule { } if (!isIOS) { - return; + return Promise.resolve(); } return this.native.initiateOnDeviceConversionMeasurementWithHashedEmailAddress( @@ -759,7 +811,7 @@ class FirebaseAnalyticsModule extends FirebaseModule { ); } - initiateOnDeviceConversionMeasurementWithPhoneNumber(phoneNumber) { + initiateOnDeviceConversionMeasurementWithPhoneNumber(phoneNumber: string): Promise { if (!isE164PhoneNumber(phoneNumber)) { throw new Error( "firebase.analytics().initiateOnDeviceConversionMeasurementWithPhoneNumber(*) 'phoneNumber' expected a string value in E.164 format.", @@ -767,13 +819,15 @@ class FirebaseAnalyticsModule extends FirebaseModule { } if (!isIOS) { - return; + return Promise.resolve(); } return this.native.initiateOnDeviceConversionMeasurementWithPhoneNumber(phoneNumber); } - initiateOnDeviceConversionMeasurementWithHashedPhoneNumber(hashedPhoneNumber) { + initiateOnDeviceConversionMeasurementWithHashedPhoneNumber( + hashedPhoneNumber: string, + ): Promise { if (isE164PhoneNumber(hashedPhoneNumber)) { throw new Error( "firebase.analytics().initiateOnDeviceConversionMeasurementWithHashedPhoneNumber(*) 'hashedPhoneNumber' expected a sha256-hashed value of a phone number in E.164 format.", @@ -787,7 +841,7 @@ class FirebaseAnalyticsModule extends FirebaseModule { } if (!isIOS) { - return; + return Promise.resolve(); } return this.native.initiateOnDeviceConversionMeasurementWithHashedPhoneNumber( @@ -796,11 +850,26 @@ class FirebaseAnalyticsModule extends FirebaseModule { } } +export type { FirebaseAnalyticsModule }; + // import { SDK_VERSION } from '@react-native-firebase/analytics'; -export const SDK_VERSION = version; +export const SDK_VERSION: string = version; // import analytics from '@react-native-firebase/analytics'; // analytics().logEvent(...); + +// import analytics, { firebase } from '@react-native-firebase/analytics'; +// analytics().logEvent(...); +// firebase.analytics().logEvent(...); + +export declare const defaultExport: ReactNativeFirebase.FirebaseModuleWithStatics< + FirebaseAnalyticsModule, + Statics +> & { + (): FirebaseAnalyticsModule; + (app?: ReactNativeFirebase.FirebaseApp): FirebaseAnalyticsModule; +}; + export default createModuleNamespace({ statics, version, @@ -810,14 +879,13 @@ export default createModuleNamespace({ hasMultiAppSupport: false, hasCustomUrlOrRegionSupport: false, ModuleClass: FirebaseAnalyticsModule, -}); - -export * from './modular/index'; - -// import analytics, { firebase } from '@react-native-firebase/analytics'; -// analytics().logEvent(...); -// firebase.analytics().logEvent(...); -export const firebase = getFirebaseRoot(); +}) as typeof defaultExport; // Register the interop module for non-native platforms. -setReactNativeModule(nativeModuleName, fallBackModule); +setReactNativeModule(nativeModuleName, RNFBAnalyticsModule); + +export const firebase: FirebaseAnalyticsModule & { + analytics: typeof defaultExport; + SDK_VERSION: string; + app(name?: string): ReactNativeFirebase.FirebaseApp & { analytics(): FirebaseAnalyticsModule }; +} = getFirebaseRoot(); diff --git a/packages/analytics/lib/struct.js b/packages/analytics/lib/struct.ts similarity index 62% rename from packages/analytics/lib/struct.js rename to packages/analytics/lib/struct.ts index 0d820e0705..84af57db36 100644 --- a/packages/analytics/lib/struct.js +++ b/packages/analytics/lib/struct.ts @@ -15,29 +15,40 @@ */ import { isUndefined } from '@react-native-firebase/app/lib/common/validate'; -import { create } from 'superstruct'; +import { create, StructError } from 'superstruct'; -export const validateStruct = (value = {}, struct, prefix = '') => { +export const validateStruct = ( + value: Record = {}, + struct: any, + prefix = '', +): Record => { try { - return create(value, struct); + return create(value, struct) as Record; } catch (e) { - const { path, message } = e; + const { path, message } = e as StructError; const key = path[0]; if (message === undefined) { throw new Error(`${prefix} unknown property '${key}'.`); } - e.message = `${prefix} ${e.message}`; + (e as StructError).message = `${prefix} ${message}`; throw e; } }; -export const validateCompound = (source = {}, a, b, prefix = '') => { +export const validateCompound = ( + source: Record = {}, + a: string, + b: string, + prefix = '', +): void => { + const sourceA = source[a]; + const sourceB = source[b]; if ( - (isUndefined(source[a]) && !isUndefined(source[b])) || - (!isUndefined(source[a]) && isUndefined(source[b])) + (isUndefined(sourceA) && !isUndefined(sourceB)) || + (!isUndefined(sourceA) && isUndefined(sourceB)) ) { throw new Error( `${prefix} if you supply the '${a}' parameter, you must also supply the '${b}' parameter.`, diff --git a/packages/analytics/lib/structs.js b/packages/analytics/lib/structs.ts similarity index 100% rename from packages/analytics/lib/structs.js rename to packages/analytics/lib/structs.ts diff --git a/packages/analytics/lib/types/analytics.ts b/packages/analytics/lib/types/analytics.ts new file mode 100644 index 0000000000..e94fe38564 --- /dev/null +++ b/packages/analytics/lib/types/analytics.ts @@ -0,0 +1,871 @@ +/** + * A currency amount. + */ +export type Currency = number; + +/** + * Consent status string values. + */ +export type ConsentStatusString = 'granted' | 'denied'; + +/** + * Promotion object for analytics events. + */ +export interface Promotion { + /** + * The name of a creative used in a promotional spot + */ + creative_name?: string; + /** + * The name of a creative slot + */ + creative_slot?: string; + /** + * The ID of a product promotion + */ + promotion_id?: string; + /** + * The name of a product promotion + */ + promotion_name?: string; + [key: string]: any; +} + +export interface Item { + /** + * The item's brand. + */ + item_brand?: string; + /** + * An item ID. + */ + item_id?: string; + /** + * An item name. + */ + item_name?: string; + /** + * First class item category. + */ + item_category?: string; + /** + * Second class item category. + */ + item_category2?: string; + /** + * Third class item category. + */ + item_category3?: string; + /** + * Fourth class item category. + */ + item_category4?: string; + /** + * Fifth class item category. + */ + item_category5?: string; + /** + * The ID of the list in which the item was presented to the user. + */ + item_list_id?: string; + /** + * The name of the list in which the item was presented to the user. + */ + item_list_name?: string; + /** + * The Google [Place ID](https://developers.google.com/places/place-id) that corresponds to the associated item (String). Alternatively, you can supply your own custom Location ID. + */ + location_id?: string; + /** + * The Item variant. + */ + item_variant?: string; + /** + * The Item quantity. + */ + quantity?: number; + /** + * The Item price. + * Note that firebase analytics will display this as an integer with trailing zeros, due to some firebase-internal conversion. + * See https://github.com/invertase/react-native-firebase/issues/4578#issuecomment-771703420 for more information + */ + price?: number; + /** + * The affiliation of the item. + */ + affiliation?: string; + /** + * The coupon associated with the item. + */ + coupon?: string; + /** + * The creative name associated with the item. + */ + creative_name?: string; + /** + * The creative slot associated with the item. + */ + creative_slot?: string; + /** + * The discount applied to the item. + */ + discount?: Currency; + /** + * The index of the item. + */ + index?: number; + /** + * The promotion ID associated with the item. + */ + promotion_id?: string; + /** + * The promotion name associated with the item. + */ + promotion_name?: string; + /** + * Custom event parameters. The parameter names can be up to 40 characters long and must start with an alphabetic character and contain only alphanumeric characters and underscores. String parameter values can be up to 100 characters long. + * The "firebase_", "google_" and "ga_" prefixes are reserved and should not be used for parameter names. + */ + [key: string]: string | number | undefined; +} + +export interface AddPaymentInfoEventParameters { + items?: Item[]; + /** + * Purchase currency in 3 letter [ISO_4217](https://en.wikipedia.org/wiki/ISO_4217#Active_codes) format. E.g. `USD`. + */ + currency?: string; + value?: number; + /** + * Coupon code for a purchasable item. + */ + coupon?: string; + /** + * The chosen method of payment + */ + payment_type?: string; +} + +export interface AddShippingInfoEventParameters { + items?: Item[]; + /** + * Purchase currency in 3 letter [ISO_4217](https://en.wikipedia.org/wiki/ISO_4217#Active_codes) format. E.g. `USD`. + */ + currency?: string; + value?: number; + /** + * Coupon code for a purchasable item. + */ + coupon?: string; + /** + * The shipping tier (e.g. Ground, Air, Next-day) selected for delivery of the purchased item + */ + shipping_tier?: string; +} + +export interface AddToCartEventParameters { + items?: Item[]; + /** + * Purchase currency in 3 letter [ISO_4217](https://en.wikipedia.org/wiki/ISO_4217#Active_codes) format. E.g. `USD`. + */ + currency?: string; + /** + * value of item + */ + value?: number; +} + +export interface AddToWishlistEventParameters { + items?: Item[]; + /** + * Purchase currency in 3 letter [ISO_4217](https://en.wikipedia.org/wiki/ISO_4217#Active_codes) format. E.g. `USD`. + */ + currency?: string; + value?: number; +} + +export interface BeginCheckoutEventParameters { + /** + * Purchase currency in 3 letter [ISO_4217](https://en.wikipedia.org/wiki/ISO_4217#Active_codes) format. E.g. `USD`. + */ + //TODO if value is a param, so must currency: https://firebase.google.com/docs/reference/android/com/google/firebase/analytics/FirebaseAnalytics.Event#public-static-final-string-add_to_wishlist + currency?: string; + value?: number; + /** + * Coupon code for a purchasable item. + */ + coupon?: string; + + items?: Item[]; + /** + * Custom event parameters. + */ + [key: string]: any; +} + +export interface CampaignDetailsEventParameters { + /** + * Used to identify a search engine, newsletter, or other source. + */ + source: string; + /** + * Used to identify a medium such as email or cost-per-click (cpc). + */ + medium: string; + /** + * Used for keyword analysis to identify a specific product promotion or strategic campaign. + */ + campaign: string; + /** + * Used with paid search to supply the keywords for ads. + */ + term?: string; + /** + * Used for A/B testing and content-targeted ads to differentiate ads or links that point to the same URL. + */ + content?: string; + /** + * A campaign detail click ID. + */ + aclid?: string; + cp1?: string; +} + +// +// Unsupported in "Enhanced Ecommerce reports": +// https://firebase.google.com/docs/reference/android/com/google/firebase/analytics/FirebaseAnalytics.Event#public-static-final-string-checkout_progress +// +// export interface CheckoutProgressEventParameters { +// checkout_step: string; +// checkout_options: string; +// } + +export interface EarnVirtualCurrencyEventParameters { + /** + * Name of virtual currency type. E.g. `gems`. + */ + virtual_currency_name: string; + /** + * A context-specific numeric value which is accumulated automatically for each event type. Values + * can include revenue, distance, time and points. + */ + value: number; +} + +export interface GenerateLeadEventParameters { + /** + * Purchase currency in 3 letter [ISO_4217](https://en.wikipedia.org/wiki/ISO_4217#Active_codes) format. E.g. `USD`. + */ + currency?: string; + /** + * A context-specific numeric value which is accumulated automatically for each event type. Values + * can include revenue, distance, time and points. When a value is set, the accompanying `currency` + * parameter should also be defined. + */ + value?: number; +} + +export interface JoinGroupEventParameters { + /** + * Group/clan/guild id. + */ + group_id: string; +} + +export interface LevelEndEventParameters { + /** + * Level in game. + */ + level: number; + /** + * The result of an operation. + */ + success?: string; +} + +export interface LevelStartEventParameters { + /** + * Level in game. + */ + level: number; +} + +export interface LevelUpEventParameters { + /** + * Level in game. + */ + level: number; + /** + * Character used in game. + */ + character?: string; +} + +export interface LoginEventParameters { + /** + * The login method. E.g. `facebook.com`. + */ + method: string; +} + +export interface PostScoreEventParameters { + /** + * Score in game. + */ + score: number; + /** + * Level in game. + */ + level?: number; + /** + * Character used in game. + */ + character?: string; +} + +export interface PurchaseEventParameters { + /** + * A product affiliation to designate a supplying company or brick and mortar store location + */ + affiliation?: string; + /** + * Coupon code for a purchasable item. + */ + coupon?: string; + /** + * Purchase currency in 3 letter [ISO_4217](https://en.wikipedia.org/wiki/ISO_4217#Active_codes) format. E.g. `USD`. + */ + currency?: string; + + items?: Item[]; + /** + * Shipping cost. + */ + shipping?: number; + /** + * Tax amount. + */ + tax?: number; + /** + * A context-specific numeric value which is accumulated automatically for each event type. Values + * can include revenue, distance, time and points. When a value is set, the accompanying `currency` + * parameter should also be defined. + */ + value?: number; + /** + * A single ID for a ecommerce group transaction. + */ + transaction_id?: string; + /** + * Custom event parameters. + */ + [key: string]: any; +} + +export interface ScreenViewParameters { + /** + * Screen name the user is currently viewing. + */ + screen_name?: string; + /** + * Current class associated with the view the user is currently viewing. + */ + screen_class?: string; + + /** + * Custom event parameters. + */ + [key: string]: any; +} + +export interface RefundEventParameters { + /** + * A product affiliation to designate a supplying company or brick and mortar store location + */ + affiliation?: string; + /** + * Coupon code for a purchasable item. + */ + coupon?: string; + /** + * Purchase currency in 3 letter [ISO_4217](https://en.wikipedia.org/wiki/ISO_4217#Active_codes) format. E.g. `USD`. + */ + currency?: string; + + items?: Item[]; + /** + * Shipping cost. + */ + shipping?: number; + /** + * Tax amount. + */ + tax?: number; + /** + * A context-specific numeric value which is accumulated automatically for each event type. Values + * can include revenue, distance, time and points. When a value is set, the accompanying `currency` + * parameter should also be defined. + */ + value?: number; + /** + * A single ID for a ecommerce group transaction. + */ + transaction_id?: string; +} + +export interface RemoveFromCartEventParameters { + items?: Item[]; + /** + * A context-specific numeric value which is accumulated automatically for each event type. Values + * can include revenue, distance, time and points. When a value is set, the accompanying `currency` + * parameter should also be defined. + */ + value?: number; + /** + * Purchase currency in 3 letter [ISO_4217](https://en.wikipedia.org/wiki/ISO_4217#Active_codes) format. E.g. `USD`. + x */ + currency?: string; +} + +export interface SearchEventParameters { + search_term: string; + /** + * Number of nights staying at hotel. + */ + number_of_nights?: number; + /** + * Number of rooms for travel events. + */ + number_of_rooms?: number; + /** + * Number of passengers traveling. + */ + number_of_passengers?: number; + /** + * Flight or Travel origin. E.g. `Mountain View, CA`. + */ + origin?: string; + /** + * Flight or Travel destination. E.g. `Mountain View, CA`. + */ + destination?: string; + /** + * The departure date, check-in date, or rental start date for the item (String). The parameter expects a date formatted as YYYY-MM-DD. + */ + start_date?: string; + /** + * The arrival date, check-out date, or rental end date for the item (String). The parameter expects a date formatted as YYYY-MM-DD. + */ + end_date?: string; + /** + * Travel class. E.g. `business`. + */ + travel_class?: string; +} + +export interface SelectContentEventParameters { + content_type: string; + /** + * An item ID. + */ + item_id: string; +} + +export interface SelectItemEventParameters { + items?: Item[]; + content_type: string; + /** + * The ID of the list in which the item was presented to the user + */ + item_list_id: string; + /** + * The name of the list in which the item was presented to the user + */ + item_list_name: string; +} + +export interface SetCheckoutOptionEventParameters { + checkout_step?: EventParams['checkout_step']; + checkout_option?: EventParams['checkout_option']; + + [key: string]: any; +} + +export interface SelectPromotionEventParameters { + /** + * The name of a creative used in a promotional spot + */ + creative_name: string; + /** + * The name of a creative slot + */ + creative_slot: string; + items?: Item[]; + /** + * The location associated with the event. Preferred to be the Google Place ID that corresponds to the associated item but could be overridden to a custom location ID string + */ + location_id: string; + /** + * The ID of a product promotion + */ + promotion_id: string; + /** + * The name of a product promotion + */ + promotion_name: string; +} + +export interface ShareEventParameters { + /** + * Type of content selected. + */ + content_type: string; + /** + * An item ID. + */ + item_id: string; + /** + * A particular approach used in an operation; for example, "facebook" or "email" in the context of a sign_up or login event. + */ + method: string; +} + +export interface SignUpEventParameters { + /** + * A particular approach used in an operation; for example, "facebook" or "email" in the context of a sign_up or login event. + */ + method: string; +} + +export interface SpendVirtualCurrencyEventParameters { + /** + * An item name. + */ + item_name: string; + /** + * Name of virtual currency type. E.g. `gems`. + */ + virtual_currency_name: string; + /** + * A context-specific numeric value which is accumulated automatically for each event type. Values + * can include revenue, distance, time and points. When a value is set, the accompanying `currency` + * parameter should also be defined. + */ + value: number; +} + +export interface UnlockAchievementEventParameters { + /** + * Game achievement ID (String). + */ + achievement_id: string; +} + +export interface ViewCartEventParameters { + items?: Item[]; + /** + * Purchase currency in 3 letter [ISO_4217](https://en.wikipedia.org/wiki/ISO_4217#Active_codes) format. E.g. `USD`. + */ + currency?: string; + /** + * A context-specific numeric value which is accumulated automatically for each event type. Values + * can include revenue, distance, time and points. When a value is set, the accompanying `currency` + * parameter should also be defined. + */ + value?: number; +} + +export interface ViewItemEventParameters { + items?: Item[]; + /** + * Purchase currency in 3 letter [ISO_4217](https://en.wikipedia.org/wiki/ISO_4217#Active_codes) format. E.g. `USD`. + */ + currency?: string; + /** + * A context-specific numeric value which is accumulated automatically for each event type. Values + * can include revenue, distance, time and points. When a value is set, the accompanying `currency` + * parameter should also be defined. + */ + value?: number; +} + +export interface ViewSearchResultsParameters { + /** + * The search string/keywords used. + */ + search_term: string; +} + +export interface ViewItemListEventParameters { + items?: Item[]; + /** + * The ID of the list in which the item was presented to the user + */ + item_list_id?: string; + /** + * The name of the list in which the item was presented to the user + */ + item_list_name?: string; +} + +export interface ViewPromotionEventParameters { + items?: Item[]; + /** + * The location associated with the event. Preferred to be the Google Place ID that corresponds to the associated item but could be overridden to a custom location ID string + */ + location_id?: string; + /** + * The name of a creative used in a promotional spot + */ + creative_name?: string; + /** + * The name of a creative slot + */ + creative_slot?: string; + /** + * The ID of a product promotion + */ + promotion_id?: string; + /** + * The name of a product promotion + */ + promotion_name?: string; +} + +export interface AddShippingInfoParameters { + items?: Item[]; + /** + * Purchase currency in 3 letter [ISO_4217](https://en.wikipedia.org/wiki/ISO_4217#Active_codes) format. E.g. `USD`. + */ + currency?: string; + /** + * A context-specific numeric value which is accumulated automatically for each event type. Values + * can include revenue, distance, time and points. When a value is set, the accompanying `currency` + * parameter should also be defined. + */ + value?: number; + /** + * Coupon code for a purchasable item. + */ + coupon?: string; + /** + * The shipping tier (e.g. Ground, Air, Next-day) selected for delivery of the purchased item + */ + shipping_tier?: string; +} + +/** + * Standard gtag.js event parameters. For more information, see the GA4 reference documentation. Web only. + */ +export interface EventParams { + checkout_option?: string; + checkout_step?: number; + item_id?: string; + content_type?: string; + coupon?: string; + currency?: string; + description?: string; + fatal?: boolean; + items?: Item[]; + method?: string; + number?: string; + promotions?: Promotion[]; + screen_name?: string; + /** + * Firebase-specific. Use to log a `screen_name` to Firebase Analytics. + */ + firebase_screen?: string; + /** + * Firebase-specific. Use to log a `screen_class` to Firebase Analytics. + */ + firebase_screen_class?: string; + search_term?: string; + shipping?: Currency; + tax?: Currency; + transaction_id?: string; + value?: number; + event_label?: string; + event_category?: string; + shipping_tier?: string; + item_list_id?: string; + item_list_name?: string; + promotion_id?: string; + promotion_name?: string; + payment_type?: string; + affiliation?: string; + page_title?: string; + page_location?: string; + page_path?: string; + + [key: string]: unknown; +} + +/** + * Unsupported in "Enhanced Ecommerce reports": + * https://firebase.google.com/docs/reference/android/com/google/firebase/analytics/FirebaseAnalytics.Event#public-static-final-string-view_search_results + */ +// export interface ViewSearchResults { +// /** +// * The search string/keywords used. +// */ +// search_term: string; +// } + +// eslint-disable-next-line @typescript-eslint/no-empty-object-type +export interface Statics {} + +/** + * Analytics instance initialization options. Web only. + */ +export interface AnalyticsSettings { + config?: GtagConfigParams | EventParams; +} + +/** + * Additional options that can be passed to Analytics method calls such as logEvent. Web only. + */ +export interface AnalyticsCallOptions { + /** + * If true, this config or event call applies globally to all Google Analytics properties on the page. Web only. + */ + global: boolean; +} + +/** + * A set of common Google Analytics config settings recognized by gtag.js. Web only. + */ +export interface GtagConfigParams { + /** + * Whether or not a page view should be sent. + * If set to true (default), a page view is automatically sent upon initialization + * of analytics. + * See {@link https://developers.google.com/analytics/devguides/collection/ga4/page-view | Page views } + */ + send_page_view?: boolean; + /** + * The title of the page. + * See {@link https://developers.google.com/analytics/devguides/collection/ga4/page-view | Page views } + */ + page_title?: string; + /** + * The URL of the page. + * See {@link https://developers.google.com/analytics/devguides/collection/ga4/page-view | Page views } + */ + page_location?: string; + /** + * Defaults to `auto`. + * See {@link https://developers.google.com/analytics/devguides/collection/ga4/cookies-user-id | Cookies and user identification } + */ + cookie_domain?: string; + /** + * Defaults to 63072000 (two years, in seconds). + * See {@link https://developers.google.com/analytics/devguides/collection/ga4/cookies-user-id | Cookies and user identification } + */ + cookie_expires?: number; + /** + * Defaults to `_ga`. + * See {@link https://developers.google.com/analytics/devguides/collection/ga4/cookies-user-id | Cookies and user identification } + */ + cookie_prefix?: string; + /** + * If set to true, will update cookies on each page load. + * Defaults to true. + * See {@link https://developers.google.com/analytics/devguides/collection/ga4/cookies-user-id | Cookies and user identification } + */ + cookie_update?: boolean; + /** + * Appends additional flags to the cookie when set. + * See {@link https://developers.google.com/analytics/devguides/collection/ga4/cookies-user-id | Cookies and user identification } + */ + cookie_flags?: string; + /** + * If set to false, disables all advertising features with `gtag.js`. + * See {@link https://developers.google.com/analytics/devguides/collection/ga4/display-features | Disable advertising features } + */ + allow_google_signals?: boolean; + /** + * If set to false, disables all advertising personalization with `gtag.js`. + * See {@link https://developers.google.com/analytics/devguides/collection/ga4/display-features | Disable advertising features } + */ + allow_ad_personalization_signals?: boolean; + + [key: string]: unknown; +} + +/** + * Consent status settings for each consent type. + * For more information, see + * {@link https://developers.google.com/tag-platform/tag-manager/templates/consent-apis + * | the GA4 reference documentation for consent state and consent types}. + */ +export interface ConsentSettings { + /** Enables storage, such as cookies, related to advertising */ + ad_storage?: boolean; + /** Sets consent for sending user data to Google for online advertising purposes */ + ad_user_data?: boolean; + /** Sets consent for personalized advertising */ + ad_personalization?: boolean; + /** Enables storage, such as cookies, related to analytics (for example, visit duration) */ + analytics_storage?: boolean; + /** + * Enables storage that supports the functionality of the website or app such as language settings + */ + functionality_storage?: boolean; + /** Enables storage related to personalization such as video recommendations */ + personalization_storage?: boolean; + /** + * Enables storage related to security such as authentication functionality, fraud prevention, + * and other user protection. + */ + security_storage?: ConsentStatusString; + + [key: string]: unknown; +} + +/** + * Specifies custom options for your Firebase Analytics instance. + * You must set these before initializing `firebase.analytics()`. + */ +export interface SettingsOptions { + /** Sets custom name for `gtag` function. */ + gtagName?: string; + /** Sets custom name for `dataLayer` array used by `gtag.js`. */ + dataLayerName?: string; +} + +/** + * Any custom event name string not in the standard list of recommended event names. + */ +export declare type CustomEventName = T extends EventNameString ? never : T; +/** + * Type for standard Google Analytics event names. logEvent also accepts any custom string and interprets it as a custom event name. + * See https://firebase.google.com/docs/reference/js/analytics.md#eventnamestring + */ +export declare type EventNameString = + | 'add_payment_info' + | 'add_shipping_info' + | 'add_to_cart' + | 'add_to_wishlist' + | 'begin_checkout' + | 'checkout_progress' + | 'exception' + | 'generate_lead' + | 'login' + | 'page_view' + | 'purchase' + | 'refund' + | 'remove_from_cart' + | 'screen_view' + | 'search' + | 'select_content' + | 'select_item' + | 'select_promotion' + | 'set_checkout_option' + | 'share' + | 'sign_up' + | 'timing_complete' + | 'view_cart' + | 'view_item' + | 'view_item_list' + | 'view_promotion' + | 'view_search_results'; diff --git a/packages/analytics/lib/types/web.ts b/packages/analytics/lib/types/web.ts new file mode 100644 index 0000000000..a94ec55659 --- /dev/null +++ b/packages/analytics/lib/types/web.ts @@ -0,0 +1,56 @@ +/* + * Copyright (c) 2016-present Invertase Limited & Contributors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this library except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +export interface AnalyticsEventParameters { + [key: string]: string | number | boolean | undefined | null; +} + +export interface AnalyticsUserProperties { + [key: string]: string | number | boolean | undefined | null; +} + +export interface AnalyticsConsent { + ad_personalization?: boolean; + [key: string]: boolean | undefined; +} + +export interface AnalyticsApi { + logEvent(name: string, params?: AnalyticsEventParameters): void; + setUserId(userId: string | null): void; + setUserProperty(key: string, value: string | null): void; + setUserProperties(properties: AnalyticsUserProperties): void; + setDefaultEventParameters(params: AnalyticsEventParameters | null): void; + setConsent(consent: AnalyticsConsent): void; + setAnalyticsCollectionEnabled(enabled: boolean): void; + setDebug(enabled: boolean): void; + setCurrentScreen(screenName: string | null): void; + _getCid(): Promise; +} + +export interface RNFBAnalyticsModule { + logEvent(name: string, params?: AnalyticsEventParameters): Promise; + setUserId(userId: string | null): Promise; + setUserProperty(key: string, value: string | null): Promise; + setUserProperties(properties: AnalyticsUserProperties): Promise; + setDefaultEventParameters(params: AnalyticsEventParameters | null): Promise; + setConsent(consent: AnalyticsConsent): Promise; + setAnalyticsCollectionEnabled(enabled: boolean): Promise; + resetAnalyticsData(): Promise; + setSessionTimeoutDuration(): Promise; + getAppInstanceId(): Promise; + getSessionId(): Promise; +} diff --git a/packages/analytics/lib/web/RNFBAnalyticsModule.android.js b/packages/analytics/lib/web/RNFBAnalyticsModule.android.js deleted file mode 100644 index af77c859b1..0000000000 --- a/packages/analytics/lib/web/RNFBAnalyticsModule.android.js +++ /dev/null @@ -1,2 +0,0 @@ -// No-op for android. -export default {}; diff --git a/packages/analytics/lib/web/RNFBAnalyticsModule.android.ts b/packages/analytics/lib/web/RNFBAnalyticsModule.android.ts new file mode 100644 index 0000000000..dd5a6be890 --- /dev/null +++ b/packages/analytics/lib/web/RNFBAnalyticsModule.android.ts @@ -0,0 +1,3 @@ +// No-op for android. +const RNFBAnalyticsModule = {}; +export { RNFBAnalyticsModule }; diff --git a/packages/analytics/lib/web/RNFBAnalyticsModule.ios.js b/packages/analytics/lib/web/RNFBAnalyticsModule.ios.js deleted file mode 100644 index a3429ada0e..0000000000 --- a/packages/analytics/lib/web/RNFBAnalyticsModule.ios.js +++ /dev/null @@ -1,2 +0,0 @@ -// No-op for ios. -export default {}; diff --git a/packages/analytics/lib/web/RNFBAnalyticsModule.ios.ts b/packages/analytics/lib/web/RNFBAnalyticsModule.ios.ts new file mode 100644 index 0000000000..8d87cbca08 --- /dev/null +++ b/packages/analytics/lib/web/RNFBAnalyticsModule.ios.ts @@ -0,0 +1,3 @@ +// No-op for ios. +const RNFBAnalyticsModule = {}; +export { RNFBAnalyticsModule }; diff --git a/packages/analytics/lib/web/RNFBAnalyticsModule.js b/packages/analytics/lib/web/RNFBAnalyticsModule.ts similarity index 63% rename from packages/analytics/lib/web/RNFBAnalyticsModule.js rename to packages/analytics/lib/web/RNFBAnalyticsModule.ts index fa183142cd..58637db0c3 100644 --- a/packages/analytics/lib/web/RNFBAnalyticsModule.js +++ b/packages/analytics/lib/web/RNFBAnalyticsModule.ts @@ -2,10 +2,20 @@ import { getApp } from '@react-native-firebase/app/lib/internal/web/firebaseApp' import { guard } from '@react-native-firebase/app/lib/internal/web/utils'; import { AnalyticsApi } from './api'; +import type { + AnalyticsEventParameters, + AnalyticsUserProperties, + AnalyticsConsent, + RNFBAnalyticsModule, +} from '../types/web'; -let analyticsInstances = {}; +interface AnalyticsInstances { + [measurementId: string]: AnalyticsApi; +} + +let analyticsInstances: AnalyticsInstances = {}; -function getAnalyticsApi(appName) { +function getAnalyticsApi(appName: string): AnalyticsApi { const app = getApp(appName); const measurementId = app.options.measurementId; if (!measurementId) { @@ -13,10 +23,16 @@ function getAnalyticsApi(appName) { console.warn( 'No measurement id (`FirebaseOptions.measurementId`) found for Firebase Analytics. Analytics will be unavailable.', ); + // Return a default instance with empty measurementId for cases where it's not configured + const defaultKey = 'default'; + if (!analyticsInstances[defaultKey]) { + analyticsInstances[defaultKey] = new AnalyticsApi('[DEFAULT]', ''); + } + return analyticsInstances[defaultKey]; } if (!analyticsInstances[measurementId]) { analyticsInstances[measurementId] = new AnalyticsApi('[DEFAULT]', measurementId); - if (globalThis.RNFBDebug) { + if ((globalThis as any).RNFBDebug) { analyticsInstances[measurementId].setDebug(true); } } @@ -29,8 +45,8 @@ function getAnalyticsApi(appName) { * the native android/ios modules e.g. `@ReactMethod` annotated * java methods on Android. */ -export default { - logEvent(name, params) { +const RNFBAnalyticsModule: RNFBAnalyticsModule = { + logEvent(name: string, params?: AnalyticsEventParameters): Promise { return guard(async () => { const api = getAnalyticsApi('[DEFAULT]'); api.logEvent(name, params); @@ -38,7 +54,7 @@ export default { }); }, - setUserId(userId) { + setUserId(userId: string | null): Promise { return guard(async () => { const api = getAnalyticsApi('[DEFAULT]'); api.setUserId(userId); @@ -46,7 +62,7 @@ export default { }); }, - setUserProperty(key, value) { + setUserProperty(key: string, value: string | null): Promise { return guard(async () => { const api = getAnalyticsApi('[DEFAULT]'); api.setUserProperty(key, value); @@ -54,7 +70,7 @@ export default { }); }, - setUserProperties(properties) { + setUserProperties(properties: AnalyticsUserProperties): Promise { return guard(async () => { const api = getAnalyticsApi('[DEFAULT]'); api.setUserProperties(properties); @@ -62,7 +78,7 @@ export default { }); }, - setDefaultEventParameters(params) { + setDefaultEventParameters(params: AnalyticsEventParameters | null): Promise { return guard(async () => { const api = getAnalyticsApi('[DEFAULT]'); api.setDefaultEventParameters(params); @@ -70,18 +86,18 @@ export default { }); }, - setConsent(consent) { + setConsent(consent: AnalyticsConsent): Promise { return guard(async () => { const api = getAnalyticsApi('[DEFAULT]'); // TODO currently we only support ad_personalization - if (consent && consent.ad_personalization) { + if (consent && consent.ad_personalization !== undefined) { api.setConsent({ ad_personalization: consent.ad_personalization }); } return null; }); }, - setAnalyticsCollectionEnabled(enabled) { + setAnalyticsCollectionEnabled(enabled: boolean): Promise { return guard(async () => { const api = getAnalyticsApi('[DEFAULT]'); api.setAnalyticsCollectionEnabled(enabled); @@ -89,31 +105,33 @@ export default { }); }, - resetAnalyticsData() { + resetAnalyticsData(): Promise { // Unsupported for web. return guard(async () => { return null; }); }, - setSessionTimeoutDuration() { + setSessionTimeoutDuration(): Promise { // Unsupported for web. return guard(async () => { return null; }); }, - getAppInstanceId() { + getAppInstanceId(): Promise { return guard(async () => { const api = getAnalyticsApi('[DEFAULT]'); return api._getCid(); }); }, - getSessionId() { + getSessionId(): Promise { // Unsupported for web. return guard(async () => { return null; }); }, }; + +export { RNFBAnalyticsModule }; diff --git a/packages/analytics/lib/web/api.js b/packages/analytics/lib/web/api.ts similarity index 78% rename from packages/analytics/lib/web/api.js rename to packages/analytics/lib/web/api.ts index d1a3f2ed91..4d05b3d4ac 100644 --- a/packages/analytics/lib/web/api.js +++ b/packages/analytics/lib/web/api.ts @@ -13,12 +13,18 @@ import { } from '@react-native-firebase/app/lib/internal/asyncStorage'; import { isNumber } from '@react-native-firebase/app/lib/common'; +import type { + AnalyticsEventParameters, + AnalyticsUserProperties, + AnalyticsConsent, + AnalyticsApi as IAnalyticsApi, +} from '../types/web'; /** * Generates a Google Analytics client ID. * @returns {string} The generated client ID. */ -function generateGAClientId() { +function generateGAClientId(): string { const randomNumber = Math.round(Math.random() * 2147483647); // TODO: Don't seem to need this for now. // var hash = 1; @@ -36,8 +42,30 @@ function generateGAClientId() { return randomPart + '.' + timestamp; } -class AnalyticsApi { - constructor(appName, measurementId) { +interface AnalyticsEvent { + name: string; + params: AnalyticsEventParameters; +} + +class AnalyticsApi implements IAnalyticsApi { + public readonly appName: string; + public readonly measurementId: string; + private eventQueue: AnalyticsEvent[]; + private queueTimer: number | null; + private readonly queueInterval: number; + private defaultEventParameters: AnalyticsEventParameters; + private userId: string | null; + private userProperties: AnalyticsUserProperties; + private consent: AnalyticsConsent; + private analyticsCollectionEnabled: boolean; + private started: boolean; + private installationId: string | null; + private debug: boolean; + private currentScreen: string | null; + private sessionId?: number; + private cid?: string | null; + + constructor(appName: string, measurementId: string) { this.appName = appName; this.measurementId = measurementId; this.eventQueue = []; @@ -54,7 +82,7 @@ class AnalyticsApi { this.currentScreen = null; this._getInstallationId().catch(error => { - if (globalThis.RNFBDebug) { + if ((globalThis as any).RNFBDebug) { console.debug('[RNFB->Analytics][🔴] Error getting Firebase Installation Id:', error); } else { // No-op. This is a non-critical error. @@ -62,7 +90,7 @@ class AnalyticsApi { }); } - setDefaultEventParameters(params) { + setDefaultEventParameters(params: AnalyticsEventParameters | null): void { if (params === null || params === undefined) { this.defaultEventParameters = {}; } else { @@ -75,36 +103,36 @@ class AnalyticsApi { } } - setDebug(enabled) { + setDebug(enabled: boolean): void { this.debug = enabled; } - setUserId(userId) { + setUserId(userId: string | null): void { this.userId = userId; } - setCurrentScreen(screenName) { + setCurrentScreen(screenName: string | null): void { this.currentScreen = screenName; } - setUserProperty(key, value) { + setUserProperty(key: string, value: string | null): void { this.userProperties[key] = value; if (value === null) { delete this.userProperties[key]; } } - setUserProperties(properties) { + setUserProperties(properties: AnalyticsUserProperties): void { for (const [key, value] of Object.entries(properties)) { - this.setUserProperty(key, value); + this.setUserProperty(key, value as string | null); } } - setConsent(consentSettings) { + setConsent(consentSettings: AnalyticsConsent): void { this.consent = { ...this.consent, ...consentSettings }; } - setAnalyticsCollectionEnabled(enabled) { + setAnalyticsCollectionEnabled(enabled: boolean): void { this.analyticsCollectionEnabled = enabled; if (!enabled) { this._stopQueueProcessing(); @@ -113,7 +141,7 @@ class AnalyticsApi { } } - logEvent(eventName, eventParams = {}) { + logEvent(eventName: string, eventParams: AnalyticsEventParameters = {}): void { if (!this.analyticsCollectionEnabled) return; this.eventQueue.push({ name: eventName, @@ -122,22 +150,26 @@ class AnalyticsApi { this._startQueueProcessing(); } - async _getInstallationId() { - navigator.onLine = true; + private async _getInstallationId(): Promise { + // @ts-ignore + if (navigator !== null) { + // @ts-ignore + (navigator as any).onLine = true; + } makeIDBAvailable(); const app = getApp(this.appName); const installations = getInstallations(app); const id = await getId(installations); - if (globalThis.RNFBDebug) { + if ((globalThis as any).RNFBDebug) { console.debug('[RNFB->Analytics][📊] Firebase Installation Id:', id); } this.installationId = id; - onIdChange(installations, newId => { + onIdChange(installations, (newId: string) => { this.installationId = newId; }); } - _startQueueProcessing() { + private _startQueueProcessing(): void { if (this.started) return; this.sessionId = Math.floor(Date.now() / 1000); this.started = true; @@ -147,13 +179,15 @@ class AnalyticsApi { ); } - _stopQueueProcessing() { + private _stopQueueProcessing(): void { if (!this.started) return; this.started = false; - clearInterval(this.queueTimer); + if (this.queueTimer) { + clearInterval(this.queueTimer); + } } - async _processQueue() { + private async _processQueue(): Promise { if (this.eventQueue.length === 0) return; const events = this.eventQueue.splice(0, 5); await this._sendEvents(events); @@ -162,7 +196,7 @@ class AnalyticsApi { } } - async _getCid() { + async _getCid(): Promise { this.cid = await getItem('analytics:cid'); if (this.cid) { return this.cid; @@ -192,7 +226,7 @@ class AnalyticsApi { return this.cid; } - async _sendEvents(events) { + private async _sendEvents(events: AnalyticsEvent[]): Promise { const cid = this.cid || (await this._getCid()); for (const event of events) { const queryParams = new URLSearchParams({ @@ -201,18 +235,18 @@ class AnalyticsApi { en: event.name, cid, pscdl: 'noapi', - sid: this.sessionId, + sid: String(this.sessionId), 'ep.origin': 'firebase', _z: 'fetch', _p: '' + Date.now(), - _s: 1, - _ee: 1, - dma: 0, - tfd: Math.round(performance.now()), - are: 1, - sct: 2, - seg: 1, - frm: 0, + _s: '1', + _ee: '1', + dma: '0', + tfd: String(Math.round(performance.now())), + are: '1', + sct: '2', + seg: '1', + frm: '0', }); if (this.debug) { @@ -297,7 +331,7 @@ class AnalyticsApi { try { const url = `https://www.google-analytics.com/g/collect?${queryParams.toString()}`; - if (globalThis.RNFBDebug) { + if ((globalThis as any).RNFBDebug) { console.debug(`[RNFB-->Fetch][📊] Sending analytics call: ${url}`); } const response = await fetch(url, { @@ -317,11 +351,11 @@ class AnalyticsApi { 'user-agent': 'react-native-firebase', }, }); - if (globalThis.RNFBDebug) { + if ((globalThis as any).RNFBDebug) { console.debug(`[RNFB<--Fetch][📊] Response: ${response.status}`); } } catch (error) { - if (globalThis.RNFBDebug) { + if ((globalThis as any).RNFBDebug) { console.debug('[RNFB<--Fetch][🔴] Error sending Analytics event:', error); } } diff --git a/packages/analytics/package.json b/packages/analytics/package.json index 24beb71987..84c1a8e2af 100644 --- a/packages/analytics/package.json +++ b/packages/analytics/package.json @@ -3,12 +3,15 @@ "version": "23.0.1", "author": "Invertase (http://invertase.io)", "description": "React Native Firebase - The analytics module provides out of the box support with Google Analytics for Firebase. Integration with the Android & iOS allows for in-depth analytical insight reporting, such as device information, location, user actions and more.", - "main": "lib/index.js", - "types": "lib/index.d.ts", + "main": "./dist/commonjs/index.js", + "module": "./dist/module/index.js", + "types": "./dist/typescript/commonjs/lib/index.d.ts", "scripts": { - "build": "genversion --semi lib/version.js", + "build": "genversion --esm --semi lib/version.ts", "build:clean": "rimraf android/build && rimraf ios/build", - "prepare": "yarn run build" + "compile": "bob build", + "prepare": "yarn run build && yarn compile", + "tsc": "../../node_modules/.bin/tsc" }, "repository": { "type": "git", @@ -30,5 +33,57 @@ }, "dependencies": { "superstruct": "^2.0.2" - } + }, + "devDependencies": { + "react-native-builder-bob": "^0.40.13" + }, + "exports": { + ".": { + "source": "./lib/index.js", + "import": { + "types": "./dist/typescript/module/lib/index.d.ts", + "default": "./dist/module/index.js" + }, + "require": { + "types": "./dist/typescript/commonjs/lib/index.d.ts", + "default": "./dist/commonjs/index.js" + } + }, + "./package.json": "./package.json" + }, + "files": [ + "lib", + "dist", + "!**/__tests__", + "!**/__fixtures__", + "!**/__mocks__" + ], + "react-native-builder-bob": { + "source": "lib", + "output": "dist", + "targets": [ + [ + "module", + { + "esm": true + } + ], + [ + "commonjs", + { + "esm": true + } + ], + [ + "typescript", + { + "tsc": "../../node_modules/.bin/tsc" + } + ] + ] + }, + "eslintIgnore": [ + "node_modules/", + "dist/" + ] } diff --git a/packages/analytics/tsconfig.json b/packages/analytics/tsconfig.json new file mode 100644 index 0000000000..e588cb8d97 --- /dev/null +++ b/packages/analytics/tsconfig.json @@ -0,0 +1,34 @@ +{ + "compilerOptions": { + "rootDir": ".", + "allowUnreachableCode": false, + "allowUnusedLabels": false, + "esModuleInterop": true, + "forceConsistentCasingInFileNames": true, + "jsx": "react-jsx", + "lib": [ + "ESNext", + // needed for web API + "DOM" + ], + "module": "ESNext", + "moduleResolution": "bundler", + "noFallthroughCasesInSwitch": true, + "noImplicitReturns": true, + "noImplicitUseStrict": false, + "noStrictGenericChecks": false, + "noUncheckedIndexedAccess": true, + "noUnusedLocals": true, + "noUnusedParameters": true, + "resolveJsonModule": true, + "skipLibCheck": true, + "strict": true, + "target": "ESNext", + "verbatimModuleSyntax": false, + "baseUrl": ".", + "typeRoots": ["lib/types", "./node_modules/@types"], + "paths": { + "@react-native-firebase/app": ["../app/lib"] + } + } +} diff --git a/packages/analytics/type-test.ts b/packages/analytics/type-test.ts deleted file mode 100644 index b391d1e8b2..0000000000 --- a/packages/analytics/type-test.ts +++ /dev/null @@ -1,121 +0,0 @@ -import analytics, { firebase } from '.'; - -analytics.SDK_VERSION; -analytics().app.name; -// checks module exists at root -console.log(firebase.analytics().app.name); - -// checks module exists at app level -console.log(firebase.app().analytics().app.name); - -// checks statics exist -console.log(firebase.analytics.SDK_VERSION); - -// checks root exists -console.log(firebase.SDK_VERSION); - -firebase - .analytics() - .logAddPaymentInfo({ value: 123, currency: 'USD' }) - .then(); -firebase - .analytics() - .logAddToCart({ value: 123, currency: 'USD' }) - .then(); -firebase - .analytics() - .logLogin({ method: 'foo' }) - .then(); -firebase - .analytics() - .setUserProperties({ foo: 'bar' }) - .then(); -firebase - .analytics() - .setConsent({ ad_storage: true }) - -console.log(firebase.analytics().logAddPaymentInfo); -console.log(firebase.analytics().logAddToCart); -console.log(firebase.analytics().logAddShippingInfo); -console.log(firebase.analytics().logAddToWishlist); -console.log(firebase.analytics().logAppOpen); -console.log(firebase.analytics().logBeginCheckout); -console.log(firebase.analytics().logCampaignDetails); -console.log(firebase.analytics().logEarnVirtualCurrency); -console.log(firebase.analytics().logEvent); -console.log(firebase.analytics().logGenerateLead); -console.log(firebase.analytics().logJoinGroup); -console.log(firebase.analytics().logLevelEnd); -console.log(firebase.analytics().logLevelStart); -console.log(firebase.analytics().logLevelUp); -console.log(firebase.analytics().logLogin); -console.log(firebase.analytics().logPostScore); -console.log(firebase.analytics().logPurchase); -console.log(firebase.analytics().logRemoveFromCart); -console.log(firebase.analytics().logRefund); -console.log(firebase.analytics().logSearch); -console.log(firebase.analytics().logSelectContent); -console.log(firebase.analytics().logSetCheckoutOption); -console.log(firebase.analytics().logShare); -console.log(firebase.analytics().logSignUp); -console.log(firebase.analytics().logSpendVirtualCurrency); -console.log(firebase.analytics().logTutorialBegin); -console.log(firebase.analytics().logTutorialComplete); -console.log(firebase.analytics().logUnlockAchievement); -console.log(firebase.analytics().logViewItem); -console.log(firebase.analytics().logViewItemList); -console.log(firebase.analytics().resetAnalyticsData); -console.log(firebase.analytics().logViewCart); -console.log(firebase.analytics().setAnalyticsCollectionEnabled); -console.log(firebase.analytics().logSelectPromotion); -console.log(firebase.analytics().logScreenView); -console.log(firebase.analytics().logViewPromotion); -console.log(firebase.analytics().setSessionTimeoutDuration); -console.log(firebase.analytics().setUserId); -console.log(firebase.analytics().setUserProperties); -console.log(firebase.analytics().logViewSearchResults); -console.log(firebase.analytics().setUserProperty); -console.log(firebase.analytics().setConsent); - -console.log(analytics().logAddPaymentInfo); -console.log(analytics().logAddToCart); -console.log(analytics().logAddShippingInfo); -console.log(analytics().logAddToWishlist); -console.log(analytics().logAppOpen); -console.log(analytics().logBeginCheckout); -console.log(analytics().logCampaignDetails); -console.log(analytics().logEarnVirtualCurrency); -console.log(analytics().logEvent); -console.log(analytics().logGenerateLead); -console.log(analytics().logJoinGroup); -console.log(analytics().logLevelEnd); -console.log(analytics().logLevelStart); -console.log(analytics().logLevelUp); -console.log(analytics().logLogin); -console.log(analytics().logPostScore); -console.log(analytics().logPurchase); -console.log(analytics().logRemoveFromCart); -console.log(analytics().logRefund); -console.log(analytics().logSearch); -console.log(analytics().logSelectContent); -console.log(analytics().logSetCheckoutOption); -console.log(analytics().logShare); -console.log(analytics().logSignUp); -console.log(analytics().logSpendVirtualCurrency); -console.log(analytics().logTutorialBegin); -console.log(analytics().logTutorialComplete); -console.log(analytics().logUnlockAchievement); -console.log(analytics().logViewItem); -console.log(analytics().logViewItemList); -console.log(analytics().resetAnalyticsData); -console.log(analytics().logViewCart); -console.log(analytics().setAnalyticsCollectionEnabled); -console.log(analytics().logSelectPromotion); -console.log(analytics().logScreenView); -console.log(analytics().logViewPromotion); -console.log(analytics().setSessionTimeoutDuration); -console.log(analytics().setUserId); -console.log(analytics().setUserProperties); -console.log(analytics().logViewSearchResults); -console.log(analytics().setUserProperty); -console.log(analytics().setConsent); diff --git a/packages/app/lib/common/index.d.ts b/packages/app/lib/common/index.d.ts new file mode 100644 index 0000000000..2d2775a10e --- /dev/null +++ b/packages/app/lib/common/index.d.ts @@ -0,0 +1,5 @@ +declare module '@react-native-firebase/app/lib/common' { + export const MODULAR_DEPRECATION_ARG: string; + export const isAndroid: boolean; + export const isNumber: (value: any) => value is number; +} diff --git a/packages/app/lib/common/validate.d.ts b/packages/app/lib/common/validate.d.ts new file mode 100644 index 0000000000..1d1131c48a --- /dev/null +++ b/packages/app/lib/common/validate.d.ts @@ -0,0 +1,110 @@ +/* + * Copyright (c) 2016-present Invertase Limited & Contributors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this library except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +/** + * Validates that all key-value pairs in an object are strings. + */ +export function objectKeyValuesAreStrings(object: any): boolean; + +/** + * Simple is null check. + */ +export function isNull(value: any): value is null; + +/** + * Simple is object check. + */ +export function isObject(value: any): value is Record; + +/** + * Simple is date check + */ +export function isDate(value: any): value is Date; + +/** + * Simple is function check + */ +export function isFunction(value: any): value is (...args: any[]) => any; + +/** + * Simple is string check + */ +export function isString(value: any): value is string; + +/** + * Simple is number check + */ +export function isNumber(value: any): value is number; + +/** + * Simple is phone number check for E.164 format + */ +export function isE164PhoneNumber(value: any): boolean; + +/** + * Simple finite check + */ +export function isFinite(value: any): boolean; + +/** + * Simple integer check + */ +export function isInteger(value: any): boolean; + +/** + * Simple is boolean check + */ +export function isBoolean(value: any): value is boolean; + +/** + * Array check + */ +export function isArray(value: any): value is Array; + +/** + * Undefined check + */ +export function isUndefined(value: any): value is undefined; + +/** + * Alphanumeric underscore pattern check (/^[a-zA-Z0-9_]+$/) + */ +export function isAlphaNumericUnderscore(value: any): boolean; + +/** + * URL validation test + */ +export function isValidUrl(url: any): boolean; + +/** + * Array includes check + */ +export function isOneOf(value: any, oneOf?: any[]): boolean; + +/** + * No-operation function + */ +export function noop(): void; + +/** + * Validates that an optional native dependency exists + */ +export function validateOptionalNativeDependencyExists( + firebaseJsonKey: string, + apiName: string, + nativeFnExists: boolean, +): void; diff --git a/packages/app/lib/index.d.ts b/packages/app/lib/index.d.ts index a51dce1ad2..de97d89580 100644 --- a/packages/app/lib/index.d.ts +++ b/packages/app/lib/index.d.ts @@ -269,16 +269,6 @@ export namespace ReactNativeFirebase { * The current `FirebaseApp` instance for this Firebase service. */ app: FirebaseApp; - - /** - * The native module instance for this Firebase service. - */ - private native: any; - - /** - * Returns the shared event emitter instance used for all JS event routing. - */ - private emitter: any; } // eslint-disable-next-line @typescript-eslint/no-empty-object-type @@ -617,5 +607,20 @@ export const utils: ReactNativeFirebase.FirebaseModuleWithStatics; + getItem(key: string): Promise; + removeItem(key: string): Promise; +} + +// Memory storage Map instance +export const memoryStorage: Map; + +// Storage key prefix +export const prefix: string; + +// Get the current AsyncStorage instance (either React Native AsyncStorage or memory storage) +export function getReactNativeAsyncStorageInternal(): Promise; + +// Set the AsyncStorage instance to use (React Native AsyncStorage or fallback to memory storage) +export function setReactNativeAsyncStorageInternal(asyncStorageInstance?: AsyncStorageStatic): void; + +// Check if currently using memory storage (fallback) +export function isMemoryStorage(): boolean; + +// Set an item in storage with the React Native Firebase prefix +export function setItem(key: string, value: string): Promise; + +// Get an item from storage with the React Native Firebase prefix +export function getItem(key: string): Promise; + +// Remove an item from storage with the React Native Firebase prefix +export function removeItem(key: string): Promise; diff --git a/packages/app/lib/internal/nativeModule.d.ts b/packages/app/lib/internal/nativeModule.d.ts new file mode 100644 index 0000000000..b901315eb0 --- /dev/null +++ b/packages/app/lib/internal/nativeModule.d.ts @@ -0,0 +1,2 @@ +export declare function getReactNativeModule(moduleName: string): any; +export declare function setReactNativeModule(moduleName: string, module: any): any; diff --git a/packages/app/lib/internal/web/firebaseApp.d.ts b/packages/app/lib/internal/web/firebaseApp.d.ts new file mode 100644 index 0000000000..3afc392bf6 --- /dev/null +++ b/packages/app/lib/internal/web/firebaseApp.d.ts @@ -0,0 +1,21 @@ +/* + * Copyright (c) 2016-present Invertase Limited & Contributors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this library except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +import { ReactNativeFirebase } from '../../index'; + +export function getApp(appName?: string): ReactNativeFirebase.FirebaseApp; +export * from 'firebase/app'; diff --git a/packages/app/lib/internal/web/firebaseInstallations.d.ts b/packages/app/lib/internal/web/firebaseInstallations.d.ts new file mode 100644 index 0000000000..c051fe8646 --- /dev/null +++ b/packages/app/lib/internal/web/firebaseInstallations.d.ts @@ -0,0 +1,45 @@ +/* + * Copyright (c) 2016-present Invertase Limited & Contributors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this library except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +import { ReactNativeFirebase } from '../../index'; + +// Firebase Installations service interface +export interface Installations { + app: ReactNativeFirebase.FirebaseApp; +} + +// Unsubscribe function type for onIdChange +export type Unsubscribe = () => void; + +// getApp function - returns ReactNativeFirebase.FirebaseApp +export function getApp(appName?: string): ReactNativeFirebase.FirebaseApp; + +// getInstallations function - gets the installations service for an app +export function getInstallations(app?: ReactNativeFirebase.FirebaseApp): Installations; + +// getId function - gets the installation ID +export function getId(installations: Installations): Promise; + +// onIdChange function - listens for installation ID changes +export function onIdChange( + installations: Installations, + observer: (installationId: string) => void, + onError?: (error: Error) => void +): Unsubscribe; + +// makeIDBAvailable function - makes IndexedDB available in environments that don't have it +export function makeIDBAvailable(): void; diff --git a/packages/app/lib/internal/web/utils.d.ts b/packages/app/lib/internal/web/utils.d.ts new file mode 100644 index 0000000000..43b8acf3a6 --- /dev/null +++ b/packages/app/lib/internal/web/utils.d.ts @@ -0,0 +1,22 @@ +/* + * Copyright (c) 2016-present Invertase Limited & Contributors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this library except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +import { ReactNativeFirebase } from '../../index'; + +export function guard(fn: () => Promise): Promise; +export function getWebError(error: Error): ReactNativeFirebase.NativeFirebaseError; +export function emitEvent(eventName: string, event: any): void; diff --git a/tests/ios/Podfile.lock b/tests/ios/Podfile.lock index 88e8059499..f1d5be5bc7 100644 --- a/tests/ios/Podfile.lock +++ b/tests/ios/Podfile.lock @@ -2234,85 +2234,85 @@ SPEC CHECKSUMS: nanopb: fad817b59e0457d11a5dfbde799381cd727c1275 PromisesObjC: f5707f49cb48b9636751c5b2e7d227e43fba9f47 PromisesSwift: 9d77319bbe72ebf6d872900551f7eeba9bce2851 - RCT-Folly: e78785aa9ba2ed998ea4151e314036f6c49e6d82 + RCT-Folly: 36fe2295e44b10d831836cc0d1daec5f8abcf809 RCTDeprecation: be794de7dc6ed8f9f7fbf525f86e7651b8b68746 RCTRequired: a83787b092ec554c2eb6019ff3f5b8d125472b3b RCTTypeSafety: 48ad3c858926b1c46f46a81a58822b476e178e2c React: 3b5754191f1b65f1dbc52fbea7959c3d2d9e39c9 React-callinvoker: 6beeaf4c7db11b6cc953fac45f2c76e3fb125013 - React-Core: 8a10ac9de53373a3ecb5dfcbcf56df1d3dad0861 - React-CoreModules: af6999b35c7c01b0e12b59d27f3e054e13da43b1 - React-cxxreact: 833f00155ce8c2fda17f6d286f8eaeff2ececc69 + React-Core: 88e817c42de035378cc71e009193b9a044d3f595 + React-CoreModules: dcf764d71efb4f75d38fcae8d4513b6729f49360 + React-cxxreact: 8cdcc937c5fbc406fe843a381102fd69440ca78a React-debug: 0a9fb34ecb645333d905645dabdcfdc945626078 - React-defaultsnativemodule: e3129434d3fc44832b7121bcbdffbe86c29ef34d - React-domnativemodule: 0dd52f92aae48f433ae5fa56876b4d10ab543faf - React-Fabric: 413d5fbb4b5df36df2d63520d529118884c9410e - React-FabricComponents: faa9035cdd551de0eaf2752afaf0b0327932696a - React-FabricImage: d43f0147c170c73cc7b546f95b7b7da82a6f34fc + React-defaultsnativemodule: b5b92d4b4716825afa8c848b793fc7efdf8aeb5a + React-domnativemodule: 073b3161e1b49dfe9045884369ae1ec2b987de26 + React-Fabric: f62d9ce5c158ae40c2a7b2805b7c055297c9dad7 + React-FabricComponents: 4c48b1052f8f6c3b03c3c3e2a231f1abd6d89703 + React-FabricImage: 5ad03b0081353e1e047ae3471bb129c521bf02b1 React-featureflags: 1bfa283a0e6f26eac629e8cef2add1b2670b6f4e - React-featureflagsnativemodule: 82733d2214096feaf44c411de375749ee1cd564f - React-graphics: 87a183c58b6a5bd5c57ae8c9a8105955f07f3947 - React-hermes: 63df5ac5a944889c8758a6213b39ed825863adb7 - React-idlecallbacksnativemodule: 6eac06a2d491a4b081ac45ab03a5ecf8b12404fa - React-ImageManager: f30c60d98a0a41eb116bf7e22a0258c821747ad2 - React-jserrorhandler: d68cef591c019bd8cd93169d253d6fe860b17844 - React-jsi: 99d6207ec802ad73473a0dad3c9ad48cd98463f6 - React-jsiexecutor: 8c8097b4ba7e7f480582d6e6238b01be5dcc01c0 - React-jsinspector: 434f39b00a5850b5479c7c0f0d06b480482d51a1 - React-jsinspectortracing: d43a8b9f953510ecebe3b5ec7e9676bef2d2c7f0 - React-jsitracing: 1df3b12bab22b3bc9078f54eefa53f82ba981dee - React-logger: 763728cf4eebc9c5dc9bfc3649e22295784f69f3 - React-Mapbuffer: 86e068fae064bbd3f24781d6ae5445b0266b2a10 - React-microtasksnativemodule: fd98e3e44af51599576705ec7a85a36e35978913 - React-NativeModulesApple: 5c61cef9e7f0e1d6216ff0af41a3b882806a5cec - React-perflogger: 5f8fa36a8e168fb355efe72099efe77213bc2ac6 - React-performancetimeline: 4f3521ee6238c9caf1b0969da2c4f610ff72b922 + React-featureflagsnativemodule: 7dc781f04bbd4b394fccb85e187bdda954362bca + React-graphics: 7eefc878da8a522942358f53abd6a7170d757bf3 + React-hermes: 08ad9fb832d1b9faef391be17309aa6a69fad23b + React-idlecallbacksnativemodule: 4a5d5ee0f8d7a9fa94ebd1426d349e866c223979 + React-ImageManager: ce227ed251701b3f37e25a2beede459078fcd82c + React-jserrorhandler: 6e5ffaef9b3364351ef6ef58d6665beabf615a0e + React-jsi: afa286d7e0c102c2478dc420d4f8935e13c973fc + React-jsiexecutor: 08f5b512b4db9e2f147416d60a0a797576b9cfef + React-jsinspector: ebe0817345b1c0194ed5c64185269b9668fadf9a + React-jsinspectortracing: 6f251cb68796f3496698127deabe5b0bbbb89b52 + React-jsitracing: 4c3fd6a14f560c52c167254a07029bcf9b60f3d8 + React-logger: 304814ae37503c8eb54359851cc55bd4f936b39c + React-Mapbuffer: 8ba61e036d346d363ad208cfb1dea6c7fce0dce0 + React-microtasksnativemodule: feb934d19767f38faf9f9f0efb7cc1dcdf2d11b7 + React-NativeModulesApple: 55d6d890aa60200292a90cc1ca6c53409650f48f + React-perflogger: 0ea25c109dba33d47dec36b2634bf7ea67c1a555 + React-performancetimeline: 21656d07aede48ca0c8c3ca7d0e755eaa17f697c React-RCTActionSheet: 2ef95837e89b9b154f13cd8401f9054fc3076aff - React-RCTAnimation: 46abefd5acfda7e6629f9e153646deecc70babd2 - React-RCTAppDelegate: 7e58e0299e304cceee3f7019fa77bc6990f66b22 - React-RCTBlob: f68c63a801ef1d27e83c4011e3b083cc86a200d7 - React-RCTFabric: ee035e3c73729b95da4ee0959b6e0d68cd512368 - React-RCTFBReactNativeSpec: 3240b9b8d792aa4be0fb85c9898fc183125ba8de - React-RCTImage: 34e0bba1507e55f1c614bd759eb91d9be48c8c5b - React-RCTLinking: a0b6c9f4871c18b0b81ea952f43e752718bd5f1d - React-RCTNetwork: bdafd661ac2b20d23b779e45bf7ac3e4c8bd1b60 - React-RCTSettings: 98aa5163796f43789314787b584a84eba47787a9 - React-RCTText: 424a274fc9015b29de89cf3cbcdf4dd85dd69f83 - React-RCTVibration: 92d9875a955b0adb34b4b773528fdbbbc5addd6c + React-RCTAnimation: 33d960d7f58a81779eea6dea47ad0364c67e1517 + React-RCTAppDelegate: 85c13403fd6f6b6cc630428d52bd8bd76a670dc9 + React-RCTBlob: 74c986a02d951931d2f6ed0e07ed5a7eb385bfc0 + React-RCTFabric: 384a6e22644799f66f545bf0de4618f4652c791f + React-RCTFBReactNativeSpec: eb1c3ec5149f76133593a516ff9d5efe32ebcecd + React-RCTImage: 2c58b5ddeb3c65e52f942bbe13ff9c59bd649b09 + React-RCTLinking: b6b14f8a3e62c02fc627ac4f3fb0c7bd941f907c + React-RCTNetwork: 1d050f2466c1541b339587d46f78d5eee218d626 + React-RCTSettings: 8148f6be0ccc0cfe6e313417ebf8a479caaa2146 + React-RCTText: 64114531ad1359e4e02a4a8af60df606dbbabc25 + React-RCTVibration: f4859417a7dd859b6bf18b1aba897e52beb72ef6 React-rendererconsistency: 80ffb3fc9635edb785c19f06eb1ba9e1d3b85ea6 - React-rendererdebug: ae050d2e1ad48d69fa20a7060766c9f132416ffa + React-rendererdebug: ea9b0383484ade00d675582d7848be6a86c3feb5 React-rncore: 7c0b895671632ea5eb84edb85f48e180816e9e33 - React-RuntimeApple: c85771bc5430980a8469ad3b28a3c8dd07f95979 - React-RuntimeCore: 45cbbed881ce89605c779b3f4111664664b63897 + React-RuntimeApple: 8e0654961ab947d3febc60f77a4d9fe97e135d0a + React-RuntimeCore: b194b603daafd68b140ab4c871f1556efc2c69bc React-runtimeexecutor: 876dfc1d8daa819dfd039c40f78f277c5a3e66a6 - React-RuntimeHermes: eb7f7ad2ad9d0bbe5e4e2521aae96de55bd4096a - React-runtimescheduler: 9957105c1d7f068a1c00760a9c332167634f945a + React-RuntimeHermes: f337612527ff2ca8bb86a861be4636f177bc3bbb + React-runtimescheduler: 307946600cf701b3ffe38b454d1d1a710e8e74e7 React-timing: 96e060d0d0bf18522d363716623ed2c61f7107c7 - React-utils: 93529ff7b4baa71aea1f42a48e9d3d06db398618 - ReactAppDependencyProvider: 4893bde33952f997a323eb1a1ee87a72764018ff - ReactCodegen: 31f8d982d351eb4dbf3af220f363c7398ae667c8 - ReactCommon: 0adf8f24a3415b6815613bad362d390726b33fc7 + React-utils: 8adf5864fc96ef51957fee06a3e43ed26559d8a7 + ReactAppDependencyProvider: b48473fe434569ff8f6cb6ed4421217ebcbda878 + ReactCodegen: dbfd0fb94c71add45b06cd6c96ccc7545489c1e6 + ReactCommon: 8fdc2d8511f4099f25d5929f7fa4284c14a7e509 RecaptchaInterop: 11e0b637842dfb48308d242afc3f448062325aba - RNCAsyncStorage: 6a8127b6987dc9fbce778669b252b14c8355c7ce - RNDeviceInfo: d863506092aef7e7af3a1c350c913d867d795047 - RNFBAnalytics: 06df9212670ba64dbee22f2d204c1cd5d2cbabba - RNFBApp: 801ac9162b2a7f518bcd7057c37db8b6d7ac77d7 - RNFBAppCheck: bef13b9b82269f892e3c6f09a09a066895ebef89 - RNFBAppDistribution: 86ac17ca151a9e7a87b27695ca68dcb1bb776091 - RNFBAuth: 40ef334d8c6b17492e4f6bd07ac63953f2170b83 - RNFBCrashlytics: 5d634e8820afbc90587bd0dbb35a17f385a45dca - RNFBDatabase: a4c0a673fccbb6112e48ed8eb8c4e06be874e58e - RNFBFirestore: 78a65900a9d64a44676a62b6f16c17fc8167a52d - RNFBFunctions: d745262d066010f4db75571ddc6c95ec1e426a52 - RNFBInAppMessaging: 93c6f82dc9b04510b8ebb316dfeaa6a05511578d - RNFBInstallations: 0a1bcc53950c3d4d4364c3b8871321623ec08b21 - RNFBMessaging: 28e23e0c21cc2f88f2904888134f291bdeacf10d - RNFBML: 58e9b55e03efe3342b7e57bf2033e300cd975121 - RNFBPerf: 50a683d2a985a245b6ddbbad3e3999d7380286b8 - RNFBRemoteConfig: 96fd4ad4e9fa30843718fbe3c3f5c88aa6af8563 - RNFBStorage: edfd9dbde3fe7edcbc0b3e5e1d88179bab6d5532 + RNCAsyncStorage: 481acf401089f312189e100815088ea5dafc583c + RNDeviceInfo: feea80a690d2bde1fe51461cf548039258bd03f2 + RNFBAnalytics: 35e918f2af228b6ec8fb16ccb6293cbbd5799088 + RNFBApp: fb8ecc637267c1655a4608061356246a410f423d + RNFBAppCheck: 0506d27faee8e058d72d8b2c9ab0562da1a93429 + RNFBAppDistribution: 80e0f444979eaf6da7c87c4aef05220396b2e9de + RNFBAuth: 11b1855318ab7dc26ad1325277718bfd5769b0e3 + RNFBCrashlytics: 7948303d6f5c8a3b1781e515d6749862e1b7bdd8 + RNFBDatabase: 677132a751f3fb0bea2a05ed8bd592545a46fc29 + RNFBFirestore: 18a6282b53dbcd5fd34456361079f2b824c06c40 + RNFBFunctions: f91d7c2526e20d2e75c0720b15f4d857c87eec0a + RNFBInAppMessaging: c62004d87be7bf137a730626362f4ab902a750a3 + RNFBInstallations: f631e5011603355fa9adf9c53f23b288042e6e13 + RNFBMessaging: bad512bf05be5c505428dfec207cbecbf14c66ff + RNFBML: eeb76b540a5a8a48772218f17538c9f6fed3a801 + RNFBPerf: 48de8ada7bf09e8445708e44929c5587e96f29ca + RNFBRemoteConfig: 881b08dac6d35f60faf7a8837480fcd0b2ef0514 + RNFBStorage: 62edd586d5c94c7229977990443f9111f8f3802f SocketRocket: d4aabe649be1e368d1318fdf28a022d714d65748 - Yoga: 6eb60fc2c0eef63e7d2ef4a56e0a3353534143a2 + Yoga: 0c521d2eddeeff54ba1126068140b6e970a77fc0 PODFILE CHECKSUM: 3abe8cfe7b06f24b788e90bea320d8ae6ea6d11a diff --git a/tests/test-app/examples/analytics/index.tsx b/tests/test-app/examples/analytics/index.tsx new file mode 100644 index 0000000000..7c9b563c4d --- /dev/null +++ b/tests/test-app/examples/analytics/index.tsx @@ -0,0 +1,46 @@ +import React from 'react'; +import { AppRegistry, Button, Text, View } from 'react-native'; +import analytics, { firebase } from '@react-native-firebase/analytics'; + +function App() { + return ( + + text text text + text text text +