@firebase/analytics 0.9.4 → 0.9.5-canary.0832dcac2

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
  # @firebase/analytics
2
2
 
3
+ ## 0.9.5
4
+
5
+ ### Patch Changes
6
+
7
+ - [`3435ba945`](https://github.com/firebase/firebase-js-sdk/commit/3435ba945a9febf5a0aece05517a5656f58b246f) [#7155](https://github.com/firebase/firebase-js-sdk/pull/7155) (fixes [#7048](https://github.com/firebase/firebase-js-sdk/issues/7048)) - Use the Trusted Types API when composing the gtag URL.
8
+
3
9
  ## 0.9.4
4
10
 
5
11
  ### Patch Changes
@@ -174,6 +174,16 @@ export declare interface EventParams {
174
174
  */
175
175
  export declare function getAnalytics(app?: FirebaseApp): Analytics;
176
176
 
177
+ /**
178
+ * Retrieves a unique Google Analytics identifier for the web client.
179
+ * See {@link https://developers.google.com/analytics/devguides/collection/ga4/reference/config#client_id | client_id}.
180
+ *
181
+ * @public
182
+ *
183
+ * @param app - The {@link @firebase/app#FirebaseApp} to use.
184
+ */
185
+ export declare function getGoogleAnalyticsClientId(analyticsInstance: Analytics): Promise<string>;
186
+
177
187
  /**
178
188
  * A set of common Google Analytics config settings recognized by
179
189
  * `gtag.js`.
@@ -174,6 +174,16 @@ export declare interface EventParams {
174
174
  */
175
175
  export declare function getAnalytics(app?: FirebaseApp): Analytics;
176
176
 
177
+ /**
178
+ * Retrieves a unique Google Analytics identifier for the web client.
179
+ * See {@link https://developers.google.com/analytics/devguides/collection/ga4/reference/config#client_id | client_id}.
180
+ *
181
+ * @public
182
+ *
183
+ * @param app - The {@link @firebase/app#FirebaseApp} to use.
184
+ */
185
+ export declare function getGoogleAnalyticsClientId(analyticsInstance: Analytics): Promise<string>;
186
+
177
187
  /**
178
188
  * A set of common Google Analytics config settings recognized by
179
189
  * `gtag.js`.
@@ -1,5 +1,5 @@
1
1
  import { getApp, _getProvider, _registerComponent, registerVersion } from '@firebase/app';
2
- import { __awaiter, __generator, __assign } from 'tslib';
2
+ import { __awaiter, __generator, __spreadArray, __assign } from 'tslib';
3
3
  import { Logger } from '@firebase/logger';
4
4
  import { ErrorFactory, calculateBackoffMillis, FirebaseError, validateIndexedDBOpenable, isIndexedDBAvailable, isBrowserExtension, areCookiesEnabled, getModularInstance, deepEqual } from '@firebase/util';
5
5
  import { Component } from '@firebase/component';
@@ -66,6 +66,66 @@ var logger = new Logger('@firebase/analytics');
66
66
  * See the License for the specific language governing permissions and
67
67
  * limitations under the License.
68
68
  */
69
+ var _a;
70
+ var ERRORS = (_a = {},
71
+ _a["already-exists" /* AnalyticsError.ALREADY_EXISTS */] = 'A Firebase Analytics instance with the appId {$id} ' +
72
+ ' already exists. ' +
73
+ 'Only one Firebase Analytics instance can be created for each appId.',
74
+ _a["already-initialized" /* AnalyticsError.ALREADY_INITIALIZED */] = 'initializeAnalytics() cannot be called again with different options than those ' +
75
+ 'it was initially called with. It can be called again with the same options to ' +
76
+ 'return the existing instance, or getAnalytics() can be used ' +
77
+ 'to get a reference to the already-intialized instance.',
78
+ _a["already-initialized-settings" /* AnalyticsError.ALREADY_INITIALIZED_SETTINGS */] = 'Firebase Analytics has already been initialized.' +
79
+ 'settings() must be called before initializing any Analytics instance' +
80
+ 'or it will have no effect.',
81
+ _a["interop-component-reg-failed" /* AnalyticsError.INTEROP_COMPONENT_REG_FAILED */] = 'Firebase Analytics Interop Component failed to instantiate: {$reason}',
82
+ _a["invalid-analytics-context" /* AnalyticsError.INVALID_ANALYTICS_CONTEXT */] = 'Firebase Analytics is not supported in this environment. ' +
83
+ 'Wrap initialization of analytics in analytics.isSupported() ' +
84
+ 'to prevent initialization in unsupported environments. Details: {$errorInfo}',
85
+ _a["indexeddb-unavailable" /* AnalyticsError.INDEXEDDB_UNAVAILABLE */] = 'IndexedDB unavailable or restricted in this environment. ' +
86
+ 'Wrap initialization of analytics in analytics.isSupported() ' +
87
+ 'to prevent initialization in unsupported environments. Details: {$errorInfo}',
88
+ _a["fetch-throttle" /* AnalyticsError.FETCH_THROTTLE */] = 'The config fetch request timed out while in an exponential backoff state.' +
89
+ ' Unix timestamp in milliseconds when fetch request throttling ends: {$throttleEndTimeMillis}.',
90
+ _a["config-fetch-failed" /* AnalyticsError.CONFIG_FETCH_FAILED */] = 'Dynamic config fetch failed: [{$httpStatus}] {$responseMessage}',
91
+ _a["no-api-key" /* AnalyticsError.NO_API_KEY */] = 'The "apiKey" field is empty in the local Firebase config. Firebase Analytics requires this field to' +
92
+ 'contain a valid API key.',
93
+ _a["no-app-id" /* AnalyticsError.NO_APP_ID */] = 'The "appId" field is empty in the local Firebase config. Firebase Analytics requires this field to' +
94
+ 'contain a valid app ID.',
95
+ _a["no-client-id" /* AnalyticsError.NO_CLIENT_ID */] = 'The "client_id" field is empty.',
96
+ _a["invalid-gtag-resource" /* AnalyticsError.INVALID_GTAG_RESOURCE */] = 'Trusted Types detected an invalid gtag resource: {$gtagURL}.',
97
+ _a);
98
+ var ERROR_FACTORY = new ErrorFactory('analytics', 'Analytics', ERRORS);
99
+
100
+ /**
101
+ * @license
102
+ * Copyright 2019 Google LLC
103
+ *
104
+ * Licensed under the Apache License, Version 2.0 (the "License");
105
+ * you may not use this file except in compliance with the License.
106
+ * You may obtain a copy of the License at
107
+ *
108
+ * http://www.apache.org/licenses/LICENSE-2.0
109
+ *
110
+ * Unless required by applicable law or agreed to in writing, software
111
+ * distributed under the License is distributed on an "AS IS" BASIS,
112
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
113
+ * See the License for the specific language governing permissions and
114
+ * limitations under the License.
115
+ */
116
+ /**
117
+ * Verifies and creates a TrustedScriptURL.
118
+ */
119
+ function createGtagTrustedTypesScriptURL(url) {
120
+ if (!url.startsWith(GTAG_URL)) {
121
+ var err = ERROR_FACTORY.create("invalid-gtag-resource" /* AnalyticsError.INVALID_GTAG_RESOURCE */, {
122
+ gtagURL: url
123
+ });
124
+ logger.warn(err.message);
125
+ return '';
126
+ }
127
+ return url;
128
+ }
69
129
  /**
70
130
  * Makeshift polyfill for Promise.allSettled(). Resolves when all promises
71
131
  * have either resolved or rejected.
@@ -75,15 +135,37 @@ var logger = new Logger('@firebase/analytics');
75
135
  function promiseAllSettled(promises) {
76
136
  return Promise.all(promises.map(function (promise) { return promise.catch(function (e) { return e; }); }));
77
137
  }
138
+ /**
139
+ * Creates a TrustedTypePolicy object that implements the rules passed as policyOptions.
140
+ *
141
+ * @param policyName A string containing the name of the policy
142
+ * @param policyOptions Object containing implementations of instance methods for TrustedTypesPolicy, see {@link https://developer.mozilla.org/en-US/docs/Web/API/TrustedTypePolicy#instance_methods
143
+ * | the TrustedTypePolicy reference documentation}.
144
+ */
145
+ function createTrustedTypesPolicy(policyName, policyOptions) {
146
+ // Create a TrustedTypes policy that we can use for updating src
147
+ // properties
148
+ var trustedTypesPolicy;
149
+ if (window.trustedTypes) {
150
+ trustedTypesPolicy = window.trustedTypes.createPolicy(policyName, policyOptions);
151
+ }
152
+ return trustedTypesPolicy;
153
+ }
78
154
  /**
79
155
  * Inserts gtag script tag into the page to asynchronously download gtag.
80
156
  * @param dataLayerName Name of datalayer (most often the default, "_dataLayer").
81
157
  */
82
158
  function insertScriptTag(dataLayerName, measurementId) {
159
+ var trustedTypesPolicy = createTrustedTypesPolicy('firebase-js-sdk-policy', {
160
+ createScriptURL: createGtagTrustedTypesScriptURL
161
+ });
83
162
  var script = document.createElement('script');
84
163
  // We are not providing an analyticsId in the URL because it would trigger a `page_view`
85
164
  // without fid. We will initialize ga-id using gtag (config) command together with fid.
86
- script.src = "".concat(GTAG_URL, "?l=").concat(dataLayerName, "&id=").concat(measurementId);
165
+ var gtagScriptURL = "".concat(GTAG_URL, "?l=").concat(dataLayerName, "&id=").concat(measurementId);
166
+ script.src = trustedTypesPolicy
167
+ ? trustedTypesPolicy === null || trustedTypesPolicy === void 0 ? void 0 : trustedTypesPolicy.createScriptURL(gtagScriptURL)
168
+ : gtagScriptURL;
87
169
  script.async = true;
88
170
  document.head.appendChild(script);
89
171
  }
@@ -254,36 +336,50 @@ measurementIdToAppId) {
254
336
  * @param idOrNameOrParams Measurement ID if command is EVENT/CONFIG, params if command is SET.
255
337
  * @param gtagParams Params if event is EVENT/CONFIG.
256
338
  */
257
- function gtagWrapper(command, idOrNameOrParams, gtagParams) {
339
+ function gtagWrapper(command) {
340
+ var args = [];
341
+ for (var _i = 1; _i < arguments.length; _i++) {
342
+ args[_i - 1] = arguments[_i];
343
+ }
258
344
  return __awaiter(this, void 0, void 0, function () {
259
- var e_3;
345
+ var measurementId, gtagParams, measurementId, gtagParams, gtagParams, measurementId, fieldName, callback, customParams, e_3;
260
346
  return __generator(this, function (_a) {
261
347
  switch (_a.label) {
262
348
  case 0:
263
349
  _a.trys.push([0, 6, , 7]);
264
350
  if (!(command === "event" /* GtagCommand.EVENT */)) return [3 /*break*/, 2];
351
+ measurementId = args[0], gtagParams = args[1];
265
352
  // If EVENT, second arg must be measurementId.
266
- return [4 /*yield*/, gtagOnEvent(gtagCore, initializationPromisesMap, dynamicConfigPromisesList, idOrNameOrParams, gtagParams)];
353
+ return [4 /*yield*/, gtagOnEvent(gtagCore, initializationPromisesMap, dynamicConfigPromisesList, measurementId, gtagParams)];
267
354
  case 1:
268
355
  // If EVENT, second arg must be measurementId.
269
356
  _a.sent();
270
357
  return [3 /*break*/, 5];
271
358
  case 2:
272
359
  if (!(command === "config" /* GtagCommand.CONFIG */)) return [3 /*break*/, 4];
360
+ measurementId = args[0], gtagParams = args[1];
273
361
  // If CONFIG, second arg must be measurementId.
274
- return [4 /*yield*/, gtagOnConfig(gtagCore, initializationPromisesMap, dynamicConfigPromisesList, measurementIdToAppId, idOrNameOrParams, gtagParams)];
362
+ return [4 /*yield*/, gtagOnConfig(gtagCore, initializationPromisesMap, dynamicConfigPromisesList, measurementIdToAppId, measurementId, gtagParams)];
275
363
  case 3:
276
364
  // If CONFIG, second arg must be measurementId.
277
365
  _a.sent();
278
366
  return [3 /*break*/, 5];
279
367
  case 4:
280
368
  if (command === "consent" /* GtagCommand.CONSENT */) {
281
- // If CONFIG, second arg must be measurementId.
369
+ gtagParams = args[0];
282
370
  gtagCore("consent" /* GtagCommand.CONSENT */, 'update', gtagParams);
283
371
  }
284
- else {
372
+ else if (command === "get" /* GtagCommand.GET */) {
373
+ measurementId = args[0], fieldName = args[1], callback = args[2];
374
+ gtagCore("get" /* GtagCommand.GET */, measurementId, fieldName, callback);
375
+ }
376
+ else if (command === "set" /* GtagCommand.SET */) {
377
+ customParams = args[0];
285
378
  // If SET, second arg must be params.
286
- gtagCore("set" /* GtagCommand.SET */, idOrNameOrParams);
379
+ gtagCore("set" /* GtagCommand.SET */, customParams);
380
+ }
381
+ else {
382
+ gtagCore.apply(void 0, __spreadArray([command], args, false));
287
383
  }
288
384
  _a.label = 5;
289
385
  case 5: return [3 /*break*/, 7];
@@ -344,51 +440,6 @@ function findGtagScriptOnPage(dataLayerName) {
344
440
  return null;
345
441
  }
346
442
 
347
- /**
348
- * @license
349
- * Copyright 2019 Google LLC
350
- *
351
- * Licensed under the Apache License, Version 2.0 (the "License");
352
- * you may not use this file except in compliance with the License.
353
- * You may obtain a copy of the License at
354
- *
355
- * http://www.apache.org/licenses/LICENSE-2.0
356
- *
357
- * Unless required by applicable law or agreed to in writing, software
358
- * distributed under the License is distributed on an "AS IS" BASIS,
359
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
360
- * See the License for the specific language governing permissions and
361
- * limitations under the License.
362
- */
363
- var _a;
364
- var ERRORS = (_a = {},
365
- _a["already-exists" /* AnalyticsError.ALREADY_EXISTS */] = 'A Firebase Analytics instance with the appId {$id} ' +
366
- ' already exists. ' +
367
- 'Only one Firebase Analytics instance can be created for each appId.',
368
- _a["already-initialized" /* AnalyticsError.ALREADY_INITIALIZED */] = 'initializeAnalytics() cannot be called again with different options than those ' +
369
- 'it was initially called with. It can be called again with the same options to ' +
370
- 'return the existing instance, or getAnalytics() can be used ' +
371
- 'to get a reference to the already-intialized instance.',
372
- _a["already-initialized-settings" /* AnalyticsError.ALREADY_INITIALIZED_SETTINGS */] = 'Firebase Analytics has already been initialized.' +
373
- 'settings() must be called before initializing any Analytics instance' +
374
- 'or it will have no effect.',
375
- _a["interop-component-reg-failed" /* AnalyticsError.INTEROP_COMPONENT_REG_FAILED */] = 'Firebase Analytics Interop Component failed to instantiate: {$reason}',
376
- _a["invalid-analytics-context" /* AnalyticsError.INVALID_ANALYTICS_CONTEXT */] = 'Firebase Analytics is not supported in this environment. ' +
377
- 'Wrap initialization of analytics in analytics.isSupported() ' +
378
- 'to prevent initialization in unsupported environments. Details: {$errorInfo}',
379
- _a["indexeddb-unavailable" /* AnalyticsError.INDEXEDDB_UNAVAILABLE */] = 'IndexedDB unavailable or restricted in this environment. ' +
380
- 'Wrap initialization of analytics in analytics.isSupported() ' +
381
- 'to prevent initialization in unsupported environments. Details: {$errorInfo}',
382
- _a["fetch-throttle" /* AnalyticsError.FETCH_THROTTLE */] = 'The config fetch request timed out while in an exponential backoff state.' +
383
- ' Unix timestamp in milliseconds when fetch request throttling ends: {$throttleEndTimeMillis}.',
384
- _a["config-fetch-failed" /* AnalyticsError.CONFIG_FETCH_FAILED */] = 'Dynamic config fetch failed: [{$httpStatus}] {$responseMessage}',
385
- _a["no-api-key" /* AnalyticsError.NO_API_KEY */] = 'The "apiKey" field is empty in the local Firebase config. Firebase Analytics requires this field to' +
386
- 'contain a valid API key.',
387
- _a["no-app-id" /* AnalyticsError.NO_APP_ID */] = 'The "appId" field is empty in the local Firebase config. Firebase Analytics requires this field to' +
388
- 'contain a valid app ID.',
389
- _a);
390
- var ERROR_FACTORY = new ErrorFactory('analytics', 'Analytics', ERRORS);
391
-
392
443
  /**
393
444
  * @license
394
445
  * Copyright 2020 Google LLC
@@ -807,6 +858,32 @@ function setUserProperties$1(gtagFunction, initializationPromise, properties, op
807
858
  });
808
859
  });
809
860
  }
861
+ /**
862
+ * Retrieves a unique Google Analytics identifier for the web client.
863
+ * See {@link https://developers.google.com/analytics/devguides/collection/ga4/reference/config#client_id | client_id}.
864
+ *
865
+ * @param gtagFunction Wrapped gtag function that waits for fid to be set before sending an event
866
+ */
867
+ function internalGetGoogleAnalyticsClientId(gtagFunction, initializationPromise) {
868
+ return __awaiter(this, void 0, void 0, function () {
869
+ var measurementId;
870
+ return __generator(this, function (_a) {
871
+ switch (_a.label) {
872
+ case 0: return [4 /*yield*/, initializationPromise];
873
+ case 1:
874
+ measurementId = _a.sent();
875
+ return [2 /*return*/, new Promise(function (resolve, reject) {
876
+ gtagFunction("get" /* GtagCommand.GET */, measurementId, 'client_id', function (clientId) {
877
+ if (!clientId) {
878
+ reject(ERROR_FACTORY.create("no-client-id" /* AnalyticsError.NO_CLIENT_ID */));
879
+ }
880
+ resolve(clientId);
881
+ });
882
+ })];
883
+ }
884
+ });
885
+ });
886
+ }
810
887
  /**
811
888
  * Set whether collection is enabled for this ID.
812
889
  *
@@ -1237,6 +1314,22 @@ function setCurrentScreen(analyticsInstance, screenName, options) {
1237
1314
  analyticsInstance = getModularInstance(analyticsInstance);
1238
1315
  setCurrentScreen$1(wrappedGtagFunction, initializationPromisesMap[analyticsInstance.app.options.appId], screenName, options).catch(function (e) { return logger.error(e); });
1239
1316
  }
1317
+ /**
1318
+ * Retrieves a unique Google Analytics identifier for the web client.
1319
+ * See {@link https://developers.google.com/analytics/devguides/collection/ga4/reference/config#client_id | client_id}.
1320
+ *
1321
+ * @public
1322
+ *
1323
+ * @param app - The {@link @firebase/app#FirebaseApp} to use.
1324
+ */
1325
+ function getGoogleAnalyticsClientId(analyticsInstance) {
1326
+ return __awaiter(this, void 0, void 0, function () {
1327
+ return __generator(this, function (_a) {
1328
+ analyticsInstance = getModularInstance(analyticsInstance);
1329
+ return [2 /*return*/, internalGetGoogleAnalyticsClientId(wrappedGtagFunction, initializationPromisesMap[analyticsInstance.app.options.appId])];
1330
+ });
1331
+ });
1332
+ }
1240
1333
  /**
1241
1334
  * Use gtag `config` command to set `user_id`.
1242
1335
  *
@@ -1322,7 +1415,7 @@ function setConsent(consentSettings) {
1322
1415
  }
1323
1416
 
1324
1417
  var name = "@firebase/analytics";
1325
- var version = "0.9.4";
1418
+ var version = "0.9.5-canary.0832dcac2";
1326
1419
 
1327
1420
  /**
1328
1421
  * Firebase Analytics
@@ -1359,5 +1452,5 @@ function registerAnalytics() {
1359
1452
  }
1360
1453
  registerAnalytics();
1361
1454
 
1362
- export { getAnalytics, initializeAnalytics, isSupported, logEvent, setAnalyticsCollectionEnabled, setConsent, setCurrentScreen, setDefaultEventParameters, setUserId, setUserProperties, settings };
1455
+ export { getAnalytics, getGoogleAnalyticsClientId, initializeAnalytics, isSupported, logEvent, setAnalyticsCollectionEnabled, setConsent, setCurrentScreen, setDefaultEventParameters, setUserId, setUserProperties, settings };
1363
1456
  //# sourceMappingURL=index.esm.js.map