@wxt-dev/analytics 0.2.8 → 0.4.1

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/README.md CHANGED
@@ -1,90 +1,269 @@
1
1
  # WXT Analytics
2
2
 
3
- Add analytics, like google analytics, to your WXT extension.
3
+ Report analytics events from your web extension extension.
4
4
 
5
5
  ## Supported Analytics Providers
6
6
 
7
7
  - [Google Analytics 4 (Measurement Protocol)](#google-analytics-4-measurement-protocol)
8
8
  - [Umami](#umami)
9
9
 
10
- ## Installation
10
+ ## Install With WXT
11
11
 
12
- Install the NPM package:
12
+ 1. Install the NPM package:
13
+ ```bash
14
+ pnpm i @wxt-dev/analytics
15
+ ```
16
+ 2. In your `wxt.config.ts`, add the WXT module:
17
+ ```ts
18
+ export default defineConfig({
19
+ modules: ['@wxt-dev/analytics/module'],
20
+ });
21
+ ```
22
+ 3. In your `<srcDir>/app.config.ts`, add a provider:
13
23
 
14
- ```bash
15
- pnpm i @wxt-dev/analytics
16
- ```
24
+ ```ts
25
+ // <srcDir>/app.config.ts
26
+ import { umami } from '@wxt-dev/analytics/providers/umami';
17
27
 
18
- Then add the module to your `wxt.config.ts` file:
28
+ export default defineAppConfig({
29
+ analytics: {
30
+ debug: true,
31
+ providers: [
32
+ // ...
33
+ ],
34
+ },
35
+ });
36
+ ```
19
37
 
20
- ```ts
21
- export default defineConfig({
22
- modules: ['@wxt-dev/analytics'],
23
- });
38
+ 4. Then use the `#analytics` module to report events:
39
+
40
+ ```ts
41
+ import { analytics } from '#analytics';
42
+
43
+ await analytics.track('some-event');
44
+ await analytics.page();
45
+ await analytics.identify('some-user-id');
46
+ analytics.autoTrack(document.body);
47
+ ```
48
+
49
+ ## Install Without WXT
50
+
51
+ 1. Install the NPM package:
52
+ ```bash
53
+ pnpm i @wxt-dev/analytics
54
+ ```
55
+ 2. Create an `analytics` instance:
56
+
57
+ ```ts
58
+ // utils/analytics.ts
59
+ import { createAnalytics } from '@wxt-dev/analytics';
60
+
61
+ export const analytics = createAnalytics({
62
+ providers: [
63
+ // ...
64
+ ],
65
+ });
66
+ ```
67
+
68
+ 3. Import your analytics module in the background to initialize the message listener:
69
+ ```ts
70
+ // background.ts
71
+ import './utils/analytics';
72
+ ```
73
+ 4. Then use your `analytics` instance to report events:
74
+
75
+ ```ts
76
+ import { analytics } from './utils/analytics';
77
+
78
+ await analytics.track('some-event');
79
+ await analytics.page();
80
+ await analytics.identify('some-user-id');
81
+ analytics.autoTrack(document.body);
82
+ ```
83
+
84
+ ## Providers
85
+
86
+ ### Google Analytics 4 (Measurement Protocol)
87
+
88
+ The [Measurement Protocol](https://developers.google.com/analytics/devguides/collection/protocol/ga4) is an alternative to GTag for reporting events to Google Analytics for MV3 extensions.
89
+
90
+ > [Why use the Measurement Protocol instead of GTag?](https://developer.chrome.com/docs/extensions/how-to/integrate/google-analytics-4#measurement-protocol)
91
+
92
+ Follow [Google's documentation](https://developer.chrome.com/docs/extensions/how-to/integrate/google-analytics-4#setup-credentials) to obtain your credentials and put them in your `.env` file:
93
+
94
+ ```dotenv
95
+ WXT_GA_API_SECRET='...'
24
96
  ```
25
97
 
26
- Create an `app.config.ts` file and fill out the required config:
98
+ Then add the `googleAnalytics4` provider to your `<srcDir>/app.config.ts` file:
27
99
 
28
100
  ```ts
29
- // <srcDir>/app.config.ts
101
+ import { googleAnalytics4 } from '@wxt-dev/analytics/providers/google-analytics-4';
102
+
30
103
  export default defineAppConfig({
31
104
  analytics: {
32
- debug: true,
33
105
  providers: [
34
- // ...
106
+ googleAnalytics4({
107
+ apiSecret: import.meta.env.WXT_GA_API_SECRET,
108
+ measurementId: '...',
109
+ }),
35
110
  ],
36
111
  },
37
112
  });
38
113
  ```
39
114
 
40
- Then use the `analytics` import to report events:
115
+ ### Umami
41
116
 
42
- ```ts
43
- import { analytics } from '#analytics';
117
+ [Umami](https://umami.is/) is a privacy-first, open source analytics platform.
44
118
 
45
- await analytics.track('some-event');
46
- await analytics.page();
47
- await analytics.identify('some-user-id');
48
- analytics.autoTrack(document.body);
49
- ```
119
+ In Umami's dashboard, create a new website. The website's name and domain can be anything. Obviously, an extension doesn't have a domain, so make one up if you don't have one.
50
120
 
51
- ## Providers
121
+ After the website has been created, save the website ID and domain to your `.env` file:
52
122
 
53
- ### Google Analytics 4 (Measurement Protocol)
123
+ ```dotenv
124
+ WXT_UMAMI_WEBSITE_ID='...'
125
+ WXT_UMAMI_DOMAIN='...'
126
+ ```
54
127
 
55
- Follow [Google's documentation](https://developer.chrome.com/docs/extensions/how-to/integrate/google-analytics-4#setup-credentials) to obtain your credentials:
128
+ Then add the `umami` provider to your `<srcDir>/app.config.ts` file:
56
129
 
57
130
  ```ts
58
- import { googleAnalytics4 } from '@wxt-dev/analytics/providers/google-analytics-4';
131
+ import { umami } from '@wxt-dev/analytics/providers/umami';
59
132
 
60
133
  export default defineAppConfig({
61
134
  analytics: {
62
135
  providers: [
63
- googleAnalytics4({
64
- apiSecret: '...',
65
- measurementId: '...',
136
+ umami({
137
+ apiUrl: 'https://<your-umami-instance>/api',
138
+ websiteId: import.meta.env.WXT_UMAMI_WEBSITE_ID,
139
+ domain: import.meta.env.WXT_UMAMI_DOMAIN,
66
140
  }),
67
141
  ],
68
142
  },
69
143
  });
70
144
  ```
71
145
 
72
- > [Why use the Measurement Protocol instead of GTag?](https://developer.chrome.com/docs/extensions/how-to/integrate/google-analytics-4#measurement-protocol)
146
+ ### Custom Provider
73
147
 
74
- ### Umami
148
+ If your analytics platform is not supported, you can provide an implementation of the `AnalyticsProvider` type in your `app.config.ts` instead:
75
149
 
76
150
  ```ts
77
- import { umami } from '@wxt-dev/analytics/providers/umami';
151
+ import { defineAnalyticsProvider } from '@wxt-dev/analytics/client';
152
+
153
+ interface CustomAnalyticsOptions {
154
+ // ...
155
+ }
156
+
157
+ const customAnalytics = defineAnalyticsProvider<CustomAnalyticsOptions>(
158
+ (analytics, analyticsConfig, providerOptions) => {
159
+ // ...
160
+ },
161
+ );
78
162
 
79
163
  export default defineAppConfig({
80
164
  analytics: {
81
165
  providers: [
82
- umami({
83
- baseUrl: 'https://your-domain.com',
84
- websiteId: '...',
85
- hostname: '...',
166
+ customAnalytics({
167
+ // ...
86
168
  }),
87
169
  ],
88
170
  },
89
171
  });
90
172
  ```
173
+
174
+ Example `AnalyticsProvider` implementations can be found at [`./modules/analytics/providers`](https://github.com/wxt-dev/wxt/tree/main/packages/analytics/modules/analytics/providers).
175
+
176
+ ## User Properties
177
+
178
+ User ID and properties are stored in `browser.storage.local`. To change this or customize where these values are stored, use the `userId` and `userProperties` config:
179
+
180
+ ```ts
181
+ // app.config.ts
182
+ import { storage } from 'wxt/storage';
183
+
184
+ export default defineAppConfig({
185
+ analytics: {
186
+ userId: storage.defineItem('local:custom-user-id-key'),
187
+ userProperties: storage.defineItem('local:custom-user-properties-key'),
188
+ },
189
+ });
190
+ ```
191
+
192
+ To set the values at runtime, use the `identify` function:
193
+
194
+ ```ts
195
+ await analytics.identify(userId, userProperties);
196
+ ```
197
+
198
+ Alternatively, a common pattern is to use a random string as the user ID. This keeps the actual user information private, while still providing useful metrics in your analytics platform. This can be done very easily using WXT's storage API:
199
+
200
+ ```ts
201
+ // app.config.ts
202
+ import { storage } from 'wxt/storage';
203
+
204
+ export default defineAppConfig({
205
+ analytics: {
206
+ userId: storage.defineItem('local:custom-user-id-key', {
207
+ init: () => crypto.randomUUID(),
208
+ }),
209
+ },
210
+ });
211
+ ```
212
+
213
+ If you aren't using `wxt` or `@wxt-dev/storage`, you can define custom implementations for the `userId` and `userProperties` config:
214
+
215
+ ```ts
216
+ const analytics = createAnalytics({
217
+ userId: {
218
+ getValue: () => ...,
219
+ setValue: (userId) => ...,
220
+ }
221
+ })
222
+ ```
223
+
224
+ ## Auto-track UI events
225
+
226
+ Call `analytics.autoTrack(container)` to automatically track UI events so you don't have to manually add them. Currently it:
227
+
228
+ - Tracks clicks to elements inside the `container`
229
+
230
+ In your extension's HTML pages, you'll want to call it with `document`:
231
+
232
+ ```ts
233
+ analytics.autoTrack(document);
234
+ ```
235
+
236
+ But in content scripts, you usually only care about interactions with your own UI:
237
+
238
+ ```ts
239
+ const ui = createIntegratedUi({
240
+ // ...
241
+ onMount(container) {
242
+ analytics.autoTrack(container);
243
+ },
244
+ });
245
+ ui.mount();
246
+ ```
247
+
248
+ ## Enabling/Disabling
249
+
250
+ By default, **analytics is disabled**. You can configure how the value is stored (and change the default value) via the `enabled` config:
251
+
252
+ ```ts
253
+ // app.config.ts
254
+ import { storage } from 'wxt/storage';
255
+
256
+ export default defineAppConfig({
257
+ analytics: {
258
+ enabled: storage.defineItem('local:analytics-enabled', {
259
+ fallback: true,
260
+ }),
261
+ },
262
+ });
263
+ ```
264
+
265
+ At runtime, you can call `setEnabled` to change the value:
266
+
267
+ ```ts
268
+ analytics.setEnabled(true);
269
+ ```
@@ -0,0 +1,3 @@
1
+ declare const _default: () => void;
2
+
3
+ export { _default as default };
@@ -0,0 +1,3 @@
1
+ declare const _default: () => void;
2
+
3
+ export { _default as default };
@@ -0,0 +1,6 @@
1
+ import '#analytics';
2
+
3
+ const backgroundPlugin = () => {
4
+ };
5
+
6
+ export { backgroundPlugin as default };
package/dist/index.d.mts CHANGED
@@ -1,11 +1,12 @@
1
- import * as wxt from 'wxt';
2
- import { A as AnalyticsConfig } from './shared/analytics.2893a879.mjs';
1
+ import { AnalyticsConfig, Analytics, AnalyticsProvider } from './types.mjs';
3
2
 
4
- declare module 'wxt/sandbox' {
5
- interface WxtAppConfig {
6
- analytics: AnalyticsConfig;
7
- }
8
- }
9
- declare const _default: wxt.WxtModule<wxt.WxtModuleOptions>;
3
+ declare function createAnalytics(config?: AnalyticsConfig): Analytics;
4
+ declare function defineAnalyticsProvider<T = never>(definition: (
5
+ /** The analytics object. */
6
+ analytics: Analytics,
7
+ /** Config passed into the analytics module from `app.config.ts`. */
8
+ config: AnalyticsConfig,
9
+ /** Provider options */
10
+ options: T) => ReturnType<AnalyticsProvider>): (options: T) => AnalyticsProvider;
10
11
 
11
- export { _default as default };
12
+ export { createAnalytics, defineAnalyticsProvider };
package/dist/index.d.ts CHANGED
@@ -1,11 +1,12 @@
1
- import * as wxt from 'wxt';
2
- import { A as AnalyticsConfig } from './shared/analytics.2893a879.js';
1
+ import { AnalyticsConfig, Analytics, AnalyticsProvider } from './types.js';
3
2
 
4
- declare module 'wxt/sandbox' {
5
- interface WxtAppConfig {
6
- analytics: AnalyticsConfig;
7
- }
8
- }
9
- declare const _default: wxt.WxtModule<wxt.WxtModuleOptions>;
3
+ declare function createAnalytics(config?: AnalyticsConfig): Analytics;
4
+ declare function defineAnalyticsProvider<T = never>(definition: (
5
+ /** The analytics object. */
6
+ analytics: Analytics,
7
+ /** Config passed into the analytics module from `app.config.ts`. */
8
+ config: AnalyticsConfig,
9
+ /** Provider options */
10
+ options: T) => ReturnType<AnalyticsProvider>): (options: T) => AnalyticsProvider;
10
11
 
11
- export { _default as default };
12
+ export { createAnalytics, defineAnalyticsProvider };
package/dist/index.mjs CHANGED
@@ -1,36 +1,208 @@
1
- import 'wxt';
2
- import 'wxt/sandbox';
3
- import { defineWxtModule, addAlias } from 'wxt/modules';
4
- import { resolve } from 'node:path';
1
+ import { UAParser } from 'ua-parser-js';
5
2
 
6
- const index = defineWxtModule({
7
- name: "analytics",
8
- imports: [{ name: "analytics", from: "#analytics" }],
9
- setup(wxt) {
10
- wxt.hook("build:manifestGenerated", (_, manifest) => {
11
- manifest.permissions ?? (manifest.permissions = []);
12
- if (!manifest.permissions.includes("storage")) {
13
- manifest.permissions.push("storage");
14
- }
15
- });
16
- const analyticsModulePath = resolve(
17
- wxt.config.wxtDir,
18
- "analytics/index.ts"
3
+ const ANALYTICS_PORT = "@wxt-dev/analytics";
4
+ function createAnalytics(config) {
5
+ if (typeof chrome === "undefined" || !chrome?.runtime?.id)
6
+ throw Error(
7
+ "Cannot use WXT analytics in contexts without access to the browser.runtime APIs"
8
+ );
9
+ if (config == null) {
10
+ console.warn(
11
+ "[@wxt-dev/analytics] Config not provided to createAnalytics. If you're using WXT, add the 'analytics' property to '<srcDir>/app.config.ts'."
19
12
  );
20
- const analyticsModuleCode = `
21
- import { createAnalytics } from '@wxt-dev/analytics/client';
22
- import { useAppConfig } from 'wxt/client';
23
-
24
- export const analytics = createAnalytics(useAppConfig().analytics);
25
- `;
26
- addAlias(wxt, "#analytics", analyticsModulePath);
27
- wxt.hook("prepare:types", async (_, entries) => {
28
- entries.push({
29
- path: analyticsModulePath,
30
- text: analyticsModuleCode
31
- });
32
- });
33
13
  }
34
- });
14
+ if (location.pathname === "/background.js")
15
+ return createBackgroundAnalytics(config);
16
+ return createFrontendAnalytics();
17
+ }
18
+ function createBackgroundAnalytics(config) {
19
+ const userIdStorage = config?.userId ?? defineStorageItem("wxt-analytics:user-id");
20
+ const userPropertiesStorage = config?.userProperties ?? defineStorageItem(
21
+ "wxt-analytics:user-properties",
22
+ {}
23
+ );
24
+ const enabled = config?.enabled ?? defineStorageItem("local:wxt-analytics:enabled", false);
25
+ const platformInfo = chrome.runtime.getPlatformInfo();
26
+ const userAgent = UAParser();
27
+ let userId = Promise.resolve(userIdStorage.getValue()).then(
28
+ (id) => id ?? globalThis.crypto.randomUUID()
29
+ );
30
+ let userProperties = userPropertiesStorage.getValue();
31
+ const manifest = chrome.runtime.getManifest();
32
+ const getBackgroundMeta = () => ({
33
+ timestamp: Date.now(),
34
+ // Don't track sessions for the background, it can be running
35
+ // indefinitely, and will inflate session duration stats.
36
+ sessionId: void 0,
37
+ language: navigator.language,
38
+ referrer: void 0,
39
+ screen: void 0,
40
+ url: location.href,
41
+ title: void 0
42
+ });
43
+ const getBaseEvent = async (meta) => {
44
+ const platform = await platformInfo;
45
+ return {
46
+ meta,
47
+ user: {
48
+ id: await userId,
49
+ properties: {
50
+ version: config?.version ?? manifest.version_name ?? manifest.version,
51
+ wxtMode: import.meta.env.MODE,
52
+ wxtBrowser: import.meta.env.BROWSER,
53
+ arch: platform.arch,
54
+ os: platform.os,
55
+ browser: userAgent.browser.name,
56
+ browserVersion: userAgent.browser.version,
57
+ ...await userProperties
58
+ }
59
+ }
60
+ };
61
+ };
62
+ const analytics = {
63
+ identify: async (newUserId, newUserProperties = {}, meta = getBackgroundMeta()) => {
64
+ userId = Promise.resolve(newUserId);
65
+ userProperties = Promise.resolve(newUserProperties);
66
+ await Promise.all([
67
+ userIdStorage.setValue?.(newUserId),
68
+ userPropertiesStorage.setValue?.(newUserProperties)
69
+ ]);
70
+ const event = await getBaseEvent(meta);
71
+ if (config?.debug)
72
+ console.debug("[@wxt-dev/analytics] identify", event);
73
+ if (await enabled.getValue()) {
74
+ await Promise.allSettled(
75
+ providers.map((provider) => provider.identify(event))
76
+ );
77
+ } else if (config?.debug) {
78
+ console.debug(
79
+ "[@wxt-dev/analytics] Analytics disabled, identify() not uploaded"
80
+ );
81
+ }
82
+ },
83
+ page: async (location2, meta = getBackgroundMeta()) => {
84
+ const baseEvent = await getBaseEvent(meta);
85
+ const event = {
86
+ ...baseEvent,
87
+ page: {
88
+ url: meta?.url ?? globalThis.location?.href,
89
+ location: location2,
90
+ title: meta?.title ?? globalThis.document?.title
91
+ }
92
+ };
93
+ if (config?.debug)
94
+ console.debug("[@wxt-dev/analytics] page", event);
95
+ if (await enabled.getValue()) {
96
+ await Promise.allSettled(
97
+ providers.map((provider) => provider.page(event))
98
+ );
99
+ } else if (config?.debug) {
100
+ console.debug(
101
+ "[@wxt-dev/analytics] Analytics disabled, page() not uploaded"
102
+ );
103
+ }
104
+ },
105
+ track: async (eventName, eventProperties, meta = getBackgroundMeta()) => {
106
+ const baseEvent = await getBaseEvent(meta);
107
+ const event = {
108
+ ...baseEvent,
109
+ event: { name: eventName, properties: eventProperties }
110
+ };
111
+ if (config?.debug)
112
+ console.debug("[@wxt-dev/analytics] track", event);
113
+ if (await enabled.getValue()) {
114
+ await Promise.allSettled(
115
+ providers.map((provider) => provider.track(event))
116
+ );
117
+ } else if (config?.debug) {
118
+ console.debug(
119
+ "[@wxt-dev/analytics] Analytics disabled, track() not uploaded"
120
+ );
121
+ }
122
+ },
123
+ setEnabled: async (newEnabled) => {
124
+ await enabled.setValue?.(newEnabled);
125
+ },
126
+ autoTrack: () => {
127
+ return () => {
128
+ };
129
+ }
130
+ };
131
+ const providers = config?.providers?.map((provider) => provider(analytics, config)) ?? [];
132
+ chrome.runtime.onConnect.addListener((port) => {
133
+ if (port.name === ANALYTICS_PORT) {
134
+ port.onMessage.addListener(({ fn, args }) => {
135
+ void analytics[fn]?.(...args);
136
+ });
137
+ }
138
+ });
139
+ return analytics;
140
+ }
141
+ function createFrontendAnalytics() {
142
+ const port = chrome.runtime.connect({ name: ANALYTICS_PORT });
143
+ const sessionId = Date.now();
144
+ const getFrontendMetadata = () => ({
145
+ sessionId,
146
+ timestamp: Date.now(),
147
+ language: navigator.language,
148
+ referrer: globalThis.document?.referrer || void 0,
149
+ screen: globalThis.window ? `${globalThis.window.screen.width}x${globalThis.window.screen.height}` : void 0,
150
+ url: location.href,
151
+ title: document.title || void 0
152
+ });
153
+ const methodForwarder = (fn) => (...args) => {
154
+ port.postMessage({ fn, args: [...args, getFrontendMetadata()] });
155
+ };
156
+ const analytics = {
157
+ identify: methodForwarder("identify"),
158
+ page: methodForwarder("page"),
159
+ track: methodForwarder("track"),
160
+ setEnabled: methodForwarder("setEnabled"),
161
+ autoTrack: (root) => {
162
+ const onClick = (event) => {
163
+ const element = event.target;
164
+ if (!element || !INTERACTIVE_TAGS.has(element.tagName) && !INTERACTIVE_ROLES.has(element.getAttribute("role")))
165
+ return;
166
+ void analytics.track("click", {
167
+ tagName: element.tagName?.toLowerCase(),
168
+ id: element.id || void 0,
169
+ className: element.className || void 0,
170
+ textContent: element.textContent?.substring(0, 50) || void 0,
171
+ // Limit text content length
172
+ href: element.href
173
+ });
174
+ };
175
+ root.addEventListener("click", onClick, { capture: true, passive: true });
176
+ return () => {
177
+ root.removeEventListener("click", onClick);
178
+ };
179
+ }
180
+ };
181
+ return analytics;
182
+ }
183
+ function defineStorageItem(key, defaultValue) {
184
+ return {
185
+ getValue: async () => (await chrome.storage.local.get(key))[key] ?? defaultValue,
186
+ setValue: (newValue) => chrome.storage.local.set({ [key]: newValue })
187
+ };
188
+ }
189
+ const INTERACTIVE_TAGS = /* @__PURE__ */ new Set([
190
+ "A",
191
+ "BUTTON",
192
+ "INPUT",
193
+ "SELECT",
194
+ "TEXTAREA"
195
+ ]);
196
+ const INTERACTIVE_ROLES = /* @__PURE__ */ new Set([
197
+ "button",
198
+ "link",
199
+ "checkbox",
200
+ "menuitem",
201
+ "tab",
202
+ "radio"
203
+ ]);
204
+ function defineAnalyticsProvider(definition) {
205
+ return (options) => (analytics, config) => definition(analytics, config, options);
206
+ }
35
207
 
36
- export { index as default };
208
+ export { createAnalytics, defineAnalyticsProvider };
@@ -0,0 +1,11 @@
1
+ import * as wxt from 'wxt';
2
+ import { AnalyticsConfig } from './types.mjs';
3
+
4
+ declare module 'wxt/sandbox' {
5
+ interface WxtAppConfig {
6
+ analytics: AnalyticsConfig;
7
+ }
8
+ }
9
+ declare const _default: wxt.WxtModule<wxt.WxtModuleOptions>;
10
+
11
+ export { _default as default };
@@ -0,0 +1,11 @@
1
+ import * as wxt from 'wxt';
2
+ import { AnalyticsConfig } from './types.js';
3
+
4
+ declare module 'wxt/sandbox' {
5
+ interface WxtAppConfig {
6
+ analytics: AnalyticsConfig;
7
+ }
8
+ }
9
+ declare const _default: wxt.WxtModule<wxt.WxtModuleOptions>;
10
+
11
+ export { _default as default };