@backstage-community/plugin-analytics-module-ga4 0.2.10 → 0.2.11

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,11 @@
1
1
  # @backstage-community/plugin-analytics-module-ga4
2
2
 
3
+ ## 0.2.11
4
+
5
+ ### Patch Changes
6
+
7
+ - 46ca1d0: Backstage version bump to v1.32.2
8
+
3
9
  ## 0.2.10
4
10
 
5
11
  ### Patch Changes
@@ -9,7 +9,7 @@ class GoogleAnalytics4 {
9
9
  allowedAttributes;
10
10
  /**
11
11
  * Instantiate the implementation and initialize ReactGA.
12
- * @param options initializes Google Analytics module with the config
12
+ * @param options - initializes Google Analytics module with the config
13
13
  */
14
14
  constructor(options) {
15
15
  const {
@@ -125,9 +125,9 @@ class GoogleAnalytics4 {
125
125
  }
126
126
  /**
127
127
  * Returns an object of dimensions/metrics given an Analytics Context and an
128
- * Event Attributes, e.g. { c_pluginId: "some value", a_attribute1: 42 }
129
- * @param context analytics context object
130
- * @param attributes additional analytics event attributes
128
+ * Event Attributes, e.g. `{ c_pluginId: "some value", a_attribute1: 42 }`
129
+ * @param context - analytics context object
130
+ * @param attributes- additional analytics event attributes
131
131
  */
132
132
  setEventParameters(context, attributes = {}) {
133
133
  const customEventParameters = {};
@@ -161,7 +161,7 @@ class GoogleAnalytics4 {
161
161
  *
162
162
  * Note: this feature requires that an integrator has set up a Google
163
163
  * Analytics User ID view in the property used to track Backstage.
164
- * @param identityApi IdentityApi object
164
+ * @param identityApi - IdentityApi object
165
165
  */
166
166
  async setUserFrom(identityApi) {
167
167
  const { userEntityRef } = await identityApi.getBackstageIdentity();
@@ -172,7 +172,7 @@ class GoogleAnalytics4 {
172
172
  /**
173
173
  * Returns a PII-free (according to Google's terms of service) user ID for
174
174
  * use in Google Analytics.
175
- * @param userEntityRef user entity as string
175
+ * @param userEntityRef - user entity as string
176
176
  */
177
177
  getPrivateUserId(userEntityRef) {
178
178
  if (this.customUserIdTransform) {
@@ -182,7 +182,7 @@ class GoogleAnalytics4 {
182
182
  }
183
183
  /**
184
184
  * Simple hash function; relies on web cryptography + the sha-256 algorithm.
185
- * @param value value to be hashed
185
+ * @param value - value to be hashed
186
186
  */
187
187
  async hash(value) {
188
188
  const digest = await window.crypto.subtle.digest(
@@ -1 +1 @@
1
- {"version":3,"file":"GoogleAnalytics4.esm.js","sources":["../../../../src/apis/implementations/AnalyticsApi/GoogleAnalytics4.ts"],"sourcesContent":["/*\n * Copyright 2023 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport ReactGA from 'react-ga4';\nimport {\n AnalyticsApi,\n AnalyticsContextValue,\n AnalyticsEventAttributes,\n AnalyticsEvent,\n IdentityApi,\n} from '@backstage/core-plugin-api';\nimport {\n AnalyticsApi as NewAnalyticsApi,\n AnalyticsEvent as NewAnalyticsEvent,\n AnalyticsContextValue as NewAnalyticsContextValue,\n} from '@backstage/frontend-plugin-api';\nimport { Config } from '@backstage/config';\nimport { DeferredCapture } from '../../../util/DeferredCapture';\n\n/**\n * Google Analytics API provider for the Backstage Analytics API.\n * @public\n */\nexport class GoogleAnalytics4 implements AnalyticsApi, NewAnalyticsApi {\n private readonly customUserIdTransform?: (\n userEntityRef: string,\n ) => Promise<string>;\n private readonly capture: DeferredCapture;\n private readonly contentGroupBy?: string;\n private readonly allowedContexts?: string[];\n private readonly allowedAttributes?: string[];\n /**\n * Instantiate the implementation and initialize ReactGA.\n * @param options initializes Google Analytics module with the config\n */\n private constructor(options: {\n identityApi?: IdentityApi;\n userIdTransform?: 'sha-256' | ((userEntityRef: string) => Promise<string>);\n identity: string;\n measurementId: string;\n testMode: boolean;\n debug: boolean;\n enableSendPageView: boolean;\n contentGroupBy?: string;\n allowedContexts?: string[];\n allowedAttributes?: string[];\n }) {\n const {\n identity,\n measurementId,\n identityApi,\n userIdTransform = 'sha-256',\n testMode,\n debug,\n enableSendPageView,\n contentGroupBy,\n allowedContexts,\n allowedAttributes,\n } = options;\n // Initialize Google Analytics.\n ReactGA.initialize(measurementId, {\n testMode,\n gaOptions: {\n debug_mode: debug,\n },\n gtagOptions: {\n debug_mode: debug,\n send_page_view: enableSendPageView,\n },\n });\n\n this.contentGroupBy = contentGroupBy;\n this.allowedAttributes = allowedAttributes;\n this.allowedContexts = allowedContexts;\n // If identity is required, defer event capture until identity is known.\n this.capture = new DeferredCapture({ defer: identity === 'required' });\n\n // Allow custom userId transformation.\n this.customUserIdTransform =\n typeof userIdTransform === 'function' ? userIdTransform : undefined;\n\n // Capture user only when explicitly enabled and provided.\n if (identity !== 'disabled') {\n if (identityApi) {\n this.setUserFrom(identityApi).then(() => {\n return;\n });\n }\n }\n }\n\n /**\n * Instantiate a fully configured GA Analytics API implementation.\n * @param config - Config object from app config\n * @param options - options with identityApi and userIdTransform config\n */\n static fromConfig(\n config: Config,\n options: {\n identityApi?: IdentityApi;\n userIdTransform?:\n | 'sha-256'\n | ((userEntityRef: string) => Promise<string>);\n } = {},\n ) {\n // Get all necessary configuration.\n const measurementId = config.getString('app.analytics.ga4.measurementId');\n const identity =\n config.getOptionalString('app.analytics.ga4.identity') || 'disabled';\n const debug = config.getOptionalBoolean('app.analytics.ga4.debug') ?? false;\n const enableSendPageView =\n config.getOptionalBoolean('app.analytics.ga4.enableSendPageView') ??\n false;\n const testMode =\n config.getOptionalBoolean('app.analytics.ga4.testMode') ?? false;\n\n const contentGroupBy = config.getOptionalString(\n 'app.analytics.ga4.contentGrouping',\n );\n const allowedContexts = config.getOptionalStringArray(\n 'app.analytics.ga4.allowedContexts',\n );\n const allowedAttributes = config.getOptionalStringArray(\n 'app.analytics.ga4.allowedAttributes',\n );\n\n if (identity === 'required' && !options.identityApi) {\n throw new Error(\n 'Invalid config: identity API must be provided to deps when ga4.identity is required',\n );\n }\n\n // Return an implementation instance.\n return new GoogleAnalytics4({\n ...options,\n identity,\n measurementId: measurementId,\n testMode,\n debug,\n enableSendPageView,\n contentGroupBy,\n allowedContexts,\n allowedAttributes,\n });\n }\n\n /**\n * Primary event capture implementation. Handles core navigate event as a\n * pageview and the rest as custom events. All custom dimensions/metrics are\n * applied as they should be (set on pageview, merged object on events).\n * @param event - AnalyticsEvent type captured\n */\n captureEvent(event: AnalyticsEvent | NewAnalyticsEvent) {\n const { context, action, subject, value, attributes } = event;\n const customEventData = this.setEventParameters(context, attributes);\n if (this.contentGroupBy) {\n customEventData.content_group = context[this.contentGroupBy]!;\n }\n\n const extensionId = context.extensionId || context.extension;\n const category = extensionId ? String(extensionId) : 'App';\n\n // The legacy default extension was 'App' and the new one is 'app'\n if (\n action === 'navigate' &&\n category.toLocaleLowerCase('en-US').startsWith('app')\n ) {\n this.capture.event(\n {\n category,\n action: 'page_view',\n label: subject,\n value,\n },\n customEventData,\n );\n return;\n }\n\n if (action === 'search') {\n customEventData.search_term = subject;\n }\n\n this.capture.event(\n {\n category,\n action,\n label: subject,\n value,\n },\n customEventData,\n );\n }\n\n /**\n * Returns an object of dimensions/metrics given an Analytics Context and an\n * Event Attributes, e.g. { c_pluginId: \"some value\", a_attribute1: 42 }\n * @param context analytics context object\n * @param attributes additional analytics event attributes\n */\n private setEventParameters(\n context: AnalyticsContextValue | NewAnalyticsContextValue,\n attributes: AnalyticsEventAttributes = {},\n ) {\n const customEventParameters: {\n [x: string]: string | number | boolean | undefined;\n } = {};\n\n const contextKeys =\n this.allowedContexts?.join('') === '*'\n ? Object.keys(context)\n : this.allowedContexts;\n\n contextKeys?.forEach(ctx => {\n if (\n context[ctx] !== undefined &&\n context[ctx] !== null &&\n context[ctx] !== ''\n ) {\n customEventParameters[`c_${ctx}`] = context[ctx];\n }\n });\n\n const attrKeys =\n this.allowedAttributes?.join('') === '*'\n ? Object.keys(attributes)\n : this.allowedAttributes;\n attrKeys?.forEach(attr => {\n if (\n attributes[attr] !== undefined &&\n attributes[attr] !== null &&\n attributes[attr] !== ''\n ) {\n customEventParameters[`a_${attr}`] = attributes[attr];\n }\n });\n\n return customEventParameters;\n }\n\n /**\n * Sets the GA userId, based on the `userEntityRef` set on the backstage\n * identity loaded from a given Backstage Identity API instance. Because\n * Google forbids sending any PII (including on the userId field), we hash\n * the entire `userEntityRef` on behalf of integrators:\n *\n * - With value `User:default/name`, userId becomes `sha256(User:default/name)`\n *\n * If an integrator wishes to use an alternative hashing mechanism or an\n * entirely different value, they may do so by passing a `userIdTransform`\n * function alongside the `identityApi` to `GoogleAnalytics.fromConfig()`.\n * This function receives the `userEntityRef` as an argument and should\n * resolve to a hashed version of whatever identifier they choose.\n *\n * Note: this feature requires that an integrator has set up a Google\n * Analytics User ID view in the property used to track Backstage.\n * @param identityApi IdentityApi object\n */\n private async setUserFrom(identityApi: IdentityApi) {\n const { userEntityRef } = await identityApi.getBackstageIdentity();\n\n // Prevent PII from being passed to Google Analytics.\n const userId = await this.getPrivateUserId(userEntityRef);\n\n // Set the user ID.\n ReactGA.set({ user_id: userId });\n\n // Notify the deferred capture mechanism that it may proceed.\n this.capture.setReady();\n }\n\n /**\n * Returns a PII-free (according to Google's terms of service) user ID for\n * use in Google Analytics.\n * @param userEntityRef user entity as string\n */\n private getPrivateUserId(userEntityRef: string): Promise<string> {\n // Allow integrators to provide their own hashing transformer.\n if (this.customUserIdTransform) {\n return this.customUserIdTransform(userEntityRef);\n }\n\n return this.hash(userEntityRef);\n }\n\n /**\n * Simple hash function; relies on web cryptography + the sha-256 algorithm.\n * @param value value to be hashed\n */\n private async hash(value: string): Promise<string> {\n const digest = await window.crypto.subtle.digest(\n 'sha-256',\n new TextEncoder().encode(value),\n );\n const hashArray = Array.from(new Uint8Array(digest));\n return hashArray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A0B,EAAA;AAClD,IAAA,MAAM,EAAE,aAAA,EAAkB,GAAA,MAAM,YAAY,oBAAqB,EAAA,CAAA;AAGjE,IAAA,MAAM,MAAS,GAAA,MAAM,IAAK,CAAA,gBAAA,CAAiB,aAAa,CAAA,CAAA;AAGxD,IAAA,OAAA,CAAQ,GAAI,CAAA,EAAE,OAAS,EAAA,MAAA,EAAQ,CAAA,CAAA;AAG/B,IAAA,IAAA,CAAK,QAAQ,QAAS,EAAA,CAAA;AAAA,GACxB;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAOQ,iBAAiB,aAAwC,EAAA;AAE/D,IAAA,IAAI,KAAK,qBAAuB,EAAA;AAC9B,MAAO,OAAA,IAAA,CAAK,sBAAsB,aAAa,CAAA,CAAA;AAAA,KACjD;AAEA,IAAO,OAAA,IAAA,CAAK,KAAK,aAAa,CAAA,CAAA;AAAA,GAChC;AAAA;AAAA;AAAA;AAAA;AAAA,EAMA,MAAc,KAAK,KAAgC,EAAA;AACjD,IAAA,MAAM,MAAS,GAAA,MAAM,MAAO,CAAA,MAAA,CAAO,MAAO,CAAA,MAAA;AAAA,MACxC,SAAA;AAAA,MACA,IAAI,WAAA,EAAc,CAAA,MAAA,CAAO,KAAK,CAAA;AAAA,KAChC,CAAA;AACA,IAAA,MAAM,YAAY,KAAM,CAAA,IAAA,CAAK,IAAI,UAAA,CAAW,MAAM,CAAC,CAAA,CAAA;AACnD,IAAA,OAAO,SAAU,CAAA,GAAA,CAAI,CAAK,CAAA,KAAA,CAAA,CAAE,QAAS,CAAA,EAAE,CAAE,CAAA,QAAA,CAAS,CAAG,EAAA,GAAG,CAAC,CAAA,CAAE,KAAK,EAAE,CAAA,CAAA;AAAA,GACpE;AACF;;;;"}
1
+ {"version":3,"file":"GoogleAnalytics4.esm.js","sources":["../../../../src/apis/implementations/AnalyticsApi/GoogleAnalytics4.ts"],"sourcesContent":["/*\n * Copyright 2023 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport ReactGA from 'react-ga4';\nimport {\n AnalyticsApi,\n AnalyticsContextValue,\n AnalyticsEventAttributes,\n AnalyticsEvent,\n IdentityApi,\n} from '@backstage/core-plugin-api';\nimport {\n AnalyticsApi as NewAnalyticsApi,\n AnalyticsEvent as NewAnalyticsEvent,\n AnalyticsContextValue as NewAnalyticsContextValue,\n} from '@backstage/frontend-plugin-api';\nimport { Config } from '@backstage/config';\nimport { DeferredCapture } from '../../../util/DeferredCapture';\n\n/**\n * Google Analytics API provider for the Backstage Analytics API.\n * @public\n */\nexport class GoogleAnalytics4 implements AnalyticsApi, NewAnalyticsApi {\n private readonly customUserIdTransform?: (\n userEntityRef: string,\n ) => Promise<string>;\n private readonly capture: DeferredCapture;\n private readonly contentGroupBy?: string;\n private readonly allowedContexts?: string[];\n private readonly allowedAttributes?: string[];\n /**\n * Instantiate the implementation and initialize ReactGA.\n * @param options - initializes Google Analytics module with the config\n */\n private constructor(options: {\n identityApi?: IdentityApi;\n userIdTransform?: 'sha-256' | ((userEntityRef: string) => Promise<string>);\n identity: string;\n measurementId: string;\n testMode: boolean;\n debug: boolean;\n enableSendPageView: boolean;\n contentGroupBy?: string;\n allowedContexts?: string[];\n allowedAttributes?: string[];\n }) {\n const {\n identity,\n measurementId,\n identityApi,\n userIdTransform = 'sha-256',\n testMode,\n debug,\n enableSendPageView,\n contentGroupBy,\n allowedContexts,\n allowedAttributes,\n } = options;\n // Initialize Google Analytics.\n ReactGA.initialize(measurementId, {\n testMode,\n gaOptions: {\n debug_mode: debug,\n },\n gtagOptions: {\n debug_mode: debug,\n send_page_view: enableSendPageView,\n },\n });\n\n this.contentGroupBy = contentGroupBy;\n this.allowedAttributes = allowedAttributes;\n this.allowedContexts = allowedContexts;\n // If identity is required, defer event capture until identity is known.\n this.capture = new DeferredCapture({ defer: identity === 'required' });\n\n // Allow custom userId transformation.\n this.customUserIdTransform =\n typeof userIdTransform === 'function' ? userIdTransform : undefined;\n\n // Capture user only when explicitly enabled and provided.\n if (identity !== 'disabled') {\n if (identityApi) {\n this.setUserFrom(identityApi).then(() => {\n return;\n });\n }\n }\n }\n\n /**\n * Instantiate a fully configured GA Analytics API implementation.\n * @param config - Config object from app config\n * @param options - options with identityApi and userIdTransform config\n */\n static fromConfig(\n config: Config,\n options: {\n identityApi?: IdentityApi;\n userIdTransform?:\n | 'sha-256'\n | ((userEntityRef: string) => Promise<string>);\n } = {},\n ) {\n // Get all necessary configuration.\n const measurementId = config.getString('app.analytics.ga4.measurementId');\n const identity =\n config.getOptionalString('app.analytics.ga4.identity') || 'disabled';\n const debug = config.getOptionalBoolean('app.analytics.ga4.debug') ?? false;\n const enableSendPageView =\n config.getOptionalBoolean('app.analytics.ga4.enableSendPageView') ??\n false;\n const testMode =\n config.getOptionalBoolean('app.analytics.ga4.testMode') ?? false;\n\n const contentGroupBy = config.getOptionalString(\n 'app.analytics.ga4.contentGrouping',\n );\n const allowedContexts = config.getOptionalStringArray(\n 'app.analytics.ga4.allowedContexts',\n );\n const allowedAttributes = config.getOptionalStringArray(\n 'app.analytics.ga4.allowedAttributes',\n );\n\n if (identity === 'required' && !options.identityApi) {\n throw new Error(\n 'Invalid config: identity API must be provided to deps when ga4.identity is required',\n );\n }\n\n // Return an implementation instance.\n return new GoogleAnalytics4({\n ...options,\n identity,\n measurementId: measurementId,\n testMode,\n debug,\n enableSendPageView,\n contentGroupBy,\n allowedContexts,\n allowedAttributes,\n });\n }\n\n /**\n * Primary event capture implementation. Handles core navigate event as a\n * pageview and the rest as custom events. All custom dimensions/metrics are\n * applied as they should be (set on pageview, merged object on events).\n * @param event - AnalyticsEvent type captured\n */\n captureEvent(event: AnalyticsEvent | NewAnalyticsEvent) {\n const { context, action, subject, value, attributes } = event;\n const customEventData = this.setEventParameters(context, attributes);\n if (this.contentGroupBy) {\n customEventData.content_group = context[this.contentGroupBy]!;\n }\n\n const extensionId = context.extensionId || context.extension;\n const category = extensionId ? String(extensionId) : 'App';\n\n // The legacy default extension was 'App' and the new one is 'app'\n if (\n action === 'navigate' &&\n category.toLocaleLowerCase('en-US').startsWith('app')\n ) {\n this.capture.event(\n {\n category,\n action: 'page_view',\n label: subject,\n value,\n },\n customEventData,\n );\n return;\n }\n\n if (action === 'search') {\n customEventData.search_term = subject;\n }\n\n this.capture.event(\n {\n category,\n action,\n label: subject,\n value,\n },\n customEventData,\n );\n }\n\n /**\n * Returns an object of dimensions/metrics given an Analytics Context and an\n * Event Attributes, e.g. `{ c_pluginId: \"some value\", a_attribute1: 42 }`\n * @param context - analytics context object\n * @param attributes- additional analytics event attributes\n */\n private setEventParameters(\n context: AnalyticsContextValue | NewAnalyticsContextValue,\n attributes: AnalyticsEventAttributes = {},\n ) {\n const customEventParameters: {\n [x: string]: string | number | boolean | undefined;\n } = {};\n\n const contextKeys =\n this.allowedContexts?.join('') === '*'\n ? Object.keys(context)\n : this.allowedContexts;\n\n contextKeys?.forEach(ctx => {\n if (\n context[ctx] !== undefined &&\n context[ctx] !== null &&\n context[ctx] !== ''\n ) {\n customEventParameters[`c_${ctx}`] = context[ctx];\n }\n });\n\n const attrKeys =\n this.allowedAttributes?.join('') === '*'\n ? Object.keys(attributes)\n : this.allowedAttributes;\n attrKeys?.forEach(attr => {\n if (\n attributes[attr] !== undefined &&\n attributes[attr] !== null &&\n attributes[attr] !== ''\n ) {\n customEventParameters[`a_${attr}`] = attributes[attr];\n }\n });\n\n return customEventParameters;\n }\n\n /**\n * Sets the GA userId, based on the `userEntityRef` set on the backstage\n * identity loaded from a given Backstage Identity API instance. Because\n * Google forbids sending any PII (including on the userId field), we hash\n * the entire `userEntityRef` on behalf of integrators:\n *\n * - With value `User:default/name`, userId becomes `sha256(User:default/name)`\n *\n * If an integrator wishes to use an alternative hashing mechanism or an\n * entirely different value, they may do so by passing a `userIdTransform`\n * function alongside the `identityApi` to `GoogleAnalytics.fromConfig()`.\n * This function receives the `userEntityRef` as an argument and should\n * resolve to a hashed version of whatever identifier they choose.\n *\n * Note: this feature requires that an integrator has set up a Google\n * Analytics User ID view in the property used to track Backstage.\n * @param identityApi - IdentityApi object\n */\n private async setUserFrom(identityApi: IdentityApi) {\n const { userEntityRef } = await identityApi.getBackstageIdentity();\n\n // Prevent PII from being passed to Google Analytics.\n const userId = await this.getPrivateUserId(userEntityRef);\n\n // Set the user ID.\n ReactGA.set({ user_id: userId });\n\n // Notify the deferred capture mechanism that it may proceed.\n this.capture.setReady();\n }\n\n /**\n * Returns a PII-free (according to Google's terms of service) user ID for\n * use in Google Analytics.\n * @param userEntityRef - user entity as string\n */\n private getPrivateUserId(userEntityRef: string): Promise<string> {\n // Allow integrators to provide their own hashing transformer.\n if (this.customUserIdTransform) {\n return this.customUserIdTransform(userEntityRef);\n }\n\n return this.hash(userEntityRef);\n }\n\n /**\n * Simple hash function; relies on web cryptography + the sha-256 algorithm.\n * @param value - value to be hashed\n */\n private async hash(value: string): Promise<string> {\n const digest = await window.crypto.subtle.digest(\n 'sha-256',\n new TextEncoder().encode(value),\n );\n const hashArray = Array.from(new Uint8Array(digest));\n return hashArray.map(b => b.toString(16).padStart(2, '0')).join('');\n }\n}\n"],"names":[],"mappings":";;;AAoCO,MAAM,gBAA0D,CAAA;AAAA,EACpD,qBAAA,CAAA;AAAA,EAGA,OAAA,CAAA;AAAA,EACA,cAAA,CAAA;AAAA,EACA,eAAA,CAAA;AAAA,EACA,iBAAA,CAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAKT,YAAY,OAWjB,EAAA;AACD,IAAM,MAAA;AAAA,MACJ,QAAA;AAAA,MACA,aAAA;AAAA,MACA,WAAA;AAAA,MACA,eAAkB,GAAA,SAAA;AAAA,MAClB,QAA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AA;AAE/D,IAAA,IAAI,KAAK,qBAAuB,EAAA;AAC9B,MAAO,OAAA,IAAA,CAAK,sBAAsB,aAAa,CAAA,CAAA;AAAA,KACjD;AAEA,IAAO,OAAA,IAAA,CAAK,KAAK,aAAa,CAAA,CAAA;AAAA,GAChC;AAAA;AAAA;AAAA;AAAA;AAAA,EAMA,MAAc,KAAK,KAAgC,EAAA;AACjD,IAAA,MAAM,MAAS,GAAA,MAAM,MAAO,CAAA,MAAA,CAAO,MAAO,CAAA,MAAA;AAAA,MACxC,SAAA;AAAA,MACA,IAAI,WAAA,EAAc,CAAA,MAAA,CAAO,KAAK,CAAA;AAAA,KAChC,CAAA;AACA,IAAA,MAAM,YAAY,KAAM,CAAA,IAAA,CAAK,IAAI,UAAA,CAAW,MAAM,CAAC,CAAA,CAAA;AACnD,IAAA,OAAO,SAAU,CAAA,GAAA,CAAI,CAAK,CAAA,KAAA,CAAA,CAAE,QAAS,CAAA,EAAE,CAAE,CAAA,QAAA,CAAS,CAAG,EAAA,GAAG,CAAC,CAAA,CAAE,KAAK,EAAE,CAAA,CAAA;AAAA,GACpE;AACF;;;;"}
package/dist/index.d.ts CHANGED
@@ -14,7 +14,7 @@ declare class GoogleAnalytics4 implements AnalyticsApi, AnalyticsApi$1 {
14
14
  private readonly allowedAttributes?;
15
15
  /**
16
16
  * Instantiate the implementation and initialize ReactGA.
17
- * @param options initializes Google Analytics module with the config
17
+ * @param options - initializes Google Analytics module with the config
18
18
  */
19
19
  private constructor();
20
20
  /**
@@ -35,9 +35,9 @@ declare class GoogleAnalytics4 implements AnalyticsApi, AnalyticsApi$1 {
35
35
  captureEvent(event: AnalyticsEvent | AnalyticsEvent$1): void;
36
36
  /**
37
37
  * Returns an object of dimensions/metrics given an Analytics Context and an
38
- * Event Attributes, e.g. { c_pluginId: "some value", a_attribute1: 42 }
39
- * @param context analytics context object
40
- * @param attributes additional analytics event attributes
38
+ * Event Attributes, e.g. `{ c_pluginId: "some value", a_attribute1: 42 }`
39
+ * @param context - analytics context object
40
+ * @param attributes- additional analytics event attributes
41
41
  */
42
42
  private setEventParameters;
43
43
  /**
@@ -56,18 +56,18 @@ declare class GoogleAnalytics4 implements AnalyticsApi, AnalyticsApi$1 {
56
56
  *
57
57
  * Note: this feature requires that an integrator has set up a Google
58
58
  * Analytics User ID view in the property used to track Backstage.
59
- * @param identityApi IdentityApi object
59
+ * @param identityApi - IdentityApi object
60
60
  */
61
61
  private setUserFrom;
62
62
  /**
63
63
  * Returns a PII-free (according to Google's terms of service) user ID for
64
64
  * use in Google Analytics.
65
- * @param userEntityRef user entity as string
65
+ * @param userEntityRef - user entity as string
66
66
  */
67
67
  private getPrivateUserId;
68
68
  /**
69
69
  * Simple hash function; relies on web cryptography + the sha-256 algorithm.
70
- * @param value value to be hashed
70
+ * @param value - value to be hashed
71
71
  */
72
72
  private hash;
73
73
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@backstage-community/plugin-analytics-module-ga4",
3
- "version": "0.2.10",
3
+ "version": "0.2.11",
4
4
  "backstage": {
5
5
  "role": "frontend-plugin-module",
6
6
  "pluginId": "app",
@@ -36,14 +36,14 @@
36
36
  },
37
37
  "dependencies": {
38
38
  "@backstage/config": "^1.2.0",
39
- "@backstage/core-components": "^0.15.0",
40
- "@backstage/core-plugin-api": "^1.9.4",
41
- "@backstage/frontend-plugin-api": "^0.8.0",
39
+ "@backstage/core-components": "^0.15.1",
40
+ "@backstage/core-plugin-api": "^1.10.0",
41
+ "@backstage/frontend-plugin-api": "^0.9.0",
42
42
  "react-ga4": "^2.0.0"
43
43
  },
44
44
  "devDependencies": {
45
- "@backstage/cli": "^0.27.1",
46
- "@backstage/dev-utils": "^1.1.1",
45
+ "@backstage/cli": "^0.28.0",
46
+ "@backstage/dev-utils": "^1.1.2",
47
47
  "@testing-library/dom": "^10.0.0",
48
48
  "@testing-library/jest-dom": "^6.0.0",
49
49
  "@testing-library/react": "^15.0.0",