UNPKG

10.3 kBSource Map (JSON)View Raw
1{"version":3,"names":[],"mappings":"","sources":["packages/workbox-google-analytics/browser.mjs"],"sourcesContent":["this.workbox = this.workbox || {};\nthis.workbox.googleAnalytics = (function (exports,Plugin_mjs,cacheNames_mjs,Route_mjs,Router_mjs,NetworkFirst_mjs,NetworkOnly_mjs) {\n 'use strict';\n\n try {\n self.workbox.v['workbox:google-analytics:3.5.0'] = 1;\n } catch (e) {} // eslint-disable-line\n\n /*\n Copyright 2017 Google Inc. All Rights Reserved.\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\n const QUEUE_NAME = 'workbox-google-analytics';\n const MAX_RETENTION_TIME = 60 * 48; // Two days in minutes\n const GOOGLE_ANALYTICS_HOST = 'www.google-analytics.com';\n const GTM_HOST = 'www.googletagmanager.com';\n const ANALYTICS_JS_PATH = '/analytics.js';\n const GTAG_JS_PATH = '/gtag/js';\n\n // This RegExp matches all known Measurement Protocol single-hit collect\n // endpoints. Most of the time the default path (/collect) is used, but\n // occasionally an experimental endpoint is used when testing new features,\n // (e.g. /r/collect or /j/collect)\n const COLLECT_PATHS_REGEX = /^\\/(\\w+\\/)?collect/;\n\n /*\n Copyright 2017 Google Inc. All Rights Reserved.\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\n /**\n * Promisifies the FileReader API to await a text response from a Blob.\n *\n * @param {Blob} blob\n * @return {Promise<string>}\n *\n * @private\n */\n const getTextFromBlob = (() => {\n var _ref = babelHelpers.asyncToGenerator(function* (blob) {\n // This usage of `return await new Promise...` is intentional to work around\n // a bug in the transpiled/minified output.\n // See https://github.com/GoogleChrome/workbox/issues/1186\n return yield new Promise(function (resolve, reject) {\n const reader = new FileReader();\n reader.onloadend = function () {\n return resolve(reader.result);\n };\n reader.onerror = function () {\n return reject(reader.error);\n };\n reader.readAsText(blob);\n });\n });\n\n return function getTextFromBlob(_x) {\n return _ref.apply(this, arguments);\n };\n })();\n\n /**\n * Creates the requestWillDequeue callback to be used with the background\n * sync queue plugin. The callback takes the failed request and adds the\n * `qt` param based on the current time, as well as applies any other\n * user-defined hit modifications.\n *\n * @param {Object} config See workbox.googleAnalytics.initialize.\n * @return {Function} The requestWillDequeu callback function.\n *\n * @private\n */\n const createRequestWillReplayCallback = config => {\n return (() => {\n var _ref2 = babelHelpers.asyncToGenerator(function* (storableRequest) {\n let { url, requestInit, timestamp } = storableRequest;\n url = new URL(url);\n\n // Measurement protocol requests can set their payload parameters in either\n // the URL query string (for GET requests) or the POST body.\n let params;\n if (requestInit.body) {\n const payload = requestInit.body instanceof Blob ? yield getTextFromBlob(requestInit.body) : requestInit.body;\n\n params = new URLSearchParams(payload);\n } else {\n params = url.searchParams;\n }\n\n // Calculate the qt param, accounting for the fact that an existing\n // qt param may be present and should be updated rather than replaced.\n const originalHitTime = timestamp - (Number(params.get('qt')) || 0);\n const queueTime = Date.now() - originalHitTime;\n\n // Set the qt param prior to applying the hitFilter or parameterOverrides.\n params.set('qt', queueTime);\n\n if (config.parameterOverrides) {\n for (const param of Object.keys(config.parameterOverrides)) {\n const value = config.parameterOverrides[param];\n params.set(param, value);\n }\n }\n\n if (typeof config.hitFilter === 'function') {\n config.hitFilter.call(null, params);\n }\n\n requestInit.body = params.toString();\n requestInit.method = 'POST';\n requestInit.mode = 'cors';\n requestInit.credentials = 'omit';\n requestInit.headers = { 'Content-Type': 'text/plain' };\n\n // Ignore URL search params as they're now in the post body.\n storableRequest.url = `${url.origin}${url.pathname}`;\n });\n\n return function (_x2) {\n return _ref2.apply(this, arguments);\n };\n })();\n };\n\n /**\n * Creates GET and POST routes to catch failed Measurement Protocol hits.\n *\n * @param {Plugin} queuePlugin\n * @return {Array<Route>} The created routes.\n *\n * @private\n */\n const createCollectRoutes = queuePlugin => {\n const match = ({ url }) => url.hostname === GOOGLE_ANALYTICS_HOST && COLLECT_PATHS_REGEX.test(url.pathname);\n\n const handler = new NetworkOnly_mjs.NetworkOnly({\n plugins: [queuePlugin]\n });\n\n return [new Route_mjs.Route(match, handler, 'GET'), new Route_mjs.Route(match, handler, 'POST')];\n };\n\n /**\n * Creates a route with a network first strategy for the analytics.js script.\n *\n * @param {string} cacheName\n * @return {Route} The created route.\n *\n * @private\n */\n const createAnalyticsJsRoute = cacheName => {\n const match = ({ url }) => url.hostname === GOOGLE_ANALYTICS_HOST && url.pathname === ANALYTICS_JS_PATH;\n const handler = new NetworkFirst_mjs.NetworkFirst({ cacheName });\n\n return new Route_mjs.Route(match, handler, 'GET');\n };\n\n /**\n * Creates a route with a network first strategy for the gtag.js script.\n *\n * @param {string} cacheName\n * @return {Route} The created route.\n *\n * @private\n */\n const createGtagJsRoute = cacheName => {\n const match = ({ url }) => url.hostname === GTM_HOST && url.pathname === GTAG_JS_PATH;\n const handler = new NetworkFirst_mjs.NetworkFirst({ cacheName });\n\n return new Route_mjs.Route(match, handler, 'GET');\n };\n\n /**\n * @param {Object=} [options]\n * @param {Object} [options.cacheName] The cache name to store and retrieve\n * analytics.js. Defaults to the cache names provided by `workbox-core`.\n * @param {Object} [options.parameterOverrides]\n * [Measurement Protocol parameters](https://developers.google.com/analytics/devguides/collection/protocol/v1/parameters),\n * expressed as key/value pairs, to be added to replayed Google Analytics\n * requests. This can be used to, e.g., set a custom dimension indicating\n * that the request was replayed.\n * @param {Function} [options.hitFilter] A function that allows you to modify\n * the hit parameters prior to replaying\n * the hit. The function is invoked with the original hit's URLSearchParams\n * object as its only argument.\n *\n * @memberof workbox.googleAnalytics\n */\n const initialize = (options = {}) => {\n const cacheName = cacheNames_mjs.cacheNames.getGoogleAnalyticsName(options.cacheName);\n\n const queuePlugin = new Plugin_mjs.Plugin(QUEUE_NAME, {\n maxRetentionTime: MAX_RETENTION_TIME,\n callbacks: {\n requestWillReplay: createRequestWillReplayCallback(options)\n }\n });\n\n const routes = [createAnalyticsJsRoute(cacheName), createGtagJsRoute(cacheName), ...createCollectRoutes(queuePlugin)];\n\n const router = new Router_mjs.Router();\n for (const route of routes) {\n router.registerRoute(route);\n }\n\n self.addEventListener('fetch', evt => {\n const responsePromise = router.handleRequest(evt);\n if (responsePromise) {\n evt.respondWith(responsePromise);\n }\n });\n };\n\n /*\n Copyright 2017 Google Inc. All Rights Reserved.\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\n exports.initialize = initialize;\n\n return exports;\n\n}({},workbox.backgroundSync,workbox.core._private,workbox.routing,workbox.routing,workbox.strategies,workbox.strategies));\n"],"file":"workbox-google-analytics.dev.js"}
\No newline at end of file