workbox-offline-ga.prod.js.map 10.9 KB
{"version":3,"file":"workbox-offline-ga.prod.js","sources":["../_version.js","../utils/constants.js","../initialize.js"],"sourcesContent":["\"use strict\";\n// @ts-ignore\ntry {\n    self['workbox:google-analytics:5.1.4'] && _();\n}\ncatch (e) { }\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*/\nimport '../_version.js';\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// 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*/\nimport { BackgroundSyncPlugin } from 'workbox-background-sync/BackgroundSyncPlugin.js';\nimport { cacheNames } from 'workbox-core/_private/cacheNames.js';\nimport { getFriendlyURL } from 'workbox-core/_private/getFriendlyURL.js';\nimport { logger } from 'workbox-core/_private/logger.js';\nimport { Route } from 'workbox-routing/Route.js';\nimport { Router } from 'workbox-routing/Router.js';\nimport { NetworkFirst } from 'workbox-strategies/NetworkFirst.js';\nimport { NetworkOnly } from 'workbox-strategies/NetworkOnly.js';\nimport { QUEUE_NAME, MAX_RETENTION_TIME, GOOGLE_ANALYTICS_HOST, GTM_HOST, ANALYTICS_JS_PATH, GTAG_JS_PATH, GTM_JS_PATH, COLLECT_PATHS_REGEX, } from './utils/constants.js';\nimport './_version.js';\n/**\n * Creates the requestWillDequeue callback to be used with the background\n * sync 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 {@link module:workbox-google-analytics.initialize}.\n * @return {Function} The requestWillDequeue 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            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                // 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                // Set the qt param prior to applying hitFilter or parameterOverrides.\n                params.set('qt', String(queueTime));\n                // Apply `parameterOverrides`, 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                // Apply `hitFilter`, if set.\n                if (typeof config.hitFilter === 'function') {\n                    config.hitFilter.call(null, params);\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                if (process.env.NODE_ENV !== 'production') {\n                    logger.log(`Request for '${getFriendlyURL(url.href)}'` +\n                        `has been replayed`);\n                }\n            }\n            catch (err) {\n                await queue.unshiftRequest(entry);\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 * Creates GET and POST routes to catch failed Measurement Protocol hits.\n *\n * @param {BackgroundSyncPlugin} bgSyncPlugin\n * @return {Array<Route>} The created routes.\n *\n * @private\n */\nconst createCollectRoutes = (bgSyncPlugin) => {\n    const match = ({ url }) => url.hostname === GOOGLE_ANALYTICS_HOST &&\n        COLLECT_PATHS_REGEX.test(url.pathname);\n    const handler = new NetworkOnly({\n        plugins: [bgSyncPlugin],\n    });\n    return [\n        new Route(match, handler, 'GET'),\n        new 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 */\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    return new Route(match, handler, 'GET');\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    return new Route(match, handler, 'GET');\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    return new Route(match, handler, 'GET');\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 module:workbox-google-analytics\n */\nconst initialize = (options = {}) => {\n    const cacheName = cacheNames.getGoogleAnalyticsName(options.cacheName);\n    const bgSyncPlugin = new BackgroundSyncPlugin(QUEUE_NAME, {\n        maxRetentionTime: MAX_RETENTION_TIME,\n        onSync: createOnSyncCallback(options),\n    });\n    const routes = [\n        createGtmJsRoute(cacheName),\n        createAnalyticsJsRoute(cacheName),\n        createGtagJsRoute(cacheName),\n        ...createCollectRoutes(bgSyncPlugin),\n    ];\n    const router = new Router();\n    for (const route of routes) {\n        router.registerRoute(route);\n    }\n    router.addFetchListener();\n};\nexport { initialize, };\n"],"names":["self","_","e","COLLECT_PATHS_REGEX","createCollectRoutes","bgSyncPlugin","match","url","hostname","test","pathname","handler","NetworkOnly","plugins","Route","createAnalyticsJsRoute","cacheName","NetworkFirst","createGtagJsRoute","createGtmJsRoute","options","cacheNames","getGoogleAnalyticsName","BackgroundSyncPlugin","maxRetentionTime","onSync","config","async","queue","entry","shiftRequest","request","timestamp","URL","params","method","URLSearchParams","clone","text","searchParams","originalHitTime","Number","get","queueTime","Date","now","set","String","parameterOverrides","param","Object","keys","value","hitFilter","call","fetch","Request","origin","body","toString","mode","credentials","headers","err","unshiftRequest","routes","router","Router","route","registerRoute","addFetchListener"],"mappings":"oGAEA,IACIA,KAAK,mCAAqCC,IAE9C,MAAOC,ICGA,MAYMC,EAAsB,qBC0E7BC,EAAuBC,UACnBC,EAAQ,EAAGC,IAAAA,KDrFgB,6BCqFNA,EAAIC,UAC3BL,EAAoBM,KAAKF,EAAIG,UAC3BC,EAAU,IAAIC,cAAY,CAC5BC,QAAS,CAACR,WAEP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