Compare commits

..

50 Commits

Author SHA1 Message Date
Aaron 150980929f chore(release): analytics-v0.4.1
vhs / vhs (push) Cancelled after 0s
2025-01-07 13:35:13 -06:00
Aaron bcd906e51b add dependency optimizations automatically 2025-01-07 13:34:52 -06:00
Aaron 00352c2eca Cleanup 2025-01-05 10:34:11 -06:00
Aaron 94027fa82e Update docs 2025-01-05 10:32:57 -06:00
Aaron c2090d64a0 sync deps 2024-12-29 20:42:10 -06:00
Aaron 2faba91ddb chore(release): analytics-v0.4.0
vhs / vhs (push) Cancelled after 0s
2024-12-29 20:36:35 -06:00
Aaron fe8e2ed23b Fix build script 2024-12-29 20:35:32 -06:00
Aaron 95369ff2c9 fix prepare script 2024-12-29 20:29:51 -06:00
Aaron 829525f824 Update workflows 2024-12-29 20:27:33 -06:00
Aaron 9ad04d325b Add missing docs 2024-12-29 20:25:51 -06:00
Aaron f218c30825 Add background if missing 2024-12-29 20:19:41 -06:00
Aaron fdee7c615c Cleanup 2024-12-29 20:16:13 -06:00
Aaron b34754b363 Cleanup 2024-12-29 19:58:08 -06:00
Aaron be74af40f9 Add plugin 2024-12-29 19:49:02 -06:00
Aaron baebe28a3e cleanup 2024-12-29 19:42:42 -06:00
Aaron 3b9f395a7d Update README 2024-12-29 19:22:30 -06:00
Aaron 95367203bf cleanup 2024-12-29 19:15:21 -06:00
Aaron 6fb1463a32 defineAnalyticsProvider and updated umami config 2024-12-29 19:10:31 -06:00
aklinker1 b727453509 docs: Update wxt init GIF 2024-12-29 22:12:30 +00:00
Aaron 446fd90bea Merge remote-tracking branch 'origin/main' into analytics-module 2024-12-29 16:10:55 -06:00
Aaron 90c2b7f9bf Bump version 2024-10-31 08:47:36 -05:00
Aaron c431dafe08 Fix readme and required minimum version 2024-10-31 08:47:09 -05:00
Aaron 3786c7b6d1 Fix types 2024-10-22 15:32:34 -05:00
Aaron 0416ff7ec2 Cleanup metadata handling 2024-10-22 15:29:44 -05:00
Aaron 26cbef5a42 Properly track title 2024-10-22 15:14:05 -05:00
Aaron e98f29fddb Fix page upload params 2024-10-22 15:07:57 -05:00
Aaron 93e6dd6db7 Improve debug logs 2024-10-22 15:03:02 -05:00
Aaron 7879fabbad Cleanup 2024-10-22 14:56:25 -05:00
Aaron a861dc1736 fix code-generation 2024-10-22 14:05:32 -05:00
Aaron f75c5ca1aa fix api check 2024-10-22 11:01:27 -05:00
Aaron e8e00e4e04 Fix build 2024-10-22 10:53:50 -05:00
Aaron 15adc77d23 Refactor to generated module instead of plugin 2024-10-22 10:47:41 -05:00
Aaron c73a4b6a96 Merge remote-tracking branch 'origin/main' into analytics-module 2024-10-22 10:18:55 -05:00
Aaron d96840b2f5 WIP 2024-10-22 10:10:14 -05:00
aklinker1 e4886af90a docs: Update wxt init GIF 2024-09-18 15:00:46 +00:00
Aaron c69e99db3f Remove wxt/storage 2024-09-18 09:59:09 -05:00
Aaron 55113d654d Remove wxt/storage 2024-09-18 09:59:09 -05:00
Aaron 50d2170844 Fix storage 2024-09-18 09:59:09 -05:00
Aaron ee53bb0a5e disable auto-imports 2024-09-18 09:59:09 -05:00
Aaron 5216d75209 Fix useAppConfig fr? 2024-09-18 09:59:09 -05:00
Aaron d0623fe173 Fix missing useAppConfig 2024-09-18 09:59:09 -05:00
Aaron e0d0618325 Fix missing useAppConfig 2024-09-18 09:59:09 -05:00
Aaron 563bd4e108 Fix __dirname reference 2024-09-18 09:59:09 -05:00
Aaron 107803bd8f Update package.json 2024-09-18 09:59:09 -05:00
Aaron 06fd7e4eac Update package.json 2024-09-18 09:59:09 -05:00
Aaron eba8788a76 Umami provider and cleanup 2024-09-18 09:59:07 -05:00
Aaron 8ace11f3cb Add missing file 2024-09-18 09:58:45 -05:00
Aaron 328acbbfe7 Cleanup 2024-09-18 09:58:45 -05:00
Aaron f99c1aa7b5 Implement client and google analytics 2024-09-18 09:58:43 -05:00
Aaron 5217279070 feat: Analytics module 2024-09-18 09:58:04 -05:00
62 changed files with 1372 additions and 545 deletions
-9
View File
@@ -1,9 +0,0 @@
# Set default
* @aklinker1 @Timeraa
# Secure Directories
/.github/ @aklinker1
# Creator of specific wxt modules
/packages/auto-icons/ @Timeraa
/packages/unocss/ @Timeraa
+14 -2
View File
@@ -1,3 +1,15 @@
# https://docs.github.com/en/repositories/managing-your-repositorys-settings-and-features/customizing-your-repository/displaying-a-sponsor-button-in-your-repository#about-funding-files
# These are supported funding model platforms
github: wxt-dev
github: [wxt-dev] # Replace with up to 4 GitHub Sponsors-enabled usernames e.g., [user1, user2]
patreon: # Replace with a single Patreon username
open_collective: # Replace with a single Open Collective username
ko_fi: # Replace with a single Ko-fi username
tidelift: # Replace with a single Tidelift platform-name/package-name e.g., npm/babel
community_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry
liberapay: # Replace with a single Liberapay username
issuehunt: # Replace with a single IssueHunt username
lfx_crowdfunding: # Replace with a single LFX Crowdfunding project-name e.g., cloud-foundry
polar: # Replace with a single Polar username
buy_me_a_coffee: # Replace with a single Buy Me a Coffee username
thanks_dev: # Replace with a single thanks.dev username
custom: # Replace with up to 4 custom sponsorship URLs e.g., ['link1', 'link2']
-13
View File
@@ -1,13 +0,0 @@
### Overview
<!-- Describe your changes and why you made them -->
### Manual Testing
<!-- Describe how to test your changes to make sure the PR works as intended -->
### Related Issue
<!-- If this PR is related to an issue, please link it here -->
This PR closes #<issue_number>
+1 -2
View File
@@ -7,6 +7,7 @@ on:
default: wxt
type: choice
options:
- analytics
- auto-icons
- i18n
- module-react
@@ -24,8 +25,6 @@ jobs:
publish:
runs-on: ubuntu-22.04
permissions:
contents: write
needs:
- validate
steps:
+1
View File
@@ -7,6 +7,7 @@ on:
default: wxt
type: choice
options:
- analytics
- auto-icons
- i18n
- module-react
+1
View File
@@ -6,6 +6,7 @@
.webextrc
.wxt
*.log
/.vscode/
/docs/.vitepress/cache
coverage
dist
-7
View File
@@ -1,7 +0,0 @@
{
"recommendations": [
"davidanson.vscode-markdownlint",
"esbenp.prettier-vscode",
"github.vscode-github-actions"
]
}
-14
View File
@@ -1,14 +0,0 @@
{
// Set default formatter
"editor.defaultFormatter": "esbenp.prettier-vscode",
"[json]": { "editor.defaultFormatter": "esbenp.prettier-vscode" },
"[yaml]": { "editor.defaultFormatter": "esbenp.prettier-vscode" },
"[typescript]": { "editor.defaultFormatter": "esbenp.prettier-vscode" },
"[markdown]": { "editor.defaultFormatter": "esbenp.prettier-vscode" },
// Additional guidelines for Copilot
"github.copilot.chat.codeGeneration.instructions": [
{ "file": "CONTRIBUTING.md" }
]
}
-15
View File
@@ -1,15 +0,0 @@
# Security Policy
While WXT is in prerelease, only the latest version will recieve security updates. The latest version is:
<img alt="npm version" src="https://img.shields.io/npm/v/wxt?labelColor=black&color=%234fa048">
<!--
## Reporting a Vulnerability
Use this section to tell people how to report a vulnerability.
Tell them where to go, how often they can expect to get an update on a
reported vulnerability, what to expect if the vulnerability is accepted or
declined, etc.
-->
@@ -62,10 +62,6 @@ const chromeExtensionIds = [
'hjjkgbibknbahijglkffklflidncplkn', // Show IP Live View of Website IPs for Developers
'ilbikcehnpkmldojkcmlldkoelofnbde', // Strong Password Generator
'ocllfkhcdopiafndigclebelbecaiocp', // ZenGram: Mindful Instagram, Your Way
'odffpjnpocjfcaclnenaaaddghkgijdb', // Blync: Preview Links, Selection Search, AI Assistant
'kofbbilhmnkcmibjbioafflgmpkbnmme', // HTML to Markdown - Convert webpages to markdown
'boecmgggeigllcdocgioijmleimjbfkg', // Walmart WFS Profit Calculator
'dlnjcbkmomenmieechnmgglgcljhoepd', // Youtube Live Chat Fullscreen
];
const { data, err, isLoading } = useListExtensionDetails(chromeExtensionIds);
+15 -7
View File
@@ -14,6 +14,7 @@ import { version as i18nVersion } from '../../packages/i18n/package.json';
import { version as autoIconsVersion } from '../../packages/auto-icons/package.json';
import { version as unocssVersion } from '../../packages/unocss/package.json';
import { version as storageVersion } from '../../packages/storage/package.json';
import { version as analyticsVersion } from '../../packages/analytics/package.json';
const title = 'Next-gen Web Extension Framework';
const titleSuffix = ' WXT';
@@ -23,6 +24,14 @@ const ogTitle = `${title}${titleSuffix}`;
const ogUrl = 'https://wxt.dev';
const ogImage = 'https://wxt.dev/social-preview.png';
const otherPackages = {
analytics: analyticsVersion,
'auto-icons': autoIconsVersion,
i18n: i18nVersion,
storage: storageVersion,
unocss: unocssVersion,
};
// https://vitepress.dev/reference/site-config
export default defineConfig({
titleTemplate: `:title${titleSuffix}`,
@@ -97,12 +106,12 @@ export default defineConfig({
'https://github.com/wxt-dev/wxt/blob/main/packages/wxt/CHANGELOG.md',
),
]),
navItem('Other Packages', [
navItem(`@wxt-dev/storage — ${storageVersion}`, '/storage'),
navItem(`@wxt-dev/auto-icons — ${autoIconsVersion}`, '/auto-icons'),
navItem(`@wxt-dev/i18n${i18nVersion}`, '/i18n'),
navItem(`@wxt-dev/unocss — ${unocssVersion}`, '/unocss'),
]),
navItem(
'Other Packages',
Object.entries(otherPackages).map(([name, version]) =>
navItem(`@wxt-dev/${name}${version}`, `/${name}`),
),
),
]),
],
@@ -152,7 +161,6 @@ export default defineConfig({
menuGroup('Resources', '/guide/resources/', [
menuItem('Compare', 'compare.md'),
menuItem('FAQ', 'faq.md'),
menuItem('Community', 'community.md'),
menuItem('Upgrading WXT', 'upgrading.md'),
menuItem('Migrate to WXT', 'migrate.md'),
menuItem('How WXT Works', 'how-wxt-works.md'),
+1
View File
@@ -0,0 +1 @@
<!--@include: ../packages/analytics/README.md-->
Binary file not shown.

Before

Width:  |  Height:  |  Size: 132 KiB

After

Width:  |  Height:  |  Size: 131 KiB

@@ -41,8 +41,6 @@ export default defineRunnerConfig({
});
```
By default, WXT will try to automatically discover where Chrome/Firefox are installed. However, if you have chrome installed in a non-standard location, you need to set it manually as shown above.
### Persist Data
By default, to keep from modifying your browser's existing profiles, `web-ext` creates a brand new profile every time you run the `dev` script.
@@ -74,7 +72,7 @@ export default defineRunnerConfig({
Now, next time you run the `dev` script, a persistent profile will be created in `.wxt/chrome-data/{profile-name}`. With a persistent profile, you can install devtools extensions to help with development, allow the browser to remember logins, etc, without worrying about the profile being reset the next time you run the `dev` script.
:::tip
You can use any directory you'd like for `--user-data-dir`, the examples above create a persistent profile for each WXT project. To create a profile for all WXT projects, you can put the `chrome-data` directory inside your user's home directory.
You can use any directory you'd like for `--user-data-dir`, the examples above create a persistent profile for each WXT project. To create a profile for all WXT projects, you can put the `chrome-data` directory inside you're user's home directory.
:::
### Disable Opening Browser
+20 -12
View File
@@ -1,17 +1,10 @@
# Manifest
In WXT, there is no `manifest.json` file in your source code. Instead, WXT generates the manifest from multiple sources:
In WXT, there is no `manifest.json` file in your source code. Instead, WXT generates it during the build process based off files in your project.
- Global options [defined in your `wxt.config.ts` file](#global-options)
- Entrypoint-specific options [defined in your entrypoints](/guide/essentials/entrypoints#defining-manifest-options)
- [WXT Modules](/guide/essentials/wxt-modules) added to your project can modify your manifest
- [Hooks](/guide/essentials/config/hooks) defined in your project can modify your manifest
## Manifest Config
Your extension's `manifest.json` will be output to `.output/{target}/manifest.json` when running `wxt build`.
## Global Options
To add a property to your manifest, use the `manifest` config inside your `wxt.config.ts`:
To manually add a property to the `manifest.json` output during builds, use the `manifest` config inside `wxt.config.ts`:
```ts
export default defineConfig({
@@ -137,7 +130,7 @@ public/
└─ icon-128.png
```
Specifically, an icon must match one of these regex to be discovered:
Specifically, if an icon must match one of these regex to be discovered:
<<< @/../packages/wxt/src/core/utils/manifest.ts#snippet
@@ -223,7 +216,22 @@ By default, whenever an `action` is generated, WXT falls back to `browser_action
### Action With Popup
To generate a manifest where a UI appears after clicking the icon, just create a [Popup entrypoint](/guide/essentials/entrypoints#popup). If you want to use a `page_action` for MV2, add the following meta tag to the HTML document's head:
To generate a manifest where a UI appears after clicking the icon, just create a [Popup entrypoint](/guide/essentials/entrypoints#popup).
```ts
export default defineConfig({
hooks: {
build: {
manifestGenerated(manifest) {
// Update the manifest variable by reference
manifest.name = 'Overriden name';
},
},
},
});
```
If you want to use a `page_action` for MV2, add the following meta tag to the HTML document's head:
```html
<meta name="manifest.type" content="page_action" />
+1 -1
View File
@@ -14,7 +14,7 @@ At a minimum, you need to create a TSConfig in your root directory that looks li
Or if you're in a monorepo, you may not want to extend the config. If you don't extend it, you need to add `.wxt/wxt.d.ts` to the TypeScript project:
```ts
/// <reference path="./.wxt/wxt.d.ts" />
/// <reference types="./.wxt/wxt.d.ts" />
```
## Compiler Options
+16 -32
View File
@@ -4,14 +4,12 @@ outline: deep
# Content Scripts
> To create a content script, see [Entrypoint Types](/guide/essentials/entrypoints#content-scripts).
## Context
The first argument to a content script's `main` function is it's "context".
```ts
// entrypoints/example.content.ts
// entrypoints/content.ts
export default defineContentScript({
main(ctx) {},
});
@@ -64,7 +62,7 @@ In regular web extensions, CSS for content scripts is usually a separate CSS fil
In WXT, to add CSS to a content script, simply import the CSS file into your JS entrypoint, and WXT will automatically add the bundled CSS output to the `css` array.
```ts
// entrypoints/example.content/index.ts
// entrypoints/content/index.ts
import './style.css';
export default defineContentScript({
@@ -80,16 +78,16 @@ To create a standalone content script that only includes a CSS file:
// wxt.config.ts
export default defineConfig({
hooks: {
'build:manifestGenerated': (wxt, manifest) => {
"build:manifestGenerated": (wxt, manifest) => {
manifest.content_scripts ??= [];
manifest.content_scripts.push({
// Build extension once to see where your CSS get's written to
css: ['content-scripts/example.css'],
matches: ['*://*/*'],
});
},
},
});
css: ["content-scripts/example.css"],
matches: ["*://*/*"]
)
}
}
})
```
## UI
@@ -200,7 +198,6 @@ export default defineContentScript({
```ts [Svelte]
// entrypoints/example-ui.content/index.ts
import App from './App.svelte';
import { mount, unmount } from 'svelte';
export default defineContentScript({
matches: ['<all_urls>'],
@@ -211,13 +208,14 @@ export default defineContentScript({
anchor: 'body',
onMount: (container) => {
// Create the Svelte app inside the UI container
mount(App, {
const app = new App({
target: container,
});
return app;
},
onRemove: (app) => {
// Destroy the app when the UI is removed
unmount(app);
app.$destroy();
},
});
@@ -381,7 +379,6 @@ export default defineContentScript({
// 1. Import the style
import './style.css';
import App from './App.svelte';
import { mount, unmount } from 'svelte';
export default defineContentScript({
matches: ['<all_urls>'],
@@ -396,13 +393,14 @@ export default defineContentScript({
anchor: 'body',
onMount: (container) => {
// Create the Svelte app inside the UI container
mount(App, {
const app = new App({
target: container,
});
return app;
},
onRemove: () => {
onRemove: (app) => {
// Destroy the app when the UI is removed
unmount(app);
app?.$destroy();
},
});
@@ -568,20 +566,6 @@ export default defineContentScript({
});
```
```json
export default defineConfig({
manifest: {
// ...
web_accessible_resources: [
{
resources: ["example-main-world.js"],
matches: ["*://*/*"],
}
]
}
});
```
`injectScript` works by creating a `script` element on the page pointing to your script. This loads the script into the page's context so it runs in the main world.
`injectScript` returns a promise, that when resolved, means the script has been evaluated by the browser and you can start communicating with it.
+3 -14
View File
@@ -28,7 +28,7 @@ For web extensions, there are two types of entrypoints:
- **Listed**: Referenced in the `manifest.json`
- **Unlisted**: Not referenced in the `manifest.json`
Throughout the rest of WXT's documentation, listed entrypoints are referred to by name. For example:
Throughout the rest of WXT's documentation, listed files are referred to by name. For example:
- Popup
- Options
@@ -42,7 +42,7 @@ Some examples of "unlisted" entrypoints:
- JS files injected by content scripts into the page's main world
:::tip
Regardless of whether an entrypoint is listed or unlisted, it will still be bundled into your extension and be available at runtime.
Regardless of whether a entrypoint is listed or unlisted, it will still be bundled into your extension and be available at runtime.
:::
## Adding Entrypoints
@@ -72,7 +72,7 @@ Refer to the [Entrypoint Types](#entrypoint-types) section for the full list of
## Defining Manifest Options
Most listed entrypoints have options that need to be added to the `manifest.json`. However with WXT, instead of defining the options in a separate file, _you define these options inside the entrypoint file itself_.
Most listed entrypoints have options that need to be added to the `manifest.json`. With WXT however, instead of defining the options in a separate file, _you define these options inside the entrypoint file itself_.
For example, here's how to define `matches` for content scripts:
@@ -86,17 +86,6 @@ export default defineContentScript({
});
```
For HTML entrypoints, options are configured as `<meta>` tags. For example, to use a `page_action` for your MV2 popup:
```html
<!doctype html>
<html lang="en">
<head>
<meta name="manifest.type" content="page_action" />
</head>
</html>
```
> Refer to the [Entrypoint Types](#entrypoint-types) sections for a list of options configurable inside each entrypoint, and how to define them.
When building your extension, WXT will look at the options defined in your entrypoints, and generate the manifest accordingly.
+7 -7
View File
@@ -1,10 +1,12 @@
# ES Modules
You source code should always be written as ESM. However, you have some control whether an entrypoint is bundled as ESM.
Currently, ESM entrypoints are opt-in, so you must configure each entrypoint with that in mind.
## HTML Pages <Badge type="warning" text="≥0.0.1" />
Vite only supports bundling JS from HTML pages as ESM. Ensure you have added `type="module"` to your `<script>` tags:
In general, you should always make HTML pages import ESM scripts, unless you need to support old browsers.
To make a script ESM, add `type="module"`:
<!-- prettier-ignore -->
```html
@@ -14,7 +16,7 @@ Vite only supports bundling JS from HTML pages as ESM. Ensure you have added `ty
## Background <Badge type="warning" text="≥0.16.0" />
By default, your background will be bundled into a single file as IIFE. You can change this by setting `type: "module"` in your background entrypoint:
In your background script, set `type: "module"`:
```ts
export default defineBackground({
@@ -25,14 +27,12 @@ export default defineBackground({
});
```
This will change the output format to ESM, enable code-spliting between your background script and HTML pages, and set `"type": "module"` in your manifest.
:::warning
Only MV3 supports ESM background scripts/service workers. When targeting MV2, the `type` option is ignored and the background is always bundled into a single file as IIFE.
:::
## Content Scripts
WXT does not yet include built-in support for bundling content scripts as ESM. The plan is to add support for chunking to reduce bundle size, but not support HMR for now. There are several technical issues that make implementing a generic solution for HMR impossible. See [Content Script ESM Support #357](https://github.com/wxt-dev/wxt/issues/357) for details.
WXT does not yet include built-in support for ESM content scripts. The plan is to add support for chunking to reduce bundle size, but not support HMR for now. There are several technical issues that make implementing a generic solution for HMR impossible. See [Content Script ESM Support #357](https://github.com/wxt-dev/wxt/issues/357) for details.
If you can't wait, and need ESM support right now, you can implement ESM support manually. See the [ESM Content Script UI](https://github.com/wxt-dev/examples/tree/main/examples/esm-content-script-ui) example to learn how.
If you can't wait, and need ESM support right now, you can implement ESM support manually. See the [ESM Content Script UI](https://github.com/wxt-dev/examples/tree/main/examples/esm-content-script-ui) example to get started.
-4
View File
@@ -81,10 +81,6 @@ However, it is recommended you stick with the vanilla API (or a package based on
- Translations are not bundled multiple times, keeping your extension small
- Zero configuration
However, there is one major downside to the vanilla API and any packages built on top of it:
- Language cannot be changed without changing your browser/system language
Here are some examples of how to setup a third party i18n library:
- [vue-i18n](https://github.com/wxt-dev/wxt-examples/tree/main/examples/vue-i18n)
+18 -18
View File
@@ -59,24 +59,24 @@ After enabling it, your project structure should look like this:
<!-- prettier-ignore -->
```html
📂 {rootDir}/
📁 .output/
📁 .wxt/
📂 src/
📁 assets/
📁 components/
📁 composables/
📁 entrypoints/
📁 hooks/
📁 modules/
📁 public/
📁 utils/
📄 app.config.ts
📄 .env
📄 .env.publish
📄 package.json
📄 tsconfig.json
📄 web-ext.config.ts
📄 wxt.config.ts
📁 .output/
📁 .wxt/
📂 src/
📁 assets/
📁 components/
📁 composables/
📁 entrypoints/
📁 hooks/
📁 modules/
📁 public/
📁 utils/
📄 app.config.ts
📄 .env
📄 .env.publish
📄 package.json
📄 tsconfig.json
📄 web-ext.config.ts
📄 wxt.config.ts
```
## Customizing Other Directories
-1
View File
@@ -121,4 +121,3 @@ Once you've run the `dev` command, continue to [Next Steps](#next-steps)!
- Keep reading on about WXT's [Project Structure](/guide/essentials/project-structure) and other essential concepts to learn
- Configure [automatic browser startup](/guide/essentials/config/browser-startup) during dev mode
- Explore [WXT's example library](/examples) to see how to use specific APIs or perform common tasks
- Checkout the [community page](/guide/resources/community) for a list of resources made by the community!
-13
View File
@@ -1,13 +0,0 @@
# Community
This page is dedicated to all the awesome people how have made something for WXT or that works with WXT. Blog posts, YouTube videos, NPM packages, etc. If a section doesn't exist for the thing you made, add one!
[[toc]]
## Blog Posts
- [Building Modern Cross Browser Web Extensions](https://aabidk.dev/tags/wxt/) by Aabid ([@aabidk20](https://github.com/aabidk20))
## NPM Packages
- [`@webext-core/*`](https://webext-core.aklinker1.io/): Easy-to-use utilities for writing and testing web extensions that work on all browsers.
-5
View File
@@ -10,7 +10,6 @@ Lets compare the features of WXT vs [Plasmo](https://docs.plasmo.com/framework)
| Features | WXT | Plasmo | CRXJS |
| ------------------------------------------------------- | :-----: | :-----: | :-----: |
| Maintained | ✅ | 🟡 [^n] | 🟡 [^m] |
| Supports all browsers | ✅ | ✅ | 🟡 [^j] |
| MV2 Support | ✅ | ✅ | 🟡 [^a] |
| MV3 Support | ✅ | ✅ | 🟡 [^a] |
@@ -65,7 +64,3 @@ Lets compare the features of WXT vs [Plasmo](https://docs.plasmo.com/framework)
[^k]: There is no built-in wrapper around this API. However, you can still access the standard APIs via `chrome`/`browser` globals or use any 3rd party NPM package.
[^l]: WIP, moving very slowly. Follow [wxt-dev/wxt#357](https://github.com/wxt-dev/wxt/issues/357) for updates.
[^m]: See [crxjs/chrome-extension-tools#974](https://github.com/crxjs/chrome-extension-tools/discussions/974)
[^n]: Appears to be in maintenance mode with little to no maintainers nor feature development happening and _(see [wxt-dev/wxt#1404 (comment)](https://github.com/wxt-dev/wxt/pull/1404#issuecomment-2643089518))_
+36 -128
View File
@@ -28,139 +28,47 @@ See https://wxt.dev/guide/essentials/config/browser-startup.html#persist-data
## My component library doesn't work in content scripts!
This is usually caused by one of two things (or both) when using `createShadowRootUi`:
Component libraries place their CSS in the document's `<head>` by default. When using `createShadowRootUi`, your UI is isolated from the document's styles because it's inside a ShadowRoot.
1. Styles are added outside the `ShadowRoot`
To fix this, you need to tell your component library to insert it's CSS inside the shadow root. Here's the docs for a couple of popular libraries:
:::details
Some component libraries manually add CSS to the page by adding a `<style>` or `<link>` element. They place this element in the document's `<head>` by default. This causes your styles to be placed outside the `ShadowRoot` and it's isolation blocks the styles from being applied to your UI.
- React
- Ant Design: [`StyleProvider`](https://ant.design/docs/react/compatible-style#shadow-dom-usage)
- Mantine: [`MantineProvider#getRootElement` and `MantineProvider#cssVariablesSelector`](https://mantine.dev/theming/mantine-provider/)
When a library does this, **you need to tell the library where to put its styles**. Here's the documentation for a few popular component libraries:
> If your library isn't listed above, try searching it's docs/issues for "shadow root", "shadow dom", or "css container".
- Ant Design: [`StyleProvider`](https://ant.design/docs/react/compatible-style#shadow-dom-usage)
- Mantine: [`MantineProvider#getRootElement` and `MantineProvider#cssVariablesSelector`](https://mantine.dev/theming/mantine-provider/)
`createShadowRootUi` provides it's own `<head>` element inside the shadow root, so that were you should tell the library to add the CSS. Here's an example with Ant Design:
> If your library isn't listed above, try searching it's docs/issues for "shadow root", "shadow dom", or "css container". Not all libraries support shadow DOMs, you may have to open an issue to request this feature.
```tsx
import { StyleProvider } from '@ant-design/cssinjs'; // [!code ++]
import ReactDOM from 'react-dom/client';
import App from './App.tsx';
Here's an example of configuring Antd's styles:
const ui = await createShadowRootUi(ctx, {
name: 'example-ui',
position: 'inline',
anchor: 'body',
onMount: (container) => { // [!code --]
onMount: (container, shadow) => { // [!code ++]
const cssContainer = shadow.querySelector("head")!; // [!code ++]
const root = ReactDOM.createRoot(container);
root.render(
<StyleProvider container={cssContainer}> // [!code ++]
<App />
</StyleProvider> // [!code ++]
);
return root;
},
onRemove: (root) => {
root?.unmount();
},
});
```
```tsx
import { StyleProvider } from '@ant-design/cssinjs';
import ReactDOM from 'react-dom/client';
import App from './App.tsx';
Note that this doesn't effect all component libraries, just ones that inject CSS themselves rather than having you import their CSS. This approach is more prevailent in the React community, but not limited to it. That's why only React libraries are listed above. Vuetify, for example, works just fine because you import its CSS - WXT picks up on this and the CSS is added inside the shadow root automatically:
const ui = await create`ShadowRoot`Ui(ctx, {
// ...
onMount: (container, shadow) => {
const cssContainer = shadow.querySelector('head')!;
const root = ReactDOM.createRoot(container);
root.render(
<StyleProvider container={cssContainer}>
<App />
</StyleProvider>,
);
return root;
},
});
```
:::
2. UI elements are added outside the `ShadowRoot`
::::::details
This is mostly caused by `Teleport` or `Portal` components that render an element somewhere else in the DOM, usually in the document's `<body>`. This is usually done for dialogs or popover components. This renders the element is outside the `ShadowRoot`, so styles are not applied to it.
To fix this, **you need to both provide a target to your app AND pass the target to the `Teleport`/`Portal`**.
First, store the reference to the `ShadowRoot`'s `<body>` element (not the document's `<body>`):
:::code-group
```ts [Vue]
import { createApp } from 'vue';
import App from './App.vue';
const ui = await create`ShadowRoot`Ui(ctx, {
// ...
onMount: (container, shadow) => {
const teleportTarget = shadow.querySelector('body')!;
const app = createApp(App)
.provide('TeleportTarget', teleportTarget)
.mount(container);
return app;
},
});
ui.mount();
```
```tsx [React]
// hooks/PortalTargetContext.ts
import { createContext } from 'react';
export const PortalTargetContext = createContext<HTMLElement>();
// entrypoints/example.content.ts
import ReactDOM from 'react-dom/client';
import App from './App.tsx';
import PortalTargetContext from '~/hooks/PortalTargetContext';
const ui = await create`ShadowRoot`Ui(ctx, {
// ...
onMount: (container, shadow) => {
const portalTarget = shadow.querySelector('body')!;
const root = ReactDOM.createRoot(container);
root.render(
<PortalTargetContext.Provider value={portalTarget}>
<App />
</PortalTargetContext.Provider>,
);
return root;
},
});
ui.mount();
```
:::
Then use the reference when teleporting/portaling part of your UI to a different place in the DOM:
:::code-group
```vue [Vue]
<script lang="ts" setup>
import { Teleport } from 'vue';
const teleportTarget = inject('TeleportTarget');
</script>
<template>
<div>
<Teleport :to="teleportTarget">
<dialog>My dialog</dialog>
</Teleport>
</div>
</template>
```
```tsx [React]
import { useContext } from 'react';
import { createPortal } from 'react-dom';
import PortalTargetContext from '~/hooks/PortalTargetContext';
const MyComponent = () => {
const portalTarget = useContext(PortalTargetContext);
return <div>{createPortal(<dialog>My dialog</dialog>, portalTarget)}</div>;
};
```
:::
If you use ShadCN, [see this blog post](https://aabidk.dev/blog/building-modern-cross-browser-web-extensions-content-scripts-and-ui/#using-radixui-portals-to-move-the-dialog-to-shadow-dom).
::::::
Both issues have the same cause: the library puts something outside the `ShadowRoot`, and the `ShadowRoot`'s isolation prevents CSS from being applied to your UI.
Both issues have the same fix: tell the library to put elements inside the `ShadowRoot`, not outside it. See the details above for more information and example fixes for each problem.
```ts
import 'vuetify/styles'; // <-- This line imports the CSS, just like importing a .css file
import { createVuetify } from 'vuetify';
```
+269
View File
@@ -0,0 +1,269 @@
# WXT Analytics
Report analytics events from your web extension extension.
## Supported Analytics Providers
- [Google Analytics 4 (Measurement Protocol)](#google-analytics-4-measurement-protocol)
- [Umami](#umami)
## Install With WXT
1. Install the NPM package:
```bash
pnpm i @wxt-dev/analytics
```
2. In your `wxt.config.ts`, add the WXT module:
```ts
export default defineConfig({
modules: ['@wxt-dev/analytics/module'],
});
```
3. In your `<srcDir>/app.config.ts`, add a provider:
```ts
// <srcDir>/app.config.ts
import { umami } from '@wxt-dev/analytics/providers/umami';
export default defineAppConfig({
analytics: {
debug: true,
providers: [
// ...
],
},
});
```
4. Then use the `#analytics` module to report events:
```ts
import { analytics } from '#analytics';
await analytics.track('some-event');
await analytics.page();
await analytics.identify('some-user-id');
analytics.autoTrack(document.body);
```
## Install Without WXT
1. Install the NPM package:
```bash
pnpm i @wxt-dev/analytics
```
2. Create an `analytics` instance:
```ts
// utils/analytics.ts
import { createAnalytics } from '@wxt-dev/analytics';
export const analytics = createAnalytics({
providers: [
// ...
],
});
```
3. Import your analytics module in the background to initialize the message listener:
```ts
// background.ts
import './utils/analytics';
```
4. Then use your `analytics` instance to report events:
```ts
import { analytics } from './utils/analytics';
await analytics.track('some-event');
await analytics.page();
await analytics.identify('some-user-id');
analytics.autoTrack(document.body);
```
## Providers
### Google Analytics 4 (Measurement Protocol)
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.
> [Why use the Measurement Protocol instead of GTag?](https://developer.chrome.com/docs/extensions/how-to/integrate/google-analytics-4#measurement-protocol)
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:
```dotenv
WXT_GA_API_SECRET='...'
```
Then add the `googleAnalytics4` provider to your `<srcDir>/app.config.ts` file:
```ts
import { googleAnalytics4 } from '@wxt-dev/analytics/providers/google-analytics-4';
export default defineAppConfig({
analytics: {
providers: [
googleAnalytics4({
apiSecret: import.meta.env.WXT_GA_API_SECRET,
measurementId: '...',
}),
],
},
});
```
### Umami
[Umami](https://umami.is/) is a privacy-first, open source analytics platform.
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.
After the website has been created, save the website ID and domain to your `.env` file:
```dotenv
WXT_UMAMI_WEBSITE_ID='...'
WXT_UMAMI_DOMAIN='...'
```
Then add the `umami` provider to your `<srcDir>/app.config.ts` file:
```ts
import { umami } from '@wxt-dev/analytics/providers/umami';
export default defineAppConfig({
analytics: {
providers: [
umami({
apiUrl: 'https://<your-umami-instance>/api',
websiteId: import.meta.env.WXT_UMAMI_WEBSITE_ID,
domain: import.meta.env.WXT_UMAMI_DOMAIN,
}),
],
},
});
```
### Custom Provider
If your analytics platform is not supported, you can provide an implementation of the `AnalyticsProvider` type in your `app.config.ts` instead:
```ts
import { defineAnalyticsProvider } from '@wxt-dev/analytics/client';
interface CustomAnalyticsOptions {
// ...
}
const customAnalytics = defineAnalyticsProvider<CustomAnalyticsOptions>(
(analytics, analyticsConfig, providerOptions) => {
// ...
},
);
export default defineAppConfig({
analytics: {
providers: [
customAnalytics({
// ...
}),
],
},
});
```
Example `AnalyticsProvider` implementations can be found at [`./modules/analytics/providers`](https://github.com/wxt-dev/wxt/tree/main/packages/analytics/modules/analytics/providers).
## User Properties
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:
```ts
// app.config.ts
import { storage } from 'wxt/storage';
export default defineAppConfig({
analytics: {
userId: storage.defineItem('local:custom-user-id-key'),
userProperties: storage.defineItem('local:custom-user-properties-key'),
},
});
```
To set the values at runtime, use the `identify` function:
```ts
await analytics.identify(userId, userProperties);
```
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:
```ts
// app.config.ts
import { storage } from 'wxt/storage';
export default defineAppConfig({
analytics: {
userId: storage.defineItem('local:custom-user-id-key', {
init: () => crypto.randomUUID(),
}),
},
});
```
If you aren't using `wxt` or `@wxt-dev/storage`, you can define custom implementations for the `userId` and `userProperties` config:
```ts
const analytics = createAnalytics({
userId: {
getValue: () => ...,
setValue: (userId) => ...,
}
})
```
## Auto-track UI events
Call `analytics.autoTrack(container)` to automatically track UI events so you don't have to manually add them. Currently it:
- Tracks clicks to elements inside the `container`
In your extension's HTML pages, you'll want to call it with `document`:
```ts
analytics.autoTrack(document);
```
But in content scripts, you usually only care about interactions with your own UI:
```ts
const ui = createIntegratedUi({
// ...
onMount(container) {
analytics.autoTrack(container);
},
});
ui.mount();
```
## Enabling/Disabling
By default, **analytics is disabled**. You can configure how the value is stored (and change the default value) via the `enabled` config:
```ts
// app.config.ts
import { storage } from 'wxt/storage';
export default defineAppConfig({
analytics: {
enabled: storage.defineItem('local:analytics-enabled', {
fallback: true,
}),
},
});
```
At runtime, you can call `setEnabled` to change the value:
```ts
analytics.setEnabled(true);
```
+20
View File
@@ -0,0 +1,20 @@
import { defineAppConfig } from 'wxt/sandbox';
import { googleAnalytics4 } from './modules/analytics/providers/google-analytics-4';
import { umami } from './modules/analytics/providers/umami';
export default defineAppConfig({
analytics: {
debug: true,
providers: [
googleAnalytics4({
apiSecret: '...',
measurementId: '...',
}),
umami({
apiUrl: 'https://umami.aklinker1.io/api',
domain: 'analytics.wxt.dev',
websiteId: '8f1c2aa4-fad3-406e-a5b2-33e8d4501716',
}),
],
},
});
+21
View File
@@ -0,0 +1,21 @@
import { defineBuildConfig } from 'unbuild';
import { resolve } from 'node:path';
// Build module and plugins
export default defineBuildConfig({
rootDir: 'modules/analytics',
outDir: resolve(__dirname, 'dist'),
entries: [
{ input: 'index.ts', name: 'module' },
{ input: 'client.ts', name: 'index' },
'background-plugin.ts',
'types.ts',
'providers/google-analytics-4.ts',
'providers/umami.ts',
],
externals: ['#analytics'],
replace: {
'import.meta.env.NPM': 'true',
},
declaration: true,
});
@@ -0,0 +1,17 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Popup</title>
</head>
<body>
<label>
<input id="enabledCheckbox" type="checkbox" />
&emsp;Analytics enabled
</label>
<button id="button1">Button 1</button>
<button class="cool-button">Button 2</button>
<script type="module" src="./main.ts"></script>
</body>
</html>
@@ -0,0 +1,9 @@
import { analytics } from '#analytics';
declare const enabledCheckbox: HTMLInputElement;
analytics.autoTrack(document);
enabledCheckbox.oninput = () => {
void analytics.setEnabled(enabledCheckbox.checked);
};
@@ -0,0 +1,3 @@
import '#analytics';
export default () => {};
@@ -0,0 +1,288 @@
import { UAParser } from 'ua-parser-js';
import type {
Analytics,
AnalyticsConfig,
AnalyticsPageViewEvent,
AnalyticsStorageItem,
AnalyticsTrackEvent,
BaseAnalyticsEvent,
AnalyticsEventMetadata,
AnalyticsProvider,
} from './types';
const ANALYTICS_PORT = '@wxt-dev/analytics';
export function createAnalytics(config?: AnalyticsConfig): Analytics {
if (typeof chrome === 'undefined' || !chrome?.runtime?.id)
throw Error(
'Cannot use WXT analytics in contexts without access to the browser.runtime APIs',
);
if (config == null) {
console.warn(
"[@wxt-dev/analytics] Config not provided to createAnalytics. If you're using WXT, add the 'analytics' property to '<srcDir>/app.config.ts'.",
);
}
// TODO: This only works for standard WXT extensions, add a more generic
// background script detector that works with non-WXT projects.
if (location.pathname === '/background.js')
return createBackgroundAnalytics(config);
return createFrontendAnalytics();
}
/**
* Creates an analytics client in the background responsible for uploading events to the server to avoid CORS errors.
*/
function createBackgroundAnalytics(
config: AnalyticsConfig | undefined,
): Analytics {
// User properties storage
const userIdStorage =
config?.userId ?? defineStorageItem<string>('wxt-analytics:user-id');
const userPropertiesStorage =
config?.userProperties ??
defineStorageItem<Record<string, string>>(
'wxt-analytics:user-properties',
{},
);
const enabled =
config?.enabled ??
defineStorageItem<boolean>('local:wxt-analytics:enabled', false);
// Cached values
const platformInfo = chrome.runtime.getPlatformInfo();
const userAgent = UAParser();
let userId = Promise.resolve(userIdStorage.getValue()).then(
(id) => id ?? globalThis.crypto.randomUUID(),
);
let userProperties = userPropertiesStorage.getValue();
const manifest = chrome.runtime.getManifest();
const getBackgroundMeta = () => ({
timestamp: Date.now(),
// Don't track sessions for the background, it can be running
// indefinitely, and will inflate session duration stats.
sessionId: undefined,
language: navigator.language,
referrer: undefined,
screen: undefined,
url: location.href,
title: undefined,
});
const getBaseEvent = async (
meta: AnalyticsEventMetadata,
): Promise<BaseAnalyticsEvent> => {
const platform = await platformInfo;
return {
meta,
user: {
id: await userId,
properties: {
version: config?.version ?? manifest.version_name ?? manifest.version,
wxtMode: import.meta.env.MODE,
wxtBrowser: import.meta.env.BROWSER,
arch: platform.arch,
os: platform.os,
browser: userAgent.browser.name,
browserVersion: userAgent.browser.version,
...(await userProperties),
},
},
};
};
const analytics = {
identify: async (
newUserId: string,
newUserProperties: Record<string, string> = {},
meta: AnalyticsEventMetadata = getBackgroundMeta(),
) => {
// Update in-memory cache for all providers
userId = Promise.resolve(newUserId);
userProperties = Promise.resolve(newUserProperties);
// Persist user info to storage
await Promise.all([
userIdStorage.setValue?.(newUserId),
userPropertiesStorage.setValue?.(newUserProperties),
]);
// Notify providers
const event = await getBaseEvent(meta);
if (config?.debug) console.debug('[@wxt-dev/analytics] identify', event);
if (await enabled.getValue()) {
await Promise.allSettled(
providers.map((provider) => provider.identify(event)),
);
} else if (config?.debug) {
console.debug(
'[@wxt-dev/analytics] Analytics disabled, identify() not uploaded',
);
}
},
page: async (
location: string,
meta: AnalyticsEventMetadata = getBackgroundMeta(),
) => {
const baseEvent = await getBaseEvent(meta);
const event: AnalyticsPageViewEvent = {
...baseEvent,
page: {
url: meta?.url ?? globalThis.location?.href,
location,
title: meta?.title ?? globalThis.document?.title,
},
};
if (config?.debug) console.debug('[@wxt-dev/analytics] page', event);
if (await enabled.getValue()) {
await Promise.allSettled(
providers.map((provider) => provider.page(event)),
);
} else if (config?.debug) {
console.debug(
'[@wxt-dev/analytics] Analytics disabled, page() not uploaded',
);
}
},
track: async (
eventName: string,
eventProperties?: Record<string, string>,
meta: AnalyticsEventMetadata = getBackgroundMeta(),
) => {
const baseEvent = await getBaseEvent(meta);
const event: AnalyticsTrackEvent = {
...baseEvent,
event: { name: eventName, properties: eventProperties },
};
if (config?.debug) console.debug('[@wxt-dev/analytics] track', event);
if (await enabled.getValue()) {
await Promise.allSettled(
providers.map((provider) => provider.track(event)),
);
} else if (config?.debug) {
console.debug(
'[@wxt-dev/analytics] Analytics disabled, track() not uploaded',
);
}
},
setEnabled: async (newEnabled) => {
await enabled.setValue?.(newEnabled);
},
autoTrack: () => {
// Noop, background doesn't have a UI
return () => {};
},
} satisfies Analytics;
const providers =
config?.providers?.map((provider) => provider(analytics, config)) ?? [];
// Listen for messages from the rest of the extension
chrome.runtime.onConnect.addListener((port) => {
if (port.name === ANALYTICS_PORT) {
port.onMessage.addListener(({ fn, args }) => {
// @ts-expect-error: Untyped fn key
void analytics[fn]?.(...args);
});
}
});
return analytics;
}
/**
* Creates an analytics client for non-background contexts.
*/
function createFrontendAnalytics(): Analytics {
const port = chrome.runtime.connect({ name: ANALYTICS_PORT });
const sessionId = Date.now();
const getFrontendMetadata = (): AnalyticsEventMetadata => ({
sessionId,
timestamp: Date.now(),
language: navigator.language,
referrer: globalThis.document?.referrer || undefined,
screen: globalThis.window
? `${globalThis.window.screen.width}x${globalThis.window.screen.height}`
: undefined,
url: location.href,
title: document.title || undefined,
});
const methodForwarder =
(fn: string) =>
(...args: any[]) => {
port.postMessage({ fn, args: [...args, getFrontendMetadata()] });
};
const analytics: Analytics = {
identify: methodForwarder('identify'),
page: methodForwarder('page'),
track: methodForwarder('track'),
setEnabled: methodForwarder('setEnabled'),
autoTrack: (root) => {
const onClick = (event: Event) => {
const element = event.target as any;
if (
!element ||
(!INTERACTIVE_TAGS.has(element.tagName) &&
!INTERACTIVE_ROLES.has(element.getAttribute('role')))
)
return;
void analytics.track('click', {
tagName: element.tagName?.toLowerCase(),
id: element.id || undefined,
className: element.className || undefined,
textContent: element.textContent?.substring(0, 50) || undefined, // Limit text content length
href: element.href,
});
};
root.addEventListener('click', onClick, { capture: true, passive: true });
return () => {
root.removeEventListener('click', onClick);
};
},
};
return analytics;
}
function defineStorageItem<T>(
key: string,
defaultValue?: NonNullable<T>,
): AnalyticsStorageItem<T> {
return {
getValue: async () =>
(await chrome.storage.local.get(key))[key] ?? defaultValue,
setValue: (newValue) => chrome.storage.local.set({ [key]: newValue }),
};
}
const INTERACTIVE_TAGS = new Set([
'A',
'BUTTON',
'INPUT',
'SELECT',
'TEXTAREA',
]);
const INTERACTIVE_ROLES = new Set([
'button',
'link',
'checkbox',
'menuitem',
'tab',
'radio',
]);
export function defineAnalyticsProvider<T = never>(
definition: (
/** The analytics object. */
analytics: Analytics,
/** Config passed into the analytics module from `app.config.ts`. */
config: AnalyticsConfig,
/** Provider options */
options: T,
) => ReturnType<AnalyticsProvider>,
): (options: T) => AnalyticsProvider {
return (options) => (analytics, config) =>
definition(analytics, config, options);
}
@@ -0,0 +1,91 @@
import 'wxt';
import 'wxt/sandbox';
import {
addAlias,
addViteConfig,
addWxtPlugin,
defineWxtModule,
} from 'wxt/modules';
import { relative, resolve } from 'node:path';
import type { AnalyticsConfig } from './types';
declare module 'wxt/sandbox' {
export interface WxtAppConfig {
analytics: AnalyticsConfig;
}
}
export default defineWxtModule({
name: 'analytics',
imports: [{ name: 'analytics', from: '#analytics' }],
setup(wxt) {
// Paths
const wxtAnalyticsFolder = resolve(wxt.config.wxtDir, 'analytics');
const wxtAnalyticsIndex = resolve(wxtAnalyticsFolder, 'index.ts');
const clientModuleId = import.meta.env.NPM
? '@wxt-dev/analytics'
: resolve(wxt.config.modulesDir, 'analytics/client');
const pluginModuleId = import.meta.env.NPM
? '@wxt-dev/analytics/background-plugin'
: resolve(wxt.config.modulesDir, 'analytics/background-plugin');
// Add required permissions
wxt.hook('build:manifestGenerated', (_, manifest) => {
manifest.permissions ??= [];
if (!manifest.permissions.includes('storage')) {
manifest.permissions.push('storage');
}
});
// Generate #analytics module
const wxtAnalyticsCode = [
`import { createAnalytics } from '${
import.meta.env.NPM
? clientModuleId
: relative(wxtAnalyticsFolder, clientModuleId)
}';`,
`import { useAppConfig } from 'wxt/client';`,
``,
`export const analytics = createAnalytics(useAppConfig().analytics);`,
``,
].join('\n');
addAlias(wxt, '#analytics', wxtAnalyticsIndex);
wxt.hook('prepare:types', async (_, entries) => {
entries.push({
path: wxtAnalyticsIndex,
text: wxtAnalyticsCode,
});
});
// Ensure there is a background entrypoint
wxt.hook('entrypoints:resolved', (_, entrypoints) => {
const hasBackground = entrypoints.find(
(entry) => entry.type === 'background',
);
if (!hasBackground) {
entrypoints.push({
type: 'background',
inputPath: 'virtual:user-background',
name: 'background',
options: {},
outputDir: wxt.config.outDir,
skipped: false,
});
}
});
// Ensure analytics is initialized in every context, mainly the background.
// TODO: Once there's a way to filter which entrypoints a plugin is applied to, only apply this to the background
addWxtPlugin(wxt, pluginModuleId);
// Fix issues with dependencies
addViteConfig(wxt, () => ({
optimizeDeps: {
// Ensure the "#analytics" import is processed by vite in the background plugin
exclude: ['@wxt-dev/analytics'],
// Ensure the CJS subdependency is preprocessed into ESM
include: ['@wxt-dev/analytics > ua-parser-js'],
},
}));
},
});
@@ -0,0 +1,73 @@
import { defineAnalyticsProvider } from '../client';
import type { BaseAnalyticsEvent } from '../types';
const DEFAULT_ENGAGEMENT_TIME_IN_MSEC = 100;
export interface GoogleAnalytics4ProviderOptions {
apiSecret: string;
measurementId: string;
}
export const googleAnalytics4 =
defineAnalyticsProvider<GoogleAnalytics4ProviderOptions>(
(_, config, options) => {
const send = async (
data: BaseAnalyticsEvent,
eventName: string,
eventProperties: Record<string, string | undefined> | undefined,
): Promise<void> => {
const url = new URL(
config?.debug ? '/debug/mp/collect' : '/mp/collect',
'https://www.google-analytics.com',
);
if (options.apiSecret)
url.searchParams.set('api_secret', options.apiSecret);
if (options.measurementId)
url.searchParams.set('measurement_id', options.measurementId);
const userProperties = {
language: data.meta.language,
screen: data.meta.screen,
...data.user.properties,
};
const mappedUserProperties = Object.fromEntries(
Object.entries(userProperties).map(([name, value]) => [
name,
value == null ? undefined : { value },
]),
);
await fetch(url.href, {
method: 'POST',
body: JSON.stringify({
client_id: data.user.id,
consent: {
ad_user_data: 'DENIED',
ad_personalization: 'DENIED',
},
user_properties: mappedUserProperties,
events: [
{
name: eventName,
params: {
session_id: data.meta.sessionId,
engagement_time_msec: DEFAULT_ENGAGEMENT_TIME_IN_MSEC,
...eventProperties,
},
},
],
}),
});
};
return {
identify: () => Promise.resolve(), // No-op, user data uploaded in page/track
page: (event) =>
send(event, 'page_view', {
page_title: event.page.title,
page_location: event.page.location,
}),
track: (event) => send(event, event.event.name, event.event.properties),
};
},
);
@@ -0,0 +1,70 @@
import { defineAnalyticsProvider } from '../client';
export interface UmamiProviderOptions {
apiUrl: string;
websiteId: string;
domain: string;
}
export const umami = defineAnalyticsProvider<UmamiProviderOptions>(
(_, config, options) => {
const send = (payload: UmamiPayload) => {
if (config.debug) {
console.debug('[@wxt-dev/analytics] Sending event to Umami:', payload);
}
return fetch(`${options.apiUrl}/send`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({ type: 'event', payload }),
});
};
return {
identify: () => Promise.resolve(), // No-op, user data uploaded in page/track
page: async (event) => {
await send({
name: 'page_view',
website: options.websiteId,
url: event.page.url,
hostname: options.domain,
language: event.meta.language ?? '',
referrer: event.meta.referrer ?? '',
screen: event.meta.screen ?? '',
title: event.page.title ?? '<blank>',
data: event.user.properties,
});
},
track: async (event) => {
await send({
name: event.event.name,
website: options.websiteId,
url: event.meta.url ?? '/',
title: '<blank>',
hostname: options.domain,
language: event.meta.language ?? '',
referrer: event.meta.referrer ?? '',
screen: event.meta.screen ?? '',
data: {
...event.event.properties,
...event.user.properties,
},
});
},
};
},
);
/** @see https://umami.is/docs/api/sending-stats#post-/api/send */
interface UmamiPayload {
hostname?: string;
language?: string;
referrer?: string;
screen?: string;
title?: string;
url?: string;
website: string;
name: string;
data?: Record<string, string | undefined>;
}
@@ -0,0 +1,99 @@
export interface Analytics {
/** Report a page change. */
page: (url: string) => void;
/** Report a custom event. */
track: (eventName: string, eventProperties?: Record<string, string>) => void;
/** Save information about the user. */
identify: (userId: string, userProperties?: Record<string, string>) => void;
/** Automatically setup and track user interactions, returning a function to remove any listeners that were setup. */
autoTrack: (root: Document | ShadowRoot | Element) => () => void;
/** Calls `config.enabled.setValue`. */
setEnabled: (enabled: boolean) => void;
}
export interface AnalyticsConfig {
/**
* Array of providers to send analytics to.
*/
providers: AnalyticsProvider[];
/**
* Enable debug logs and other provider-specific debugging features.
*/
debug?: boolean;
/**
* Your extension's version, reported alongside events.
* @default browser.runtime.getManifest().version`.
*/
version?: string;
/**
* Configure how the enabled flag is persisted. Defaults to using `browser.storage.local`.
*/
enabled?: AnalyticsStorageItem<boolean>;
/**
* Configure how the user Id is persisted. Defaults to using `browser.storage.local`.
*/
userId?: AnalyticsStorageItem<string>;
/**
* Configure how user properties are persisted. Defaults to using `browser.storage.local`.
*/
userProperties?: AnalyticsStorageItem<Record<string, string>>;
}
export interface AnalyticsStorageItem<T> {
getValue: () => T | Promise<T>;
setValue?: (newValue: T) => void | Promise<void>;
}
export type AnalyticsProvider = (
analytics: Analytics,
config: AnalyticsConfig,
) => {
/** Upload a page view event. */
page: (event: AnalyticsPageViewEvent) => Promise<void>;
/** Upload a custom event. */
track: (event: AnalyticsTrackEvent) => Promise<void>;
/** Upload information about the user. */
identify: (event: BaseAnalyticsEvent) => Promise<void>;
};
export interface BaseAnalyticsEvent {
meta: AnalyticsEventMetadata;
user: {
id: string;
properties: Record<string, string | undefined>;
};
}
export interface AnalyticsEventMetadata {
/** Identifier of the session the event was fired from. */
sessionId: number | undefined;
/** `Date.now()` of when the event was reported. */
timestamp: number;
/** Ex: `"1920x1080"`. */
screen: string | undefined;
/** `document.referrer` */
referrer: string | undefined;
/** `navigator.language` */
language: string | undefined;
/** `location.href` */
url: string | undefined;
/** `document.title` */
title: string | undefined;
}
export interface AnalyticsPageInfo {
url: string;
title: string | undefined;
location: string | undefined;
}
export interface AnalyticsPageViewEvent extends BaseAnalyticsEvent {
page: AnalyticsPageInfo;
}
export interface AnalyticsTrackEvent extends BaseAnalyticsEvent {
event: {
name: string;
properties?: Record<string, string>;
};
}
+65
View File
@@ -0,0 +1,65 @@
{
"name": "@wxt-dev/analytics",
"version": "0.4.1",
"description": "Add analytics to your web extension",
"repository": {
"type": "git",
"url": "git+https://github.com/wxt-dev/wxt.git",
"directory": "packages/analytics"
},
"license": "MIT",
"type": "module",
"exports": {
".": {
"types": "./dist/index.d.mts",
"default": "./dist/index.mjs"
},
"./module": {
"types": "./dist/module.d.mts",
"default": "./dist/module.mjs"
},
"./background-plugin": {
"types": "./dist/background-plugin.d.mts",
"default": "./dist/background-plugin.mjs"
},
"./types": {
"types": "./dist/types.d.mts"
},
"./providers/google-analytics-4": {
"types": "./dist/providers/google-analytics-4.d.mts",
"default": "./dist/providers/google-analytics-4.mjs"
},
"./providers/umami": {
"types": "./dist/providers/umami.d.mts",
"default": "./dist/providers/umami.mjs"
}
},
"module": "./dist/index.mjs",
"types": "./dist/index.d.ts",
"files": [
"dist"
],
"scripts": {
"dev": "buildc --deps-only -- wxt",
"dev:build": "buildc --deps-only -- wxt build",
"check": "pnpm build && check",
"build": "buildc -- unbuild",
"prepack": "pnpm -s build",
"prepare": "buildc --deps-only -- wxt prepare"
},
"peerDependencies": {
"wxt": ">=0.19.23"
},
"devDependencies": {
"@aklinker1/check": "^1.4.5",
"@types/chrome": "^0.0.268",
"@types/ua-parser-js": "^0.7.39",
"publint": "^0.2.12",
"typescript": "^5.6.3",
"unbuild": "^2.0.0",
"wxt": "workspace:*"
},
"dependencies": {
"ua-parser-js": "^1.0.38"
}
}
View File
+10
View File
@@ -0,0 +1,10 @@
{
"extends": ["../../tsconfig.base.json", "./.wxt/tsconfig.json"],
"compilerOptions": {
"paths": {
"#analytics": ["./.wxt/analytics/index.ts"]
},
"types": ["chrome"]
},
"exclude": ["node_modules", "dist"]
}
+11
View File
@@ -0,0 +1,11 @@
import { defineConfig } from 'wxt';
export default defineConfig({
// Unimport doesn't look for imports in node_modules, so when developing a
// WXT module, we need to disable this to simplify the build process
imports: false,
manifest: {
name: 'Analytics Demo',
},
});
-1
View File
@@ -354,7 +354,6 @@ You'll need to configure it the extension so it knows where your localization fi
# You can check available language ids here: https://code.visualstudio.com/docs/languages/identifiers
languageIds:
- typescript
- typescriptreact
# Look for t("...")
usageMatchRegex:
+1 -1
View File
@@ -52,7 +52,7 @@
"devDependencies": {
"@aklinker1/check": "^1.4.5",
"publint": "^0.2.12",
"solid-js": "^1.9.4",
"solid-js": "^1.9.3",
"typescript": "^5.6.3",
"unbuild": "^2.0.0",
"wxt": "workspace:*"
-12
View File
@@ -1,17 +1,5 @@
# Changelog
## v2.0.3
[compare changes](https://github.com/wxt-dev/wxt/compare/module-svelte-v2.0.2...module-svelte-v2.0.3)
### 🩹 Fixes
- Upgrade `vite-plugin-svelte` to support Vite 6 ([#1375](https://github.com/wxt-dev/wxt/pull/1375))
### ❤️ Contributors
- Eli ([@lishaduck](http://github.com/lishaduck))
## v2.0.2
[compare changes](https://github.com/wxt-dev/wxt/compare/module-svelte-v2.0.1...module-svelte-v2.0.2)
+2 -2
View File
@@ -17,7 +17,7 @@
"email": "aaronklinker1+wxt@gmail.com"
},
"license": "MIT",
"version": "2.0.3",
"version": "2.0.2",
"type": "module",
"main": "./dist/index.cjs",
"module": "./dist/index.mjs",
@@ -46,7 +46,7 @@
"svelte": ">=5"
},
"dependencies": {
"@sveltejs/vite-plugin-svelte": "^4.0.0 || ^5.0.0"
"@sveltejs/vite-plugin-svelte": "^4.0.0"
},
"devDependencies": {
"@aklinker1/check": "^1.4.5",
-17
View File
@@ -1,22 +1,5 @@
# Changelog
## v1.1.0
[compare changes](https://github.com/wxt-dev/wxt/compare/storage-v1.0.1...storage-v1.1.0)
### 🚀 Enhancements
- Add `storage.clear` ([#1368](https://github.com/wxt-dev/wxt/pull/1368))
### 📖 Documentation
- Update link ([654a54a](https://github.com/wxt-dev/wxt/commit/654a54a))
### ❤️ Contributors
- Chengxi ([@chengxilo](http://github.com/chengxilo))
- Aaron ([@aklinker1](http://github.com/aklinker1))
## v1.0.1
[compare changes](https://github.com/wxt-dev/wxt/compare/storage-v1.0.0...storage-v1.0.1)
+1 -1
View File
@@ -1,7 +1,7 @@
{
"name": "@wxt-dev/storage",
"description": "Web extension storage API provided by WXT, supports all browsers.",
"version": "1.1.0",
"version": "1.0.1",
"type": "module",
"repository": {
"type": "git",
@@ -489,18 +489,6 @@ describe('Storage Utils', () => {
});
});
describe('clear', () => {
it('should remove all items', async () => {
await fakeBrowser.storage[storageArea].set({
one: 1,
two: 2,
});
await storage.clear(storageArea);
expect(await fakeBrowser.storage[storageArea].get()).toEqual({});
});
});
describe('removeMeta', () => {
it('should remove all metadata', async () => {
await fakeBrowser.storage[storageArea].set({ count$: { v: 4 } });
+1 -15
View File
@@ -326,10 +326,6 @@ function createStorage(): WxtStorage {
}),
);
},
clear: async (base) => {
const driver = getDriver(base);
await driver.clear();
},
removeMeta: async (key, properties) => {
const { driver, driverKey } = resolveKey(key);
await removeMeta(driver, driverKey, properties);
@@ -538,9 +534,6 @@ function createDriver(storageArea: StorageArea): WxtStorageDriver {
removeItems: async (keys) => {
await getStorageArea().remove(keys);
},
clear: async () => {
await getStorageArea().clear();
},
snapshot: async () => {
return await getStorageArea().get();
},
@@ -681,12 +674,6 @@ export interface WxtStorage {
| { item: WxtStorageItem<any, any>; options?: RemoveItemOptions }
>,
): Promise<void>;
/**
* Removes all items from the provided storage area.
*/
clear(base: StorageArea): Promise<void>;
/**
* Remove the entire metadata for a key, or specific properties by name.
*
@@ -725,7 +712,7 @@ export interface WxtStorage {
/**
* Define a storage item with a default value, type, or versioning.
*
* Read full docs: https://wxt.dev/storage.html#defining-storage-items
* Read full docs: https://wxt.dev/guide/extension-apis/storage.html#defining-storage-items
*/
defineItem<TValue, TMetadata extends Record<string, unknown> = {}>(
key: StorageItemKey,
@@ -743,7 +730,6 @@ interface WxtStorageDriver {
setItems(values: Array<{ key: string; value: any }>): Promise<void>;
removeItem(key: string): Promise<void>;
removeItems(keys: string[]): Promise<void>;
clear(): Promise<void>;
snapshot(): Promise<Record<string, unknown>>;
restoreSnapshot(data: Record<string, unknown>): Promise<void>;
watch<T>(key: string, cb: WatchCallback<T | null>): Unwatch;
+3 -3
View File
@@ -38,10 +38,10 @@ The module can be configured via the `unocss` config:
export default defineConfig({
modules: ['@wxt-dev/unocss'],
unocss: {
// Exclude unocss from running for the background
excludeEntrypoints: ['background'],
// Will only apply unocss for popup/main.ts
entrypoints: ['popup/main.ts'],
},
});
```
Options have JSDocs available in your editor, or you can read them in the source code: [`UnoCSSOptions`](https://github.com/wxt-dev/wxt/blob/main/packages/unocss/src/index.ts).
Options have JSDocs available in your editor, or you can read them in the source code: [`UnoCSSOptions`](https://github.com/wxt-dev/wxt/blob/main/packages/auto-icons/src/index.ts).
+1 -65
View File
@@ -1,69 +1,5 @@
# Changelog
## v0.19.27
[compare changes](https://github.com/wxt-dev/wxt/compare/wxt-v0.19.26...wxt-v0.19.27)
### 🩹 Fixes
- Allow `vite-node@^3.0.0` ([#1378](https://github.com/wxt-dev/wxt/pull/1378))
- Use path triple slash directive for types that are referenced via path ([#1407](https://github.com/wxt-dev/wxt/pull/1407))
- Support `publish-browser-extension` v3.0.0 ([ac92d40](https://github.com/wxt-dev/wxt/commit/ac92d40))
- Respect `inlineConfig.mode` when setting NODE_ENV ([#1416](https://github.com/wxt-dev/wxt/pull/1416))
- Auto-import does not work when using `@vitejs/plugin-vue` alone ([#1412](https://github.com/wxt-dev/wxt/pull/1412))
### ❤️ Contributors
- Jaguar Zhou ([@aiktb](http://github.com/aiktb))
- Alec Larson ([@aleclarson](http://github.com/aleclarson))
- Aaron ([@aklinker1](http://github.com/aklinker1))
- St3h3n <st3h3n@gmail.com>
- Eli ([@lishaduck](http://github.com/lishaduck))
## v0.19.26
[compare changes](https://github.com/wxt-dev/wxt/compare/wxt-v0.19.25...wxt-v0.19.26)
### 🩹 Fixes
- **context:** Deduplicate `wxt:content-script-started` ([#1364](https://github.com/wxt-dev/wxt/pull/1364))
### ❤️ Contributors
- Deniz Uğur ([@DenizUgur](http://github.com/DenizUgur))
## v0.19.25
[compare changes](https://github.com/wxt-dev/wxt/compare/wxt-v0.19.24...wxt-v0.19.25)
### 🩹 Fixes
- Drop support for vite 6.0.9+ until websocket fix is finished ([8e2badc](https://github.com/wxt-dev/wxt/commit/8e2badc))
### ❤️ Contributors
- Aaron ([@aklinker1](http://github.com/aklinker1))
## v0.19.24
[compare changes](https://github.com/wxt-dev/wxt/compare/wxt-v0.19.23...wxt-v0.19.24)
### 🩹 Fixes
- **init:** Remove "experimental" from bun package manager ([b150a52](https://github.com/wxt-dev/wxt/commit/b150a52))
- **web-ext:** Correctly pass `browserConsole` option to open devtools in Firefox ([#1308](https://github.com/wxt-dev/wxt/pull/1308))
- `autoMount` not working if anchor is already present ([#1350](https://github.com/wxt-dev/wxt/pull/1350))
### 🏡 Chore
- Fix typo in CLI docs ([028c601](https://github.com/wxt-dev/wxt/commit/028c601))
### ❤️ Contributors
- 1natsu ([@1natsu172](http://github.com/1natsu172))
- Paulo Pinto ([@psrpinto](https://github.com/psrpinto))
- Aaron ([@aklinker1](http://github.com/aklinker1))
## v0.19.23
[compare changes](https://github.com/wxt-dev/wxt/compare/wxt-v0.19.22...wxt-v0.19.23)
@@ -2839,4 +2775,4 @@ Initial release of WXT. Full support for production builds and initial toolkit f
### 🤖 CI
- Create validation workflow ([#12](https://github.com/wxt-dev/wxt/pull/12))
- Create release workflow ([#13](https://github.com/wxt-dev/wxt/pull/13))
- Create release workflow ([#13](https://github.com/wxt-dev/wxt/pull/13))
+7 -7
View File
@@ -52,10 +52,10 @@ describe('Auto Imports', () => {
----------------------------------------
// Generated by wxt
/// <reference types="wxt/vite-builder-env" />
/// <reference path="./types/paths.d.ts" />
/// <reference path="./types/i18n.d.ts" />
/// <reference path="./types/globals.d.ts" />
/// <reference path="./types/imports.d.ts" />
/// <reference types="./types/paths.d.ts" />
/// <reference types="./types/i18n.d.ts" />
/// <reference types="./types/globals.d.ts" />
/// <reference types="./types/imports.d.ts" />
"
`);
});
@@ -91,9 +91,9 @@ describe('Auto Imports', () => {
----------------------------------------
// Generated by wxt
/// <reference types="wxt/vite-builder-env" />
/// <reference path="./types/paths.d.ts" />
/// <reference path="./types/i18n.d.ts" />
/// <reference path="./types/globals.d.ts" />
/// <reference types="./types/paths.d.ts" />
/// <reference types="./types/i18n.d.ts" />
/// <reference types="./types/globals.d.ts" />
"
`,
);
@@ -236,10 +236,10 @@ describe('TypeScript Project', () => {
----------------------------------------
// Generated by wxt
/// <reference types="wxt/vite-builder-env" />
/// <reference path="./types/paths.d.ts" />
/// <reference path="./types/i18n.d.ts" />
/// <reference path="./types/globals.d.ts" />
/// <reference path="./types/imports.d.ts" />
/// <reference types="./types/paths.d.ts" />
/// <reference types="./types/i18n.d.ts" />
/// <reference types="./types/globals.d.ts" />
/// <reference types="./types/imports.d.ts" />
"
`);
});
+4 -4
View File
@@ -1,7 +1,7 @@
{
"name": "wxt",
"type": "module",
"version": "0.19.27",
"version": "0.19.23",
"description": "Next gen framework for developing web extensions",
"repository": {
"type": "git",
@@ -120,11 +120,11 @@
"perfect-debounce": "^1.0.0",
"picocolors": "^1.1.1",
"prompts": "^2.4.2",
"publish-browser-extension": "^2.3.0 || ^3.0.0",
"publish-browser-extension": "^2.2.2",
"scule": "^1.3.0",
"unimport": "^3.13.1",
"vite": "^5.0.0 || <=6.0.8",
"vite-node": "^2.1.4 || ^3.0.0",
"vite": "^5.0.0 || ^6.0.0",
"vite-node": "^2.1.4",
"web-ext-run": "^0.2.1",
"webextension-polyfill": "^0.12.0"
},
+30 -2
View File
@@ -6,7 +6,8 @@ import type {
WxtResolvedUnimportOptions,
} from '../types';
import { type Unimport, createUnimport } from 'unimport';
import UnimportPlugin from 'unimport/unplugin';
import { Plugin } from 'vite';
import { extname } from 'node:path';
export default defineWxtModule({
name: 'wxt:built-in:unimport',
@@ -52,11 +53,38 @@ export default defineWxtModule({
// Add vite plugin
addViteConfig(wxt, () => ({
plugins: [UnimportPlugin.vite(options)],
plugins: [vitePlugin(unimport)],
}));
},
});
export function vitePlugin(unimport: Unimport): Plugin {
const ENABLED_EXTENSIONS = new Set([
'.js',
'.jsx',
'.ts',
'.tsx',
'.vue',
'.svelte',
]);
return {
name: 'wxt:unimport',
async transform(code, id) {
// Don't transform dependencies
if (id.includes('node_modules')) return;
// Don't transform non-js files
if (!ENABLED_EXTENSIONS.has(extname(id))) return;
const injected = await unimport.injectImports(code, id);
return {
code: injected.code,
map: injected.s.generateMap({ hires: 'boundary', source: id }),
};
},
};
}
async function getImportsDeclarationEntry(
unimport: Unimport,
): Promise<WxtDirFileEntry> {
@@ -42,7 +42,6 @@ export class ContentScriptContext implements AbortController {
private isTopFrame = window.self === window.top;
private abortController: AbortController;
private locationWatcher = createLocationWatcher(this);
private receivedMessageIds = new Set<string>();
constructor(
private readonly contentScriptName: string,
@@ -234,28 +233,19 @@ export class ContentScriptContext implements AbortController {
{
type: ContentScriptContext.SCRIPT_STARTED_MESSAGE_TYPE,
contentScriptName: this.contentScriptName,
messageId: Math.random().toString(36).slice(2),
},
'*',
);
}
verifyScriptStartedEvent(event: MessageEvent) {
const isScriptStartedEvent =
event.data?.type === ContentScriptContext.SCRIPT_STARTED_MESSAGE_TYPE;
const isSameContentScript =
event.data?.contentScriptName === this.contentScriptName;
const isNotDuplicate = !this.receivedMessageIds.has(event.data?.messageId);
return isScriptStartedEvent && isSameContentScript && isNotDuplicate;
}
listenForNewerScripts(options?: { ignoreFirstEvent?: boolean }) {
let isFirst = true;
const cb = (event: MessageEvent) => {
if (this.verifyScriptStartedEvent(event)) {
this.receivedMessageIds.add(event.data.messageId);
if (
event.data?.type === ContentScriptContext.SCRIPT_STARTED_MESSAGE_TYPE &&
event.data?.contentScriptName === this.contentScriptName
) {
const wasFirst = isFirst;
isFirst = false;
if (wasFirst && options?.ignoreFirstEvent) return;
@@ -546,25 +546,6 @@ describe('Content Script UIs', () => {
] as const)(
'built-in UI type: $name',
({ name, createUiFunction, uiSelector }) => {
it('should mount if an anchor already exists at the initialization', async () => {
const onMount = vi.fn(appendTestApp);
ui = await createUiFunction(ctx, {
position: 'inline',
onMount,
anchor: `#parent > #${DYNAMIC_CHILD_ID}`,
page: name === 'iframe' ? '/page.html' : undefined,
name: 'test-component',
});
appendTestElement({ id: DYNAMIC_CHILD_ID });
ui.autoMount();
await runMicrotasks();
await expect
.poll(() => document.querySelector(uiSelector))
.not.toBeNull();
});
it('should mount when an anchor is dynamically added and unmount when an anchor is removed', async () => {
const onMount = vi.fn(appendTestApp);
const onRemove = vi.fn();
@@ -355,11 +355,6 @@ function autoMountUi(
async function observeElement(selector: string | null | undefined) {
let isAnchorExist = !!getAnchor(options);
// Mount if anchor exists at initialization.
if (isAnchorExist) {
uiCallbacks.mount();
}
while (!abortController.signal.aborted) {
try {
const changedAnchor = await waitElement(selector ?? 'body', {
+1 -1
View File
@@ -217,7 +217,7 @@ function getMainDeclarationEntry(references: WxtDirEntry[]): WxtDirFileEntry {
} else if (ref.tsReference) {
const absolutePath = resolve(wxt.config.wxtDir, ref.path);
const relativePath = relative(wxt.config.wxtDir, absolutePath);
lines.push(`/// <reference path="./${normalizePath(relativePath)}" />`);
lines.push(`/// <reference types="./${normalizePath(relativePath)}" />`);
}
});
return {
+1 -2
View File
@@ -21,8 +21,7 @@ export async function registerWxt(
): Promise<void> {
// Default NODE_ENV environment variable before other packages, like vite, do it
// See https://github.com/wxt-dev/wxt/issues/873#issuecomment-2254555523
process.env.NODE_ENV ??=
inlineConfig.mode ?? (command === 'serve' ? 'development' : 'production');
process.env.NODE_ENV ??= command === 'serve' ? 'development' : 'production';
const hooks = createHooks<WxtHooks>();
const config = await resolveConfig(inlineConfig, command);
@@ -7,7 +7,8 @@ import {
resolveAppConfig,
} from '../core/builders/vite/plugins';
import { InlineConfig } from '../types';
import UnimportPlugin from 'unimport/unplugin';
import { vitePlugin as unimportPlugin } from '../builtin-modules/unimport';
import { createUnimport } from 'unimport';
import { registerWxt, wxt } from '../core/wxt';
/**
@@ -38,7 +39,9 @@ export async function WxtVitest(
extensionApiMock(wxt.config),
];
if (wxt.config.imports !== false) {
plugins.push(UnimportPlugin.vite(wxt.config.imports));
const unimport = createUnimport(wxt.config.imports);
await unimport.init();
plugins.push(unimportPlugin(unimport));
}
return plugins;
+117 -45
View File
@@ -83,6 +83,34 @@ importers:
specifier: workspace:*
version: link:packages/wxt
packages/analytics:
dependencies:
ua-parser-js:
specifier: ^1.0.38
version: 1.0.40
devDependencies:
'@aklinker1/check':
specifier: ^1.4.5
version: 1.4.5(typescript@5.6.3)
'@types/chrome':
specifier: ^0.0.268
version: 0.0.268
'@types/ua-parser-js':
specifier: ^0.7.39
version: 0.7.39
publint:
specifier: ^0.2.12
version: 0.2.12
typescript:
specifier: ^5.6.3
version: 5.6.3
unbuild:
specifier: ^2.0.0
version: 2.0.0(sass@1.80.7)(typescript@5.6.3)
wxt:
specifier: workspace:*
version: link:../wxt
packages/auto-icons:
dependencies:
defu:
@@ -195,7 +223,7 @@ importers:
dependencies:
vite-plugin-solid:
specifier: ^2.10.2
version: 2.10.2(solid-js@1.9.4)(vite@5.4.11(@types/node@20.17.6)(sass@1.80.7))
version: 2.10.2(solid-js@1.9.3)(vite@5.4.11(@types/node@20.17.6)(sass@1.80.7))
devDependencies:
'@aklinker1/check':
specifier: ^1.4.5
@@ -204,8 +232,8 @@ importers:
specifier: ^0.2.12
version: 0.2.12
solid-js:
specifier: ^1.9.4
version: 1.9.4
specifier: ^1.9.3
version: 1.9.3
typescript:
specifier: ^5.6.3
version: 5.6.3
@@ -219,7 +247,7 @@ importers:
packages/module-svelte:
dependencies:
'@sveltejs/vite-plugin-svelte':
specifier: ^4.0.0 || ^5.0.0
specifier: ^4.0.0
version: 4.0.0(svelte@5.1.6)(vite@5.4.11(@types/node@20.17.6)(sass@1.80.7))
svelte:
specifier: '>=5'
@@ -448,8 +476,8 @@ importers:
specifier: ^2.4.2
version: 2.4.2
publish-browser-extension:
specifier: ^2.3.0 || ^3.0.0
version: 3.0.0
specifier: ^2.2.2
version: 2.2.2
scule:
specifier: ^1.3.0
version: 1.3.0
@@ -457,10 +485,10 @@ importers:
specifier: ^3.13.1
version: 3.13.1(rollup@4.24.0)(webpack-sources@3.2.3)
vite:
specifier: ^5.0.0 || <=6.0.8
specifier: ^5.0.0 || ^6.0.0
version: 5.4.11(@types/node@20.17.6)(sass@1.80.7)
vite-node:
specifier: ^2.1.4 || ^3.0.0
specifier: ^2.1.4
version: 2.1.4(@types/node@20.17.6)(sass@1.80.7)
web-ext-run:
specifier: ^0.2.1
@@ -1982,8 +2010,8 @@ packages:
'@types/prompts@2.4.9':
resolution: {integrity: sha512-qTxFi6Buiu8+50/+3DGIWLHM6QuWsEKugJnnP6iv2Mc4ncxE4A/OJkjuVOA+5X0X1S/nq5VJRa8Lu+nwcvbrKA==}
'@types/prop-types@15.7.14':
resolution: {integrity: sha512-gNMvNH49DJ7OJYv+KAKn0Xp45p8PLl6zo2YnvDIbTd4J6MER2BmWN49TG7n9LvkyihINxeKW8+3bfS2yDC9dzQ==}
'@types/prop-types@15.7.9':
resolution: {integrity: sha512-n1yyPsugYNSmHgxDFjicaI2+gCNjsBck8UX9kuofAKlc0h1bL+20oSF72KeNaW2DUlesbEVCFgyV2dPGTiY42g==}
'@types/react-dom@19.0.2':
resolution: {integrity: sha512-c1s+7TKFaDRRxr1TxccIX2u7sfCnc3RxkVyBIUA2lCpyqCF+QoAwQ/CBg7bsMdVwP120HEH143VQezKtef5nCg==}
@@ -1999,6 +2027,9 @@ packages:
'@types/resolve@1.20.2':
resolution: {integrity: sha512-60BCwRFOZCQhDncwQdxxeOEEkbc5dIMccYLwbxsS4TUNeVECQ/pBJ0j09mrHOl/JJvpRPGwO9SvE4nR2Nb/a4Q==}
'@types/ua-parser-js@0.7.39':
resolution: {integrity: sha512-P/oDfpofrdtF5xw433SPALpdSchtJmY7nsJItf8h3KXqOslkbySh8zq4dSWXH2oTjRvJ5PczVEoCZPow6GicLg==}
'@types/unist@3.0.2':
resolution: {integrity: sha512-dqId9J8K/vGi5Zr7oo212BGii5m3q5Hxlkwy3WpYuKPklmBEvsbMYYyLxAQpSffdLl/gdW0XUpKWFvYmyoWCoQ==}
@@ -2262,6 +2293,10 @@ packages:
ansi-align@3.0.1:
resolution: {integrity: sha512-IOfwwBF5iczOjp/WeY4YxyjqAFMQoZufdQWDd19SEExbVLNXqvpzSJ/M7Za4/sCPmQ0+GRquoA7bGcINcxew6w==}
ansi-escapes@6.2.0:
resolution: {integrity: sha512-kzRaCqXnpzWs+3z5ABPQiVke+iq0KXkHo8xiWV4RPTi5Yli0l97BEQuhXV1s7+aSU/fu1kUuxgS4MsQ0fRuygw==}
engines: {node: '>=14.16'}
ansi-escapes@7.0.0:
resolution: {integrity: sha512-GdYO7a61mR0fOlAsvC9/rIHf7L96sBc6dEWzeOu+KAea5bZyQRPIpojrVoI4AXGJS/ycu/fBTdLrUkA4ODrvjw==}
engines: {node: '>=18'}
@@ -2899,6 +2934,10 @@ packages:
resolution: {integrity: sha512-k0er2gUkLf8O0zKJiAhmkTnJlTvINGv7ygDNPbeIsX/TJjGJZHuh9B2UxbsaEkmlEo9MfhrSzmhIlhRlI2GXnw==}
engines: {node: '>=6'}
escalade@3.1.2:
resolution: {integrity: sha512-ErCHMCae19vR8vQGe50xIsVomy19rg6gFu3+r3jkEO46suLMWBksvVyoGgQV+jOfl84ZSOSlmv6Gxa89PmTGmA==}
engines: {node: '>=6'}
escalade@3.2.0:
resolution: {integrity: sha512-WUj2qlxaQtO4g6Pq5c29GTcWGDyd8itL8zTlipgECz3JesAiiOKotd8JU6otB3PACgG6xkJUyVhboMS+bje/jA==}
engines: {node: '>=6'}
@@ -3406,10 +3445,6 @@ packages:
resolution: {integrity: sha512-2yTgeWTWzMWkHu6Jp9NKgePDaYHbntiwvYuuJLbbN9vl7DC9DvXKOB2BC3ZZ92D3cvV/aflH0osDfwpHepQ53w==}
hasBin: true
jiti@1.21.7:
resolution: {integrity: sha512-/imKNG4EbWNrVjoNC/1H5/9GFy+tqjGBHCaSsN+P2RnPqjsLmv6UD3Ej+Kj8nBWaRAwyk7kK5ZUc+OEatnTR3A==}
hasBin: true
jiti@2.0.0-beta.3:
resolution: {integrity: sha512-pmfRbVRs/7khFrSAYnSiJ8C0D5GvzkE4Ey2pAvUcJsw1ly/p+7ut27jbJrjY79BpAJQJ4gXYFtK6d1Aub+9baQ==}
hasBin: true
@@ -3491,6 +3526,10 @@ packages:
engines: {node: '>=18.12.0'}
hasBin: true
listr2@8.2.1:
resolution: {integrity: sha512-irTfvpib/rNiD637xeevjO2l3Z5loZmuaRi0L0YE5LfijwVY96oyVn0DFD3o/teAok7nfobMG1THvvcHh/BP6g==}
engines: {node: '>=18.0.0'}
listr2@8.2.5:
resolution: {integrity: sha512-iyAZCeyD+c1gPyE9qpFu8af0Y+MRtmKOncdGoA2S5EY8iFq99dmmvkNnHiWo+pj0s7yH7l3KPIgee77tKpXPWQ==}
engines: {node: '>=18.0.0'}
@@ -3532,6 +3571,10 @@ packages:
resolution: {integrity: sha512-i24m8rpwhmPIS4zscNzK6MSEhk0DUWa/8iYQWxhffV8jkI4Phvs3F+quL5xvS0gdQR0FyTCMMH33Y78dDTzzIw==}
engines: {node: '>=18'}
log-update@6.0.0:
resolution: {integrity: sha512-niTvB4gqvtof056rRIrTZvjNYE4rCUzO6X/X+kYjd7WFxXeJ0NwEFnRxX6ehkvv3jTwrXnNdtAak5XYZuIyPFw==}
engines: {node: '>=18'}
log-update@6.1.0:
resolution: {integrity: sha512-9ie8ItPR6tjY5uYJh8K/Zrv/RMZ5VOlOWvtZdEHYSTFKZfIBPQa9tOAEeAWhd+AnIneLJ22w5fjOYtoutpWq5w==}
engines: {node: '>=18'}
@@ -4217,8 +4260,8 @@ packages:
engines: {node: '>=16'}
hasBin: true
publish-browser-extension@3.0.0:
resolution: {integrity: sha512-gwjH8mIepNqID2VqKIxzT6lmtvkcc5tcWYzrGSUdkeUFFFSHhGp9xx01EZ7j8wPq50dDe0XU5VNbHMAqr6wWAA==}
publish-browser-extension@2.2.2:
resolution: {integrity: sha512-+Kr6/S+X51PL6FhMg36yAiFxOFO9O+YQQRVNRD1ItG64Nt+QVmhSKUGJbyLrCwsS4lI0e6kqhxV8r9cy8sAWDQ==}
engines: {node: ^18.0.0 || >=20.0.0}
hasBin: true
@@ -4412,14 +4455,14 @@ packages:
engines: {node: '>=10'}
hasBin: true
seroval-plugins@1.2.1:
resolution: {integrity: sha512-H5vs53+39+x4Udwp4J5rNZfgFuA+Lt+uU+09w1gYBVWomtAl98B+E9w7yC05Xc81/HgLvJdlyqJbU0fJCKCmdw==}
seroval-plugins@1.1.0:
resolution: {integrity: sha512-KtcJg590L3X3dd7ixs6am4UGVcV69TyjYhHtanIdQJq4dy2OceWXmmvWrYx7oFDNe+LNdxdWd0I5BQXuV5fBhA==}
engines: {node: '>=10'}
peerDependencies:
seroval: ^1.0
seroval@1.2.1:
resolution: {integrity: sha512-yBxFFs3zmkvKNmR0pFSU//rIsYjuX418TnlDmc2weaq5XFDqDIV/NOMPBoLrbxjLH42p4UzRuXHryXh9dYcKcw==}
seroval@1.1.0:
resolution: {integrity: sha512-74Wpe+hhPx4V8NFe00I2Fu9gTJopKoH5vE7nCqFzVgKOXV8AnN23T58K79QLYQotzGpH93UZ+UN2Y11j9huZJg==}
engines: {node: '>=10'}
set-value@4.1.0:
@@ -4489,8 +4532,8 @@ packages:
resolution: {integrity: sha512-bSiSngZ/jWeX93BqeIAbImyTbEihizcwNjFoRUIY/T1wWQsfsm2Vw1agPKylXvQTU7iASGdHhyqRlqQzfz+Htg==}
engines: {node: '>=18'}
solid-js@1.9.4:
resolution: {integrity: sha512-ipQl8FJ31bFUoBNScDQTG3BjN6+9Rg+Q+f10bUbnO6EOTTf5NGerJeHc7wyu5I4RMHEl/WwZwUmy/PTRgxxZ8g==}
solid-js@1.9.3:
resolution: {integrity: sha512-5ba3taPoZGt9GY3YlsCB24kCg0Lv/rie/HTD4kG6h4daZZz7+yK02xn8Vx8dLYBc9i6Ps5JwAbEiqjmKaLB3Ag==}
solid-refresh@0.6.3:
resolution: {integrity: sha512-F3aPsX6hVw9ttm5LYlth8Q15x6MlI/J3Dn+o3EQyRTtTxidepSTwAYdozt01/YA+7ObcciagGEyXIopGZzQtbA==}
@@ -4759,6 +4802,10 @@ packages:
engines: {node: '>=14.17'}
hasBin: true
ua-parser-js@1.0.40:
resolution: {integrity: sha512-z6PJ8Lml+v3ichVojCiB8toQJBuwR42ySM4ezjXIqXK3M0HczmKQ3LF4rhU55PfD99KEEXQG6yb7iOMyvYuHew==}
hasBin: true
ufo@1.5.3:
resolution: {integrity: sha512-Y7HYmWaFwPUmkoQCUIAYpKqkOf+SbVj/2fJJZ4RJMCfZp0rTGwRbzQD+HghfnhKOjL9E01okqz+ncJskGYfBNw==}
@@ -6411,7 +6458,7 @@ snapshots:
'@types/node': 20.17.6
kleur: 3.0.3
'@types/prop-types@15.7.14':
'@types/prop-types@15.7.9':
optional: true
'@types/react-dom@19.0.2(@types/react@19.0.1)':
@@ -6420,7 +6467,7 @@ snapshots:
'@types/react@18.3.12':
dependencies:
'@types/prop-types': 15.7.14
'@types/prop-types': 15.7.9
csstype: 3.1.3
optional: true
@@ -6430,6 +6477,8 @@ snapshots:
'@types/resolve@1.20.2': {}
'@types/ua-parser-js@0.7.39': {}
'@types/unist@3.0.2': {}
'@types/web-bluetooth@0.0.20': {}
@@ -6809,6 +6858,10 @@ snapshots:
dependencies:
string-width: 4.2.3
ansi-escapes@6.2.0:
dependencies:
type-fest: 3.13.1
ansi-escapes@7.0.0:
dependencies:
environment: 1.1.0
@@ -7521,6 +7574,8 @@ snapshots:
escalade@3.1.1: {}
escalade@3.1.2: {}
escalade@3.2.0: {}
escape-goat@4.0.0: {}
@@ -7867,7 +7922,7 @@ snapshots:
debug: 4.3.7
esbuild: 0.21.5
jiti: 2.0.0-beta.3
jiti-v1: jiti@1.21.7
jiti-v1: jiti@1.21.6
pathe: 1.1.2
tsx: 4.19.1
transitivePeerDependencies:
@@ -7959,7 +8014,7 @@ snapshots:
is-reference@1.2.1:
dependencies:
'@types/estree': 1.0.6
'@types/estree': 1.0.5
is-reference@3.0.2:
dependencies:
@@ -8026,8 +8081,6 @@ snapshots:
jiti@1.21.6: {}
jiti@1.21.7: {}
jiti@2.0.0-beta.3: {}
js-tokens@4.0.0: {}
@@ -8111,6 +8164,15 @@ snapshots:
transitivePeerDependencies:
- supports-color
listr2@8.2.1:
dependencies:
cli-truncate: 4.0.0
colorette: 2.0.20
eventemitter3: 5.0.1
log-update: 6.0.0
rfdc: 1.4.1
wrap-ansi: 9.0.0
listr2@8.2.5:
dependencies:
cli-truncate: 4.0.0
@@ -8151,6 +8213,14 @@ snapshots:
chalk: 5.3.0
is-unicode-supported: 1.3.0
log-update@6.0.0:
dependencies:
ansi-escapes: 6.2.0
cli-cursor: 4.0.0
slice-ansi: 7.1.0
strip-ansi: 7.1.0
wrap-ansi: 9.0.0
log-update@6.1.0:
dependencies:
ansi-escapes: 7.0.0
@@ -8798,7 +8868,7 @@ snapshots:
dependencies:
nanoid: 3.3.7
picocolors: 1.1.1
source-map-js: 1.2.1
source-map-js: 1.2.0
postcss@8.4.47:
dependencies:
@@ -8839,7 +8909,7 @@ snapshots:
picocolors: 1.1.1
sade: 1.8.1
publish-browser-extension@3.0.0:
publish-browser-extension@2.2.2:
dependencies:
cac: 6.7.14
cli-highlight: 2.1.11
@@ -8847,11 +8917,11 @@ snapshots:
dotenv: 16.4.5
extract-zip: 2.0.1
formdata-node: 6.0.3
listr2: 8.2.5
listr2: 8.2.1
lodash.camelcase: 4.3.0
lodash.kebabcase: 4.1.1
lodash.snakecase: 4.1.1
ofetch: 1.4.1
ofetch: 1.4.0
open: 9.1.0
ora: 6.3.1
prompts: 2.4.2
@@ -9060,11 +9130,11 @@ snapshots:
semver@7.6.3: {}
seroval-plugins@1.2.1(seroval@1.2.1):
seroval-plugins@1.1.0(seroval@1.1.0):
dependencies:
seroval: 1.2.1
seroval: 1.1.0
seroval@1.2.1: {}
seroval@1.1.0: {}
set-value@4.1.0:
dependencies:
@@ -9157,18 +9227,18 @@ snapshots:
ansi-styles: 6.2.1
is-fullwidth-code-point: 5.0.0
solid-js@1.9.4:
solid-js@1.9.3:
dependencies:
csstype: 3.1.3
seroval: 1.2.1
seroval-plugins: 1.2.1(seroval@1.2.1)
seroval: 1.1.0
seroval-plugins: 1.1.0(seroval@1.1.0)
solid-refresh@0.6.3(solid-js@1.9.4):
solid-refresh@0.6.3(solid-js@1.9.3):
dependencies:
'@babel/generator': 7.24.7
'@babel/helper-module-imports': 7.24.7
'@babel/types': 7.24.7
solid-js: 1.9.4
solid-js: 1.9.3
transitivePeerDependencies:
- supports-color
@@ -9416,6 +9486,8 @@ snapshots:
typescript@5.6.3: {}
ua-parser-js@1.0.40: {}
ufo@1.5.3: {}
ufo@1.5.4: {}
@@ -9568,7 +9640,7 @@ snapshots:
update-browserslist-db@1.0.16(browserslist@4.23.1):
dependencies:
browserslist: 4.23.1
escalade: 3.2.0
escalade: 3.1.2
picocolors: 1.1.1
update-browserslist-db@1.1.1(browserslist@4.24.0):
@@ -9627,14 +9699,14 @@ snapshots:
- supports-color
- terser
vite-plugin-solid@2.10.2(solid-js@1.9.4)(vite@5.4.11(@types/node@20.17.6)(sass@1.80.7)):
vite-plugin-solid@2.10.2(solid-js@1.9.3)(vite@5.4.11(@types/node@20.17.6)(sass@1.80.7)):
dependencies:
'@babel/core': 7.24.7
'@types/babel__core': 7.20.5
babel-preset-solid: 1.8.17(@babel/core@7.24.7)
merge-anything: 5.1.7
solid-js: 1.9.4
solid-refresh: 0.6.3(solid-js@1.9.4)
solid-js: 1.9.3
solid-refresh: 0.6.3(solid-js@1.9.3)
vite: 5.4.11(@types/node@20.17.6)(sass@1.80.7)
vitefu: 0.2.5(vite@5.4.11(@types/node@20.17.6)(sass@1.80.7))
transitivePeerDependencies:
@@ -9902,7 +9974,7 @@ snapshots:
yargs@16.2.0:
dependencies:
cliui: 7.0.4
escalade: 3.2.0
escalade: 3.1.2
get-caller-file: 2.0.5
require-directory: 2.1.1
string-width: 4.2.3
@@ -23,6 +23,15 @@ a:hover {
color: #535bf2;
}
a {
font-weight: 500;
color: #646cff;
text-decoration: inherit;
}
a:hover {
color: #535bf2;
}
body {
margin: 0;
display: flex;