@serwist/google-analytics 9.0.0-preview.17 → 9.0.0-preview.19

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/dist/index.d.ts CHANGED
@@ -1,5 +1,3 @@
1
- import type { GoogleAnalyticsInitializeOptions } from "./initialize.js";
2
- import { initialize } from "./initialize.js";
3
- export { initialize };
4
- export type { GoogleAnalyticsInitializeOptions };
1
+ export { initializeGoogleAnalytics as initialize } from "@serwist/sw/plugins";
2
+ export type { GoogleAnalyticsInitializeOptions } from "@serwist/sw/plugins";
5
3
  //# sourceMappingURL=index.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAQA,OAAO,KAAK,EAAE,gCAAgC,EAAE,MAAM,iBAAiB,CAAC;AACxE,OAAO,EAAE,UAAU,EAAE,MAAM,iBAAiB,CAAC;AAE7C,OAAO,EAAE,UAAU,EAAE,CAAC;AACtB,YAAY,EAAE,gCAAgC,EAAE,CAAC"}
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,yBAAyB,IAAI,UAAU,EAAE,MAAM,qBAAqB,CAAC;AAC9E,YAAY,EAAE,gCAAgC,EAAE,MAAM,qBAAqB,CAAC"}
package/dist/index.js CHANGED
@@ -1,5 +1 @@
1
- export { initialize } from './initialize.js';
2
- import '@serwist/background-sync';
3
- import '@serwist/core/internal';
4
- import '@serwist/routing';
5
- import '@serwist/strategies';
1
+ export { initializeGoogleAnalytics as initialize } from '@serwist/sw/plugins';
package/package.json CHANGED
@@ -1,8 +1,8 @@
1
1
  {
2
2
  "name": "@serwist/google-analytics",
3
- "version": "9.0.0-preview.17",
3
+ "version": "9.0.0-preview.19",
4
4
  "type": "module",
5
- "description": "Queues failed requests and uses the Background Sync API to replay them when the network is available",
5
+ "description": "Queues failed requests and uses the Background Sync API to replay them when the network is available.",
6
6
  "files": [
7
7
  "src",
8
8
  "dist"
@@ -18,15 +18,15 @@
18
18
  ],
19
19
  "author": "Google's Web DevRel Team, Serwist's Team",
20
20
  "license": "MIT",
21
- "repository": "serwist/serwist",
22
- "bugs": "https://github.com/serwist/serwist/issues",
21
+ "repository": "https://gitlab.com/serwist/serwist",
22
+ "bugs": "https://gitlab.com/serwist/serwist/issues",
23
23
  "homepage": "https://serwist.pages.dev",
24
24
  "main": "./dist/index.js",
25
25
  "types": "./dist/index.d.ts",
26
26
  "typesVersions": {
27
27
  "*": {
28
28
  "initialize": [
29
- "./dist/initialize.d.ts"
29
+ "./dist/index.d.ts"
30
30
  ]
31
31
  }
32
32
  },
@@ -36,21 +36,18 @@
36
36
  "default": "./dist/index.js"
37
37
  },
38
38
  "./initialize": {
39
- "types": "./dist/initialize.d.ts",
40
- "default": "./dist/initialize.js"
39
+ "types": "./dist/index.d.ts",
40
+ "default": "./dist/index.js"
41
41
  },
42
42
  "./package.json": "./package.json"
43
43
  },
44
44
  "dependencies": {
45
- "@serwist/background-sync": "9.0.0-preview.17",
46
- "@serwist/core": "9.0.0-preview.17",
47
- "@serwist/routing": "9.0.0-preview.17",
48
- "@serwist/strategies": "9.0.0-preview.17"
45
+ "@serwist/sw": "9.0.0-preview.19"
49
46
  },
50
47
  "devDependencies": {
51
48
  "rollup": "4.13.0",
52
49
  "typescript": "5.5.0-dev.20240323",
53
- "@serwist/constants": "9.0.0-preview.17"
50
+ "@serwist/constants": "9.0.0-preview.19"
54
51
  },
55
52
  "peerDependencies": {
56
53
  "typescript": ">=5.0.0"
@@ -62,7 +59,6 @@
62
59
  },
63
60
  "scripts": {
64
61
  "build": "rimraf dist && cross-env NODE_ENV=production rollup --config rollup.config.js",
65
- "dev": "rollup --config rollup.config.js --watch",
66
62
  "lint": "biome lint ./src",
67
63
  "typecheck": "tsc"
68
64
  }
package/src/index.ts CHANGED
@@ -1,13 +1,2 @@
1
- /*
2
- Copyright 2018 Google LLC
3
-
4
- Use of this source code is governed by an MIT-style
5
- license that can be found in the LICENSE file or at
6
- https://opensource.org/licenses/MIT.
7
- */
8
-
9
- import type { GoogleAnalyticsInitializeOptions } from "./initialize.js";
10
- import { initialize } from "./initialize.js";
11
-
12
- export { initialize };
13
- export type { GoogleAnalyticsInitializeOptions };
1
+ export { initializeGoogleAnalytics as initialize } from "@serwist/sw/plugins";
2
+ export type { GoogleAnalyticsInitializeOptions } from "@serwist/sw/plugins";
@@ -1,26 +0,0 @@
1
- export interface GoogleAnalyticsInitializeOptions {
2
- /**
3
- * The cache name to store and retrieve analytics.js. Defaults to the cache names provided by `@serwist/core`.
4
- */
5
- cacheName?: string;
6
- /**
7
- * [Measurement Protocol parameters](https://developers.google.com/analytics/devguides/collection/protocol/v1/parameters),
8
- * expressed as key/value pairs, to be added to replayed Google Analytics
9
- * requests. This can be used to, e.g., set a custom dimension indicating
10
- * that the request was replayed.
11
- */
12
- parameterOverrides?: {
13
- [paramName: string]: string;
14
- };
15
- /**
16
- * A function that allows you to modify the hit parameters prior to replaying
17
- * the hit. The function is invoked with the original hit's URLSearchParams
18
- * object as its only argument.
19
- */
20
- hitFilter?: (params: URLSearchParams) => void;
21
- }
22
- /**
23
- * @param options
24
- */
25
- export declare const initialize: (options?: GoogleAnalyticsInitializeOptions) => void;
26
- //# sourceMappingURL=initialize.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"initialize.d.ts","sourceRoot":"","sources":["../src/initialize.ts"],"names":[],"mappings":"AA0BA,MAAM,WAAW,gCAAgC;IAC/C;;OAEG;IACH,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB;;;;;OAKG;IACH,kBAAkB,CAAC,EAAE;QAAE,CAAC,SAAS,EAAE,MAAM,GAAG,MAAM,CAAA;KAAE,CAAC;IACrD;;;;OAIG;IACH,SAAS,CAAC,EAAE,CAAC,MAAM,EAAE,eAAe,KAAK,IAAI,CAAC;CAC/C;AAyID;;GAEG;AACH,eAAO,MAAM,UAAU,aAAa,gCAAgC,KAAQ,IAa3E,CAAC"}
@@ -1,110 +0,0 @@
1
- import { BackgroundSyncPlugin } from '@serwist/background-sync';
2
- import { privateCacheNames, logger, getFriendlyURL } from '@serwist/core/internal';
3
- import { registerRoute, Route } from '@serwist/routing';
4
- import { NetworkOnly, NetworkFirst } from '@serwist/strategies';
5
-
6
- const QUEUE_NAME = "serwist-google-analytics";
7
- const MAX_RETENTION_TIME = 60 * 48;
8
- const GOOGLE_ANALYTICS_HOST = "www.google-analytics.com";
9
- const GTM_HOST = "www.googletagmanager.com";
10
- const ANALYTICS_JS_PATH = "/analytics.js";
11
- const GTAG_JS_PATH = "/gtag/js";
12
- const GTM_JS_PATH = "/gtm.js";
13
- const COLLECT_PATHS_REGEX = /^\/(\w+\/)?collect/;
14
-
15
- const createOnSyncCallback = (config)=>{
16
- return async ({ queue })=>{
17
- let entry = undefined;
18
- while(entry = await queue.shiftRequest()){
19
- const { request, timestamp } = entry;
20
- const url = new URL(request.url);
21
- try {
22
- const params = request.method === "POST" ? new URLSearchParams(await request.clone().text()) : url.searchParams;
23
- const originalHitTime = timestamp - (Number(params.get("qt")) || 0);
24
- const queueTime = Date.now() - originalHitTime;
25
- params.set("qt", String(queueTime));
26
- if (config.parameterOverrides) {
27
- for (const param of Object.keys(config.parameterOverrides)){
28
- const value = config.parameterOverrides[param];
29
- params.set(param, value);
30
- }
31
- }
32
- if (typeof config.hitFilter === "function") {
33
- config.hitFilter.call(null, params);
34
- }
35
- await fetch(new Request(url.origin + url.pathname, {
36
- body: params.toString(),
37
- method: "POST",
38
- mode: "cors",
39
- credentials: "omit",
40
- headers: {
41
- "Content-Type": "text/plain"
42
- }
43
- }));
44
- if (process.env.NODE_ENV !== "production") {
45
- logger.log(`Request for '${getFriendlyURL(url.href)}' has been replayed`);
46
- }
47
- } catch (err) {
48
- await queue.unshiftRequest(entry);
49
- if (process.env.NODE_ENV !== "production") {
50
- logger.log(`Request for '${getFriendlyURL(url.href)}' failed to replay, putting it back in the queue.`);
51
- }
52
- throw err;
53
- }
54
- }
55
- if (process.env.NODE_ENV !== "production") {
56
- logger.log("All Google Analytics request successfully replayed; " + "the queue is now empty!");
57
- }
58
- };
59
- };
60
- const createCollectRoutes = (bgSyncPlugin)=>{
61
- const match = ({ url })=>url.hostname === GOOGLE_ANALYTICS_HOST && COLLECT_PATHS_REGEX.test(url.pathname);
62
- const handler = new NetworkOnly({
63
- plugins: [
64
- bgSyncPlugin
65
- ]
66
- });
67
- return [
68
- new Route(match, handler, "GET"),
69
- new Route(match, handler, "POST")
70
- ];
71
- };
72
- const createAnalyticsJsRoute = (cacheName)=>{
73
- const match = ({ url })=>url.hostname === GOOGLE_ANALYTICS_HOST && url.pathname === ANALYTICS_JS_PATH;
74
- const handler = new NetworkFirst({
75
- cacheName
76
- });
77
- return new Route(match, handler, "GET");
78
- };
79
- const createGtagJsRoute = (cacheName)=>{
80
- const match = ({ url })=>url.hostname === GTM_HOST && url.pathname === GTAG_JS_PATH;
81
- const handler = new NetworkFirst({
82
- cacheName
83
- });
84
- return new Route(match, handler, "GET");
85
- };
86
- const createGtmJsRoute = (cacheName)=>{
87
- const match = ({ url })=>url.hostname === GTM_HOST && url.pathname === GTM_JS_PATH;
88
- const handler = new NetworkFirst({
89
- cacheName
90
- });
91
- return new Route(match, handler, "GET");
92
- };
93
- const initialize = (options = {})=>{
94
- const cacheName = privateCacheNames.getGoogleAnalyticsName(options.cacheName);
95
- const bgSyncPlugin = new BackgroundSyncPlugin(QUEUE_NAME, {
96
- maxRetentionTime: MAX_RETENTION_TIME,
97
- onSync: createOnSyncCallback(options)
98
- });
99
- const routes = [
100
- createGtmJsRoute(cacheName),
101
- createAnalyticsJsRoute(cacheName),
102
- createGtagJsRoute(cacheName),
103
- ...createCollectRoutes(bgSyncPlugin)
104
- ];
105
- for (const route of routes){
106
- registerRoute(route);
107
- }
108
- };
109
-
110
- export { initialize };
@@ -1,10 +0,0 @@
1
- export declare const QUEUE_NAME = "serwist-google-analytics";
2
- export declare const MAX_RETENTION_TIME: number;
3
- export declare const GOOGLE_ANALYTICS_HOST = "www.google-analytics.com";
4
- export declare const GTM_HOST = "www.googletagmanager.com";
5
- export declare const ANALYTICS_JS_PATH = "/analytics.js";
6
- export declare const GTAG_JS_PATH = "/gtag/js";
7
- export declare const GTM_JS_PATH = "/gtm.js";
8
- export declare const COLLECT_DEFAULT_PATH = "/collect";
9
- export declare const COLLECT_PATHS_REGEX: RegExp;
10
- //# sourceMappingURL=constants.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"constants.d.ts","sourceRoot":"","sources":["../../src/utils/constants.ts"],"names":[],"mappings":"AAQA,eAAO,MAAM,UAAU,6BAA6B,CAAC;AACrD,eAAO,MAAM,kBAAkB,QAAU,CAAC;AAC1C,eAAO,MAAM,qBAAqB,6BAA6B,CAAC;AAChE,eAAO,MAAM,QAAQ,6BAA6B,CAAC;AACnD,eAAO,MAAM,iBAAiB,kBAAkB,CAAC;AACjD,eAAO,MAAM,YAAY,aAAa,CAAC;AACvC,eAAO,MAAM,WAAW,YAAY,CAAC;AACrC,eAAO,MAAM,oBAAoB,aAAa,CAAC;AAM/C,eAAO,MAAM,mBAAmB,QAAuB,CAAC"}
package/src/initialize.ts DELETED
@@ -1,198 +0,0 @@
1
- /*
2
- Copyright 2018 Google LLC
3
-
4
- Use of this source code is governed by an MIT-style
5
- license that can be found in the LICENSE file or at
6
- https://opensource.org/licenses/MIT.
7
- */
8
-
9
- import type { Queue, QueueEntry } from "@serwist/background-sync";
10
- import { BackgroundSyncPlugin } from "@serwist/background-sync";
11
- import type { RouteMatchCallbackOptions } from "@serwist/core";
12
- import { getFriendlyURL, logger, privateCacheNames } from "@serwist/core/internal";
13
- import { Route, registerRoute } from "@serwist/routing";
14
- import { NetworkFirst, NetworkOnly } from "@serwist/strategies";
15
-
16
- import {
17
- ANALYTICS_JS_PATH,
18
- COLLECT_PATHS_REGEX,
19
- GOOGLE_ANALYTICS_HOST,
20
- GTAG_JS_PATH,
21
- GTM_HOST,
22
- GTM_JS_PATH,
23
- MAX_RETENTION_TIME,
24
- QUEUE_NAME,
25
- } from "./utils/constants.js";
26
-
27
- export interface GoogleAnalyticsInitializeOptions {
28
- /**
29
- * The cache name to store and retrieve analytics.js. Defaults to the cache names provided by `@serwist/core`.
30
- */
31
- cacheName?: string;
32
- /**
33
- * [Measurement Protocol parameters](https://developers.google.com/analytics/devguides/collection/protocol/v1/parameters),
34
- * expressed as key/value pairs, to be added to replayed Google Analytics
35
- * requests. This can be used to, e.g., set a custom dimension indicating
36
- * that the request was replayed.
37
- */
38
- parameterOverrides?: { [paramName: string]: string };
39
- /**
40
- * A function that allows you to modify the hit parameters prior to replaying
41
- * the hit. The function is invoked with the original hit's URLSearchParams
42
- * object as its only argument.
43
- */
44
- hitFilter?: (params: URLSearchParams) => void;
45
- }
46
-
47
- /**
48
- * Creates the requestWillDequeue callback to be used with the background
49
- * sync plugin. The callback takes the failed request and adds the
50
- * `qt` param based on the current time, as well as applies any other
51
- * user-defined hit modifications.
52
- *
53
- * @param config
54
- * @returns The requestWillDequeue callback function.
55
- * @private
56
- */
57
- const createOnSyncCallback = (config: GoogleAnalyticsInitializeOptions) => {
58
- return async ({ queue }: { queue: Queue }) => {
59
- let entry: QueueEntry | undefined = undefined;
60
- while ((entry = await queue.shiftRequest())) {
61
- const { request, timestamp } = entry;
62
- const url = new URL(request.url);
63
-
64
- try {
65
- // Measurement protocol requests can set their payload parameters in
66
- // either the URL query string (for GET requests) or the POST body.
67
- const params = request.method === "POST" ? new URLSearchParams(await request.clone().text()) : url.searchParams;
68
-
69
- // Calculate the qt param, accounting for the fact that an existing
70
- // qt param may be present and should be updated rather than replaced.
71
- const originalHitTime = timestamp! - (Number(params.get("qt")) || 0);
72
- const queueTime = Date.now() - originalHitTime;
73
-
74
- // Set the qt param prior to applying hitFilter or parameterOverrides.
75
- params.set("qt", String(queueTime));
76
-
77
- // Apply `parameterOverrides`, if set.
78
- if (config.parameterOverrides) {
79
- for (const param of Object.keys(config.parameterOverrides)) {
80
- const value = config.parameterOverrides[param];
81
- params.set(param, value);
82
- }
83
- }
84
-
85
- // Apply `hitFilter`, if set.
86
- if (typeof config.hitFilter === "function") {
87
- config.hitFilter.call(null, params);
88
- }
89
-
90
- // Retry the fetch. Ignore URL search params from the URL as they're
91
- // now in the post body.
92
- await fetch(
93
- new Request(url.origin + url.pathname, {
94
- body: params.toString(),
95
- method: "POST",
96
- mode: "cors",
97
- credentials: "omit",
98
- headers: { "Content-Type": "text/plain" },
99
- }),
100
- );
101
-
102
- if (process.env.NODE_ENV !== "production") {
103
- logger.log(`Request for '${getFriendlyURL(url.href)}' has been replayed`);
104
- }
105
- } catch (err) {
106
- await queue.unshiftRequest(entry);
107
-
108
- if (process.env.NODE_ENV !== "production") {
109
- logger.log(`Request for '${getFriendlyURL(url.href)}' failed to replay, putting it back in the queue.`);
110
- }
111
- throw err;
112
- }
113
- }
114
- if (process.env.NODE_ENV !== "production") {
115
- logger.log("All Google Analytics request successfully replayed; " + "the queue is now empty!");
116
- }
117
- };
118
- };
119
-
120
- /**
121
- * Creates GET and POST routes to catch failed Measurement Protocol hits.
122
- *
123
- * @param bgSyncPlugin
124
- * @returns The created routes.
125
- * @private
126
- */
127
- const createCollectRoutes = (bgSyncPlugin: BackgroundSyncPlugin) => {
128
- const match = ({ url }: RouteMatchCallbackOptions) => url.hostname === GOOGLE_ANALYTICS_HOST && COLLECT_PATHS_REGEX.test(url.pathname);
129
-
130
- const handler = new NetworkOnly({
131
- plugins: [bgSyncPlugin],
132
- });
133
-
134
- return [new Route(match, handler, "GET"), new Route(match, handler, "POST")];
135
- };
136
-
137
- /**
138
- * Creates a route with a network first strategy for the analytics.js script.
139
- *
140
- * @param cacheName
141
- * @returns The created route.
142
- * @private
143
- */
144
- const createAnalyticsJsRoute = (cacheName: string) => {
145
- const match = ({ url }: RouteMatchCallbackOptions) => url.hostname === GOOGLE_ANALYTICS_HOST && url.pathname === ANALYTICS_JS_PATH;
146
-
147
- const handler = new NetworkFirst({ cacheName });
148
-
149
- return new Route(match, handler, "GET");
150
- };
151
-
152
- /**
153
- * Creates a route with a network first strategy for the gtag.js script.
154
- *
155
- * @param cacheName
156
- * @returns The created route.
157
- * @private
158
- */
159
- const createGtagJsRoute = (cacheName: string) => {
160
- const match = ({ url }: RouteMatchCallbackOptions) => url.hostname === GTM_HOST && url.pathname === GTAG_JS_PATH;
161
-
162
- const handler = new NetworkFirst({ cacheName });
163
-
164
- return new Route(match, handler, "GET");
165
- };
166
-
167
- /**
168
- * Creates a route with a network first strategy for the gtm.js script.
169
- *
170
- * @param cacheName
171
- * @returns The created route.
172
- * @private
173
- */
174
- const createGtmJsRoute = (cacheName: string) => {
175
- const match = ({ url }: RouteMatchCallbackOptions) => url.hostname === GTM_HOST && url.pathname === GTM_JS_PATH;
176
-
177
- const handler = new NetworkFirst({ cacheName });
178
-
179
- return new Route(match, handler, "GET");
180
- };
181
-
182
- /**
183
- * @param options
184
- */
185
- export const initialize = (options: GoogleAnalyticsInitializeOptions = {}): void => {
186
- const cacheName = privateCacheNames.getGoogleAnalyticsName(options.cacheName);
187
-
188
- const bgSyncPlugin = new BackgroundSyncPlugin(QUEUE_NAME, {
189
- maxRetentionTime: MAX_RETENTION_TIME,
190
- onSync: createOnSyncCallback(options),
191
- });
192
-
193
- const routes = [createGtmJsRoute(cacheName), createAnalyticsJsRoute(cacheName), createGtagJsRoute(cacheName), ...createCollectRoutes(bgSyncPlugin)];
194
-
195
- for (const route of routes) {
196
- registerRoute(route);
197
- }
198
- };
@@ -1,22 +0,0 @@
1
- /*
2
- Copyright 2018 Google LLC
3
-
4
- Use of this source code is governed by an MIT-style
5
- license that can be found in the LICENSE file or at
6
- https://opensource.org/licenses/MIT.
7
- */
8
-
9
- export const QUEUE_NAME = "serwist-google-analytics";
10
- export const MAX_RETENTION_TIME = 60 * 48; // Two days in minutes
11
- export const GOOGLE_ANALYTICS_HOST = "www.google-analytics.com";
12
- export const GTM_HOST = "www.googletagmanager.com";
13
- export const ANALYTICS_JS_PATH = "/analytics.js";
14
- export const GTAG_JS_PATH = "/gtag/js";
15
- export const GTM_JS_PATH = "/gtm.js";
16
- export const COLLECT_DEFAULT_PATH = "/collect";
17
-
18
- // This RegExp matches all known Measurement Protocol single-hit collect
19
- // endpoints. Most of the time the default path (/collect) is used, but
20
- // occasionally an experimental endpoint is used when testing new features,
21
- // (e.g. /r/collect or /j/collect)
22
- export const COLLECT_PATHS_REGEX = /^\/(\w+\/)?collect/;