Compare commits

...

56 Commits

Author SHA1 Message Date
GitHub Actions 44e4bc5295 chore(release): v0.8.0 2023-10-14 15:38:11 +00:00
Aaron f464d7d33f chore(deps): Use NodeJS v20 for development (#170) 2023-10-14 10:28:34 -05:00
Aaron d0672739f0 chore(deps): Upgrade vite to 4.4.11 (#169) 2023-10-14 10:19:00 -05:00
Aaron 44464f914f feat!: Use defineUnlistedScript to define unlisted scripts (#167)
BREAKING CHANGE: Unlisted scripts must now `export default defineUnlistedScript(...)`
2023-10-14 10:06:52 -05:00
Aaron 8940c41bdb chore(deps): Upgrade vitest to 0.34.6 (#168) 2023-10-14 10:06:20 -05:00
Aaron Klinker 446f265b6c types!: Rename BackgroundScriptDefintition to BackgroundDefinition 2023-10-14 09:41:07 -05:00
渣渣120 7a465684c0 docs: Fix wrong links (#166) 2023-10-14 08:09:46 -05:00
GitHub Actions 0369316463 chore(release): v0.7.5 2023-10-13 23:13:01 +00:00
Aaron 8b74291d18 fix: Add browser_style to popup options (#165) 2023-10-13 18:06:40 -05:00
Aaron 739b738100 fix: Ignore non-manifest fields when merging content script entries (#164) 2023-10-13 18:01:13 -05:00
Aaron 95442dd39b fix: More consistent version_name generation between browsers (#163) 2023-10-13 17:37:08 -05:00
GitHub Actions 4f82645c08 chore(release): v0.7.4 2023-10-11 15:59:17 +00:00
Aaron d200c376f8 fix: Support react-refresh when pre-rendering HTML pages in dev mode (#158) 2023-10-11 10:52:48 -05:00
Aaron Klinker b58fb02016 docs: Add migration guides 2023-10-07 10:49:31 -05:00
Aaron e1bab6c746 chore: Upgrade templates to v0.7 (#156) 2023-10-07 10:00:36 -05:00
GitHub Actions d10c22fbd9 chore(release): v0.7.3 2023-10-07 14:59:25 +00:00
Aaron da1f7f3ea5 feat: Support JS entrypoints (#155) 2023-10-07 09:53:47 -05:00
GitHub Actions 2659272f8a chore(release): v0.7.2 2023-10-05 22:17:59 +00:00
Aaron 868fd27804 feat: Allow customizing entrypoint options per browser (#154) 2023-10-05 17:12:20 -05:00
Aaron Klinker d9fdcb5b33 fix: Add missing persistent type to defineBackgroundScript 2023-10-05 16:08:03 -05:00
Aaron Klinker 580793158f fix: Default safari to MV2 2023-10-05 16:07:20 -05:00
Aaron Klinker f58d69dc5f docs: Add docs for development and testing 2023-10-02 15:05:47 -05:00
Aaron c9028dd335 docs: Restructure website to improve UX (#149) 2023-10-02 09:42:46 -05:00
dependabot[bot] 6342f59c5e chore(deps-dev): bump typescript from 5.1 to 5.2 (#148)
Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
Co-authored-by: Aaron Klinker <aaronklinker1@gmail.com>
2023-10-01 17:58:31 -05:00
dependabot[bot] 2d91898452 chore(deps-dev): bump vitest from 0.34.3 to 0.34.6 (#145)
Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2023-10-01 17:36:48 -05:00
dependabot[bot] 4acefd601c chore(deps-dev): bump vitest-mock-extended from 1.2.1 to 1.3.0 (#147)
Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2023-10-01 17:27:00 -05:00
dependabot[bot] 9a2e71b481 chore(deps-dev): bump @faker-js/faker from 8.0.2 to 8.1.0 (#146)
Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2023-10-01 17:26:20 -05:00
dependabot[bot] 6e578f3156 chore(deps-dev): bump @types/fs-extra from 11.0.1 to 11.0.2 (#144)
Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2023-10-01 17:25:42 -05:00
GitHub Actions 474de83e28 chore(release): v0.7.1 2023-10-01 04:18:14 +00:00
Aaron Klinker 65fcfc0064 docs: Add docs for createContentScriptUi 2023-09-30 23:05:07 -05:00
Aaron Klinker 2d4983e88b chore(release): v0.7.1-alpha1 2023-09-30 21:59:20 -05:00
Aaron 4150e42c05 feat: createContentScriptUi helper (#143) 2023-09-30 21:57:57 -05:00
Aaron 8d7150653a Tweak badge colors for readability 2023-09-30 21:57:16 -05:00
Aaron Klinker 61e57b7b7c Remove all from sync-releases script 2023-09-30 12:49:04 -05:00
Aaron Klinker 83add72312 Update breaking change docs 2023-09-30 12:48:22 -05:00
GitHub Actions 3c723d2c92 chore(release): v0.7.0 2023-09-30 17:45:03 +00:00
Aaron Klinker 1eb35c7207 Reduce codecov requirement to 80% 2023-09-30 12:38:14 -05:00
Aaron 725ecf7c64 fix: Reorder typescript paths to give priority to @ and ~ over @@ and ~~ (#142) 2023-09-30 12:33:33 -05:00
Aaron 3847092df4 feat: Content script cssInjectionMode (#141) 2023-09-30 12:32:00 -05:00
Aaron 19b11c236f fix!: Output content script CSS to content-scripts/<name>.css (#140)
BREAKING CHANGE: Content script CSS used to be output to `assets/<name>.css`, but is now `content-scripts/<name>.css` to match the docs.
2023-09-30 12:20:41 -05:00
Aaron Klinker 4b2012c489 fix: Validate transformed manifest correctly 2023-09-30 10:32:57 -05:00
Aaron Klinker 0591050f31 chore: Store user config metadata in memory
This will be used in #16
2023-09-30 10:30:25 -05:00
GitHub Actions b15dc7fc11 chore(release): v0.6.6 2023-09-30 15:05:16 +00:00
Aaron 89d15babc2 feat: Disable opening browser automatically during dev mode (#136) 2023-09-30 08:45:24 -05:00
GitHub Actions c616125689 chore(release): v0.6.5 2023-09-30 03:15:10 +00:00
Aaron e97071b7d7 fix: Support loading tsx entrypoints (#134) 2023-09-29 22:08:20 -05:00
Aaron 1fa049c5a7 Update badge colors 2023-09-29 12:43:28 -05:00
Aaron Klinker b48cee9715 fix: Don't crash when <all_urls> matches is used in dev mode 2023-09-29 08:18:56 -05:00
Aaron Klinker 24e69fe1bf docs: Add link to update extensions using WXT 2023-09-28 12:26:29 -05:00
Aaron Klinker 41e154992a docs: Fix DX section sizing 2023-09-28 12:22:56 -05:00
Aaron Klinker 55707932a9 docs: Add more content to the homepage 2023-09-28 12:08:21 -05:00
Aaron Klinker 08115a40ae Add explicit title to homepage 2023-09-28 10:22:20 -05:00
Aaron Klinker 96be879918 docs: Add tags for SEO and socials 2023-09-28 10:13:18 -05:00
Aaron 1fc4ada66d Add badges to README 2023-09-27 12:41:37 -05:00
Aaron Klinker d27f299641 Remove files from coverage 2023-09-27 12:27:58 -05:00
Aaron 7183114370 chore: Code coverage improvements (#131) 2023-09-27 12:21:50 -05:00
133 changed files with 4028 additions and 970 deletions
+8
View File
@@ -0,0 +1,8 @@
coverage:
status:
project:
default:
informational: true
patch:
default:
informational: true
+1 -1
View File
@@ -24,7 +24,7 @@ jobs:
- name: Setup NodeJS
uses: actions/setup-node@v3
with:
node-version: 18
node-version: 20
cache: 'pnpm'
- name: Install dependencies
+7 -2
View File
@@ -26,7 +26,7 @@ jobs:
- name: Setup NodeJS
uses: actions/setup-node@v3
with:
node-version: 18
node-version: 20
cache: 'pnpm'
- name: Install dependencies
@@ -51,6 +51,11 @@ jobs:
- name: Tests
run: pnpm test:coverage --reporter=default --reporter=hanging-process
- name: Upload coverage reports to Codecov
uses: codecov/codecov-action@v3
env:
CODECOV_TOKEN: ${{ secrets.CODECOV_TOKEN }}
project-templates:
name: Project Templates
runs-on: ubuntu-22.04
@@ -66,7 +71,7 @@ jobs:
- name: Setup NodeJS
uses: actions/setup-node@v3
with:
node-version: 18
node-version: 20
cache: 'pnpm'
- name: Install dependencies
+3 -1
View File
@@ -17,5 +17,7 @@ web-ext.config.ts
templates/*/pnpm-lock.yaml
templates/*/yarn.lock
templates/*/package-lock.json
docs/config.md
docs/api/config.md
docs/api/cli.md
stats.html
.tool-versions
+3
View File
@@ -10,4 +10,7 @@ CHANGELOG.md
.prettierignore
*.png
*.svg
*.txt
_gitignore
_redirects
*.svelte
+151
View File
@@ -1,5 +1,156 @@
# Changelog
## v0.8.0
[compare changes](https://github.com/wxt-dev/wxt/compare/v0.7.5...v0.8.0)
### 🚀 Enhancements
- ⚠️ Use `defineUnlistedScript` to define unlisted scripts ([#167](https://github.com/wxt-dev/wxt/pull/167))
### 📖 Documentation
- Fix wrong links ([#166](https://github.com/wxt-dev/wxt/pull/166))
### 🌊 Types
- ⚠️ Rename `BackgroundScriptDefintition` to `BackgroundDefinition` ([446f265](https://github.com/wxt-dev/wxt/commit/446f265))
#### ⚠️ Breaking Changes
- ⚠️ Use `defineUnlistedScript` to define unlisted scripts ([#167](https://github.com/wxt-dev/wxt/pull/167))
- ⚠️ Rename `BackgroundScriptDefintition` to `BackgroundDefinition` ([446f265](https://github.com/wxt-dev/wxt/commit/446f265))
### ❤️ Contributors
- 渣渣120 <WOSHIZHAZHA120@qq.com>
## v0.7.5
[compare changes](https://github.com/wxt-dev/wxt/compare/v0.7.4...v0.7.5)
### 🩹 Fixes
- More consistent `version_name` generation between browsers ([#163](https://github.com/wxt-dev/wxt/pull/163))
- Ignore non-manifest fields when merging content script entries ([#164](https://github.com/wxt-dev/wxt/pull/164))
- Add `browser_style` to popup options ([#165](https://github.com/wxt-dev/wxt/pull/165))
## v0.7.4
[compare changes](https://github.com/wxt-dev/wxt/compare/v0.7.3...v0.7.4)
### 🩹 Fixes
- Support `react-refresh` when pre-rendering HTML pages in dev mode ([#158](https://github.com/wxt-dev/wxt/pull/158))
### 📖 Documentation
- Add migration guides ([b58fb02](https://github.com/wxt-dev/wxt/commit/b58fb02))
### 🏡 Chore
- Upgrade templates to v0.7 ([#156](https://github.com/wxt-dev/wxt/pull/156))
## v0.7.3
[compare changes](https://github.com/wxt-dev/wxt/compare/v0.7.2...v0.7.3)
### 🚀 Enhancements
- Support JS entrypoints ([#155](https://github.com/wxt-dev/wxt/pull/155))
## v0.7.2
[compare changes](https://github.com/wxt-dev/wxt/compare/v0.7.1...v0.7.2)
### 🚀 Enhancements
- Allow customizing entrypoint options per browser ([#154](https://github.com/wxt-dev/wxt/pull/154))
### 🩹 Fixes
- Default safari to MV2 ([5807931](https://github.com/wxt-dev/wxt/commit/5807931))
- Add missing `persistent` type to `defineBackgroundScript` ([d9fdcb5](https://github.com/wxt-dev/wxt/commit/d9fdcb5))
### 📖 Documentation
- Restructure website to improve UX ([#149](https://github.com/wxt-dev/wxt/pull/149))
- Add docs for development and testing ([f58d69d](https://github.com/wxt-dev/wxt/commit/f58d69d))
### 🏡 Chore
- **deps-dev:** Bump @types/fs-extra from 11.0.1 to 11.0.2 ([#144](https://github.com/wxt-dev/wxt/pull/144))
- **deps-dev:** Bump @faker-js/faker from 8.0.2 to 8.1.0 ([#146](https://github.com/wxt-dev/wxt/pull/146))
- **deps-dev:** Bump vitest-mock-extended from 1.2.1 to 1.3.0 ([#147](https://github.com/wxt-dev/wxt/pull/147))
- **deps-dev:** Bump vitest from 0.34.3 to 0.34.6 ([#145](https://github.com/wxt-dev/wxt/pull/145))
- **deps-dev:** Bump typescript from 5.1 to 5.2 ([#148](https://github.com/wxt-dev/wxt/pull/148))
## v0.7.1
[compare changes](https://github.com/wxt-dev/wxt/compare/v0.7.0...v0.7.1)
### 🚀 Enhancements
- `createContentScriptUi` helper ([#143](https://github.com/wxt-dev/wxt/pull/143))
### 📖 Documentation
- Add docs for `createContentScriptUi` ([65fcfc0](https://github.com/wxt-dev/wxt/commit/65fcfc0))
### 🏡 Chore
- **release:** V0.7.1-alpha1 ([2d4983e](https://github.com/wxt-dev/wxt/commit/2d4983e))
## v0.7.0
[compare changes](https://github.com/wxt-dev/wxt/compare/v0.6.6...v0.7.0)
### 🚀 Enhancements
- Content script `cssInjectionMode` ([#141](https://github.com/wxt-dev/wxt/pull/141))
### 🩹 Fixes
- Validate transformed manifest correctly ([4b2012c](https://github.com/wxt-dev/wxt/commit/4b2012c))
- ⚠️ Output content script CSS to `content-scripts/<name>.css` ([#140](https://github.com/wxt-dev/wxt/pull/140))
- Reorder typescript paths to give priority to `@` and `~` over `@@` and `~~` ([#142](https://github.com/wxt-dev/wxt/pull/142))
### 🏡 Chore
- Store user config metadata in memory ([0591050](https://github.com/wxt-dev/wxt/commit/0591050))
#### ⚠️ Breaking Changes
- ⚠️ Content script CSS used to be output to `assets/<name>.css`, but is now `content-scripts/<name>.css` to match the docs. ([#140](https://github.com/wxt-dev/wxt/pull/140))
## v0.6.6
[compare changes](https://github.com/wxt-dev/wxt/compare/v0.6.5...v0.6.6)
### 🚀 Enhancements
- Disable opening browser automatically during dev mode ([#136](https://github.com/wxt-dev/wxt/pull/136))
## v0.6.5
[compare changes](https://github.com/wxt-dev/wxt/compare/v0.6.4...v0.6.5)
### 🩹 Fixes
- Don't crash when `<all_urls>` matches is used in dev mode ([b48cee9](https://github.com/wxt-dev/wxt/commit/b48cee9))
- Support loading `tsx` entrypoints ([#134](https://github.com/wxt-dev/wxt/pull/134))
### 📖 Documentation
- Add tags for SEO and socials ([96be879](https://github.com/wxt-dev/wxt/commit/96be879))
- Add more content to the homepage ([5570793](https://github.com/wxt-dev/wxt/commit/5570793))
- Fix DX section sizing ([41e1549](https://github.com/wxt-dev/wxt/commit/41e1549))
- Add link to update extensions using WXT ([24e69fe](https://github.com/wxt-dev/wxt/commit/24e69fe))
### 🏡 Chore
- Code coverage improvements ([#131](https://github.com/wxt-dev/wxt/pull/131))
## v0.6.4
[compare changes](https://github.com/wxt-dev/wxt/compare/v0.6.3...v0.6.4)
+18 -4
View File
@@ -3,6 +3,20 @@
<span>WXT</span>
</h1>
<p align="center">
<a href="https://www.npmjs.com/package/wxt" target="_blank">
<img alt="npm" src="https://img.shields.io/npm/v/wxt?labelColor=black&color=%234fa048">
</a>
<span> </span>
<img alt="npm" src="https://img.shields.io/npm/dm/wxt?labelColor=black&color=%234fa048">
<span> </span>
<img alt="NPM" src="https://img.shields.io/npm/l/wxt?labelColor=black&color=%234fa048">
<span> </span>
<a href="https://codecov.io/github/wxt-dev/wxt" target="_blank">
<img alt="Codecov" src="https://img.shields.io/codecov/c/github/wxt-dev/wxt?labelColor=black&color=%234fa048">
</a>
</p>
<p align="center">
<span>Next-gen framework for developing web extensions.</span>
<br/>
@@ -14,11 +28,11 @@
<p align="center">
<a href="https://wxt.dev" target="_blank">Get Started</a>
&bull;
<a href="https://wxt.dev/get-started/installation.html" target="_blank">Installation</a>
<a href="https://wxt.dev/guide/installation.html" target="_blank">Installation</a>
&bull;
<a href="https://wxt.dev/guide/background.html" target="_blank">Entrypoints</a>
<a href="https://wxt.dev/entrypoints/background.html" target="_blank">Entrypoints</a>
&bull;
<a href="https://wxt.dev/config.html" target="_blank">Configuration</a>
<a href="https://wxt.dev/api/config.html" target="_blank">Configuration</a>
</p>
![Example CLI Output](./docs/assets/cli-output.png)
@@ -31,7 +45,7 @@ Bootstrap a new project:
pnpx wxt@latest init <project-name>
```
Or see the [installation guide](https://wxt.dev/get-started/installation.html) to get started with WXT.
Or see the [installation guide](https://wxt.dev/guide/installation.html) to get started with WXT.
## Features
+5 -1
View File
@@ -16,9 +16,13 @@
"postinstall": "pnpm -w build && wxt prepare"
},
"dependencies": {
"webextension-polyfill": "^0.10.0"
"webextension-polyfill": "^0.10.0",
"react": "^18.2.0",
"react-dom": "^18.2.0"
},
"devDependencies": {
"@types/react": "^18.2.14",
"@types/react-dom": "^18.2.6",
"@types/webextension-polyfill": "^0.10.0",
"sass": "^1.64.0",
"wxt": "workspace:*"
@@ -1,7 +1,7 @@
import '../../common/style.css';
import ReactDOM from 'react-dom/client';
export default defineContentScript({
matches: ['*://*/*'],
matches: ['<all_urls>'],
async main(ctx) {
console.log(browser.runtime.id);
logId();
@@ -13,6 +13,13 @@ export default defineContentScript({
console.log(n, browser.runtime.id);
}, 1e3);
mountContentScriptUi();
const container = document.createElement('div');
document.body.append(container);
ReactDOM.createRoot(container).render(<SomeComponent />);
},
});
function SomeComponent() {
return <div>Some component</div>;
}
+24
View File
@@ -0,0 +1,24 @@
import '../../common/style.css';
import './style.css';
export default defineContentScript({
matches: ['https://*.duckduckgo.com/*'],
cssInjectionMode: 'ui',
async main(ctx) {
const ui = await createContentScriptUi(ctx, {
name: 'demo-ui',
type: 'inline',
append: 'before',
anchor: 'form[role=search]',
mount: (container) => {
const app = document.createElement('div');
app.textContent = 'Custom content script UI';
container.append(app);
},
});
ui.mount();
setTimeout(ui.remove, 5000);
},
});
+11
View File
@@ -0,0 +1,11 @@
:root {
color-scheme: dark;
color: indianred;
}
html {
background-color: black;
}
div {
padding: 16px;
}
+3
View File
@@ -0,0 +1,3 @@
export default defineUnlistedScript(() => {
console.log('injected');
});
+5 -1
View File
@@ -1,3 +1,7 @@
{
"extends": ["../tsconfig.base.json", "./.wxt/tsconfig.json"]
"extends": ["../tsconfig.base.json", "./.wxt/tsconfig.json"],
"compilerOptions": {
"allowImportingTsExtensions": true,
"jsx": "react-jsx"
}
}
+99 -36
View File
@@ -1,29 +1,68 @@
<script lang="ts" setup>
import useListExtensionDetails from '../composables/useListExtensionDetails';
import { computed } from 'vue';
import useListExtensionDetails, {
ChromeExtension,
} from '../composables/useListExtensionDetails';
// Add extension IDs here. Order doesn't matter, will be sorted by weekly active users
const chromeExtensionIds = [
'ocfdgncpifmegplaglcnglhioflaimkd', // GitHub: Better Line Counts
'mgmdkjcljneegjfajchedjpdhbadklcf', // Anime Skip Player
];
const { data } = useListExtensionDetails(chromeExtensionIds);
const sortedExtensions = computed(() =>
!data.value
? undefined
: [...data.value].sort((l, r) => r.weeklyActiveUsers - l.weeklyActiveUsers),
);
function getStoreUrl(extension: ChromeExtension) {
const url = new URL(extension.storeUrl);
url.searchParams.set('utm_source', 'wxt.dev');
return url.href;
}
</script>
<template>
<section class="vp-doc">
<div class="container">
<h2>Who's Using WXT?</h2>
<p>
Battle tested and ready for production. Explore chrome extensions made
with WXT.
</p>
<ul>
<li v-for="extension of data">
<li v-for="extension of sortedExtensions">
<img
:src="extension.iconUrl"
:alt="`${extension.name} icon`"
referrerpolicy="no-referrer"
/>
<a :href="extension.storeUrl" target="_blank">{{ extension.name }}</a>
<small>{{ extension.shortDescription }}</small>
<div>
<a
:href="getStoreUrl(extension)"
target="_blank"
:title="extension.name"
>{{ extension.name }}</a
>
<p class="description" :title="extension.shortDescription">
{{ extension.shortDescription }}
</p>
<p class="user-count">
{{ extension.weeklyActiveUsers.toLocaleString() }} users
</p>
</div>
</li>
</ul>
<p>Open a PR to add your extension to the list!</p>
<p class="centered pr">
<a
href="https://github.com/wxt-dev/wxt/edit/main/docs/.vitepress/components/UsingWxtSection.vue"
target="_blank"
>Open a PR</a
>
to add your extension to the list!
</p>
</div>
</section>
</template>
@@ -33,10 +72,6 @@ const { data } = useListExtensionDetails(chromeExtensionIds);
padding: 0 24px;
}
h2 {
margin-bottom: 32px;
}
@media (min-width: 640px) {
.vp-doc {
padding: 0 48px;
@@ -56,58 +91,86 @@ h2 {
flex-direction: column;
}
img {
width: 96px;
height: 96px;
margin-bottom: 16px;
li img {
width: 116px;
height: 116px;
padding: 16px;
border-radius: 8px;
background-color: var(--vp-c-default-soft);
}
ul {
display: grid;
grid-template-columns: repeat(2, 1fr);
grid-template-columns: repeat(1, 1fr);
align-items: stretch;
gap: 16px;
list-style: none;
margin: 0;
margin: 16px 0;
padding: 0;
}
@media (min-width: 640px) {
ul {
grid-template-columns: repeat(3, 1fr);
}
}
@media (min-width: 960px) {
ul {
grid-template-columns: repeat(4, 1fr);
grid-template-columns: repeat(2, 1fr);
}
}
li {
margin: 0 !important;
padding: 12px;
padding: 16px;
display: flex;
flex-direction: column;
align-items: center;
background-color: var(--vp-c-bg-soft);
border-radius: 12px;
flex: 1;
}
a,
small {
text-align: center;
}
small {
opacity: 50%;
gap: 16px;
}
p {
.centered {
text-align: center;
opacity: 50%;
}
a {
color: var(--vp-c-text-1);
li a,
li .user-count,
li .description {
padding: 0;
margin: 0;
}
li .user-count {
opacity: 70%;
text-align: right;
width: 100%;
font-size: small;
}
li a {
display: -webkit-box;
-webkit-line-clamp: 1;
-webkit-box-orient: vertical;
overflow: hidden;
cursor: pointer;
padding: 0;
margin: 0;
text-decoration: none;
}
li a:hover {
text-decoration: underline;
}
li div {
flex: 1;
display: flex;
flex-direction: column;
}
li .description {
opacity: 90%;
display: -webkit-box;
-webkit-line-clamp: 2;
-webkit-box-orient: vertical;
overflow: hidden;
flex-grow: 1;
}
.pr {
opacity: 70%;
}
</style>
+78 -36
View File
@@ -1,17 +1,37 @@
import { defineConfig } from 'vitepress';
import { generateConfigDocs } from './plugins/generate-config-docs';
import { generateCliDocs } from './plugins/generate-cli-docs';
const title = 'Next-gen Web Extension Framework';
const titleSuffix = ' WXT';
const description =
"WXT provides the best developer experience, making it quick, easy, and fun to develop chrome extensions for all browsers. With built-in utilties for building, zipping, and publishing your extension, it's easy to get started.";
const ogTitle = `${title}${titleSuffix}`;
const ogUrl = 'https://wxt.dev';
const ogImage = 'https://wxt.dev/social-preview.png';
// https://vitepress.dev/reference/site-config
export default defineConfig({
titleTemplate: `:title${titleSuffix}`,
title: 'WXT',
description,
vite: {
clearScreen: false,
plugins: [generateConfigDocs()],
plugins: [generateConfigDocs(), generateCliDocs()],
},
description: 'Next gen framework for developing web extensions',
lastUpdated: true,
sitemap: {
hostname: 'https://wxt.dev',
},
head: [
['meta', { property: 'og:type', content: 'website' }],
['meta', { property: 'og:title', content: ogTitle }],
['meta', { property: 'og:image', content: ogImage }],
['meta', { property: 'og:url', content: ogUrl }],
['meta', { property: 'og:description', content: description }],
['meta', { name: 'twitter:card', content: 'summary_large_image' }],
[
'script',
{
@@ -24,7 +44,10 @@ export default defineConfig({
themeConfig: {
// https://vitepress.dev/reference/default-theme-config
logo: '/logo.svg',
logo: {
src: '/logo.svg',
alt: 'WXT logo',
},
editLink: {
pattern: 'https://github.com/wxt-dev/wxt/edit/main/docs/:path',
},
@@ -33,56 +56,75 @@ export default defineConfig({
},
nav: [
{ text: 'Get Started', link: '/get-started/installation.md' },
{ text: 'Guide', link: '/guide/auto-imports.md' },
{ text: 'Config', link: '/config.md' },
{ text: 'API', link: '/api.md' },
{ text: 'Guide', link: '/guide/installation.md' },
{ text: 'Entrypoints', link: '/entrypoints/background.md' },
{ text: 'API', link: '/api/cli.md' },
],
sidebar: {
'/get-started/': [
{
text: 'Get Started',
items: [
{ text: 'Introduction', link: '/get-started/introduction.md' },
{ text: 'Installation', link: '/get-started/installation.md' },
{ text: 'Configuration', link: '/get-started/configuration.md' },
{ text: 'Entrypoints', link: '/get-started/entrypoints.md' },
{ text: 'Assets', link: '/get-started/assets.md' },
{ text: 'Build Targets', link: '/get-started/build-targets.md' },
{ text: 'Publishing', link: '/get-started/publishing.md' },
{ text: 'Testing', link: '/get-started/testing.md' },
{ text: 'Compare', link: '/get-started/compare.md' },
],
},
],
'/guide/': [
{
text: 'Guide',
items: [
{ text: 'Introduction', link: '/guide/introduction.md' },
{ text: 'Installation', link: '/guide/installation.md' },
{ text: 'Configuration', link: '/guide/configuration.md' },
{ text: 'Entrypoints', link: '/guide/entrypoints.md' },
{ text: 'Assets', link: '/guide/assets.md' },
{ text: 'Multiple Browsers', link: '/guide/multiple-browsers.md' },
{ text: 'Publishing', link: '/guide/publishing.md' },
{ text: 'Auto-imports', link: '/guide/auto-imports.md' },
{ text: 'Manifest.json', link: '/guide/manifest.md' },
{ text: 'Extension APIs', link: '/guide/extension-apis.md' },
{ text: 'Remote Code', link: '/guide/remote-code.md' },
{ text: 'Development', link: '/guide/development.md' },
{ text: 'Testing', link: '/guide/testing.md' },
{ text: 'Vite', link: '/guide/vite.md' },
],
},
{
text: 'Other',
items: [
{ text: 'Migrate to WXT', link: '/guide/migrate-to-wxt.md' },
{ text: 'Compare', link: '/guide/compare.md' },
],
},
],
'/entrypoints/': [
{
text: 'Entrypoints',
items: [
{ text: 'Background', link: '/guide/background.md' },
{ text: 'Bookmarks', link: '/guide/bookmarks.md' },
{ text: 'Content Scripts', link: '/guide/content-scripts.md' },
{ text: 'CSS', link: '/guide/css.md' },
{ text: 'Devtools', link: '/guide/devtools.md' },
{ text: 'History', link: '/guide/history.md' },
{ text: 'Newtab', link: '/guide/newtab.md' },
{ text: 'Options', link: '/guide/options.md' },
{ text: 'Popup', link: '/guide/popup.md' },
{ text: 'Sandbox', link: '/guide/sandbox.md' },
{ text: 'Sidepanel', link: '/guide/sidepanel.md' },
{ text: 'Unlisted Pages', link: '/guide/unlisted-pages.md' },
{ text: 'Unlisted Scripts', link: '/guide/unlisted-scripts.md' },
{ text: 'Background', link: '/entrypoints/background.md' },
{ text: 'Bookmarks', link: '/entrypoints/bookmarks.md' },
{
text: 'Content Scripts',
link: '/entrypoints/content-scripts.md',
},
{ text: 'CSS', link: '/entrypoints/css.md' },
{ text: 'Devtools', link: '/entrypoints/devtools.md' },
{ text: 'History', link: '/entrypoints/history.md' },
{ text: 'Newtab', link: '/entrypoints/newtab.md' },
{ text: 'Options', link: '/entrypoints/options.md' },
{ text: 'Popup', link: '/entrypoints/popup.md' },
{ text: 'Sandbox', link: '/entrypoints/sandbox.md' },
{ text: 'Sidepanel', link: '/entrypoints/sidepanel.md' },
{ text: 'Unlisted Pages', link: '/entrypoints/unlisted-pages.md' },
{
text: 'Unlisted Scripts',
link: '/entrypoints/unlisted-scripts.md',
},
].sort((l, r) => l.text.localeCompare(r.text)),
},
],
'/api/': [
{
items: [
{ text: 'CLI', link: '/api/cli.md' },
{ text: 'Config', link: '/api/config.md' },
{ text: 'wxt', link: '/api/wxt.md' },
{ text: 'wxt/browser', link: '/api/wxt-browser.md' },
{ text: 'wxt/client', link: '/api/wxt-client.md' },
{ text: 'wxt/sandbox', link: '/api/wxt-sandbox.md' },
],
},
],
@@ -0,0 +1,108 @@
import { relative, resolve } from 'node:path';
import { readFileSync, writeFileSync } from 'node:fs';
import { format } from 'prettier';
import consola from 'consola';
import { execaCommand } from 'execa';
let hasGenerated = false;
const cliDir = resolve('src/cli/commands');
const cliDirGlob = resolve(cliDir, '**');
const cliTemplatePath = resolve('docs/api/cli.tpl.md');
const cliPath = resolve('docs/api/cli.md');
const PREFACE = `<!--
DO NOT EDIT
Generated by \`wxt/docs/.vitepress/plugins/generate-config-docs.ts\`
To make changes to the config reference, update the JSDoc in \`src/core/types/external.ts\`.
-->`;
export function generateCliDocs() {
writeFileSync(cliPath, '');
const generateDocs = async () => {
consola.info(`Generating ${relative(process.cwd(), cliPath)}`);
try {
const res = await execaCommand('pnpm -s wxt --help');
const dev = splitInfo(res.stdout);
const lines: Array<string | string[]> = [
`## \`wxt\``,
'```sh',
dev.rest,
'```',
];
const commands = await Promise.all(
extractCommands(dev.info).map(async (command) => {
const res = await execaCommand(`pnpm -s wxt ${command} --help`);
const { rest: docs } = splitInfo(res.stdout);
return [`## \`wxt ${command}\``, '```sh', docs, '```'];
}),
);
lines.push(...commands);
const text = await format(
PREFACE +
'\n\n' +
readFileSync(cliTemplatePath, 'utf-8').replace(
'{{ DOCS }}',
lines.flat().join('\n'),
),
{ parser: 'markdown' },
);
writeFileSync(cliPath, text);
consola.success(`Generated ${relative(process.cwd(), cliPath)}`);
} catch (err) {
consola.fail(`Failed to generate ${relative(process.cwd(), cliPath)}`);
consola.error(err.message);
}
};
return {
name: 'docs:generate-cli-docs',
async config() {
if (!hasGenerated) {
hasGenerated = true;
await generateDocs();
}
},
configureServer(server: any) {
server.watcher.add(cliDirGlob);
},
async handleHotUpdate(ctx: { file: string }) {
if (ctx.file === cliTemplatePath || ctx.file.includes(cliDir)) {
await generateDocs();
}
},
};
}
function splitInfo(text: string): { info: string; rest: string } {
const infoStart = text.indexOf('For more info,');
const infoEnd = text.indexOf('\n\nOptions:');
if (infoStart === -1 || infoEnd === -1) {
return { info: '', rest: text };
}
const info = text.substring(infoStart, infoEnd).trim();
const rest = text.replace(info, '').trim().replace('\n\n\n\n', '\n\n');
return { info, rest };
}
function extractCommands(info: string): string[] {
const commands: string[] = [];
// Split the info by line and iterate through each line
info.split('\n').forEach((line) => {
// Use regex to capture the command after "$ wxt " and before "--help"
const match = line.match(/\$ wxt (\w+) --help/);
if (match && match[1]) {
commands.push(match[1]);
}
});
return commands;
}
@@ -1,4 +1,4 @@
import { resolve } from 'node:path';
import { relative, resolve } from 'node:path';
import { Project, ts, Type, Node, JSDocableNode } from 'ts-morph';
import { readFileSync, writeFileSync } from 'node:fs';
import { format } from 'prettier';
@@ -7,8 +7,8 @@ import consola from 'consola';
let hasGenerated = false;
const externalTypesPath = resolve('src/core/types/external.ts');
const configTemplatePath = resolve('docs/config.tpl.md');
const configPath = resolve('docs/config.md');
const configTemplatePath = resolve('docs/api/config.tpl.md');
const configPath = resolve('docs/api/config.md');
const PREFACE = `<!--
DO NOT EDIT
@@ -39,7 +39,7 @@ export function generateConfigDocs() {
writeFileSync(configPath, '');
const generateDocs = async () => {
consola.info('Generating /config.md');
consola.info(`Generating ${relative(process.cwd(), configPath)}`);
try {
const project = new Project({
tsConfigFilePath: resolve('tsconfig.json'),
@@ -118,9 +118,9 @@ export function generateConfigDocs() {
);
writeFileSync(configPath, text);
consola.success('Generated /config.md');
consola.success(`Generated ${relative(process.cwd(), configPath)}`);
} catch (err) {
consola.fail('Failed to generate /config.md');
consola.fail(`Failed to generate ${relative(process.cwd(), configPath)}`);
consola.error(err.message);
}
};
-5
View File
@@ -1,5 +0,0 @@
# API Reference
:::warning 🚧&ensp;Under construction
This documentation does not exist yet.
:::
+5
View File
@@ -0,0 +1,5 @@
# CLI Reference
> Reference generated from `wxt <command> --help`
{{ DOCS }}
+5
View File
@@ -0,0 +1,5 @@
# Config Reference
All the options you can use in your `wxt.config.ts` file.
{{ DOCS }}
+10
View File
@@ -0,0 +1,10 @@
# `wxt/browser` Reference
:::warning 🚧&ensp;Under construction
This documentation does not exist yet. All APIs are documented with JSDoc, so for now, you can view the documentation in your editor.
```ts
import { browser } from 'wxt/browser';
```
:::
+14
View File
@@ -0,0 +1,14 @@
# `wxt/client` Reference
:::warning 🚧&ensp;Under construction
This documentation does not exist yet. All APIs are documented with JSDoc, so for now, you can view the documentation in your editor.
```ts
import {
createContentScriptUi,
defineBackground,
defineContentScript,
} from 'wxt/client';
```
:::
+12
View File
@@ -0,0 +1,12 @@
# `wxt/sandbox` Reference
The `wxt/sandbox` module contains exports that do not use the `browser` global (ie: a "sandboxed" environment).
:::warning 🚧&ensp;Under construction
This documentation does not exist yet. All APIs are documented with JSDoc, so for now, you can view the documentation in your editor.
```ts
import { defineUnlistedScript } from 'wxt/sandbox';
```
:::
+17
View File
@@ -0,0 +1,17 @@
# `wxt` Reference
:::warning 🚧&ensp;Under construction
This documentation does not exist yet. All APIs are documented with JSDoc, so for now, you can view the documentation in your editor.
```ts
import {
build,
clean,
createServer,
defineConfig,
defineRunnerConfig,
version,
} from 'wxt';
```
:::
-5
View File
@@ -1,5 +0,0 @@
# Config Reference
Discover all the options you can use in your `wxt.config.ts` file.
{{ DOCS }}
@@ -8,8 +8,8 @@ For MV2, the background is added as a script to the background page. For MV3, th
<EntrypointPatterns
:patterns="[
['background.ts', 'background.js'],
['background/index.ts', 'background.js'],
['background.[jt]s', 'background.js'],
['background/index.[jt]s', 'background.js'],
]"
/>
+292
View File
@@ -0,0 +1,292 @@
# Content Scripts
[Chrome Docs](https://developer.chrome.com/docs/extensions/mv3/content_scripts/) &bull; [Firefox Docs](https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/Content_scripts)
When creating content script entrypoints, they are automatically included in the `manifest.json` along with any CSS files they import.
## Filenames
<EntrypointPatterns
:patterns="[
['content.[jt]sx?', 'content-scripts/content.js'],
['content/index.[jt]sx?', 'content-scripts/content.js'],
['<name>.content.[jt]sx?', 'content-scripts/<name>.js'],
['<name>.content/index.[jt]sx?', 'content-scripts/<name>.js'],
]"
/>
## Definition
```ts
export default defineContentScript({
// Set manifest options
matches: ['*://google.com/*', '*://duckduckgo.com/*'],
excludeMatches: undefined | [],
includeGlobs: undefined | [],
excludeGlobs: undefined | [],
allFrames: undefined | [],
runAt: undefined | 'document_start' | 'document_end' | 'document_idle',
matchAboutBlank: undefined | true | false,
matchOriginAsFallback: undefined | true | false,
world: undefined | 'ISOLATED' | 'MAIN',
// Set include/exclude if the background should be removed from some builds
include: undefined | string[],
exclude: undefined | string[],
// Configure how CSS is injected onto the page
cssInjectionMode: undefined | "manifest" | "manual" | "ui",
main(ctx) {
// Executed when content script is loaded
},
});
```
> All manifest options default to `undefined`.
When defining multiple content scripts, content script entrypoints that have the same set of options will be merged into a single `content_script` item in the manifest.
## Context
Old content scripts are not automatically stopped when an extension updates and reloads. Often, this leads to "Invalidated context" errors in production when a content script from an old version of your extension tries to use a extension API.
WXT provides a utility for managing this process: `ContentScriptContext`. An instance of this class is provided to you automatically inside the `main` function of your content script.
```ts
export default defineContentScript({
// ...
main(ctx: ContentScriptContext) {
// Add custom listeners for stopping work
ctx.onInvalidated(() => {
// ...
});
// Stop fetch requests
fetch('...url', { signal: ctx.signal });
// Timeout utilities
ctx.setTimeout(() => {
// ...
}, 5e3);
ctx.setInterval(() => {
// ...
}, 60e3);
},
});
```
The class extends [`AbortController`](https://developer.mozilla.org/en-US/docs/Web/API/AbortController) and provides other utilities for stopping a content script's logic once it becomes invalidated.
:::tip
When working with content scripts, **you should always use the `ctx` object to stop any async or future work.**
This prevents old content scripts from interfering with new content scripts, and prevents error messages from the console in production.
:::
## CSS
To include CSS with your content script, import the CSS file at the top of your entrypoint.
```
<srcDir>
└─ entrypoints/
└─ overlay.content/
├─ index.ts
└─ style.css
```
```ts
// entrypoints/overlay.content/index.ts
import './style.css';
export default defineContentScript({
matches: ['*://google.com/*', '*://duckduckgo.com/*'],
main(ctx) {
// ...
},
});
```
Any styles imported in your content script will be added to that content script's `css` array in your `manifest.json`:
```json
// .output/chrome-mv3/manifest.json
{
"content_scripts": [
{
"matches": ["*://google.com/*", "*://duckduckgo.com/*"],
"js": ["content-scripts/overlay.js"],
"css": ["content-scripts/overlay.css"]
}
]
}
```
To disable this behavior, set `cssInjectionMode` to `"manual"` or `"ui"`.
```ts
export default defineContentScript({
matches: ['*://google.com/*', '*://duckduckgo.com/*'],
cssInjectionMode: 'manual',
main(ctx) {
// ...
},
});
```
## UI
WXT provides a utility function, `createContentScriptUi` to simplify mounting a UI from a content script. Internally, it uses the `ShadowRoot` API to isolate your CSS from the webpages.
`createContentScriptUi` requires a `ContentScriptContext` so that when the context is invalidated, the UI is automatically removed from the webpage.
:::details When to use `createContentScriptUi`
You should only use `createContentScriptUi` if you want your UI's styles isolated from the webpages. If you want to create a more "integrated" UI that uses the page's styles, you can just use the regular JS API's to append your UI to the page.
```ts
const ui = document.createElement('div');
const anchor = document.querySelector('#anchor-selector');
anchor.append(ui);
```
:::
### Usage
To use `createContentScriptUi`, follow these steps:
1. Import your CSS file at the top of your content script
2. Set `cssInjectionMode: "ui"` inside `defineContentScript`
3. Call `createContentScriptUi`
4. Call `ui.mount()` to add the UI to the webpage
Here's a basic example:
```ts
// entrypoints/ui.content/index.ts
import './style.css';
export default defineContentScript({
// ...
cssInjectionMode: 'ui',
async main(ctx) {
const ui = await createContentScriptUi(ctx, {
name: 'example-ui',
type: 'inline',
anchor: '#some-element',
append: 'after',
mount(container) {
// Mount UI inside `container`...
},
});
// Yoy must call `mount` to add the UI to the page.
ui.mount();
},
});
```
If you're using a frontend framework, you'll also need to include an `onRemoved` callback:
:::code-group
```ts [Vue]
import { createApp } from 'vue';
createContentScriptUi(ctx, {
// ...
mount(container) {
// Create a new app and mount it inside the container
const app = createApp(...);
app.mount(container);
return app;
},
onRemove(app) {
// When the UI is removed from the DOM, call unmount to stop the app
app.unmount();
},
});
```
```ts [React]
import ReactDOM from 'react-dom/client';
createContentScriptUi(ctx, {
// ...
mount(container) {
// Create a root using the container and render your app
const root = ReactDOM.createRoot(container);
root.render(...);
return root;
},
onRemove(root) {
// When the UI is removed from the DOM, call unmount to stop the app
root.unmount();
},
});
```
```ts [Svelte]
import App from './App.svelte';
createContentScriptUi(ctx, {
// ...
mount(container) {
// Mount your app component inside the container
return new App({
target: container,
});
},
onRemove(app) {
// When the UI is removed from the DOM, call $destroy to stop the app
app.$destroy();
},
});
```
```ts [Solid]
import { render } from 'solid-js/web';
createContentScriptUi(ctx, {
// ...
mount(container) {
// Render your app component into the container
return render(() => ..., container)
},
onRemove(unmount) {
// When the UI is removed from the DOM, call unmount to stop the app
unmount();
},
});
```
:::
### `anchor`
The anchor dictates where the UI will be mounted.
### `append`
Customize where the UI get's appended to the DOM, relative to the `anchor` element.
### `type`
There are 3 types of UI's you can mount.
- `inline`: Shows up inline based on the `anchor` and `append` options
- `overlay`: Shows up inline, but styled to be 0px by 0px, with overflow visible. This causes the UI to overlay on top of the webpage's content
- `modal`: A fullscreen overlay that covers the entire screen, regardless of where it's anchored.
> TODO: Add visualization of the different UI types.
### Overlay `alignment`
Because the overlay UI type results in a 0px by 0px container being added to the webpage, the `alignment` option allows you to configure which corner of your UI is aligned with the 0x0 element.
> TODO: Add visualization of the different alignments.
@@ -2,10 +2,10 @@
WXT can build CSS entrypoints individually. CSS entrypoints are always unlisted.
See [Content Script CSS](/guide/content-scripts.md#css) documentation for the recomended approach to include CSS with a content script.
See [Content Script CSS](/entrypoints/content-scripts#css) documentation for the recomended approach to include CSS with a content script.
:::info
If the recommended approach doesn't work for your use case, you can use any of the filename patterns below to build the styles separate from the JS and use the [`transformManifest` hook](/config.md#transformmanifest) to manually add your CSS file to the manifest.
If the recommended approach doesn't work for your use case, you can use any of the filename patterns below to build the styles separate from the JS and use the [`transformManifest` hook](/api/config#transformmanifest) to manually add your CSS file to the manifest.
:::
## Filenames
@@ -29,6 +29,7 @@
}"
/>
<meta name="manifest.type" content="page_action|browser_action" />
<meta name="manifest.browser_style" content="true|false" />
<!-- Set include/exclude if the page should be removed from some builds -->
<meta name="manifest.include" content="['chrome', ...]" />
<meta name="manifest.exclude" content="['chrome', ...]" />
+37
View File
@@ -0,0 +1,37 @@
# Unlisted Scripts
TypeScript files that are built, but are not included in the manifest.
You are responsible for loading/running these scripts where needed.
## Filenames
<EntrypointPatterns
:patterns="[
['<name>.[jt]sx?', '<name>.js'],
['<name>/index.[jt]sx?', '<name>.js'],
]"
/>
## Definition
```ts
export default defineUnlistedScript(() => {
// Executed when script is loaded
});
```
or
```ts
export default defineUnlistedScript({
// Set include/exclude if the script should be removed from some builds
include: undefined | string[],
exclude: undefined | string[],
// Executed when script is loaded
main() {
// ...
},
});
```
-46
View File
@@ -1,46 +0,0 @@
# Build Targets
You can build an extension for any combination of browser and manifest verison. Different browsers and manifest versions support different APIs and entrypoints, so be sure to check that your extension functions as expected for each target.
Separate build targets are written to their own output directories:
```
<rootDir>
└─ .output
├─ chrome-mv3
├─ firefox-mv2
├─ edge-mv3
└─ ...
```
## Target Browser
To build for a specific browser, pass the `-b --browser` flag from the CLI:
```
wxt --browser firefox
wxt build --browser firefox
```
By default, it will build for `chrome`. When excluding the [`--mv2` or `--mv3` flags](#target-manifest-version), it will default to the commonly accepted manifest version used with that browser.
| Browser | Default Manifest Version |
| ---------------- | :----------------------: |
| `chrome` | 3 |
| `firefox` | 2 |
| `safari` | 2 |
| `edge` | 3 |
| Any other string | 3 |
## Target Manifest Version
To build for a specific manifest version, pass either the `--mv2` flag or `--mv3` flag from the CLI.
```sh
wxt --mv2
wxt build --mv2
```
When the `-b --browser` flag is not passed, it defaults to `chrome`. So here, we're targetting MV2 for Chrome.
-5
View File
@@ -1,5 +0,0 @@
# Testing
:::warning 🚧&ensp;Testing utils are not implemented yet!
Eventually, the plan is to have an integration with Vitest.
:::
+7 -5
View File
@@ -3,18 +3,20 @@
WXT uses the same tool as Nuxt for auto-imports, [`unimport`](https://github.com/unjs/unimport).
:::info Testing
To setup your test environment for auto-imports, see [Testing](/get-started/testing.md).
To setup your test environment for auto-imports, see [Testing](/guide/testing).
:::
## WXT Auto-imports
Some WXT APIs can be used without importing them:
- [`browser`](/config.md#browser) from `wxt/browser`, a small wrapper around `webextension-polyfill`
- [`defineContentScript`](/config.md#defiencontentscript) from `wxt/client`
- [`defineBackground`](/config.md#definebackgroundscript) from `wxt/client`
- [`browser`](/api/wxt-browser#browser) from `wxt/browser`, a small wrapper around `webextension-polyfill`
- [`defineContentScript`](/api/wxt-client#defiencontentscript) from `wxt/client`
- [`defineBackground`](/api/wxt-client#definebackground) from `wxt/client`
- [`createContentScriptUi`](/api/wxt-client#createcontentscriptui) from `wxt/client`
- [`defineUnlistedScript`](/api/wxt-sandbox#defineunlistedscript) from `wxt/sandbox`
And more. All [`wxt/client`](/config.md#wxtclient) APIs can be used without imports.
And more. All [`wxt/client`](/api/wxt-client) APIs can be used without imports.
## Project Auto-imports
@@ -15,7 +15,7 @@ export default defineConfig({
```
:::info
See the [Config reference](/config.md) for a full list of options.
See the [Config reference](/api/config) for a full list of options.
:::
## Directory Config
@@ -25,7 +25,7 @@ WXT allows you to edit several directories to your liking:
- `root` (default: `process.cwd()`) - Root of the WXT project
- `srcDir` (default: `<rootDir>`) - Location of all your source code
- `entrypointsDir` (default: `<srcDir>/entrypoints`) - Folder containing all the entrypoints.
- `publicDir` (default: `<srcDir>/public`) - Folder containing [public assets](/get-started/assets.md)
- `publicDir` (default: `<srcDir>/public`) - Folder containing [public assets](/guide/assets)
### Example
-122
View File
@@ -1,122 +0,0 @@
# Content Scripts
[Chrome Docs](https://developer.chrome.com/docs/extensions/mv3/content_scripts/) &bull; [Firefox Docs](https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/Content_scripts)
When creating content script entrypoints, they are automatically included in the `manifest.json` along with any CSS files they import.
## Filenames
<EntrypointPatterns
:patterns="[
['content.(ts|tsx)', 'content-scripts/content.js'],
['content/index.(ts|tsx)', 'content-scripts/content.js'],
['<name>.content.(ts|tsx)', 'content-scripts/<name>.js'],
['<name>.content/index.(ts|tsx)', 'content-scripts/<name>.js'],
]"
/>
## Definition
```ts
export default defineContentScript({
// Set manifest options
matches: ['*://google.com/*', '*://duckduckgo.com/*'],
excludeMatches: undefined | [],
includeGlobs: undefined | [],
excludeGlobs: undefined | [],
allFrames: undefined | [],
runAt: undefined | 'document_start' | 'document_end' | 'document_idle',
matchAboutBlank: undefined | true | false,
matchOriginAsFallback: undefined | true | false,
world: undefined | 'ISOLATED' | 'MAIN',
// Set include/exclude if the background should be removed from some builds
include: undefined | string[],
exclude: undefined | string[],
main(ctx) {
// Executed when content script is loaded
},
});
```
> All manifest options default to `undefined`.
When defining multiple content scripts, content script entrypoints that have the same set of options will be merged into a single `content_script` item in the manifest.
## CSS
To include CSS with your content script, import the CSS file at the top of your entrypoint.
```
<srcDir>
└─ entrypoints/
└─ overlay.content/
├─ index.ts
└─ style.css
```
```ts
// entrypoints/overlay.content/index.ts
import './style.css';
export default defineContentScript({
matches: ['*://google.com/*', '*://duckduckgo.com/*'],
main(ctx) {
// ...
},
});
```
Any styles imported in your content script will be added to that content script's `css` array in your `manifest.json`:
```json
// .output/chrome-mv3/manifest.json
{
"content_scripts": [
{
"matches": ["*://google.com/*", "*://duckduckgo.com/*"],
"js": ["content-scripts/overlay.js"],
"css": ["content-scripts/overlay.css"]
}
]
}
```
## Context
Old content scripts are not automatically stopped when an extension updates and restarts. Often, this leads to "Invalidated context" errors in production when a content script from an old version of your extension tries to use a web extension API. Since it's not connected to the latest version of your extension, the browser decides to throw an error.
WXT provides a utility for managing this process: `ContentScriptContext`. An instance of this class is provided to you automatically inside the `main` function of your content script.
```ts
export default defineContentScript({
// ...
main(ctx: ContentScriptContext) {
// Add custom listeners for stopping work
ctx.onInvalidated(() => {
// ...
});
// Stop fetch requests
fetch('...url', { signal: ctx.signal });
// Timeout utilities
ctx.setTimeout(() => {
// ...
}, 5e3);
ctx.setInterval(() => {
// ...
}, 60e3);
},
});
```
The class extends [`AbortController`](https://developer.mozilla.org/en-US/docs/Web/API/AbortController) and provides other utilities for stopping a content script's logic once it becomes invalidated.
:::tip
When working with content scripts, **you should always use the `ctx` object to stop any async or future work.**
This prevents old content scripts from interfering with new content scripts, and prevents error messages from the console in production.
:::
+53
View File
@@ -0,0 +1,53 @@
# Development
WXT's main goal is providing the best DX it possibly can. When running your extension in dev mode, each part of your extension is reloaded separately when possible.
| | HMR | Reloaded individually | Reload extension | Restart browser |
| ------------------- | :-: | :-------------------: | :--------------: | :----------------------------------------------------: |
| HTML File | | ✅ |
| HTML Dependency | ✅ |
| MV3 Content Script | | ✅ |
| MV2 Content Script | | | ✅ |
| Background | | | ✅ |
| manifest.json | | | | 🟡 See [#16](https://github.com/wxt-dev/wxt/issues/16) |
| `wxt.config.ts` | | | | 🟡 See [#10](https://github.com/wxt-dev/wxt/issues/10) |
| `web-ext.config.ts` | | | | 🟡 See [#10](https://github.com/wxt-dev/wxt/issues/10) |
## Configure Browser Startup
WXT uses [`web-ext` by Mozilla](https://github.com/mozilla/web-ext) to automatically open a browser with the extension installed. You can configure the runner's behavior via the [`runner`](/api/config#runner.disabled) option, or in a separate gitignored file, `web-ext.config.ts`.
:::code-group
```ts [wxt.config.ts]
import { defineConfig } from 'wxt';
export default defineConfig({
runner: {
// Runner config
},
});
```
```ts [web-ext.config.ts]
import { defineRunnerConfig } from 'wxt';
export default defineRunnerConfig({
// Runner config
});
```
:::
You may also setup default for your entire computer by creating a `web-ext.config.ts` file in your home directory. This is useful if you want to specify config for all project on your computer, like that you want to use Chrome Beta instead of Chrome.
```ts
// ~/web-ext.config.ts
import { defineRunnerConfig } from 'wxt';
export default defineRunnerConfig({
binaries: {
chrome: '/path/to/chrome-beta',
},
});
```
@@ -42,7 +42,7 @@ would result in the following `manifest.json`:
}
```
If a file uses a [special name recognized by WXT](/get-started/entrypoints.md), it will be added to the manifest. In this case:
If a file uses a special name recognized by WXT, it will be added to the manifest. In this case:
- `popup.html` &rarr; `action.default_popup`
- `content.ts` &rarr; `content_scripts.0.js.0`
@@ -53,7 +53,7 @@ But not all entrypoints are added to the `manifest.json`. If the filename is not
In this case, `injected.ts` gets output to `<outdir>/injected.js` and is accessible via `browser.runtime.getURL("/injected.js")`.
:::info
See [`/entrypoints` folder](/guide/background.md) documentation for a full list of recognized entrypoint filenames.
See [`/entrypoints` folder](/entrypoints/background) documentation for a full list of recognized entrypoint filenames.
:::
## Entrypoint Options
@@ -84,5 +84,5 @@ export default defineContentScript({
```
:::info
For a full list of entrypoints and each of their options, see the [`/entrypoints` folder](/guide/background.md) documentation.
For a full list of entrypoints and each of their options, see the [`/entrypoints` folder](/entrypoints/background) documentation.
:::
+3 -3
View File
@@ -11,7 +11,7 @@ And that's it! Your extension now supports Chrome, Firefox, Safari, Edge, and ot
## Basic Usage
The `browser` variable is available globally via [auto-imports](/guide/auto-imports.md), or it can be imported manually.
The `browser` variable is available globally via [auto-imports](/guide/auto-imports), or it can be imported manually.
```ts
import { browser } from 'wxt/browser';
@@ -79,8 +79,8 @@ There are a number of message passing libraries you can use to improve the messa
Here are some that are compatible with WXT (because they are based off `webextension-polyfill` as well):
- [`@webext-core/messaging`](https://webext-core.aklinker1.io/guide/proxy-service/) - "A light-weight, type-safe wrapper around the `browser.runtime` messaging APIs"
- [`@webext-core/proxy-service`](https://webext-core.aklinker1.io/guide/messaging/) - "Create TRPC-like services that can be called from anywhere but run in the background"
- [`@webext-core/messaging`](https://webext-core.aklinker1.io/guide/messaging/) - "A light-weight, type-safe wrapper around the `browser.runtime` messaging APIs"
- [`@webext-core/proxy-service`](https://webext-core.aklinker1.io/guide/proxy-service/) - "Create TRPC-like services that can be called from anywhere but run in the background"
- [`webext-bridge`](https://github.com/zikaari/webext-bridge) - "Messaging in Web Extensions made super easy. Out of the box."
## Browser Differences
@@ -1,6 +1,6 @@
# Installation
Bootstrap a new project, start from scratch, or migrate an existing project.
Bootstrap a new project, start from scratch, or [migrate an existing project](/guide/migrate-to-wxt).
## Bootstrap Project
@@ -26,7 +26,9 @@ There are several starting templates available.
| <Icon name="Svelte" /> [`svelte`](https://github.com/wxt-dev/wxt/tree/main/templates/svelte) |
| <Icon name="Solid" icon="https://www.solidjs.com/img/favicons/favicon-32x32.png" /> [`solid`](https://github.com/wxt-dev/wxt/tree/main/templates/solid) |
> All templates are in TypeScript. WXT does not support JS at this time.
:::info
All templates default to TypeScript. Rename the file extensions to `.js` to use JavaScript instead.
:::
## From Scratch
@@ -142,6 +144,6 @@ If you're an experienced web extension developer and think the dev manifest look
You're ready to build your web extension!
- Learn how to [add entrypoints](./entrypoints.md) like the popup, options page, or content scripts
- [Configure WXT](./configuration.md) by creating a `wxt.config.ts` file
- Learn how to [add entrypoints](./entrypoints) like the popup, options page, or content scripts
- [Configure WXT](./configuration) by creating a `wxt.config.ts` file
- Checkout [example projects](https://github.com/wxt-dev/wxt-examples) to see how to perfom common tasks with WXT
@@ -1,3 +1,10 @@
---
head:
- - link
- rel: canonical
href: https://wxt.dev
---
# Introduction
WXT is a free and open source framework for building web extensions in an conventional, intuative, and safe way **_for all browsers_**.
@@ -28,5 +35,5 @@ Production builds are optimized for store review, changing as few files as possi
In addition, WXT fully supports Firefox's source code requirements when using a bundler. It will automatically create and upload a ZIP file of your source code.
:::info
See [Publishing](./publishing.md) for more info around production builds.
See [Publishing](./publishing) for more info around production builds.
:::
+2 -2
View File
@@ -49,7 +49,7 @@ The [manifest's `version` and `version_name`](https://developer.chrome.com/docs/
## `icons`
By default, WXT will discover icons in your [`public` directory](/get-started/assets#public-directory) and use them for the [manifest's `icons`](https://developer.chrome.com/docs/extensions/mv3/manifest/icons/).
By default, WXT will discover icons in your [`public` directory](/guide/assets#public-directory) and use them for the [manifest's `icons`](https://developer.chrome.com/docs/extensions/mv3/manifest/icons/).
```
public/
@@ -94,7 +94,7 @@ export default defineConfig({
## Localization
Similar to the icon, the [`_locales` directory](https://developer.chrome.com/docs/extensions/reference/i18n/) should be placed inside the the WXT's [`public` directory](/get-started/assets#public-directory).
Similar to the icon, the [`_locales` directory](https://developer.chrome.com/docs/extensions/reference/i18n/) should be placed inside the the WXT's [`public` directory](/guide/assets#public-directory).
```
public/
+57
View File
@@ -0,0 +1,57 @@
---
outline: deep
---
# Migrate to WXT
> If you have problems migrating to WXT, feel free to ask for help in GitHub by [starting a discussion](https://github.com/wxt-dev/wxt/discussions/new?category=q-a)!
## Overview
Always start by generating a new vanilla project and merging it into your project one file at a time.
```sh
cd path/to/your/project
pnpx wxt@latest init example-wxt --template vanilla
```
In general, you'll need to:
<input type="checkbox" /> Install `wxt`<br />
<input type="checkbox" /> Update/create `package.json` scripts to use `wxt` (don't forget about `postinstall`)<br />
<input type="checkbox" /> Move entrypoints into `entrypoints/` directory<br />
<input type="checkbox" /> Move assets into either the `assets/` or `public/` directories<br />
<input type="checkbox" /> Move manifest.json content into `wxt.config.ts`<br />
<input type="checkbox" /> Convert custom import syntax to be compatible with Vite<br />
<input type="checkbox" /> Add a default export to JS entrypoints<br />
<input type="checkbox" /> Use the `browser` global instead of `chrome`<br />
<input type="checkbox" /> Compare final `manifest.json` files, making sure permissions and host permissions are unchanged<br />
<input type="checkbox" /> Extension output by `wxt build` works the same way as before the migration<br />
Every project is different, so there's no one-solution-fits-all to migrating your project. Just make sure `wxt dev` runs, `wxt build` results in a working extension, and the list of permissions in the `manifest.json` hasn't changed. If all that looks good, you've finished migrating your extension!
## Popular Tools/Frameworks
Here's specific steps for other popuplar frameworks/build tools.
### `vite-plugin-web-extension`
Since you're already using Vite, it's a simple refactor.
1. Install `wxt`
2. Move and refactor your entrypoints to WXT's style (with a default export)
3. Update package.json scripts to use `wxt`
4. Add `"postinstall": "wxt prepare"` script
5. Move the `manifest.json` into `wxt.config.ts`
6. Move any custom settings from `vite.config.ts` into `wxt.config.ts`'s
7. Compare `dist/manifest.json` to `.output/*/manifest.json`, they should have the same content as before. If not, tweak your entrypoints and config to get as close as possible.
### `plasmo`
1. Install `wxt`
2. Move entrypoints into `entrypoints/` directory, merging the named exports used to configure your JS entrypoints into WXT's default export
3. Move public `assets/*` into the `public/` directory
4. If you use CSUI, migrate to WXT's `createContentScriptUi`
5. Convert Plasmo's custom import resolutions to Vite's
6. If importing remote code via a URL, add a `url:` prefix so it works with WXT
7. Compare your output `manifest.json` files from before the migration to after the migration. They should have the same content. If not, tweak your entrypoints and config to get as close as possible.
+110
View File
@@ -0,0 +1,110 @@
# Multiple Browsers
You can build an extension for any combination of browser and manifest verison. Different browsers and manifest versions support different APIs and entrypoints, so be sure to check that your extension functions as expected for each target.
Separate build targets are written to their own output directories:
```
<rootDir>
└─ .output
├─ chrome-mv3
├─ firefox-mv2
├─ edge-mv3
└─ ...
```
## Target Browser
To build for a specific browser, pass the `-b --browser` flag from the CLI:
```
wxt --browser firefox
wxt build --browser firefox
```
By default, it will build for `chrome`. When excluding the [`--mv2` or `--mv3` flags](#target-manifest-version), it will default to the commonly accepted manifest version used with that browser.
| Browser | Default Manifest Version |
| ---------------- | :----------------------: |
| `chrome` | 3 |
| `firefox` | 2 |
| `safari` | 2 |
| `edge` | 3 |
| Any other string | 3 |
## Target Manifest Version
To build for a specific manifest version, pass either the `--mv2` flag or `--mv3` flag from the CLI.
```sh
wxt --mv2
wxt build --mv2
```
When the `-b --browser` flag is not passed, it defaults to `chrome`. So here, we're targetting MV2 for Chrome.
## Customizing Entrypoints
There are several ways to customize entrypoint definitions per browser.
First, you can use either the `include` or `exclude` option to include or exclude the entrypoint from specific browsers. Here are some examples
:::code-group
```ts [Background]
export default defineBackground({
// Only include a background script when targeting chrome
include: ['chrome'],
});
```
```ts [Content Script]
export default defineContentScript({
// Do not add this content script to the manifest when targeting firefox
exclude: ['firefox'],
});
```
```html [HTML page]
<!-- entrypoints/options.html -->
<html>
<head>
<!-- Don't include the options page for safari -->
<meta name="manifest.exclude" content="['safari']" />
</head>
</html>
```
:::
Second, you can change individual options per-browser:
:::code-group
```ts [Background]
export default defineBackground({
persistent: {
// Use a non-persistent background script for just safari
safari: false,
},
});
```
```ts [Content Script]
export default defineContentScript({
matches: {
// Run the content script on different pages for each browser
chrome: ['*://*.google.com/*'],
firefox: ['*://*.duckduckgo.com/*'],
edge: ['*://*.bing.com/*'],
},
});
```
:::
:::warning
Only `defineBackground` and `defineContentScript` support per-browser options right now.
:::
+92
View File
@@ -0,0 +1,92 @@
# Testing
WXT provides a couple of utils for unit testing your extension.
[[toc]]
## Fake Browser
The `wxt/fake-browser` package includes an in-memory implementation of the `browser` variable you can use for testing. WXT simply re-exports the `fakeBrowser` variable from [`@webext-core/fake-browser`](https://webext-core.aklinker1.io/guide/fake-browser/).
Here's an example test using Vitest:
```ts
import { describe, it, expect, vi } from 'vitest';
import { browser } from 'wxt/browser';
import { fakeBrowser } from 'wxt';
// Function we're testing
function onHelloMessage(cb: () => void) {
browser.runtime.onMessage.addEventListener((message) => {
if (message.type === 'hello') return 'world';
});
}
// Mock the real `browser` object with a fake one
vi.mock('wxt/browser', () => import('wxt/fake-browser'));
describe('onHelloMessage', () => {
it("should call the callback when the message type is 'hello'", () => {
const cb = vi.fn();
const expected = 'world';
onHelloMessage(cb);
const actual = await fakeBrowser.runtime.sendMessage({ type: 'hello' });
expect(cb).toBeCalledTimes(1);
expect(actual).toBe(expected);
});
it("should ignore the message when the message type is not 'hello'", () => {
const cb = vi.fn();
onHelloMessage(cb);
await fakeBrowser.runtime.sendMessage({ type: 'not-hello' }).catch();
expect(cb).not.toBeCalled();
});
});
```
See [`@webext-core/fake-browser`](https://webext-core.aklinker1.io/guide/fake-browser/) for setup, implemented APIs, and example tests.
## Handling Auto-imports
By default, WXT uses auto-imports. For tests, this can cause issues if your test environment is not setup to handle them correctly.
:::warning 🚧&ensp;Testing utils are not implemented yet!
Eventually, WXT will provide utilities for setting up these auto-imports. For now, you'll need to set them up manually.
:::
Not all testing frameworks can handle auto-imports. If your framework or setup is not listed below, it may be easiest to disable auto-imports.
To setup auto-imports manually, use [`unplugin-auto-import`](https://www.npmjs.com/package/unplugin-auto-import). It uses the same tool, `unimport`, as WXT and will result in compatiple auto-imports. `unplugin-auto-import` supports lots of different tools (vite, webpack, esbuild, rollup, etc). You can try and integrate it into your build process.
### Vitest (Recommended)
Vitest is easy, simply add `uplugin-auto-import` to your project.
```ts
// vitest.config.ts
import autoImports from 'unplugin-auto-import/vite';
export default defineConfig({
plugins: [
autoImports({
imports: [{ name: 'defineConfig', from: 'wxt' }],
presets: [{ package: 'wxt/client' }, { package: 'wxt/browser' }],
dirs: ['components', 'composables', 'hooks', 'utils'],
}),
],
});
```
### Jest
Don't use jest and auto-imports. You could try and configure jest to be transpiled by one of `unplugin-auto-import`'s supported built tools, but I don't know of a way to configure this. See [unplugin/unplugin-auto-import#33](https://github.com/unplugin/unplugin-auto-import/issues/33) if you want to try and set it up.
I would recommend disabling auto-imports or migrating to Vitest if you want to use auto-imports.
### Mocha
TODO: Is this possible? Maybe with `esbuild-mocha`? I would recommend moving to Vitest.
-20
View File
@@ -1,20 +0,0 @@
# Unlisted Scripts
TypeScript files that are built, but are not included in the manifest.
## Filenames
<EntrypointPatterns
:patterns="[
['<name>.(ts|tsx)', '<name>.js'],
['<name>/index.(ts|tsx)', '<name>.js'],
]"
/>
## Definition
Unlike the background or content scripts, you can define this script's logic in the top level scope.
```ts
// Code goes here
```
+50 -12
View File
@@ -1,59 +1,97 @@
---
# https://vitepress.dev/reference/default-theme-home-page
layout: home
titleTemplate: 'Next Generation Web Extension Framework'
title: Next-gen Web Extension Framework
hero:
name: WXT
text: Next-gen Web Extension Framework
tagline: Powered by Vite, inspired by Nuxt.
tagline: An open source tool that makes Chrome Extension devlopment faster than ever before.
image:
src: /hero-logo.svg
alt: WXT
actions:
- theme: brand
text: Get Started
link: /get-started/installation
link: /guide/installation
- theme: alt
text: Learn More
link: /get-started/introduction
link: /guide/introduction
features:
- icon: 🌐
title: Supported Browsers
details: Chrome, Firefox, Edge, Safari, and any Chromium based browser.
details: WXT will build extensions for Chrome, Firefox, Edge, Safari, and any Chromium based browser.
link: /guide/multiple-browsers
linkText: Read docs
- icon: ✅
title: MV2 and MV3
details: Supports both manifest versions for each browser.
details: Build Manifest V2 or V3 extensions for any browser using the same codebase.
link: /guide/multiple-browsers#target-manifest-version
linkText: Read docs
- icon: ⚡
title: Fast Dev Mode
details: HMR for UIs and fast reload for background and content scripts.
details: Lighting fast HMR for UI development and fast reloads for content/background scripts enables faster iterations.
link: /guide/development.html
linkText: Learn more
- icon: 📂
title: File Based Entrypoints
details: Manifest is generated based on files inside the project.
details: Manifest is generated based on files in the project with inline configuration.
link: /guide/entrypoints
linkText: See project structure
- icon: 🚔
title: TypeScript
details: Scale projects with full TS support.
details: Create large projects with confidence using TS by default.
- icon: 🦾
title: Auto-imports
details: Nuxt-like auto-imports to speed up development.
link: /guide/auto-imports
linkText: Read docs
- icon: ⬇️
title: Bundle Remote Code
details: Downloads and bundles remote code imported from URLs.
link: /guide/remote-code
linkText: Read docs
- icon: 🎨
title: Frontend Framework Agnostic
details: Works with any front-end framework with a Vite plugin.
link: /guide/configuration#frontend-frameworks
linkText: Add a framework
- icon: 🖍️
title: Bootstrap a New Project
details: Comes with starter templates for all major frontend frameworks.
details: Get started quickly with several awesome project templates.
link: /guide/installation#bootstrap-project
linkText: See templates
- icon: 📏
title: Bundle Analysis
details: 'Tools for analyizing the final extension bundle.'
details: Tools for analyizing the final extension bundle and minimizing your extension's size.
- icon: 🤖
title: Automated Publishing
details: 'TODO: Automatically zip, upload, and release extensions.'
details: 'Coming soon. Automatically zip, upload, and release extensions.'
---
<section class="vp-doc">
<div class="container">
<h2>Put <span style="color: var(--vp-c-brand-1)">Developer Experience</span> First</h2>
<p>
WXT's simplifies the chrome extension development process by providing tools for zipping and publishing, the best-in-class dev mode, an opinionated project structure, and more. Iterate faster, develop features not build scripts, and use everything the JS ecosystem has to offer.
</p>
<div style="margin: auto; width: 100%; max-width: 700px; text-align: center">
<img src="./assets/cli-output.png" alt="Screenshot of WXT's build output" />
<small>
And who doesn't appreciate a beautiful CLI?
</small>
</div>
</div>
</section>
<ClientOnly>
<UsingWxtSection />
</ClientOnly>
<style scoped>
.container {
margin: 0 auto;
max-width: 1152px;
}
</style>
+30
View File
@@ -0,0 +1,30 @@
# Netlify Redirects File
# https://docs.netlify.com/routing/redirects/
# Old URLs -> New URLs
/config.html /api/config.html
/entrypoints /entrypoints/background.html
/get-started/assets.html /guide/assets.html
/get-started/build-targets.html /guide/multiple-browsers.html
/get-started/compare.html /guide/compare.html
/get-started/configuration.html /guide/configuration.html
/get-started/entrypoints.html /guide/entrypoints.html
/get-started/installation.html /guide/installation.html
/get-started/introduction.html /guide/introduction.html
/get-started/publishing.html /guide/publishing.html
/get-started/testing.html /guide/testing.html
/guide/background.html /entrypoints/background.html
/guide/bookmarks.html /entrypoints/bookmarks.html
/guide/content-scripts.html /entrypoints/content-scripts.html
/guide/css.html /entrypoints/css.html
/guide/devtools.html /entrypoints/devtools.html
/guide/history.html /entrypoints/history.html
/guide/manifest.html /entrypoints/manifest.html
/guide/newtab.html /entrypoints/newtab.html
/guide/options.html /entrypoints/options.html
/guide/popup.html /entrypoints/popup.html
/guide/sandbox.html /entrypoints/sandbox.html
/guide/sidepanel.html /entrypoints/sidepanel.html
/guide/unlisted-pages.html /entrypoints/unlisted-pages.html
/guide/unlisted-scripts.html /entrypoints/unlisted-scripts.html
/guide/build-targets.html /guide/multiple-browsers.html
+5
View File
@@ -0,0 +1,5 @@
User-agent: *
Disallow: /api.html
Disallow: /config.html
Sitemap: https://wxt.dev/sitemap.xml
+2 -1
View File
@@ -18,10 +18,11 @@ describe('Auto Imports', () => {
declare global {
const ContentScriptContext: typeof import('wxt/client')['ContentScriptContext']
const browser: typeof import('wxt/browser')['browser']
const createContentScriptUi: typeof import('wxt/client')['createContentScriptUi']
const defineBackground: typeof import('wxt/client')['defineBackground']
const defineConfig: typeof import('wxt')['defineConfig']
const defineContentScript: typeof import('wxt/client')['defineContentScript']
const mountContentScriptUi: typeof import('wxt/client')['mountContentScriptUi']
const defineUnlistedScript: typeof import('wxt/sandbox')['defineUnlistedScript']
}
"
`);
+361 -93
View File
@@ -193,118 +193,295 @@ describe('Manifest Content', () => {
});
});
it('should group content scripts and styles together based on their matches and run_at', async () => {
const project = new TestProject();
project.addFile(
'entrypoints/one.content/index.ts',
`import "./style.css";
export default defineContentScript({
matches: ["*://google.com/*"],
main: () => {},
})`,
);
project.addFile('entrypoints/one.content/style.css', `body { color: red }`);
project.addFile(
'entrypoints/two.content/index.ts',
`import "./style.css";
export default defineContentScript({
matches: ["*://google.com/*"],
runAt: "document_end",
main: () => {},
})`,
);
project.addFile(
'entrypoints/two.content/style.css',
`body { color: green }`,
);
project.addFile(
'entrypoints/three.content/index.ts',
`import "./style.css";
export default defineContentScript({
matches: ["*://google.com/*"],
runAt: "document_end",
main: () => {},
})`,
);
project.addFile(
'entrypoints/three.content/style.css',
`body { color: blue }`,
);
project.addFile(
'entrypoints/four.content/index.ts',
`import "./style.css";
export default defineContentScript({
matches: ["*://duckduckgo.com/*"],
runAt: "document_end",
main: () => {},
})`,
);
project.addFile(
'entrypoints/four.content/style.css',
`body { color: yellow }`,
);
describe('content_scripts', () => {
it('should group content scripts and styles together based on their manifest properties', async () => {
const project = new TestProject();
project.addFile(
'entrypoints/one.content/index.ts',
`import "./style.css";
export default defineContentScript({
matches: ["*://google.com/*"],
main: () => {},
})`,
);
project.addFile(
'entrypoints/one.content/style.css',
`body { color: red }`,
);
project.addFile(
'entrypoints/two.content/index.ts',
`import "./style.css";
export default defineContentScript({
matches: ["*://google.com/*"],
runAt: "document_end",
main: () => {},
})`,
);
project.addFile(
'entrypoints/two.content/style.css',
`body { color: green }`,
);
project.addFile(
'entrypoints/three.content/index.ts',
`import "./style.css";
export default defineContentScript({
matches: ["*://google.com/*"],
runAt: "document_end",
main: () => {},
})`,
);
project.addFile(
'entrypoints/three.content/style.css',
`body { color: blue }`,
);
project.addFile(
'entrypoints/four.content/index.ts',
`import "./style.css";
export default defineContentScript({
matches: ["*://duckduckgo.com/*"],
runAt: "document_end",
main: () => {},
})`,
);
project.addFile(
'entrypoints/four.content/style.css',
`body { color: yellow }`,
);
await project.build();
await project.build();
const manifest = await project.getOutputManifest();
const manifest = await project.getOutputManifest();
expect(manifest.content_scripts).toContainEqual({
matches: ['*://duckduckgo.com/*'],
run_at: 'document_end',
css: ['assets/four.css'],
js: ['content-scripts/four.js'],
expect(manifest.content_scripts).toContainEqual({
matches: ['*://duckduckgo.com/*'],
run_at: 'document_end',
css: ['content-scripts/four.css'],
js: ['content-scripts/four.js'],
});
expect(manifest.content_scripts).toContainEqual({
matches: ['*://google.com/*'],
run_at: 'document_end',
css: ['content-scripts/three.css', 'content-scripts/two.css'],
js: ['content-scripts/three.js', 'content-scripts/two.js'],
});
expect(manifest.content_scripts).toContainEqual({
matches: ['*://google.com/*'],
css: ['content-scripts/one.css'],
js: ['content-scripts/one.js'],
});
});
expect(manifest.content_scripts).toContainEqual({
matches: ['*://google.com/*'],
run_at: 'document_end',
css: ['assets/three.css', 'assets/two.css'],
js: ['content-scripts/three.js', 'content-scripts/two.js'],
it('should add to any content scripts declared in wxt.config.ts', async () => {
const project = new TestProject();
project.addFile(
'entrypoints/one.content/index.ts',
`export default defineContentScript({
matches: ["*://google.com/*"],
main: () => {},
})`,
);
project.addFile(
'entrypoints/two.content/style.css',
`body {
background-color: red;
}`,
);
project.setConfigFileConfig({
manifest: {
content_scripts: [
{
css: ['content-scripts/two.css'],
matches: ['*://*.google.com/*'],
},
],
},
});
await project.build();
const manifest = await project.getOutputManifest();
expect(manifest.content_scripts).toContainEqual({
css: ['content-scripts/two.css'],
matches: ['*://*.google.com/*'],
});
expect(manifest.content_scripts).toContainEqual({
matches: ['*://google.com/*'],
js: ['content-scripts/one.js'],
});
});
expect(manifest.content_scripts).toContainEqual({
matches: ['*://google.com/*'],
css: ['assets/one.css'],
js: ['content-scripts/one.js'],
it('should add a CSS entry when cssInjectionMode is undefined', async () => {
const project = new TestProject();
project.addFile(
'entrypoints/content/style.css',
'body { background-color: red; }',
);
project.addFile(
'entrypoints/content/index.ts',
`import "./style.css";
export default defineContentScript({
matches: ["https://*.google.com/*"],
main() {},
});`,
);
await project.build();
expect(await project.serializeFile('.output/chrome-mv3/manifest.json'))
.toMatchInlineSnapshot(`
".output/chrome-mv3/manifest.json
----------------------------------------
{\\"manifest_version\\":3,\\"name\\":\\"E2E Extension\\",\\"description\\":\\"Example description\\",\\"version\\":\\"0.0.0\\",\\"content_scripts\\":[{\\"matches\\":[\\"https://*.google.com/*\\"],\\"css\\":[\\"content-scripts/content.css\\"],\\"js\\":[\\"content-scripts/content.js\\"]}]}"
`);
});
it('should add a CSS entry when cssInjectionMode is "manifest"', async () => {
const project = new TestProject();
project.addFile(
'entrypoints/content/style.css',
'body { background-color: red; }',
);
project.addFile(
'entrypoints/content/index.ts',
`import "./style.css";
export default defineContentScript({
matches: ["https://*.google.com/*"],
cssInjectionMode: "manifest",
main() {},
});`,
);
await project.build();
expect(await project.serializeFile('.output/chrome-mv3/manifest.json'))
.toMatchInlineSnapshot(`
".output/chrome-mv3/manifest.json
----------------------------------------
{\\"manifest_version\\":3,\\"name\\":\\"E2E Extension\\",\\"description\\":\\"Example description\\",\\"version\\":\\"0.0.0\\",\\"content_scripts\\":[{\\"matches\\":[\\"https://*.google.com/*\\"],\\"css\\":[\\"content-scripts/content.css\\"],\\"js\\":[\\"content-scripts/content.js\\"]}]}"
`);
});
it('should not add an entry for CSS when cssInjectionMode is "manual"', async () => {
const project = new TestProject();
project.addFile(
'entrypoints/content/style.css',
'body { background-color: red; }',
);
project.addFile(
'entrypoints/content/index.ts',
`import "./style.css";
export default defineContentScript({
matches: ["https://*.google.com/*"],
cssInjectionMode: "manual",
main() {},
});`,
);
await project.build();
expect(await project.serializeFile('.output/chrome-mv3/manifest.json'))
.toMatchInlineSnapshot(`
".output/chrome-mv3/manifest.json
----------------------------------------
{\\"manifest_version\\":3,\\"name\\":\\"E2E Extension\\",\\"description\\":\\"Example description\\",\\"version\\":\\"0.0.0\\",\\"content_scripts\\":[{\\"matches\\":[\\"https://*.google.com/*\\"],\\"js\\":[\\"content-scripts/content.js\\"]}]}"
`);
});
it('should not add a content script entry for CSS when cssInjectionMode is "ui", but add a web_accessible_resources entry for MV2', async () => {
const project = new TestProject();
project.addFile(
'entrypoints/content/style.css',
'body { background-color: red; }',
);
project.addFile(
'entrypoints/content/index.ts',
`import "./style.css";
export default defineContentScript({
matches: ["https://*.google.com/*"],
cssInjectionMode: "ui",
main() {},
});`,
);
await project.build({
manifestVersion: 2,
});
expect(await project.serializeFile('.output/chrome-mv2/manifest.json'))
.toMatchInlineSnapshot(`
".output/chrome-mv2/manifest.json
----------------------------------------
{\\"manifest_version\\":2,\\"name\\":\\"E2E Extension\\",\\"description\\":\\"Example description\\",\\"version\\":\\"0.0.0\\",\\"content_scripts\\":[{\\"matches\\":[\\"https://*.google.com/*\\"],\\"js\\":[\\"content-scripts/content.js\\"]}],\\"web_accessible_resources\\":[\\"content-scripts/content.css\\"]}"
`);
});
it('should not add a content script entry for CSS when cssInjectionMode is "ui", but add a web_accessible_resources entry for MV3', async () => {
const project = new TestProject();
project.addFile(
'entrypoints/content/style.css',
'body { background-color: red; }',
);
project.addFile(
'entrypoints/content/index.ts',
`import "./style.css";
export default defineContentScript({
matches: ["https://*.google.com/*"],
cssInjectionMode: "ui",
main() {},
});`,
);
await project.build({
manifestVersion: 3,
});
expect(await project.serializeFile('.output/chrome-mv3/manifest.json'))
.toMatchInlineSnapshot(`
".output/chrome-mv3/manifest.json
----------------------------------------
{\\"manifest_version\\":3,\\"name\\":\\"E2E Extension\\",\\"description\\":\\"Example description\\",\\"version\\":\\"0.0.0\\",\\"content_scripts\\":[{\\"matches\\":[\\"https://*.google.com/*\\"],\\"js\\":[\\"content-scripts/content.js\\"]}],\\"web_accessible_resources\\":[{\\"resources\\":[\\"content-scripts/content.css\\"],\\"matches\\":[\\"https://*.google.com/*\\"]}]}"
`);
});
});
it('should add to any content scripts declared in wxt.config.ts', async () => {
it('should combine web accessible resources', async () => {
const project = new TestProject();
project.addFile(
'entrypoints/one.content/index.ts',
`export default defineContentScript({
matches: ["*://google.com/*"],
main: () => {},
})`,
'entrypoints/content/style.css',
'body { background-color: red; }',
);
project.addFile(
'entrypoints/two.content/style.css',
`body {
background-color: red;
}`,
'entrypoints/content/index.ts',
`import "./style.css";
export default defineContentScript({
matches: ["https://*.google.com/*"],
cssInjectionMode: "ui",
main() {},
});`,
);
project.setConfigFileConfig({
manifest: {
content_scripts: [
{
css: ['content-scripts/two.css'],
matches: ['*://*.google.com/*'],
},
web_accessible_resources: [
{ resources: ['one.png'], matches: ['https://one.com/*'] },
],
},
});
await project.build();
const manifest = await project.getOutputManifest();
expect(manifest.content_scripts).toContainEqual({
css: ['content-scripts/two.css'],
matches: ['*://*.google.com/*'],
});
expect(manifest.content_scripts).toContainEqual({
matches: ['*://google.com/*'],
js: ['content-scripts/one.js'],
});
expect(await project.serializeFile('.output/chrome-mv3/manifest.json'))
.toMatchInlineSnapshot(`
".output/chrome-mv3/manifest.json
----------------------------------------
{\\"manifest_version\\":3,\\"name\\":\\"E2E Extension\\",\\"description\\":\\"Example description\\",\\"version\\":\\"0.0.0\\",\\"web_accessible_resources\\":[{\\"resources\\":[\\"one.png\\"],\\"matches\\":[\\"https://one.com/*\\"]},{\\"resources\\":[\\"content-scripts/content.css\\"],\\"matches\\":[\\"https://*.google.com/*\\"]}],\\"content_scripts\\":[{\\"matches\\":[\\"https://*.google.com/*\\"],\\"js\\":[\\"content-scripts/content.js\\"]}]}"
`);
});
it('should respect the transformManifest option', async () => {
@@ -328,7 +505,98 @@ describe('Manifest Content', () => {
expect(output).toMatchInlineSnapshot(`
".output/chrome-mv3/manifest.json
----------------------------------------
{\\"manifest_version\\":3,\\"name\\":\\"E2E Extension\\",\\"description\\":\\"Example description\\",\\"version\\":\\"0.0.0\\",\\"version_name\\":\\"0.0.0-test\\",\\"author\\":\\"Custom Author\\"}"
{\\"manifest_version\\":3,\\"name\\":\\"E2E Extension\\",\\"description\\":\\"Example description\\",\\"version\\":\\"0.0.0\\",\\"author\\":\\"Custom Author\\"}"
`);
});
it.each([
{ browser: undefined, outDir: 'chrome-mv3', expected: undefined },
{ browser: 'chrome', outDir: 'chrome-mv3', expected: undefined },
{ browser: 'firefox', outDir: 'firefox-mv2', expected: true },
{ browser: 'safari', outDir: 'safari-mv2', expected: false },
])(
'should respect the per-browser entrypoint option with %j',
async ({ browser, expected, outDir }) => {
const project = new TestProject();
project.addFile(
'entrypoints/background.ts',
`export default defineBackground({
persistent: {
firefox: true,
safari: false,
},
main: () => {},
})`,
);
await project.build({ browser });
const safariManifest = await project.getOutputManifest(
`.output/${outDir}/manifest.json`,
);
expect(safariManifest.background.persistent).toBe(expected);
},
);
describe('versions', () => {
it.each([
['chrome', 3] as const,
['safari', 2] as const,
['edge', 3] as const,
])(
'should include version_name on %s when it needs simplified',
async (browser, manifestVersion) => {
const project = new TestProject({
version: '1.0.0-alpha1',
});
await project.build({ browser, manifestVersion });
const manifest = await project.getOutputManifest(
`.output/${browser}-mv${manifestVersion}/manifest.json`,
);
expect(manifest.version).toBe('1.0.0');
expect(manifest.version_name).toBe('1.0.0-alpha1');
},
);
it.each([['firefox', 2] as const])(
"should not include a version_name on %s because the browser doesn't support it",
async (browser, manifestVersion) => {
const project = new TestProject({
version: '1.0.0-alpha1',
});
await project.build({ browser, manifestVersion });
const manifest = await project.getOutputManifest(
`.output/${browser}-mv${manifestVersion}/manifest.json`,
);
expect(manifest.version).toBe('1.0.0');
expect(manifest.version_name).toBeUndefined();
},
);
it.each([
['chrome', 3] as const,
['firefox', 2] as const,
['safari', 3] as const,
['edge', 3] as const,
])(
'should not include the version_name if it is equal to version',
async (browser, manifestVersion) => {
const project = new TestProject({
version: '1.0.0.1',
});
await project.build({ browser, manifestVersion });
const manifest = await project.getOutputManifest(
`.output/${browser}-mv${manifestVersion}/manifest.json`,
);
expect(manifest.version).toBe('1.0.0.1');
expect(manifest.version_name).toBeUndefined();
},
);
});
});
+52 -9
View File
@@ -13,7 +13,7 @@ describe('Output Directory Structure', () => {
expect(await project.serializeOutput()).toMatchInlineSnapshot(`
".output/chrome-mv3/manifest.json
----------------------------------------
{\\"manifest_version\\":3,\\"name\\":\\"E2E Extension\\",\\"description\\":\\"Example description\\",\\"version\\":\\"0.0.0\\",\\"version_name\\":\\"0.0.0-test\\"}"
{\\"manifest_version\\":3,\\"name\\":\\"E2E Extension\\",\\"description\\":\\"Example description\\",\\"version\\":\\"0.0.0\\"}"
`);
});
@@ -49,19 +49,19 @@ describe('Output Directory Structure', () => {
'.output/chrome-mv3/content-scripts/two.js',
]),
).toMatchInlineSnapshot(`
".output/chrome-mv3/assets/one.css
".output/chrome-mv3/content-scripts/one.css
----------------------------------------
body{color:#00f}
================================================================================
.output/chrome-mv3/assets/two.css
----------------------------------------
body{color:red}
================================================================================
.output/chrome-mv3/content-scripts/one.js
----------------------------------------
<contents-ignored>
================================================================================
.output/chrome-mv3/content-scripts/two.css
----------------------------------------
body{color:red}
================================================================================
.output/chrome-mv3/content-scripts/two.js
----------------------------------------
@@ -69,7 +69,7 @@ describe('Output Directory Structure', () => {
================================================================================
.output/chrome-mv3/manifest.json
----------------------------------------
{\\"manifest_version\\":3,\\"name\\":\\"E2E Extension\\",\\"description\\":\\"Example description\\",\\"version\\":\\"0.0.0\\",\\"version_name\\":\\"0.0.0-test\\",\\"content_scripts\\":[{\\"matches\\":[\\"*://*/*\\"],\\"css\\":[\\"assets/one.css\\",\\"assets/two.css\\"],\\"js\\":[\\"content-scripts/one.js\\",\\"content-scripts/two.js\\"]}]}"
{\\"manifest_version\\":3,\\"name\\":\\"E2E Extension\\",\\"description\\":\\"Example description\\",\\"version\\":\\"0.0.0\\",\\"content_scripts\\":[{\\"matches\\":[\\"*://*/*\\"],\\"css\\":[\\"content-scripts/one.css\\",\\"content-scripts/two.css\\"],\\"js\\":[\\"content-scripts/one.js\\",\\"content-scripts/two.js\\"]}]}"
`);
});
@@ -96,7 +96,7 @@ describe('Output Directory Structure', () => {
================================================================================
.output/chrome-mv3/manifest.json
----------------------------------------
{\\"manifest_version\\":3,\\"name\\":\\"E2E Extension\\",\\"description\\":\\"Example description\\",\\"version\\":\\"0.0.0\\",\\"version_name\\":\\"0.0.0-test\\",\\"content_scripts\\":[{\\"matches\\":[\\"*://*/*\\"],\\"js\\":[\\"content-scripts/overlay-one.js\\"]}]}"
{\\"manifest_version\\":3,\\"name\\":\\"E2E Extension\\",\\"description\\":\\"Example description\\",\\"version\\":\\"0.0.0\\",\\"content_scripts\\":[{\\"matches\\":[\\"*://*/*\\"],\\"js\\":[\\"content-scripts/overlay-one.js\\"]}]}"
`);
});
@@ -165,4 +165,47 @@ describe('Output Directory Structure', () => {
expect(await project.fileExists('stats.html')).toBe(true);
});
it('should support JavaScript entrypoints', async () => {
const project = new TestProject();
project.addFile(
'entrypoints/background.js',
`export default defineBackground(() => {});`,
);
project.addFile(
'entrypoints/unlisted.js',
`export default defineUnlistedScript(() => {})`,
);
project.addFile(
'entrypoints/content.js',
`export default defineContentScript({
matches: ["*://*.google.com/*"],
main() {},
})`,
);
project.addFile(
'entrypoints/named.content.jsx',
`export default defineContentScript({
matches: ["*://*.duckduckgo.com/*"],
main() {},
})`,
);
await project.build();
expect(await project.serializeFile('.output/chrome-mv3/manifest.json'))
.toMatchInlineSnapshot(`
".output/chrome-mv3/manifest.json
----------------------------------------
{\\"manifest_version\\":3,\\"name\\":\\"E2E Extension\\",\\"description\\":\\"Example description\\",\\"version\\":\\"0.0.0\\",\\"background\\":{\\"service_worker\\":\\"background.js\\"},\\"content_scripts\\":[{\\"matches\\":[\\"*://*.google.com/*\\"],\\"js\\":[\\"content-scripts/content.js\\"]},{\\"matches\\":[\\"*://*.duckduckgo.com/*\\"],\\"js\\":[\\"content-scripts/named.js\\"]}]}"
`);
expect(await project.fileExists('.output/chrome-mv3/background.js'));
expect(
await project.fileExists('.output/chrome-mv3/content-scripts/content.js'),
);
expect(
await project.fileExists('.output/chrome-mv3/content-scripts/named.js'),
);
expect(await project.fileExists('.output/chrome-mv3/unlisted.js'));
});
});
+43
View File
@@ -0,0 +1,43 @@
import { describe, expect, it } from 'vitest';
import { TestProject } from '../utils';
describe('React', () => {
it('should prepare and build an project with a tsx entrypoint', async () => {
const project = new TestProject({
dependencies: {
react: '^18.2.0',
'react-dom': '^18.2.0',
},
devDependencies: {
'@types/react': '^18.2.14',
'@types/react-dom': '^18.2.6',
},
});
project.addFile(
'entrypoints/demo.content.tsx',
`import ReactDOM from 'react-dom/client';
export default defineContentScript({
matches: "<all_urls>",
main() {
const container = document.createElement("div");
document.body.append(container)
const root = ReactDOM.createRoot(container);
root.render(<h1>Hello, world!</h1>);
}
})`,
);
await project.build();
expect(
await project.fileExists('.output/chrome-mv3/content-scripts/demo.js'),
).toBe(true);
expect(await project.serializeFile('.output/chrome-mv3/manifest.json'))
.toMatchInlineSnapshot(`
".output/chrome-mv3/manifest.json
----------------------------------------
{\\"manifest_version\\":3,\\"name\\":\\"E2E Extension\\",\\"description\\":\\"Example description\\",\\"version\\":\\"0.0.0\\",\\"content_scripts\\":[{\\"matches\\":\\"<all_urls>\\",\\"js\\":[\\"content-scripts/demo.js\\"]}]}"
`);
});
});
+5 -1
View File
@@ -5,7 +5,11 @@ describe('Remote Code', () => {
it('should download "url:*" modules and include them in the final bundle', async () => {
const url = 'https://code.jquery.com/jquery-3.7.1.slim.min.js';
const project = new TestProject();
project.addFile('entrypoints/popup.ts', `import "url:${url}"`);
project.addFile(
'entrypoints/popup.ts',
`import "url:${url}"
export default defineUnlistedScript(() => {})`,
);
await project.build();
+10 -10
View File
@@ -255,14 +255,14 @@ describe('TypeScript Project', () => {
\\"lib\\": [\\"DOM\\", \\"WebWorker\\"],
\\"skipLibCheck\\": true,
\\"paths\\": {
\\"@@\\": [\\"..\\"],
\\"@@/*\\": [\\"../*\\"],
\\"~~\\": [\\"..\\"],
\\"~~/*\\": [\\"../*\\"],
\\"@\\": [\\"..\\"],
\\"@/*\\": [\\"../*\\"],
\\"~\\": [\\"..\\"],
\\"~/*\\": [\\"../*\\"]
\\"~/*\\": [\\"../*\\"],
\\"@@\\": [\\"..\\"],
\\"@@/*\\": [\\"../*\\"],
\\"~~\\": [\\"..\\"],
\\"~~/*\\": [\\"../*\\"]
}
},
\\"include\\": [
@@ -299,14 +299,14 @@ describe('TypeScript Project', () => {
\\"lib\\": [\\"DOM\\", \\"WebWorker\\"],
\\"skipLibCheck\\": true,
\\"paths\\": {
\\"@@\\": [\\"..\\"],
\\"@@/*\\": [\\"../*\\"],
\\"~~\\": [\\"..\\"],
\\"~~/*\\": [\\"../*\\"],
\\"@\\": [\\"../src\\"],
\\"@/*\\": [\\"../src/*\\"],
\\"~\\": [\\"../src\\"],
\\"~/*\\": [\\"../src/*\\"]
\\"~/*\\": [\\"../src/*\\"],
\\"@@\\": [\\"..\\"],
\\"@@/*\\": [\\"../*\\"],
\\"~~\\": [\\"..\\"],
\\"~~/*\\": [\\"../*\\"]
}
},
\\"include\\": [
+3 -3
View File
@@ -28,7 +28,7 @@ describe('User Config', () => {
================================================================================
.output/chrome-mv3/manifest.json
----------------------------------------
{\\"manifest_version\\":3,\\"name\\":\\"E2E Extension\\",\\"description\\":\\"Example description\\",\\"version\\":\\"0.0.0\\",\\"version_name\\":\\"0.0.0-test\\",\\"background\\":{\\"service_worker\\":\\"background.js\\"}}"
{\\"manifest_version\\":3,\\"name\\":\\"E2E Extension\\",\\"description\\":\\"Example description\\",\\"version\\":\\"0.0.0\\",\\"background\\":{\\"service_worker\\":\\"background.js\\"}}"
`);
});
@@ -54,7 +54,7 @@ describe('User Config', () => {
================================================================================
.output/chrome-mv3/manifest.json
----------------------------------------
{\\"manifest_version\\":3,\\"name\\":\\"E2E Extension\\",\\"description\\":\\"Example description\\",\\"version\\":\\"0.0.0\\",\\"version_name\\":\\"0.0.0-test\\",\\"background\\":{\\"service_worker\\":\\"background.js\\"}}"
{\\"manifest_version\\":3,\\"name\\":\\"E2E Extension\\",\\"description\\":\\"Example description\\",\\"version\\":\\"0.0.0\\",\\"background\\":{\\"service_worker\\":\\"background.js\\"}}"
`);
});
@@ -82,7 +82,7 @@ describe('User Config', () => {
expect(output).toMatchInlineSnapshot(`
".output/chrome-mv3/manifest.json
----------------------------------------
{\\"manifest_version\\":3,\\"name\\":\\"E2E Extension\\",\\"description\\":\\"Example description\\",\\"version\\":\\"0.0.0\\",\\"version_name\\":\\"0.0.0-test\\",\\"example_customization\\":[\\"production\\",\\"chrome\\",\\"3\\",\\"build\\"]}"
{\\"manifest_version\\":3,\\"name\\":\\"E2E Extension\\",\\"description\\":\\"Example description\\",\\"version\\":\\"0.0.0\\",\\"example_customization\\":[\\"production\\",\\"chrome\\",\\"3\\",\\"build\\"]}"
`);
});
});
+13 -9
View File
@@ -4,29 +4,33 @@ import glob from 'fast-glob';
import { execaCommand } from 'execa';
import { InlineConfig, UserConfig, build } from '../src';
import { normalizePath } from '../src/core/utils/paths';
import merge from 'lodash.merge';
export class TestProject {
files: Array<[string, string]> = [];
config: UserConfig | undefined;
readonly root: string;
constructor(root = 'e2e/dist') {
constructor(packageJson: any = {}) {
// We can't put each test's project inside e2e/dist directly, otherwise the wxt.config.ts
// file is cached and cannot be different between each test. Instead, we add a random ID to the
// end to make each test's path unique.
const id = Math.random().toString(32).substring(3);
this.root = join(root, id);
this.root = join('e2e/dist', id);
this.files.push([
'package.json',
JSON.stringify(
{
name: 'E2E Extension',
description: 'Example description',
version: '0.0.0-test',
dependencies: {
wxt: '../../..',
merge(
{
name: 'E2E Extension',
description: 'Example description',
version: '0.0.0',
dependencies: {
wxt: '../../..',
},
},
},
packageJson,
),
null,
2,
),
+19 -12
View File
@@ -1,10 +1,10 @@
{
"name": "wxt",
"type": "module",
"version": "0.6.4",
"version": "0.8.0",
"description": "Next gen framework for developing web extensions",
"engines": {
"node": ">=18.16.0",
"node": ">=18",
"pnpm": ">=8"
},
"repository": {
@@ -44,6 +44,10 @@
"import": "./dist/client.js",
"types": "./dist/client.d.ts"
},
"./sandbox": {
"import": "./dist/sandbox.js",
"types": "./dist/sandbox.d.ts"
},
"./browser": {
"import": "./dist/browser.js",
"types": "./dist/browser.d.ts"
@@ -56,22 +60,24 @@
"format:check": "prettier --write .",
"compile": "tsc --noEmit",
"test": "vitest",
"test:coverage": "vitest run --coverage",
"test:coverage": "vitest run --coverage.enabled --coverage.exclude=e2e --coverage.exclude=src/testing",
"prepare": "simple-git-hooks",
"prepublish": "pnpm -s build",
"docs:dev": "vitepress dev docs",
"docs:build": "vitepress build docs",
"docs:preview": "vitepress preview docs",
"sync-releases": "pnpx changelogen@latest gh release all"
"sync-releases": "pnpx changelogen@latest gh release"
},
"dependencies": {
"@types/webextension-polyfill": "^0.10.1",
"@webext-core/fake-browser": "^1.2.2",
"@webext-core/match-patterns": "^1.0.1",
"@webext-core/isolated-element": "^1.0.4",
"@webext-core/match-patterns": "^1.0.2",
"async-mutex": "^0.4.0",
"c12": "^1.4.2",
"cac": "^6.7.14",
"consola": "^3.2.3",
"esbuild": "^0.19.4",
"fast-glob": "^3.3.1",
"filesize": "^10.0.8",
"fs-extra": "^11.1.1",
@@ -88,7 +94,7 @@
"prompts": "^2.4.2",
"rollup-plugin-visualizer": "^5.9.2",
"unimport": "^3.1.0",
"vite": "^4.4.7",
"vite": "^4.4.11",
"web-ext-run": "^0.1.0",
"webextension-polyfill": "^0.10.0",
"zip-dir": "^2.0.0"
@@ -97,22 +103,23 @@
"@faker-js/faker": "^8.0.2",
"@types/fs-extra": "^11.0.1",
"@types/lodash.merge": "^4.6.7",
"@types/node": "^20.4.5",
"@types/node": "^20.8.6",
"@types/prompts": "^2.4.4",
"@vitest/coverage-v8": "^0.34.1",
"@vitest/coverage-v8": "^0.34.6",
"execa": "^7.2.0",
"jsdom": "^22.1.0",
"lint-staged": "^14.0.0",
"lodash.merge": "^4.6.2",
"npm-run-all": "^4.1.5",
"prettier": "^3.0.1",
"simple-git-hooks": "^2.9.0",
"ts-morph": "^19.0.0",
"ts-morph": "^20.0.0",
"tsup": "^7.1.0",
"tsx": "^3.12.7",
"typescript": "^5.1.6",
"typescript": "^5.2.2",
"vitepress": "1.0.0-rc.10",
"vitest": "^0.34.1",
"vitest-mock-extended": "^1.1.4",
"vitest": "^0.34.6",
"vitest-mock-extended": "^1.3.1",
"vue": "^3.3.4",
"webextension-polyfill": "^0.10.0"
},
+591 -255
View File
File diff suppressed because it is too large Load Diff
+8 -1
View File
@@ -10,7 +10,7 @@ const spinner = ora('Building WXT').start();
const startTime = Date.now();
const outDir = 'dist';
const virtualEntrypoints = ['background', 'content-script'];
const virtualEntrypoints = ['background', 'content-script', 'unlisted-script'];
await fs.rm(outDir, { recursive: true, force: true });
@@ -48,6 +48,13 @@ await Promise.all([
silent: true,
external: ['vite'],
}),
tsup.build({
entry: { sandbox: 'src/client/sandbox/index.ts' },
format: ['esm'],
sourcemap: 'inline',
dts: true,
silent: true,
}),
...virtualEntrypoints.map((entryName) =>
tsup.build({
entry: {
@@ -0,0 +1,336 @@
/** @vitest-environment jsdom */
import { describe, it, expect, vi, beforeEach } from 'vitest';
import { ContentScriptContext, createContentScriptUi } from '..';
import { createIsolatedElement } from '@webext-core/isolated-element';
import { mock } from 'vitest-mock-extended';
import { browser } from '../browser';
vi.mock('webextension-polyfill', () =>
vi.importActual('../virtual-modules/fake-browser'),
);
vi.mock('@webext-core/isolated-element', async () => {
const { vi } = await import('vitest');
return {
createIsolatedElement: vi.fn(),
};
});
const createIsolatedElementMock = vi.mocked(createIsolatedElement);
const testApp = (container: Element) => {
const app = document.createElement('div');
app.textContent = 'App';
container.append(app);
};
const createCtx = () => new ContentScriptContext('test');
const fetch = vi.fn();
describe('createContentScriptUi', () => {
beforeEach(() => {
document.body.innerHTML = `
<div id="parent">
<p id="one">one</p>
<p id="two">two</p>
<p id="three"></p>
</div>
`;
window.fetch = fetch;
fetch.mockResolvedValue({ text: () => Promise.resolve('') });
createIsolatedElementMock.mockImplementation(async (config) => {
const parentElement = document.createElement(config.name);
const isolatedElement = document.createElement('html');
parentElement.append(isolatedElement);
return {
isolatedElement,
parentElement: parentElement,
shadow: mock<ShadowRoot>({
querySelector: (selector: string) => {
if (selector === 'html') return isolatedElement;
},
}),
};
});
});
describe('css', () => {
it('should load the CSS for the current entrypoint when cssInjectionMode=ui', async () => {
fetch.mockResolvedValue({ text: () => Promise.resolve('body {}') });
const ctx = new ContentScriptContext('test', {
matches: [],
cssInjectionMode: 'ui',
});
await createContentScriptUi(ctx, {
name: 'test',
type: 'inline',
mount: testApp,
});
expect(fetch).toBeCalledTimes(1);
expect(fetch).toBeCalledWith(
`chrome-extension://${browser.runtime.id}/content-scripts/${__ENTRYPOINT__}.css`,
);
expect(createIsolatedElementMock).toBeCalledTimes(1);
expect(createIsolatedElementMock).toBeCalledWith(
expect.objectContaining({
css: {
textContent: 'body {}',
},
}),
);
});
it('should still load the UI when fetch fails to load CSS file when cssInjectionMode=ui', async () => {
const error = Error('Test fetch error');
fetch.mockRejectedValue(error);
const ctx = new ContentScriptContext('test', {
matches: [],
cssInjectionMode: 'ui',
});
await createContentScriptUi(ctx, {
name: 'test',
type: 'inline',
mount: testApp,
});
expect(fetch).toBeCalledTimes(1);
expect(fetch).toBeCalledWith(
`chrome-extension://${browser.runtime.id}/content-scripts/${__ENTRYPOINT__}.css`,
);
expect(createIsolatedElementMock).toBeCalledTimes(1);
expect(createIsolatedElementMock).toBeCalledWith(
expect.objectContaining({
css: {
textContent: '',
},
}),
);
});
it.each(['manifest', 'manual'] as const)(
'should not fetch CSS when cssInjectionMode=%s',
async (cssInjectionMode) => {
const ctx = new ContentScriptContext('test', {
matches: [],
cssInjectionMode,
});
await createContentScriptUi(ctx, {
name: 'test',
type: 'inline',
mount: testApp,
});
expect(fetch).not.toBeCalled();
},
);
});
describe('mount', () => {
describe('append option', () => {
it.each([undefined, 'last' as const])(
'should append the element as the last child to the anchor when append=%s',
async (append) => {
const ui = await createContentScriptUi(createCtx(), {
name: 'test-app',
type: 'inline',
anchor: '#parent',
append,
mount: testApp,
});
ui.mount();
expect(
document.querySelector('#parent > :nth-child(4)')?.tagName,
).toEqual('TEST-APP');
},
);
it('should append the element as the first child to the anchor when append=first', async () => {
const ui = await createContentScriptUi(createCtx(), {
name: 'test-app',
type: 'inline',
anchor: '#parent',
append: 'first',
mount: testApp,
});
ui.mount();
expect(
document.querySelector('#parent > :nth-child(1)')?.tagName,
).toEqual('TEST-APP');
});
it('should append the element normally when append=first but there are no other children', async () => {
const ui = await createContentScriptUi(createCtx(), {
name: 'test-app',
type: 'inline',
anchor: '#three',
append: 'first',
mount: testApp,
});
ui.mount();
expect(
document.querySelector('#three > :nth-child(1)')?.tagName,
).toEqual('TEST-APP');
});
it('should replace the anchor with the element when append=replace', async () => {
const ui = await createContentScriptUi(createCtx(), {
name: 'test-app',
type: 'inline',
anchor: '#two',
append: 'replace',
mount: testApp,
});
ui.mount();
expect(
document.querySelector('#parent > :nth-child(2)')?.tagName,
).toEqual('TEST-APP');
});
it('should append the element after the anchor when append=before', async () => {
const ui = await createContentScriptUi(createCtx(), {
name: 'test-app',
type: 'inline',
anchor: '#two',
append: 'before',
mount: testApp,
});
ui.mount();
expect(
document.querySelector('#parent > :nth-child(2)')?.tagName,
).toEqual('TEST-APP');
});
it('should append the element after the anchor when append=after', async () => {
const ui = await createContentScriptUi(createCtx(), {
name: 'test-app',
type: 'inline',
anchor: '#two',
append: 'after',
mount: testApp,
});
ui.mount();
expect(
document.querySelector('#parent > :nth-child(3)')?.tagName,
).toEqual('TEST-APP');
});
it('should apply a custom function', async () => {
const ui = await createContentScriptUi(createCtx(), {
name: 'test-app',
type: 'inline',
anchor: '#three',
append: (anchor, ui) => anchor.replaceWith(ui),
mount: testApp,
});
ui.mount();
expect(
document.querySelector('#parent > :nth-child(3)')?.tagName,
).toEqual('TEST-APP');
});
});
it('should default the anchor to the body when unset', async () => {
const ui = await createContentScriptUi(createCtx(), {
name: 'test-app',
type: 'inline',
mount: testApp,
});
ui.mount();
expect(document.querySelector('body > :nth-child(2)')?.tagName).toEqual(
'TEST-APP',
);
});
it.each(['#four', () => document.querySelector('#four')])(
"should throw an error if the anchor doesn't exist",
async (anchor) => {
const ui = await createContentScriptUi(createCtx(), {
name: 'test',
type: 'inline',
anchor,
mount: testApp,
});
expect(ui.mount).toThrow(
'Failed to mount content script ui: could not find anchor element',
);
},
);
});
describe('remove', () => {
it("should not fail if the ui hasn't been mounted", async () => {
const ui = await createContentScriptUi(createCtx(), {
name: 'test-app',
type: 'inline',
mount: testApp,
});
ui.remove();
});
it('should automatically remove the UI when the context is invalidated', async () => {
const ctx = createCtx();
const ui = await createContentScriptUi(ctx, {
name: 'test-app',
type: 'inline',
mount: testApp,
});
ui.mount();
expect(document.querySelector('test-app')).toBeDefined();
ctx.abort();
expect(document.querySelector('test-app')).toBeNull();
});
});
describe('type', () => {
it.each(['inline', 'overlay', 'modal'] as const)(
'should render type=%s',
async (type) => {
const ui = await createContentScriptUi(createCtx(), {
name: 'test-app',
type,
mount: testApp,
});
ui.mount();
expect(document.querySelector('test-app')).toBeDefined();
},
);
});
describe('anchor', () => {
it.each([
() => '#two',
() => () => '#two',
() => document.querySelector('#two'),
() => () => document.querySelector('#two'),
])('should render anchor=%s', async (getAnchor) => {
const ui = await createContentScriptUi(createCtx(), {
name: 'test-app',
type: 'inline',
anchor: getAnchor(),
mount: testApp,
});
ui.mount();
expect(document.querySelector('test-app')).toBeDefined();
});
});
});
@@ -0,0 +1,25 @@
import { describe, expect, it, vi } from 'vitest';
import { defineBackground } from '../defineBackground';
import { BackgroundDefinition } from '../../core/types';
describe('defineBackground', () => {
it('should return the object definition when given an object', () => {
const definition: BackgroundDefinition = {
include: [''],
persistent: false,
main: vi.fn(),
};
const actual = defineBackground(definition);
expect(actual).toEqual(definition);
});
it('should return the object definition when given a main function', () => {
const main = vi.fn();
const actual = defineBackground(main);
expect(actual).toEqual({ main });
});
});
@@ -0,0 +1,17 @@
import { describe, expect, it, vi } from 'vitest';
import { defineContentScript } from '../defineContentScript';
import { ContentScriptDefinition } from '../../core/types';
describe('defineContentScript', () => {
it('should return the object passed in', () => {
const definition: ContentScriptDefinition = {
matches: [],
include: [''],
main: vi.fn(),
};
const actual = defineContentScript(definition);
expect(actual).toEqual(definition);
});
});
+298
View File
@@ -0,0 +1,298 @@
import { createIsolatedElement } from '@webext-core/isolated-element';
import { browser } from './browser';
import { logger } from './utils/logger';
import { ContentScriptContext } from '.';
/**
* Utility for mounting content script UI's with isolated styles. Automatically removed from the DOM
* when the content script's context is invalidated.
*
* See <https://wxt.dev/entrypoints/content-scripts.html#ui> for full documentation.
*
* @example
* // entrypoints/example-ui.content/index.ts
* import "./style.css"
*
* export default defineContentScript({
* matches: ["*://*.google.com/*"],
* cssInjectionMode: "ui",
*
* async main(ctx) {
* const ui = await createContentScriptUi(ctx, {
* name: "example-overlay",
* type: "modal",
* mount(container) {
* const app = document.createElement("div");
* app.textContent = "Content Script UI";
* container.append(app);
* }
* })
* ui.mount();
* }
* })
*/
export async function createContentScriptUi<T>(
ctx: ContentScriptContext,
options: ContentScriptUiOptions<T>,
): Promise<ContentScriptUi<T>> {
const css = [options.css ?? ''];
if (ctx.options?.cssInjectionMode === 'ui') {
css.push(await loadCss());
}
const {
isolatedElement: uiContainer,
parentElement: shadowHost,
shadow,
} = await createIsolatedElement({
name: options.name,
css: {
textContent: css.join('\n').trim(),
},
mode: 'open',
});
const getAnchor = (): Element | undefined => {
if (options.anchor == null) return document.body;
let resolved =
typeof options.anchor === 'function' ? options.anchor() : options.anchor;
if (typeof resolved === 'string')
return document.querySelector<Element>(resolved) ?? undefined;
return resolved ?? undefined;
};
let mounted: T;
const mount = () => {
const anchor = getAnchor();
if (anchor == null)
throw Error(
'Failed to mount content script ui: could not find anchor element',
);
// Mount UI inside shadow root
mounted = options.mount(uiContainer);
// Add shadow root element to DOM
switch (options.append) {
case undefined:
case 'last':
anchor.append(shadowHost);
break;
case 'first':
if (anchor.firstChild) {
anchor.insertBefore(shadowHost, anchor.firstChild);
} else {
anchor.append(shadowHost);
}
break;
case 'replace':
anchor.replaceWith(shadowHost);
break;
case 'after':
anchor.replaceWith(anchor, shadowHost);
break;
case 'before':
anchor.replaceWith(shadowHost, anchor);
break;
default:
options.append(anchor, shadowHost);
break;
}
// Apply types
if (options.type !== 'inline') {
if (options.zIndex != null)
shadowHost.style.zIndex = String(options.zIndex);
shadowHost.style.overflow = 'visible';
shadowHost.style.position = 'relative';
shadowHost.style.width = '0';
shadowHost.style.height = '0';
shadowHost.style.display = 'block';
const html = shadow.querySelector('html')!;
// HTML doesn't exist in tests
if (options.type === 'overlay') {
html.style.position = 'absolute';
if (options.alignment?.startsWith('bottom-')) html.style.bottom = '0';
else html.style.top = '0';
if (options.alignment?.endsWith('-right')) html.style.right = '0';
else html.style.left = '0';
} else {
html.style.position = 'fixed';
html.style.top = '0';
html.style.bottom = '0';
html.style.left = '0';
html.style.right = '0';
}
}
};
const remove = () => {
// Detatch shadow root from DOM
shadowHost.remove();
// Cleanup mounted state
options.onRemove?.(mounted);
// Remove children from uiContainer
while (uiContainer.lastChild)
uiContainer.removeChild(uiContainer.lastChild);
};
ctx.onInvalidated(remove);
return {
shadow,
shadowHost,
uiContainer,
mount,
remove,
mounted: mounted!,
};
}
/**
* Load the CSS for the current entrypoint.
*/
async function loadCss(): Promise<string> {
const url = browser.runtime.getURL(`/content-scripts/${__ENTRYPOINT__}.css`);
try {
const res = await fetch(url);
const css = await res.text();
// Replace :root selectors with :host since we're in a shadow root
return css.replaceAll(':root', ':host');
} catch (err) {
logger.warn(
`Failed to load styles @ ${url}. Did you forget to import the stylesheet in your entrypoint?`,
err,
);
return '';
}
}
export interface ContentScriptUi<T> {
/**
* The `HTMLElement` hosting the shadow root used to isolate the UI's styles. This is the element
* that get's added to the DOM. This element's style is not isolated from the webpage.
*/
shadowHost: HTMLElement;
/**
* The container element inside the `ShadowRoot` whose styles are isolated. The UI is mounted
* inside this `HTMLElement`.
*/
uiContainer: HTMLElement;
/**
* The shadow root performing the isolation.
*/
shadow: ShadowRoot;
/**
* Custom data returned from the `options.mount` function.
*/
mounted: T;
/**
* Function that mounts or remounts the UI on the page.
*/
mount: () => void;
/**
* Function that removes the UI from the webpage.
*/
remove: () => void;
}
interface BaseContentScriptUiOptions<T> {
/**
* The name of the custom component used to host the ShadowRoot. Must be kebab-case.
*/
name: string;
/**
* In combination with `anchor`, decide how to add the UI to the DOM.
*
* - `"last"` (default) - Add the UI as the last child of the `anchor` element
* - `"first"` - Add the UI as the last child of the `anchor` element
* - `"replace"` - Replace the `anchor` element with the UI.
* - `"before"` - Add the UI as the sibling before the `anchor` element
* - `"after"` - Add the UI as the sibling after the `anchor` element
* - `(anchor, ui) => void` - Customizable function that let's you add the UI to the DOM
*/
append?: ContentScriptAppendMode | ((anchor: Element, ui: Element) => void);
/**
* A CSS selector, element, or function that returns one of the two. Along with `append`, the
* `anchor` dictates where in the page the UI will be added.
*/
anchor?:
| string
| Element
| null
| undefined
| (() => string | Element | null | undefined);
/**
* Callback executed when mounting the UI. This function should create and append the UI to the
* `container` element. It is called every time `ui.mount()` is called
*
* Optionally return a value that can be accessed at `ui.mounted` or in the `onRemove` callback.
*/
mount: (container: Element) => T;
/**
* Callback called when the UI is removed from the webpage. Use to cleanup your UI, like
* unmounting your vue or react apps.
*/
onRemove?: (mounted: T) => void;
/**
* Custom CSS text to apply to the UI. If your content script imports/generates CSS and you've
* set `cssInjectionMode: "ui"`, the imported CSS will be included automatically. You do not need
* to pass those styles in here. This is for any additional styles not in the imported CSS.
*
* See <https://wxt.dev/entrypoints/content-scripts.html#ui> for more info.
*/
css?: string;
}
export type OverlayContentScriptUiOptions<T> = BaseContentScriptUiOptions<T> & {
type: 'overlay';
/**
* When using `type: "overlay"`, the mounted element is 0px by 0px in size. Alignment specifies
* which corner is aligned with that 0x0 pixel space.
*
* @default "top-left"
*/
alignment?: ContentScriptUiOverlayAlignment;
/**
* The `z-index` used on the `shadowHost`. Set to a positive number to show your UI over website
* content.
*/
zIndex?: number;
};
export type ModalContentScriptUiOptions<T> = BaseContentScriptUiOptions<T> & {
type: 'modal';
/**
* The `z-index` used on the `shadowHost`. Set to a positive number to show your UI over website
* content.
*/
zIndex?: number;
};
export type InlineContentScriptUiOptions<T> = BaseContentScriptUiOptions<T> & {
type: 'inline';
};
export type ContentScriptUiOverlayAlignment =
| 'top-left'
| 'top-right'
| 'bottom-left'
| 'bottom-right';
export type ContentScriptAppendMode =
| 'last'
| 'first'
| 'replace'
| 'before'
| 'after';
export type ContentScriptUiOptions<T> =
| OverlayContentScriptUiOptions<T>
| ModalContentScriptUiOptions<T>
| InlineContentScriptUiOptions<T>;
+6 -6
View File
@@ -1,12 +1,12 @@
import { BackgroundScriptDefintition } from '..';
import { BackgroundDefinition } from '..';
export function defineBackground(main: () => void): BackgroundScriptDefintition;
export function defineBackground(main: () => void): BackgroundDefinition;
export function defineBackground(
definition: BackgroundScriptDefintition,
): BackgroundScriptDefintition;
definition: BackgroundDefinition,
): BackgroundDefinition;
export function defineBackground(
arg: (() => void) | BackgroundScriptDefintition,
): BackgroundScriptDefintition {
arg: (() => void) | BackgroundDefinition,
): BackgroundDefinition {
if (typeof arg === 'function') return { main: arg };
return arg;
}
+1 -1
View File
@@ -1,4 +1,4 @@
export * from './defineContentScript';
export * from './defineBackground';
export * from './mountContentScriptUi';
export * from './createContentScriptUi';
export * from './utils/ContentScriptContext';
-3
View File
@@ -1,3 +0,0 @@
export function mountContentScriptUi() {
throw Error('Not implemented: mountContentScriptUi');
}
@@ -0,0 +1,24 @@
import { describe, expect, it, vi } from 'vitest';
import { defineUnlistedScript } from '../defineUnlistedScript';
import { UnlistedScriptDefinition } from '../../../core/types';
describe('defineUnlistedScript', () => {
it('should return the object definition when given an object', () => {
const definition: UnlistedScriptDefinition = {
include: [''],
main: vi.fn(),
};
const actual = defineUnlistedScript(definition);
expect(actual).toEqual(definition);
});
it('should return the object definition when given a main function', () => {
const main = vi.fn();
const actual = defineUnlistedScript(main);
expect(actual).toEqual({ main });
});
});
@@ -0,0 +1,14 @@
import { UnlistedScriptDefinition } from '../../core/types';
export function defineUnlistedScript(
main: () => void,
): UnlistedScriptDefinition;
export function defineUnlistedScript(
definition: UnlistedScriptDefinition,
): UnlistedScriptDefinition;
export function defineUnlistedScript(
arg: (() => void) | UnlistedScriptDefinition,
): UnlistedScriptDefinition {
if (typeof arg === 'function') return { main: arg };
return arg;
}
+1
View File
@@ -0,0 +1 @@
export * from './defineUnlistedScript';
+12 -5
View File
@@ -1,3 +1,4 @@
import { ContentScriptDefinition } from '../../core/types';
import { browser } from '../browser';
import { logger } from './logger';
@@ -13,7 +14,10 @@ export class ContentScriptContext extends AbortController {
#isTopFrame = window.self === window.top;
constructor(private readonly contentScriptName: string) {
constructor(
private readonly contentScriptName: string,
public readonly options?: Omit<ContentScriptDefinition, 'main'>,
) {
super();
if (this.#isTopFrame) {
@@ -157,10 +161,13 @@ export class ContentScriptContext extends AbortController {
#stopOldScripts() {
// Use postMessage so it get's sent to all the frames of the page.
window.postMessage({
event: ContentScriptContext.SCRIPT_STARTED_MESSAGE_TYPE,
contentScriptName: this.contentScriptName,
});
window.postMessage(
{
event: ContentScriptContext.SCRIPT_STARTED_MESSAGE_TYPE,
contentScriptName: this.contentScriptName,
},
'*',
);
}
#listenForNewerScripts() {
@@ -37,6 +37,6 @@ try {
);
}
} catch (err) {
logger.error('The background script crashed on startup!');
logger.error('The background crashed on startup!');
throw err;
}
@@ -4,10 +4,14 @@ import { ContentScriptContext } from '../utils/ContentScriptContext';
(async () => {
try {
const ctx = new ContentScriptContext(__ENTRYPOINT__);
const { main, ...options } = definition;
const ctx = new ContentScriptContext(__ENTRYPOINT__, options);
await definition.main(ctx);
await main(ctx);
} catch (err) {
logger.error('The content script crashed on startup!', err);
logger.error(
`The content script "${__ENTRYPOINT__}" crashed on startup!`,
err,
);
}
})();
@@ -0,0 +1,13 @@
import definition from 'virtual:user-unlisted-script';
import { logger } from '../utils/logger';
(async () => {
try {
await definition.main();
} catch (err) {
logger.error(
`The unlisted script "${__ENTRYPOINT__}" crashed on startup!`,
err,
);
}
})();
+6 -1
View File
@@ -6,7 +6,7 @@ declare module '*?raw' {
}
declare module 'virtual:user-background' {
const definition: import('../../').BackgroundScriptDefintition;
const definition: import('../../').BackgroundDefinition;
export default definition;
}
@@ -15,6 +15,11 @@ declare module 'virtual:user-content-script' {
export default definition;
}
declare module 'virtual:user-unlisted-script' {
const definition: import('../../').UnlistedScriptDefinition;
export default definition;
}
// Globals defined by the vite-plugins/devServerGlobals.ts and utils/globals.ts
declare const __COMMAND__: 'build' | 'serve';
declare const __DEV_SERVER_PROTOCOL__: string;
@@ -261,6 +261,43 @@ describe('findEntrypoints', () => {
});
});
it.each<[string, Omit<GenericEntrypoint, 'options'>]>([
[
'injected.ts',
{
type: 'unlisted-script',
name: 'injected',
inputPath: resolve(config.entrypointsDir, 'injected.ts'),
outputDir: config.outDir,
},
],
[
'injected/index.ts',
{
type: 'unlisted-script',
name: 'injected',
inputPath: resolve(config.entrypointsDir, 'injected/index.ts'),
outputDir: config.outDir,
},
],
])(
'should find and load unlisted-script entrypoint config from %s',
async (path, expected) => {
const options: GenericEntrypoint['options'] = {};
globMock.mockResolvedValueOnce([path]);
importEntrypointFileMock.mockResolvedValue(options);
const entrypoints = await findEntrypoints(config);
expect(entrypoints).toHaveLength(1);
expect(entrypoints[0]).toEqual({ ...expected, options });
expect(importEntrypointFileMock).toBeCalledWith(
expected.inputPath,
config,
);
},
);
it.each<[string, GenericEntrypoint]>([
// Sandbox
[
@@ -456,28 +493,6 @@ describe('findEntrypoints', () => {
},
],
// unlisted-script
[
'injected.ts',
{
type: 'unlisted-script',
name: 'injected',
inputPath: resolve(config.entrypointsDir, 'injected.ts'),
outputDir: config.outDir,
options: {},
},
],
[
'injected/index.ts',
{
type: 'unlisted-script',
name: 'injected',
inputPath: resolve(config.entrypointsDir, 'injected/index.ts'),
outputDir: config.outDir,
options: {},
},
],
// unlisted-style
[
'iframe.scss',
+14 -5
View File
@@ -53,7 +53,11 @@ async function buildSingleEntrypoint(
config: InternalConfig,
): Promise<BuildStepOutput> {
// Should this entrypoint be wrapped by the vite-plugins/virtualEntrypoint plugin?
const isVirtual = ['background', 'content-script'].includes(entrypoint.type);
const isVirtual = [
'background',
'content-script',
'unlisted-script',
].includes(entrypoint.type);
const entry = isVirtual
? `virtual:wxt-${entrypoint.type}?${entrypoint.inputPath}`
: entrypoint.inputPath;
@@ -84,10 +88,15 @@ async function buildSingleEntrypoint(
config.outDir,
'.js',
),
// Output content script CSS to assets/ with a hash to prevent conflicts. Defaults to
// "[name].[ext]" in lib mode, which usually results in "style.css". That means multiple
// content scripts with styles would overwrite each other if it weren't changed below.
assetFileNames: `assets/${entrypoint.name}.[ext]`,
// Output content script CSS to `content-scripts/`, but all other scripts are written to
// `assets/`.
assetFileNames: ({ name }) => {
if (entrypoint.type === 'content-script' && name?.endsWith('css')) {
return `content-scripts/${entrypoint.name}.[ext]`;
} else {
return `assets/${entrypoint.name}.[ext]`;
}
},
},
},
},
+76 -26
View File
@@ -1,7 +1,7 @@
import { relative, resolve } from 'path';
import {
BackgroundEntrypoint,
BackgroundScriptDefintition,
BackgroundDefinition,
BaseEntrypointOptions,
ContentScriptDefinition,
ContentScriptEntrypoint,
@@ -10,6 +10,7 @@ import {
InternalConfig,
OptionsEntrypoint,
PopupEntrypoint,
UnlistedScriptDefinition,
} from '../types';
import fs from 'fs-extra';
import { minimatch } from 'minimatch';
@@ -17,7 +18,10 @@ import { parseHTML } from 'linkedom';
import JSON5 from 'json5';
import { importEntrypointFile } from '../utils/importEntrypointFile';
import glob from 'fast-glob';
import { getEntrypointName } from '../utils/entrypoints';
import {
getEntrypointName,
resolvePerBrowserOption,
} from '../utils/entrypoints';
import { VIRTUAL_NOOP_BACKGROUND_MODULE_ID } from '../vite-plugins/noopBackground';
import { CSS_EXTENSIONS_PATTERN } from '../utils/paths';
@@ -71,15 +75,14 @@ export async function findEntrypoints(
hasBackground = true;
break;
case 'content-script':
entrypoint = await getContentScriptEntrypoint(
config,
getEntrypointName(config.entrypointsDir, path),
path,
);
entrypoint = await getContentScriptEntrypoint(config, path);
break;
case 'unlisted-page':
entrypoint = await getUnlistedPageEntrypoint(config, path);
break;
case 'unlisted-script':
entrypoint = await getUnlistedScriptEntrypoint(config, path);
break;
case 'content-script-style':
entrypoint = {
type,
@@ -198,12 +201,19 @@ async function getPopupEntrypoint(
}
}
const mv2KeyContent = document
const mv2TypeContent = document
.querySelector("meta[name='manifest.type']")
?.getAttribute('content');
if (mv2KeyContent) {
if (mv2TypeContent) {
options.mv2Key =
mv2KeyContent === 'page_action' ? 'page_action' : 'browser_action';
mv2TypeContent === 'page_action' ? 'page_action' : 'browser_action';
}
const browserStyleContent = document
.querySelector("meta[name='manifest.browser_style']")
?.getAttribute('content');
if (browserStyleContent) {
options.browserStyle = browserStyleContent === 'true';
}
return {
@@ -278,6 +288,35 @@ async function getUnlistedPageEntrypoint(
};
}
/**
* @param path Absolute path to the script's file.
* @param content String contents of the file at the path.
*/
async function getUnlistedScriptEntrypoint(
config: InternalConfig,
path: string,
): Promise<GenericEntrypoint> {
const name = getEntrypointName(config.entrypointsDir, path);
const defaultExport = await importEntrypointFile<UnlistedScriptDefinition>(
path,
config,
);
if (defaultExport == null) {
throw Error(
`${name}: Default export not found, did you forget to call "export default defineUnlistedScript(...)"?`,
);
}
const { main: _, ...moduleOptions } = defaultExport;
const options: Omit<UnlistedScriptDefinition, 'main'> = moduleOptions;
return {
type: 'unlisted-script',
name,
inputPath: path,
outputDir: config.outDir,
options,
};
}
/**
* @param path Absolute path to the background's TS file.
*/
@@ -285,22 +324,31 @@ async function getBackgroundEntrypoint(
config: InternalConfig,
path: string,
): Promise<BackgroundEntrypoint> {
let options: Omit<BackgroundScriptDefintition, 'main'> = {};
const name = 'background';
let options: Omit<BackgroundDefinition, 'main'> = {};
if (path !== VIRTUAL_NOOP_BACKGROUND_MODULE_ID) {
const defaultExport =
await importEntrypointFile<BackgroundScriptDefintition>(path, config);
const defaultExport = await importEntrypointFile<BackgroundDefinition>(
path,
config,
);
if (defaultExport == null) {
throw Error('Background script does not have a default export');
throw Error(
`${name}: Default export not found, did you forget to call "export default defineBackground(...)"?`,
);
}
const { main: _, ...moduleOptions } = defaultExport;
options = moduleOptions;
}
return {
type: 'background',
name: 'background',
name,
inputPath: path,
outputDir: config.outDir,
options: options,
options: {
...options,
type: resolvePerBrowserOption(options.type, config.browser),
persistent: resolvePerBrowserOption(options.persistent, config.browser),
},
};
}
@@ -309,17 +357,19 @@ async function getBackgroundEntrypoint(
*/
async function getContentScriptEntrypoint(
config: InternalConfig,
name: string,
path: string,
): Promise<ContentScriptEntrypoint> {
const name = getEntrypointName(config.entrypointsDir, path);
const { main: _, ...options } =
await importEntrypointFile<ContentScriptDefinition>(path, config);
if (options == null) {
throw Error(`Content script ${name} does not have a default export`);
throw Error(
`${name}: Default export not found, did you forget to call "export default defineContentScript(...)"?`,
);
}
return {
type: 'content-script',
name: getEntrypointName(config.entrypointsDir, path),
name,
inputPath: path,
outputDir: resolve(config.outDir, CONTENT_SCRIPT_OUT_DIR),
options,
@@ -349,14 +399,14 @@ const PATH_GLOB_TO_TYPE_MAP: Record<string, Entrypoint['type'] | 'ignored'> = {
'devtools.html': 'devtools',
'devtools/index.html': 'devtools',
'background.ts': 'background',
'background/index.ts': 'background',
'background.[jt]s': 'background',
'background/index.[jt]s': 'background',
[VIRTUAL_NOOP_BACKGROUND_MODULE_ID]: 'background',
'content.ts?(x)': 'content-script',
'content/index.ts?(x)': 'content-script',
'*.content.ts?(x)': 'content-script',
'*.content/index.ts?(x)': 'content-script',
'content.[jt]s?(x)': 'content-script',
'content/index.[jt]s?(x)': 'content-script',
'*.content.[jt]s?(x)': 'content-script',
'*.content/index.[jt]s?(x)': 'content-script',
[`content.${CSS_EXTENSIONS_PATTERN}`]: 'content-script-style',
[`*.content.${CSS_EXTENSIONS_PATTERN}`]: 'content-script-style',
[`content/index.${CSS_EXTENSIONS_PATTERN}`]: 'content-script-style',
@@ -370,7 +420,7 @@ const PATH_GLOB_TO_TYPE_MAP: Record<string, Entrypoint['type'] | 'ignored'> = {
'*.html': 'unlisted-page',
'*/index.html': 'unlisted-page',
'*.ts': 'unlisted-script',
'*.[jt]s': 'unlisted-script',
'*/index.ts': 'unlisted-script',
[`*.${CSS_EXTENSIONS_PATTERN}`]: 'unlisted-style',
[`*/index.${CSS_EXTENSIONS_PATTERN}`]: 'unlisted-style',
+5 -5
View File
@@ -213,14 +213,14 @@ async function writeTsConfigFile(
"lib": ["DOM", "WebWorker"],
"skipLibCheck": true,
"paths": {
"@@": ["${rootPath}"],
"@@/*": ["${rootPath}/*"],
"~~": ["${rootPath}"],
"~~/*": ["${rootPath}/*"],
"@": ["${srcPath}"],
"@/*": ["${srcPath}/*"],
"~": ["${srcPath}"],
"~/*": ["${srcPath}/*"]
"~/*": ["${srcPath}/*"],
"@@": ["${rootPath}"],
"@@/*": ["${rootPath}/*"],
"~~": ["${rootPath}"],
"~~/*": ["${rootPath}/*"]
}
},
"include": [
+79
View File
@@ -0,0 +1,79 @@
import { describe, expect, it, vi } from 'vitest';
import { createExtensionRunner } from '..';
import { fakeInternalConfig } from '../../../testing/fake-objects';
import { mock } from 'vitest-mock-extended';
import { createSafariRunner } from '../safari';
import { ExtensionRunner } from '../extension-runner';
import { createWslRunner } from '../wsl';
import { createManualRunner } from '../manual';
import { isWsl } from '../../utils/wsl';
import { createWebExtRunner } from '../web-ext';
vi.mock('../../utils/wsl');
const isWslMock = vi.mocked(isWsl);
vi.mock('../safari');
const createSafariRunnerMock = vi.mocked(createSafariRunner);
vi.mock('../wsl');
const createWslRunnerMock = vi.mocked(createWslRunner);
vi.mock('../manual');
const createManualRunnerMock = vi.mocked(createManualRunner);
vi.mock('../web-ext');
const createWebExtRunnerMock = vi.mocked(createWebExtRunner);
describe('createExtensionRunner', () => {
it('should return a Safari runner when browser is "safari"', async () => {
const config = fakeInternalConfig({
browser: 'safari',
});
const safariRunner = mock<ExtensionRunner>();
createSafariRunnerMock.mockReturnValue(safariRunner);
await expect(createExtensionRunner(config)).resolves.toBe(safariRunner);
});
it('should return a WSL runner when `is-wsl` is true', async () => {
isWslMock.mockResolvedValueOnce(true);
const config = fakeInternalConfig({
browser: 'chrome',
});
const wslRunner = mock<ExtensionRunner>();
createWslRunnerMock.mockReturnValue(wslRunner);
await expect(createExtensionRunner(config)).resolves.toBe(wslRunner);
});
it('should return a manual runner when `runner.disabled` is true', async () => {
isWslMock.mockResolvedValueOnce(false);
const config = fakeInternalConfig({
browser: 'chrome',
runnerConfig: {
config: {
disabled: true,
},
},
});
const manualRunner = mock<ExtensionRunner>();
createManualRunnerMock.mockReturnValue(manualRunner);
await expect(createExtensionRunner(config)).resolves.toBe(manualRunner);
});
it('should return a web-ext runner otherwise', async () => {
const config = fakeInternalConfig({
browser: 'chrome',
runnerConfig: {
config: {
disabled: undefined,
},
},
});
const manualRunner = mock<ExtensionRunner>();
createWebExtRunnerMock.mockReturnValue(manualRunner);
await expect(createExtensionRunner(config)).resolves.toBe(manualRunner);
});
});
+4 -2
View File
@@ -3,14 +3,16 @@ import { ExtensionRunner } from './extension-runner';
import { createWslRunner } from './wsl';
import { createWebExtRunner } from './web-ext';
import { createSafariRunner } from './safari';
import { createManualRunner } from './manual';
import { isWsl } from '../utils/wsl';
export async function createExtensionRunner(
config: InternalConfig,
): Promise<ExtensionRunner> {
if (config.browser === 'safari') return createSafariRunner();
const { default: isWsl } = await import('is-wsl'); // ESM only, requires dynamic import
if (isWsl) return createWslRunner();
if (await isWsl()) return createWslRunner();
if (config.runnerConfig.config?.disabled) return createManualRunner();
return createWebExtRunner();
}
+21
View File
@@ -0,0 +1,21 @@
import { ExtensionRunner } from './extension-runner';
import { relative } from 'node:path';
/**
* The manual runner tells the user to load the unpacked extension manually.
*/
export function createManualRunner(): ExtensionRunner {
return {
async openBrowser(config) {
config.logger.info(
`Load "${relative(
process.cwd(),
config.outDir,
)}" as an unpacked extension manually`,
);
},
async closeBrowser() {
// noop
},
};
}
+22 -6
View File
@@ -6,8 +6,14 @@ import {
} from './types';
import * as vite from 'vite';
import { Scripting } from 'webextension-polyfill';
import { getEntrypointBundlePath } from './utils/entrypoints';
import { getContentScriptCssFiles } from './utils/manifest';
import {
getEntrypointBundlePath,
resolvePerBrowserOption,
} from './utils/entrypoints';
import {
getContentScriptCssFiles,
getContentScriptsCssMap,
} from './utils/manifest';
import { buildInternal } from './build';
import { createExtensionRunner } from './runners';
@@ -99,12 +105,22 @@ export function reloadContentScripts(
if (Array.isArray(entry) || entry.type !== 'content-script') return;
const js = [getEntrypointBundlePath(entry, config.outDir, '.js')];
const css = getContentScriptCssFiles([entry], server.currentOutput);
const { include: _1, exclude: _2, ...options } = entry.options;
const cssMap = getContentScriptsCssMap(server.currentOutput, [entry]);
const css = getContentScriptCssFiles([entry], cssMap);
server.reloadContentScript({
...options,
allFrames: resolvePerBrowserOption(
entry.options.allFrames,
config.browser,
),
excludeMatches: resolvePerBrowserOption(
entry.options.excludeMatches,
config.browser,
),
matches: resolvePerBrowserOption(entry.options.matches, config.browser),
runAt: resolvePerBrowserOption(entry.options.runAt, config.browser),
// @ts-expect-error: Chrome accepts this, not typed in webextension-polyfill (https://developer.chrome.com/docs/extensions/reference/scripting/#type-RegisteredContentScript)
world: resolvePerBrowserOption(entry.options.world, config.browser),
js,
css,
});
+48 -11
View File
@@ -177,6 +177,8 @@ export interface InlineConfig {
/**
* Explicitly include bundle analysis when running `wxt build`. This can be overridden by the
* command line `--analysis` option.
*
* @default false
*/
enabled?: boolean;
/**
@@ -184,6 +186,8 @@ export interface InlineConfig {
* bundle will be visualized. See
* [`rollup-plugin-visualizer`](https://github.com/btd/rollup-plugin-visualizer#how-to-use-generated-files)
* for more details.
*
* @default "treemap"
*/
template?: PluginVisualizerOptions['template'];
};
@@ -339,6 +343,7 @@ export interface PopupEntrypoint extends BaseEntrypoint {
mv2Key?: 'browser_action' | 'page_action';
defaultIcon?: Record<string, string>;
defaultTitle?: string;
browserStyle?: boolean;
} & BaseEntrypointOptions;
}
@@ -361,58 +366,84 @@ export type Entrypoint =
export type OnContentScriptStopped = (cb: () => void) => void;
export interface ContentScriptDefinition extends ExcludableEntrypoint {
matches: Manifest.ContentScript['matches'];
matches: PerBrowserOption<Manifest.ContentScript['matches']>;
/**
* See https://developer.chrome.com/docs/extensions/mv3/content_scripts/
* @default "documentIdle"
*/
runAt?: Manifest.ContentScript['run_at'];
runAt?: PerBrowserOption<Manifest.ContentScript['run_at']>;
/**
* See https://developer.chrome.com/docs/extensions/mv3/content_scripts/
* @default false
*/
matchAboutBlank?: Manifest.ContentScript['match_about_blank'];
matchAboutBlank?: PerBrowserOption<
Manifest.ContentScript['match_about_blank']
>;
/**
* See https://developer.chrome.com/docs/extensions/mv3/content_scripts/
* @default []
*/
excludeMatches?: Manifest.ContentScript['exclude_matches'];
excludeMatches?: PerBrowserOption<Manifest.ContentScript['exclude_matches']>;
/**
* See https://developer.chrome.com/docs/extensions/mv3/content_scripts/
* @default []
*/
includeGlobs?: Manifest.ContentScript['include_globs'];
includeGlobs?: PerBrowserOption<Manifest.ContentScript['include_globs']>;
/**
* See https://developer.chrome.com/docs/extensions/mv3/content_scripts/
* @default []
*/
excludeGlobs?: Manifest.ContentScript['exclude_globs'];
excludeGlobs?: PerBrowserOption<Manifest.ContentScript['exclude_globs']>;
/**
* See https://developer.chrome.com/docs/extensions/mv3/content_scripts/
* @default false
*/
allFrames?: Manifest.ContentScript['all_frames'];
allFrames?: PerBrowserOption<Manifest.ContentScript['all_frames']>;
/**
* See https://developer.chrome.com/docs/extensions/mv3/content_scripts/
* @default false
*/
matchOriginAsFallback?: boolean;
matchOriginAsFallback?: PerBrowserOption<boolean>;
/**
* See https://developer.chrome.com/docs/extensions/mv3/content_scripts/
* @default "ISOLATED"
*/
world?: 'ISOLATED' | 'MAIN';
world?: PerBrowserOption<'ISOLATED' | 'MAIN'>;
/**
* Customize how imported/generated styles are injected with the content script. Regardless of the
* mode selected, CSS will always be built and included in the output directory.
*
* - `"manifest"` - Include the CSS in the manifest, under the content script's `css` array.
* - `"manual"` - Exclude the CSS from the manifest. You are responsible for manually loading it
* onto the page. Use `browser.runtime.getURL("content-scripts/<name>.css")` to get the file's
* URL
* - `"ui"` - Exclude the CSS from the manifest. CSS will be automatically added to your UI when
* calling `createContentScriptUi`
*
* @default "manifest"
*/
cssInjectionMode?: PerBrowserOption<'manifest' | 'manual' | 'ui'>;
/**
* Main function executed when the content script is loaded.
*/
main(ctx: ContentScriptContext): void | Promise<void>;
}
export interface BackgroundScriptDefintition extends ExcludableEntrypoint {
type?: 'module';
export interface BackgroundDefinition extends ExcludableEntrypoint {
type?: PerBrowserOption<'module'>;
persistent?: PerBrowserOption<boolean>;
main(): void;
}
export interface UnlistedScriptDefinition extends ExcludableEntrypoint {
/**
* Main function executed when the unlisted script is ran.
*/
main(): void | Promise<void>;
}
export type PerBrowserOption<T> = T | { [browser: TargetBrowser]: T };
export interface ExcludableEntrypoint {
/**
* List of target browsers to include this entrypoint in. Defaults to being included in all
@@ -474,6 +505,12 @@ export interface ConfigEnv {
* Configure how the browser starts up.
*/
export interface ExtensionRunnerConfig {
/**
* Whether or not to open the browser with the extension installed in dev mode.
*
* @default false
*/
disabled?: boolean;
/**
* @see https://extensionworkshop.com/documentation/develop/web-ext-command-reference/#browser-console
*/
+2
View File
@@ -8,6 +8,7 @@ import {
UserManifest,
ExtensionRunnerConfig,
ConfigEnv,
UserConfig,
} from './external';
import { UnimportOptions } from 'unimport';
import { ResolvedConfig } from 'c12';
@@ -48,6 +49,7 @@ export interface InternalConfig {
enabled: boolean;
template: NonNullable<PluginVisualizerOptions['template']>;
};
userConfigMetadata: Omit<ResolvedConfig<UserConfig>, 'config'>;
}
export type EntrypointGroup = Entrypoint | Entrypoint[];
@@ -1,26 +1,36 @@
import { describe, expect, it } from 'vitest';
import { hashContentScriptOptions } from '../content-scripts';
import { fakeInternalConfig } from '../../../testing/fake-objects';
describe('Content Script Utils', () => {
describe('hashContentScriptOptions', () => {
it('should return a string containing all the options with defaults applied', () => {
const hash = hashContentScriptOptions({ matches: [] });
const hash = hashContentScriptOptions(
{ matches: [] },
fakeInternalConfig(),
);
expect(hash).toMatchInlineSnapshot(
'"[[\\"allFrames\\",false],[\\"excludeGlobs\\",[]],[\\"excludeMatches\\",[]],[\\"includeGlobs\\",[]],[\\"matchAboutBlank\\",false],[\\"matches\\",[]],[\\"matchOriginAsFallback\\",false],[\\"runAt\\",\\"document_idle\\"],[\\"world\\",\\"ISOLATED\\"]]"',
'"[[\\"all_frames\\",false],[\\"exclude_globs\\",[]],[\\"exclude_matches\\",[]],[\\"include_globs\\",[]],[\\"match_about_blank\\",false],[\\"match_origin_as_fallback\\",false],[\\"matches\\",[]],[\\"run_at\\",\\"document_idle\\"],[\\"world\\",\\"ISOLATED\\"]]"',
);
});
it('should be consistent regardless of the object ordering and default values', () => {
const hash1 = hashContentScriptOptions({
allFrames: true,
matches: ['*://google.com/*', '*://duckduckgo.com/*'],
matchAboutBlank: false,
});
const hash2 = hashContentScriptOptions({
matches: ['*://duckduckgo.com/*', '*://google.com/*'],
allFrames: true,
});
const hash1 = hashContentScriptOptions(
{
allFrames: true,
matches: ['*://google.com/*', '*://duckduckgo.com/*'],
matchAboutBlank: false,
},
fakeInternalConfig(),
);
const hash2 = hashContentScriptOptions(
{
matches: ['*://duckduckgo.com/*', '*://google.com/*'],
allFrames: true,
},
fakeInternalConfig(),
);
expect(hash1).toBe(hash2);
});
+26 -1
View File
@@ -1,5 +1,9 @@
import { describe, it, expect } from 'vitest';
import { getEntrypointName, getEntrypointOutputFile } from '../entrypoints';
import {
getEntrypointName,
getEntrypointOutputFile,
resolvePerBrowserOption,
} from '../entrypoints';
import { Entrypoint } from '../../types';
import { resolve } from 'path';
@@ -49,4 +53,25 @@ describe('Entrypoint Utils', () => {
expect(actual).toBe(expected);
});
});
describe('resolvePerBrowserOption', () => {
it('should return the value directly', () => {
expect(resolvePerBrowserOption('some-string', '')).toEqual('some-string');
expect(resolvePerBrowserOption(false, '')).toEqual(false);
expect(resolvePerBrowserOption([1], '')).toEqual([1]);
expect(resolvePerBrowserOption(['string'], '')).toEqual(['string']);
});
it('should return the value for the specific browser', () => {
expect(resolvePerBrowserOption({ a: 'one', b: 'two' }, 'a')).toEqual(
'one',
);
expect(resolvePerBrowserOption({ c: ['one'], d: ['two'] }, 'c')).toEqual([
'one',
]);
expect(resolvePerBrowserOption({ c: false, d: true }, 'e')).toEqual(
undefined,
);
});
});
});
@@ -0,0 +1,41 @@
import { describe, expect, it } from 'vitest';
import { importEntrypointFile } from '../importEntrypointFile';
import { fakeInternalConfig } from '../../../testing/fake-objects';
import { resolve } from 'node:path';
const entrypointPath = (filename: string) =>
resolve('src/core/utils/__tests__/test-entrypoints', filename);
const config = fakeInternalConfig({
imports: false,
debug: false,
// Run inside the demo folder so that wxt is in the node_modules
// WXT must also be built for these tests to pass
root: 'demo',
});
describe('importEntrypointFile', () => {
it.each([
['background.ts', { main: expect.any(Function) }],
['content.ts', { main: expect.any(Function), matches: ['<all_urls>'] }],
['unlisted.ts', { main: expect.any(Function) }],
['react.tsx', { main: expect.any(Function) }],
['with-named.ts', { main: expect.any(Function) }],
])(
'should return the default export of test-entrypoints/%s',
async (file, expected) => {
const actual = await importEntrypointFile(entrypointPath(file), config);
expect(actual).toEqual(expected);
},
);
it('should return undefined when there is no default export', async () => {
const actual = await importEntrypointFile(
entrypointPath('no-default-export.ts'),
config,
);
expect(actual).toBeUndefined();
});
});
@@ -0,0 +1,5 @@
import { defineBackground } from '../../../../client';
export default defineBackground({
main() {},
});
@@ -0,0 +1,6 @@
import { defineContentScript } from '../../../../client';
export default defineContentScript({
matches: ['<all_urls>'],
main() {},
});

Some files were not shown because too many files have changed in this diff Show More