blob: 68d2fb8bd183bc16af5620619bd504b75b17966e [file] [log] [blame]
{"version":3,"file":"workbox-offline-ga.prod.js","sources":["../_version.mjs","../utils/constants.mjs","../initialize.mjs"],"sourcesContent":["try{self['workbox:google-analytics:4.3.1']&&_()}catch(e){}// eslint-disable-line","/*\n Copyright 2018 Google LLC\n\n Use of this source code is governed by an MIT-style\n license that can be found in the LICENSE file or at\n https://opensource.org/licenses/MIT.\n*/\n\nimport '../_version.mjs';\n\nexport const QUEUE_NAME = 'workbox-google-analytics';\nexport const MAX_RETENTION_TIME = 60 * 48; // Two days in minutes\nexport const GOOGLE_ANALYTICS_HOST = 'www.google-analytics.com';\nexport const GTM_HOST = 'www.googletagmanager.com';\nexport const ANALYTICS_JS_PATH = '/analytics.js';\nexport const GTAG_JS_PATH = '/gtag/js';\nexport const GTM_JS_PATH = '/gtm.js';\nexport const COLLECT_DEFAULT_PATH = '/collect';\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)\nexport const COLLECT_PATHS_REGEX = /^\\/(\\w+\\/)?collect/;\n","/*\n Copyright 2018 Google LLC\n\n Use of this source code is governed by an MIT-style\n license that can be found in the LICENSE file or at\n https://opensource.org/licenses/MIT.\n*/\n\nimport {Plugin} from 'workbox-background-sync/Plugin.mjs';\nimport {cacheNames} from 'workbox-core/_private/cacheNames.mjs';\nimport {getFriendlyURL} from 'workbox-core/_private/getFriendlyURL.mjs';\nimport {logger} from 'workbox-core/_private/logger.mjs';\nimport {Route} from 'workbox-routing/Route.mjs';\nimport {Router} from 'workbox-routing/Router.mjs';\nimport {NetworkFirst} from 'workbox-strategies/NetworkFirst.mjs';\nimport {NetworkOnly} from 'workbox-strategies/NetworkOnly.mjs';\nimport {\n QUEUE_NAME,\n MAX_RETENTION_TIME,\n GOOGLE_ANALYTICS_HOST,\n GTM_HOST,\n ANALYTICS_JS_PATH,\n GTAG_JS_PATH,\n GTM_JS_PATH,\n COLLECT_PATHS_REGEX,\n} from './utils/constants.mjs';\nimport './_version.mjs';\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 */\nconst createOnSyncCallback = (config) => {\n return async ({queue}) => {\n let entry;\n while (entry = await queue.shiftRequest()) {\n const {request, timestamp} = entry;\n const url = new URL(request.url);\n\n try {\n // Measurement protocol requests can set their payload parameters in\n // either the URL query string (for GET requests) or the POST body.\n const params = request.method === 'POST' ?\n new URLSearchParams(await request.clone().text()) :\n url.searchParams;\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 hitFilter or parameterOverrides.\n params.set('qt', queueTime);\n\n // Apply `paramterOverrideds`, if set.\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 // Apply `hitFilter`, if set.\n if (typeof config.hitFilter === 'function') {\n config.hitFilter.call(null, params);\n }\n\n // Retry the fetch. Ignore URL search params from the URL as they're\n // now in the post body.\n await fetch(new Request(url.origin + url.pathname, {\n body: params.toString(),\n method: 'POST',\n mode: 'cors',\n credentials: 'omit',\n headers: {'Content-Type': 'text/plain'},\n }));\n\n\n if (process.env.NODE_ENV !== 'production') {\n logger.log(`Request for '${getFriendlyURL(url.href)}'` +\n `has been replayed`);\n }\n } catch (err) {\n await queue.unshiftRequest(entry);\n\n if (process.env.NODE_ENV !== 'production') {\n logger.log(`Request for '${getFriendlyURL(url.href)}'` +\n `failed to replay, putting it back in the queue.`);\n }\n throw err;\n }\n }\n if (process.env.NODE_ENV !== 'production') {\n logger.log(`All Google Analytics request successfully replayed; ` +\n `the queue is now empty!`);\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 */\nconst createCollectRoutes = (queuePlugin) => {\n const match = ({url}) => url.hostname === GOOGLE_ANALYTICS_HOST &&\n COLLECT_PATHS_REGEX.test(url.pathname);\n\n const handler = new NetworkOnly({\n plugins: [queuePlugin],\n });\n\n return [\n new Route(match, handler, 'GET'),\n new Route(match, handler, 'POST'),\n ];\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 */\nconst createAnalyticsJsRoute = (cacheName) => {\n const match = ({url}) => url.hostname === GOOGLE_ANALYTICS_HOST &&\n url.pathname === ANALYTICS_JS_PATH;\n const handler = new NetworkFirst({cacheName});\n\n return new 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 */\nconst createGtagJsRoute = (cacheName) => {\n const match = ({url}) => url.hostname === GTM_HOST &&\n url.pathname === GTAG_JS_PATH;\n const handler = new NetworkFirst({cacheName});\n\n return new Route(match, handler, 'GET');\n};\n\n/**\n * Creates a route with a network first strategy for the gtm.js script.\n *\n * @param {string} cacheName\n * @return {Route} The created route.\n *\n * @private\n */\nconst createGtmJsRoute = (cacheName) => {\n const match = ({url}) => url.hostname === GTM_HOST &&\n url.pathname === GTM_JS_PATH;\n const handler = new NetworkFirst({cacheName});\n\n return new 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 */\nconst initialize = (options = {}) => {\n const cacheName = cacheNames.getGoogleAnalyticsName(options.cacheName);\n\n const queuePlugin = new Plugin(QUEUE_NAME, {\n maxRetentionTime: MAX_RETENTION_TIME,\n onSync: createOnSyncCallback(options),\n });\n\n const routes = [\n createGtmJsRoute(cacheName),\n createAnalyticsJsRoute(cacheName),\n createGtagJsRoute(cacheName),\n ...createCollectRoutes(queuePlugin),\n ];\n\n const router = new Router();\n for (const route of routes) {\n router.registerRoute(route);\n }\n\n router.addFetchListener();\n};\n\nexport {\n initialize,\n};\n"],"names":["self","_","e","COLLECT_PATHS_REGEX","createOnSyncCallback","config","async","queue","entry","shiftRequest","request","timestamp","url","URL","params","method","URLSearchParams","clone","text","searchParams","originalHitTime","Number","get","queueTime","Date","now","set","parameterOverrides","param","Object","keys","value","hitFilter","call","fetch","Request","origin","pathname","body","toString","mode","credentials","headers","err","unshiftRequest","createCollectRoutes","queuePlugin","match","hostname","test","handler","NetworkOnly","plugins","Route","createAnalyticsJsRoute","cacheName","NetworkFirst","createGtagJsRoute","createGtmJsRoute","options","cacheNames","getGoogleAnalyticsName","Plugin","maxRetentionTime","onSync","routes","router","Router","route","registerRoute","addFetchListener"],"mappings":"gGAAA,IAAIA,KAAK,mCAAmCC,IAAI,MAAMC,ICU/C,MAaMC,EAAsB,qBCgB7BC,EAAwBC,GACrBC,OAAQC,MAAAA,UACTC,OACGA,QAAcD,EAAME,gBAAgB,OACnCC,QAACA,EAADC,UAAUA,GAAaH,EACvBI,EAAM,IAAIC,IAAIH,EAAQE,eAKpBE,EAA4B,SAAnBJ,EAAQK,OACnB,IAAIC,sBAAsBN,EAAQO,QAAQC,QAC1CN,EAAIO,aAIFC,EAAkBT,GAAaU,OAAOP,EA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