123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176 |
- import { BackgroundSyncPlugin } from 'workbox-background-sync/BackgroundSyncPlugin.js';
- import { cacheNames } from 'workbox-core/_private/cacheNames.js';
- import { getFriendlyURL } from 'workbox-core/_private/getFriendlyURL.js';
- import { logger } from 'workbox-core/_private/logger.js';
- import { Route } from 'workbox-routing/Route.js';
- import { Router } from 'workbox-routing/Router.js';
- import { NetworkFirst } from 'workbox-strategies/NetworkFirst.js';
- import { NetworkOnly } from 'workbox-strategies/NetworkOnly.js';
- import { 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';
- import './_version.js';
- const createOnSyncCallback = (config) => {
- return async ({ queue }) => {
- let entry;
- while ((entry = await queue.shiftRequest())) {
- const { request, timestamp } = entry;
- const url = new URL(request.url);
- try {
-
-
- const params = request.method === 'POST'
- ? new URLSearchParams(await request.clone().text())
- : url.searchParams;
-
-
- const originalHitTime = timestamp - (Number(params.get('qt')) || 0);
- const queueTime = Date.now() - originalHitTime;
-
- params.set('qt', String(queueTime));
-
- if (config.parameterOverrides) {
- for (const param of Object.keys(config.parameterOverrides)) {
- const value = config.parameterOverrides[param];
- params.set(param, value);
- }
- }
-
- if (typeof config.hitFilter === 'function') {
- config.hitFilter.call(null, params);
- }
-
-
- await fetch(new Request(url.origin + url.pathname, {
- body: params.toString(),
- method: 'POST',
- mode: 'cors',
- credentials: 'omit',
- headers: { 'Content-Type': 'text/plain' },
- }));
- if (process.env.NODE_ENV !== 'production') {
- logger.log(`Request for '${getFriendlyURL(url.href)}' ` + `has been replayed`);
- }
- }
- catch (err) {
- await queue.unshiftRequest(entry);
- if (process.env.NODE_ENV !== 'production') {
- logger.log(`Request for '${getFriendlyURL(url.href)}' ` +
- `failed to replay, putting it back in the queue.`);
- }
- throw err;
- }
- }
- if (process.env.NODE_ENV !== 'production') {
- logger.log(`All Google Analytics request successfully replayed; ` +
- `the queue is now empty!`);
- }
- };
- };
- const createCollectRoutes = (bgSyncPlugin) => {
- const match = ({ url }) => url.hostname === GOOGLE_ANALYTICS_HOST &&
- COLLECT_PATHS_REGEX.test(url.pathname);
- const handler = new NetworkOnly({
- plugins: [bgSyncPlugin],
- });
- return [new Route(match, handler, 'GET'), new Route(match, handler, 'POST')];
- };
- const createAnalyticsJsRoute = (cacheName) => {
- const match = ({ url }) => url.hostname === GOOGLE_ANALYTICS_HOST &&
- url.pathname === ANALYTICS_JS_PATH;
- const handler = new NetworkFirst({ cacheName });
- return new Route(match, handler, 'GET');
- };
- const createGtagJsRoute = (cacheName) => {
- const match = ({ url }) => url.hostname === GTM_HOST && url.pathname === GTAG_JS_PATH;
- const handler = new NetworkFirst({ cacheName });
- return new Route(match, handler, 'GET');
- };
- const createGtmJsRoute = (cacheName) => {
- const match = ({ url }) => url.hostname === GTM_HOST && url.pathname === GTM_JS_PATH;
- const handler = new NetworkFirst({ cacheName });
- return new Route(match, handler, 'GET');
- };
- const initialize = (options = {}) => {
- const cacheName = cacheNames.getGoogleAnalyticsName(options.cacheName);
- const bgSyncPlugin = new BackgroundSyncPlugin(QUEUE_NAME, {
- maxRetentionTime: MAX_RETENTION_TIME,
- onSync: createOnSyncCallback(options),
- });
- const routes = [
- createGtmJsRoute(cacheName),
- createAnalyticsJsRoute(cacheName),
- createGtagJsRoute(cacheName),
- ...createCollectRoutes(bgSyncPlugin),
- ];
- const router = new Router();
- for (const route of routes) {
- router.registerRoute(route);
- }
- router.addFetchListener();
- };
- export { initialize };
|