Compare commits

..

36 Commits

Author SHA1 Message Date
GitHub Actions 6a30dc46fa chore(release): v0.8.6 2023-10-30 15:41:46 +00:00
Aaron Klinker b75c553e51 fix: Inline WXT modules inside WxtVitest plugin 2023-10-30 10:25:22 -05:00
GitHub Actions a56face03d chore(release): v0.8.5 2023-10-30 14:54:59 +00:00
Aaron Klinker 19756c61ce docs: Add test.server.deps.inline to Vitest guide 2023-10-30 09:48:52 -05:00
Aaron 5f54b4de17 chore: Reduce package size by 70%, 1.92 MB to 590 kB (#190) 2023-10-29 23:00:10 -05:00
Aaron Klinker ea8935c47c Hide code coverage badge while it's broken 2023-10-29 21:24:21 -05:00
Aaron e37f73880d feat: Refactor project structure to export initialize, prepare, and zip functions (#182) 2023-10-29 21:19:31 -05:00
Aaron Klinker 2e24b9e18a chore: Update template docs 2023-10-29 20:24:38 -05:00
Aaron Klinker f8a0fb37a2 fix: Enable Vue SFC auto-imports in vue template 2023-10-29 20:24:27 -05:00
Nenad Novaković dd26b99027 docs: Update auto-imports.md (#186) 2023-10-29 08:29:54 -05:00
Aaron Klinker d9e9b43f8d docs: Improve runner.binaries documentation 2023-10-25 03:14:53 -05:00
GitHub Actions d580083727 chore(release): v0.8.4 2023-10-20 15:26:38 +00:00
Aaron 5a70d9e57d fix: Allow actions without a popup (#181) 2023-10-20 10:20:40 -05:00
GitHub Actions 1b1af245bd chore(release): v0.8.3 2023-10-18 21:38:14 +00:00
Aaron 874a531a62 feat: Add testing utils under wxt/testing (#178) 2023-10-18 16:28:26 -05:00
GitHub Actions a3d409f250 chore(release): v0.8.2 2023-10-17 20:39:45 +00:00
Aaron b6758ca9fa fix(firefox): Stop extending AbortController to fix crash in content scripts (#176) 2023-10-17 15:33:55 -05:00
Aaron 2672308946 chore: Improve output consistency (#175) 2023-10-16 11:00:33 -05:00
GitHub Actions 7ac171ed3b chore(release): v0.8.1 2023-10-16 14:33:06 +00:00
Aaron Klinker 6a93f20bb3 fix: Output action.browser_style correctly 2023-10-16 09:20:40 -05:00
Aaron Klinker 921af6a5a1 Rename jobs 2023-10-15 15:08:34 -05:00
Aaron Klinker 21ebeacd20 chore(deps): Revert node 20 upgrade due to OOM errors in CI 2023-10-15 14:51:36 -05:00
Aaron 527600031f docs: Generate full API docs with typedoc (#174) 2023-10-14 22:03:23 -05:00
Aaron Klinker 91a804c492 Update changelog 2023-10-14 10:40:36 -05:00
Aaron Klinker 54f3785063 Upgrade templates to use v0.8 2023-10-14 10:40:10 -05:00
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
168 changed files with 2478 additions and 1963 deletions
+28 -7
View File
@@ -7,13 +7,9 @@ on:
- main
jobs:
wxt:
name: WXT
strategy:
fail-fast: false
matrix:
os: [ubuntu-latest, windows-latest]
runs-on: ${{ matrix.os }}
checks:
name: Checks
runs-on: ubuntu-22.04
steps:
- name: Checkout
uses: actions/checkout@v3
@@ -46,6 +42,7 @@ jobs:
pnpm build:all:firefox-mv3
pnpm tsc --noEmit
pnpm wxt zip
pnpm vitest run
working-directory: demo
- name: Tests
@@ -56,6 +53,30 @@ jobs:
env:
CODECOV_TOKEN: ${{ secrets.CODECOV_TOKEN }}
windows-tests:
name: Windows Tests
runs-on: windows-latest
steps:
- name: Checkout
uses: actions/checkout@v3
- name: Setup PNPM
uses: pnpm/action-setup@v2
with:
version: 8
- name: Setup NodeJS
uses: actions/setup-node@v3
with:
node-version: 18
cache: 'pnpm'
- name: Install dependencies
run: pnpm install
- name: Tests
run: pnpm test:coverage --reporter=default --reporter=hanging-process
project-templates:
name: Project Templates
runs-on: ubuntu-22.04
+2 -2
View File
@@ -17,6 +17,6 @@ web-ext.config.ts
templates/*/pnpm-lock.yaml
templates/*/yarn.lock
templates/*/package-lock.json
docs/api/config.md
docs/api/cli.md
docs/api
stats.html
.tool-versions
+110
View File
@@ -1,5 +1,115 @@
# Changelog
## v0.8.6
[compare changes](https://github.com/wxt-dev/wxt/compare/v0.8.5...v0.8.6)
### 🩹 Fixes
- Inline WXT modules inside `WxtVitest` plugin ([b75c553](https://github.com/wxt-dev/wxt/commit/b75c553))
## v0.8.5
[compare changes](https://github.com/wxt-dev/wxt/compare/v0.8.4...v0.8.5)
### 🚀 Enhancements
- Refactor project structure to export `initialize`, `prepare`, and `zip` functions ([#182](https://github.com/wxt-dev/wxt/pull/182))
### 🩹 Fixes
- Enable Vue SFC auto-imports in `vue` template ([f8a0fb3](https://github.com/wxt-dev/wxt/commit/f8a0fb3))
### 📖 Documentation
- Improve `runner.binaries` documentation ([d9e9b43](https://github.com/wxt-dev/wxt/commit/d9e9b43))
- Update auto-imports.md ([#186](https://github.com/wxt-dev/wxt/pull/186))
- Add `test.server.deps.inline` to Vitest guide ([19756c6](https://github.com/wxt-dev/wxt/commit/19756c6))
### 🏡 Chore
- Update template docs ([2e24b9e](https://github.com/wxt-dev/wxt/commit/2e24b9e))
- Reduce package size by 70%, 1.92 MB to 590 kB ([#190](https://github.com/wxt-dev/wxt/pull/190))
### ❤️ Contributors
- Nenad Novaković
## v0.8.4
[compare changes](https://github.com/wxt-dev/wxt/compare/v0.8.3...v0.8.4)
### 🩹 Fixes
- Allow actions without a popup ([#181](https://github.com/wxt-dev/wxt/pull/181))
## v0.8.3
[compare changes](https://github.com/wxt-dev/wxt/compare/v0.8.2...v0.8.3)
### 🚀 Enhancements
- Add testing utils under `wxt/testing` ([#178](https://github.com/wxt-dev/wxt/pull/178))
## v0.8.2
[compare changes](https://github.com/wxt-dev/wxt/compare/v0.8.1...v0.8.2)
### 🩹 Fixes
- **firefox:** Stop extending `AbortController` to fix crash in content scripts ([#176](https://github.com/wxt-dev/wxt/pull/176))
### 🏡 Chore
- Improve output consistency ([#175](https://github.com/wxt-dev/wxt/pull/175))
## v0.8.1
[compare changes](https://github.com/wxt-dev/wxt/compare/v0.8.0...v0.8.1)
### 🩹 Fixes
- Output `action.browser_style` correctly ([6a93f20](https://github.com/wxt-dev/wxt/commit/6a93f20))
### 📖 Documentation
- Generate full API docs with typedoc ([#174](https://github.com/wxt-dev/wxt/pull/174))
## 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
- ⚠️ Unlisted scripts must now `export default defineUnlistedScript(...)` ([#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)
+34
View File
@@ -70,3 +70,37 @@ pnpm test manifest-contents
Unit and E2E tests are ran together via [Vitest workspaces](https://vitest.dev/guide/#workspaces-support).
If you want to manually test a change, you can modify the demo project for your test, but please don't leave those changes committed once you open a PR.
## Templates
Each directory inside `templates/` is it's own standalone project. Simply `cd` into the directory you're updating, install dependencies with `npm` (NOT `pnpm`), and run the relevant commands
```sh
cd templates/vue
npm i
npm run dev
npm run build
```
Note that templates are hardcoded to a specific version of `wxt` from NPM, they do not use the local version. PR checks will test your changes against the templates, but if you want to manually do it, update the package.json dependency:
```diff
"devDependencies": {
"typescript": "^5.1.6",
"vite-plugin-solid": "^2.7.0",
- "wxt": "^0.8.0"
+ "wxt": "../.."
}
```
Then run `npm i` again.
### Adding Templates
To add a template, copy the vanilla template and give it a new name.
```sh
cp -r templates/vailla templates/<new-template-name>
```
That's it. Once your template is merged, it will be available inside `wxt init` immediately. You don't need to release a new version of WXT to release a new template.
+3 -2
View File
@@ -11,10 +11,11 @@
<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>
<!-- Hide code coverage while it's broken -->
<!-- <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>
</a> -->
</p>
<p align="center">
+4 -2
View File
@@ -11,14 +11,16 @@
"build:all:chrome-mv2": "wxt build --mv2",
"build:all:firefox-mv3": "wxt build -b firefox --mv3",
"build:all:firefox-mv2": "wxt build -b firefox",
"test": "pnpm -w build && vitest",
"zip": "pnpm -w build && wxt zip",
"compile": "pnpm -w build && tsc --noEmit",
"postinstall": "pnpm -w build && wxt prepare"
},
"dependencies": {
"webextension-polyfill": "^0.10.0",
"react": "^18.2.0",
"react-dom": "^18.2.0"
"react-dom": "^18.2.0",
"vitest": "^0.34.6",
"webextension-polyfill": "^0.10.0"
},
"devDependencies": {
"@types/react": "^18.2.14",
@@ -0,0 +1,18 @@
import { describe, expect, it, vi } from 'vitest';
import background from '../background';
browser.i18n.getMessage = () => 'fake-message';
const logMock = vi.fn();
console.log = logMock;
describe('Background Entrypoint', () => {
it("should log the extenion's runtime ID", () => {
const id = 'some-id';
fakeBrowser.runtime.id = id;
background.main();
expect(logMock).toBeCalledWith(id);
});
});
+3
View File
@@ -0,0 +1,3 @@
export default defineUnlistedScript(() => {
console.log('injected');
});
+10
View File
@@ -0,0 +1,10 @@
import { defineConfig } from 'vitest/config';
import { WxtVitest } from 'wxt/testing';
export default defineConfig({
test: {
mockReset: true,
restoreMocks: true,
},
plugins: [WxtVitest()],
});
+20 -7
View File
@@ -1,6 +1,19 @@
import { defineConfig } from 'vitepress';
import { generateConfigDocs } from './plugins/generate-config-docs';
import { DefaultTheme, defineConfig } from 'vitepress';
import { generateCliDocs } from './plugins/generate-cli-docs';
import typedocSidebar from '../api/typedoc-sidebar.json';
const filteredTypedocSidebar = typedocSidebar.filter(
(item) => item.text !== 'API',
);
// Typedoc's markdown theme adds collapse: true to all our items, event ones without any children,
// so they need to be removed.
function removeCollapsedWithNoItems(items: DefaultTheme.SidebarItem[]) {
for (const item of items) {
if (item.items) removeCollapsedWithNoItems(item.items);
else delete item.collapsed;
}
}
removeCollapsedWithNoItems(filteredTypedocSidebar);
const title = 'Next-gen Web Extension Framework';
const titleSuffix = ' WXT';
@@ -18,7 +31,7 @@ export default defineConfig({
description,
vite: {
clearScreen: false,
plugins: [generateConfigDocs(), generateCliDocs()],
plugins: [generateCliDocs()],
},
lastUpdated: true,
sitemap: {
@@ -120,10 +133,10 @@ export default defineConfig({
{
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: 'Modules',
items: filteredTypedocSidebar,
},
],
},
],
+1 -1
View File
@@ -8,7 +8,7 @@ let hasGenerated = false;
const cliDir = resolve('src/cli/commands');
const cliDirGlob = resolve(cliDir, '**');
const cliTemplatePath = resolve('docs/api/cli.tpl.md');
const cliTemplatePath = resolve('docs/.vitepress/plugins/cli.tpl.md');
const cliPath = resolve('docs/api/cli.md');
const PREFACE = `<!--
@@ -1,145 +0,0 @@
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';
import consola from 'consola';
let hasGenerated = false;
const externalTypesPath = resolve('src/core/types/external.ts');
const configTemplatePath = resolve('docs/api/config.tpl.md');
const configPath = resolve('docs/api/config.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\`.
-->`;
/**
* Custom property paths that should not be recursively inspected. Usually 3rd party types.
*/
const LEAF_PATHS = ['imports', 'vite', 'server'];
/**
* Override any types that resolve to `import(...)` instead of their type names when calling
* `type.getText()`.
*
* This also stops any further type inspection for objects, meaning the object will be documented,
* not it's properties.
*/
const CUSTOM_TYPES = {
manifest:
'Manifest | Promise<Manifest> | () => Manifest | () => Promise<Manifest>',
imports: "false | Partial<import('unimport').UnimportOptions>",
vite: "Omit<import('vite').UserConfig, 'root' | 'configFile' | 'mode'>",
};
export function generateConfigDocs() {
writeFileSync(configPath, '');
const generateDocs = async () => {
consola.info(`Generating ${relative(process.cwd(), configPath)}`);
try {
const project = new Project({
tsConfigFilePath: resolve('tsconfig.json'),
});
// Load file containing "UserConfig"
const externalTypesFile = project.addSourceFileAtPath(externalTypesPath);
project.resolveSourceFileDependencies();
const inlineConfigInterface =
externalTypesFile.getInterfaceOrThrow('InlineConfig');
const getDocsFor = (path: string[], node: Node<ts.Node>): string[] => {
const pathStr = path.join('.');
let type: Type<ts.Type>;
if (node.isKind(ts.SyntaxKind.InterfaceDeclaration)) {
type = node.getType();
} else if (node.isKind(ts.SyntaxKind.PropertySignature)) {
type = node.getTypeNodeOrThrow()?.getType();
} else if (node.isKind(ts.SyntaxKind.MethodSignature)) {
type = node.getType();
} else {
throw Error('Unsupported type node: ' + node.getKindName());
}
if (type.isObject() && !type.isArray() && !CUSTOM_TYPES[pathStr]) {
return type.getProperties().flatMap((property) => {
const childPath = [...path, property.getName()];
return getDocsFor(childPath, property.getDeclarations()[0]);
});
}
if ('getJsDocs' in node) {
const lines: string[] = [];
const docs = (node as unknown as JSDocableNode).getJsDocs();
let typeText: string;
if (CUSTOM_TYPES[pathStr]) {
typeText = CUSTOM_TYPES[pathStr];
} else if (type.isUnion() && !type.isBoolean()) {
typeText = type
.getUnionTypes()
.map((type) => type.getText())
.join(' | ');
} else {
typeText = type.getText();
}
const defaultValue = docs
.flatMap((doc) => doc.getTags())
.find((tag) => tag.getTagName() === 'default')
?.getCommentText();
lines.push(
'',
`## ${pathStr}`,
'',
`- **Type**: \`${typeText}\``,
`- **Default**: \`${defaultValue}\``,
...docs.flatMap((doc) => doc.getDescription()),
);
return lines;
}
return [];
};
const lines = getDocsFor([], inlineConfigInterface);
const text = await format(
PREFACE +
'\n\n' +
readFileSync(configTemplatePath, 'utf-8').replace(
'{{ DOCS }}',
lines.join('\n'),
),
{ parser: 'markdown' },
);
writeFileSync(configPath, text);
consola.success(`Generated ${relative(process.cwd(), configPath)}`);
} catch (err) {
consola.fail(`Failed to generate ${relative(process.cwd(), configPath)}`);
consola.error(err.message);
}
};
return {
name: 'docs:generate-config-docs',
async config() {
if (!hasGenerated) {
hasGenerated = true;
await generateDocs();
}
},
configureServer(server: any) {
server.watcher.add(externalTypesPath);
},
async handleHotUpdate(ctx: { file: string }) {
if ([externalTypesPath, configTemplatePath].includes(ctx.file)) {
await generateDocs();
}
},
};
}
-5
View File
@@ -1,5 +0,0 @@
# Config Reference
All the options you can use in your `wxt.config.ts` file.
{{ DOCS }}
-10
View File
@@ -1,10 +0,0 @@
# `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
@@ -1,14 +0,0 @@
# `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';
```
:::
-17
View File
@@ -1,17 +0,0 @@
# `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';
```
:::
+1 -1
View File
@@ -5,7 +5,7 @@ WXT can build CSS entrypoints individually. CSS entrypoints are always unlisted.
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](/api/config#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/wxt/interfaces/InlineConfig#transformmanifest) to manually add your CSS file to the manifest.
:::
## Filenames
+1
View File
@@ -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', ...]" />
+19 -2
View File
@@ -2,6 +2,8 @@
TypeScript files that are built, but are not included in the manifest.
You are responsible for loading/running these scripts where needed.
## Filenames
<EntrypointPatterns
@@ -13,8 +15,23 @@ TypeScript files that are built, but are not included in the manifest.
## Definition
Unlike the background or content scripts, you can define this script's logic in the top level scope.
```ts
export default defineUnlistedScript(() => {
// Executed when script is loaded
});
```
or
```ts
// Code goes here
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() {
// ...
},
});
```
+8 -6
View File
@@ -10,12 +10,14 @@ To setup your test environment for auto-imports, see [Testing](/guide/testing).
Some WXT APIs can be used without importing them:
- [`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#definebackgroundscript) from `wxt/client`
- [`createContentScriptUi`](/api/wxt-client#createcontentscriptui) from `wxt/client`
- [`browser`](/api/wxt/browser/variables/browser) from `wxt/browser`, a small wrapper around `webextension-polyfill`
- [`defineContentScript`](/api/wxt/client/functions/defineContentScript) from `wxt/client`
- [`defineBackground`](/api/wxt/client/functions/defineBackground) from `wxt/client`
- [`createContentScriptUi`](/api/wxt/client/functions/createContentScriptUi) from `wxt/client`
- [`defineUnlistedScript`](/api/wxt/sandbox/functions/defineUnlistedScript) from `wxt/sandbox`
- [`fakeBrowser`](/api/wxt/testing/variables/fakeBrowser) from `wxt/testing`
And more. All [`wxt/client`](/api/wxt-client) APIs can be used without imports.
And more. All `wxt/*` APIs can be used without imports.
## Project Auto-imports
@@ -62,7 +64,7 @@ import { defineConfig } from 'wxt';
export default defineConfig({
imports: {
// Add auto-imports for vue fuctions like createApp, ref, computed, watch, toRaw, etc...
preset: ['vue'],
presets: ['vue'],
},
});
```
+1 -1
View File
@@ -15,7 +15,7 @@ export default defineConfig({
```
:::info
See the [Config reference](/api/config) for a full list of options.
See the [Config reference](/api/wxt/interfaces/InlineConfig) for a full list of options.
:::
## Directory Config
+9 -3
View File
@@ -15,7 +15,7 @@ WXT's main goal is providing the best DX it possibly can. When running your exte
## 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`.
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/wxt/interfaces/InlineConfig#runner) option, or in a separate gitignored file, `web-ext.config.ts`.
:::code-group
@@ -39,7 +39,7 @@ export default defineRunnerConfig({
:::
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.
`web-ext`'s browser discovery is very limitted. By default, it only guesses at where Chrome and Firefox are installed. If you've customized your install locations, you may need to tell `web-ext` where the binaries/executables are located using the [`binaries` option](/api/wxt/interfaces/ExtensionRunnerConfig#binaries). For other Chromium based browsers, like Edge or Opera, you'll need to explicitly list them in the `binaries` option as well, otherwise they will open in Chrome by default.
```ts
// ~/web-ext.config.ts
@@ -47,7 +47,13 @@ import { defineRunnerConfig } from 'wxt';
export default defineRunnerConfig({
binaries: {
chrome: '/path/to/chrome-beta',
chrome: '/path/to/chrome-beta', // Use Chrome Beta instead of regular Chrome
firefox: 'firefoxdeveloperedition', // Use Firefox Developer Edition instead of regular Firefox
edge: '/path/to/edge', // Open MS Edge when running "wxt -b edge"
},
});
```
:::tip
When configuring browser binaries, it's helpful to put them in `~/web-ext.config.ts` instead of the project directory's `web-ext.config.ts` file. When placed in your home directory (`~/`), this config will be used by all WXT projects, so you only need to configure the binaries once.
:::
+2 -2
View File
@@ -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
+5 -1
View File
@@ -24,7 +24,7 @@ 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.
By default, it will build for `chrome`. When excluding the [manifest version flags](#target-manifest-version), it will default to the commonly accepted manifest version for that browser.
| Browser | Default Manifest Version |
| ---------------- | :----------------------: |
@@ -34,6 +34,10 @@ By default, it will build for `chrome`. When excluding the [`--mv2` or `--mv3` f
| `edge` | 3 |
| Any other string | 3 |
:::tip
To configure which browser is opened when running dev mode via `wxt -b <browser>`, see the [Development docs](/guide/development#configure-browser-startup) docs.
:::
## Target Manifest Version
To build for a specific manifest version, pass either the `--mv2` flag or `--mv3` flag from the CLI.
+141 -71
View File
@@ -1,92 +1,162 @@
# Testing
WXT provides a couple of utils for unit testing your extension.
WXT provides several utils for writing tests.
[[toc]]
## Unit tests
## Fake Browser
If you're using auto-imports (enabled by default), [Vitest](https://vitest.dev/) is the only testing framework that supports them.
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/).
If you want to use a different testing library/framework (like Jest, mocha, node:test, etc), you can keep using it, but you have two options:
Here's an example test using Vitest:
1. Switch to Vitest (recommended)
2. Configure the testing library manually
- Disable auto-imports by setting `imports: false` in your `wxt.config.ts` file
- Manually add globals normally provided by WXT (like `__BROWSER__`) that you consume to the global scope before accessing them (`globalThis.__BROWSER__ = "chrome"`)
```ts
import { describe, it, expect, vi } from 'vitest';
import { browser } from 'wxt/browser';
import { fakeBrowser } from 'wxt';
### Vitest Setup
// Function we're testing
function onHelloMessage(cb: () => void) {
browser.runtime.onMessage.addEventListener((message) => {
if (message.type === 'hello') return 'world';
});
}
Install vitest and add the `WxtVitest` plugin to your `vitest.config.ts` file.
// 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();
});
});
```sh
pnpm i -D vitest
```
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';
// <root>/vitest.config.ts
import { defineConfig } from 'vitest/config';
import { WxtVitest } from 'wxt/testing';
export default defineConfig({
plugins: [
autoImports({
imports: [{ name: 'defineConfig', from: 'wxt' }],
presets: [{ package: 'wxt/client' }, { package: 'wxt/browser' }],
dirs: ['components', 'composables', 'hooks', 'utils'],
}),
],
plugins: [WxtVitest()],
test: {
server: {
deps: {
// Add any dependencies that import webextension-polyfill here, otherwise tests will attempt to import the real polyfill, breaking the
// TODO: Auto-detect these dependencies inside `WxtVitest` so maintaining this list manually isn't necessary
inline: [...],
},
},
},
});
```
### Jest
And that's it. You're ready to start writing tests.
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.
### Writing Tests
I would recommend disabling auto-imports or migrating to Vitest if you want to use auto-imports.
Here's a very basic test, written with a few different testing libraries, with a few different approaches for mocking the `browser` global.
### Mocha
:::code-group
TODO: Is this possible? Maybe with `esbuild-mocha`? I would recommend moving to Vitest.
```ts [Vitest]
import { describe, it, expect, vi } from 'vitest';
function logRuntimeId() {
// Vitest automatically mocks "browser" with "fakeBrowser"
console.log(browser.runtime.id);
}
describe('logRuntimeId', () => {
it("should log the extension's runtime ID", () => {
// Set a known ID on fakeBrowser for the test
const id = 'some-runtime-id';
fakeBrowser.runtime.id = id;
const logSpy = vi.spyOn(console, 'log');
logRuntimeId();
expect(logSpy).toBeCalledWith(id);
});
});
```
```ts [Jest - Manual Mock]
import { fakeBrowser } from 'wxt/testing';
import { browser } from 'wxt/browser';
function logRuntimeId() {
console.log(browser.runtime.id);
}
// Manually mock
jest.mock('wxt/browser', () => {
const { fakeBrowser } = require('wxt/testing');
return { browser: fakeBrowser };
});
describe('logRuntimeId', () => {
it("should log the extension's runtime ID", () => {
// Set a known ID on fakeBrowser for the test
const id = 'some-runtime-id';
fakeBrowser.runtime.id = id;
const logSpy = jest.spyOn(console, 'log');
logRuntimeId();
expect(logSpy).toBeCalledWith(id);
});
});
```
```ts [node:test - Parameterized]
import { describe, it, mock } from 'node:test';
import { assert } from 'node:assert';
import { fakeBrowser } from 'wxt/testing';
import { browser } from 'wxt/browser';
// Add browser as a parameter so fakeBrowser can be passed instead of browser
function logRuntimeId(browser = browser) {
console.log(browser.runtime.id);
}
describe('logRuntimeId', () => {
it("should log the extension's runtime ID", () => {
// Set a known ID on fakeBrowser for the test
const id = 'some-runtime-id';
fakeBrowser.runtime.id = id;
console.log = mock.fn();
// pass in fakeBrowser during tests
logRuntimeId(fakeBrowser);
assert.deepStrictEqual(console.log.mock.calls[0].arguments, [id]);
});
});
```
:::
:::warning
Without mocking the `browser` variable, you'll see errors like this:
```
This script should only be loaded in a browser extension.
```
:::
WXT provides an in-memory, partial implementation of `browser`, [`fakeBrowser`](/api/wxt/testing/variables/fakeBrowser), from the [`@webext-core/fake-browser`](https://webext-core.aklinker1.io/guide/fake-browser/) package. `fakeBrowser` works with all testing frameworks/libraries. See their docs for a list of [implemented APIs](https://webext-core.aklinker1.io/guide/fake-browser/implemented-apis.html) and more example tests.
## E2E Tests
WXT does not provide any utils for running E2E tests. There are two libraries you can use to run E2E tests for any chrome extension.
- [`playwright`](https://playwright.dev/docs/chrome-extensions) (recommended) - "A high-level API to automate web browsers"
- [`puppeteer`](https://pptr.dev/guides/chrome-extensions) - "A high-level API to control headless Chrome over the DevTools Protocol"
:::info
Note that both only support running tests on Chrome.
:::
Before running tests with either of these tools, you must build the extension with `wxt build` and then load the extension from the output directory in a new tab.
To test an extension's UI, like the popup or options page, you'll need to know the extension's ID to open the URL directly.
> _chrome-extension://`browser.runtime.id`/popup.html_
- Playwright provides an API to get your extension ID after it has been installed. [See their docs](https://playwright.dev/docs/chrome-extensions#testing).
- Puppeteer requires you know the ID before installing the extension, so you can hard code it into the URLs you open. Follow [Chrome's guide](https://developer.chrome.com/docs/extensions/mv3/manifest/key/) to setup a consistent runtime id.
:::info
You cannot test popups in their normal popup window, you have to open them in a tab.
:::
+2 -1
View File
@@ -2,7 +2,8 @@
# https://docs.netlify.com/routing/redirects/
# Old URLs -> New URLs
/config.html /api/config.html
/config.html /api/wxt/interfaces/InlineConfig.html
/api/config.html /api/wxt/interfaces/InlineConfig.html
/entrypoints /entrypoints/background.html
/get-started/assets.html /guide/assets.html
/get-started/build-targets.html /guide/multiple-browsers.html
+16
View File
@@ -0,0 +1,16 @@
{
"entryPoints": [
"../src",
"../src/client",
"../src/browser.ts",
"../src/sandbox",
"../src/testing"
],
"plugin": ["typedoc-plugin-markdown", "typedoc-vitepress-theme"],
"out": "./api",
"githubPages": false,
"excludePrivate": true,
"excludeProtected": true,
"excludeInternal": true,
"readme": "none"
}
+2
View File
@@ -22,6 +22,8 @@ describe('Auto Imports', () => {
const defineBackground: typeof import('wxt/client')['defineBackground']
const defineConfig: typeof import('wxt')['defineConfig']
const defineContentScript: typeof import('wxt/client')['defineContentScript']
const defineUnlistedScript: typeof import('wxt/sandbox')['defineUnlistedScript']
const fakeBrowser: typeof import('wxt/testing')['fakeBrowser']
}
"
`);
+122 -35
View File
@@ -194,15 +194,15 @@ describe('Manifest Content', () => {
});
describe('content_scripts', () => {
it('should group content scripts and styles together based on their matches and run_at', async () => {
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: () => {},
})`,
export default defineContentScript({
matches: ["*://google.com/*"],
main: () => {},
})`,
);
project.addFile(
'entrypoints/one.content/style.css',
@@ -211,11 +211,11 @@ describe('Manifest Content', () => {
project.addFile(
'entrypoints/two.content/index.ts',
`import "./style.css";
export default defineContentScript({
matches: ["*://google.com/*"],
runAt: "document_end",
main: () => {},
})`,
export default defineContentScript({
matches: ["*://google.com/*"],
runAt: "document_end",
main: () => {},
})`,
);
project.addFile(
'entrypoints/two.content/style.css',
@@ -224,11 +224,11 @@ describe('Manifest Content', () => {
project.addFile(
'entrypoints/three.content/index.ts',
`import "./style.css";
export default defineContentScript({
matches: ["*://google.com/*"],
runAt: "document_end",
main: () => {},
})`,
export default defineContentScript({
matches: ["*://google.com/*"],
runAt: "document_end",
main: () => {},
})`,
);
project.addFile(
'entrypoints/three.content/style.css',
@@ -237,11 +237,11 @@ describe('Manifest Content', () => {
project.addFile(
'entrypoints/four.content/index.ts',
`import "./style.css";
export default defineContentScript({
matches: ["*://duckduckgo.com/*"],
runAt: "document_end",
main: () => {},
})`,
export default defineContentScript({
matches: ["*://duckduckgo.com/*"],
runAt: "document_end",
main: () => {},
})`,
);
project.addFile(
'entrypoints/four.content/style.css',
@@ -276,15 +276,15 @@ describe('Manifest Content', () => {
project.addFile(
'entrypoints/one.content/index.ts',
`export default defineContentScript({
matches: ["*://google.com/*"],
main: () => {},
})`,
matches: ["*://google.com/*"],
main: () => {},
})`,
);
project.addFile(
'entrypoints/two.content/style.css',
`body {
background-color: red;
}`,
background-color: red;
}`,
);
project.setConfigFileConfig({
manifest: {
@@ -333,7 +333,7 @@ describe('Manifest Content', () => {
.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\\",\\"content_scripts\\":[{\\"matches\\":[\\"https://*.google.com/*\\"],\\"css\\":[\\"content-scripts/content.css\\"],\\"js\\":[\\"content-scripts/content.js\\"]}]}"
{\\"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\\"]}]}"
`);
});
@@ -360,7 +360,7 @@ describe('Manifest Content', () => {
.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\\",\\"content_scripts\\":[{\\"matches\\":[\\"https://*.google.com/*\\"],\\"css\\":[\\"content-scripts/content.css\\"],\\"js\\":[\\"content-scripts/content.js\\"]}]}"
{\\"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\\"]}]}"
`);
});
@@ -385,10 +385,10 @@ describe('Manifest Content', () => {
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\\",\\"version_name\\":\\"0.0.0-test\\",\\"content_scripts\\":[{\\"matches\\":[\\"https://*.google.com/*\\"],\\"js\\":[\\"content-scripts/content.js\\"]}]}"
`);
".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 () => {
@@ -416,7 +416,7 @@ describe('Manifest Content', () => {
.toMatchInlineSnapshot(`
".output/chrome-mv2/manifest.json
----------------------------------------
{\\"manifest_version\\":2,\\"name\\":\\"E2E Extension\\",\\"description\\":\\"Example description\\",\\"version\\":\\"0.0.0\\",\\"version_name\\":\\"0.0.0-test\\",\\"content_scripts\\":[{\\"matches\\":[\\"https://*.google.com/*\\"],\\"js\\":[\\"content-scripts/content.js\\"]}],\\"web_accessible_resources\\":[\\"content-scripts/content.css\\"]}"
{\\"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\\"]}"
`);
});
@@ -445,7 +445,7 @@ describe('Manifest Content', () => {
.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\\",\\"content_scripts\\":[{\\"matches\\":[\\"https://*.google.com/*\\"],\\"js\\":[\\"content-scripts/content.js\\"]}],\\"web_accessible_resources\\":[{\\"resources\\":[\\"content-scripts/content.css\\"],\\"matches\\":[\\"https://*.google.com/*\\"]}]}"
{\\"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/*\\"]}]}"
`);
});
});
@@ -480,7 +480,7 @@ describe('Manifest Content', () => {
.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\\",\\"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\\"]}]}"
{\\"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\\"]}]}"
`);
});
@@ -505,7 +505,7 @@ 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\\"}"
`);
});
@@ -537,4 +537,91 @@ describe('Manifest Content', () => {
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();
},
);
});
it('should respect the action field in the manifest without a popup', async () => {
const project = new TestProject();
project.setConfigFileConfig({
manifest: {
action: {
default_title: 'Hello world',
},
},
});
await project.build();
expect(await project.getOutputManifest()).toMatchInlineSnapshot(`
{
"action": {
"default_title": "Hello world",
},
"description": "Example description",
"manifest_version": 3,
"name": "E2E Extension",
"version": "0.0.0",
}
`);
});
});
+11 -8
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\\"}"
`);
});
@@ -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\\":[\\"content-scripts/one.css\\",\\"content-scripts/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\\"]}]}"
`);
});
@@ -172,7 +172,10 @@ describe('Output Directory Structure', () => {
'entrypoints/background.js',
`export default defineBackground(() => {});`,
);
project.addFile('entrypoints/unlisted.js', ``);
project.addFile(
'entrypoints/unlisted.js',
`export default defineUnlistedScript(() => {})`,
);
project.addFile(
'entrypoints/content.js',
`export default defineContentScript({
@@ -192,10 +195,10 @@ describe('Output Directory Structure', () => {
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\\",\\"version_name\\":\\"0.0.0-test\\",\\"background\\":{\\"service_worker\\":\\"background.js\\"},\\"content_scripts\\":[{\\"matches\\":[\\"*://*.google.com/*\\"],\\"js\\":[\\"content-scripts/content.js\\"]},{\\"matches\\":[\\"*://*.duckduckgo.com/*\\"],\\"js\\":[\\"content-scripts/named.js\\"]}]}"
`);
".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'),
+4 -4
View File
@@ -35,9 +35,9 @@ describe('React', () => {
).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\\",\\"version_name\\":\\"0.0.0-test\\",\\"content_scripts\\":[{\\"matches\\":\\"<all_urls>\\",\\"js\\":[\\"content-scripts/demo.js\\"]}]}"
`);
".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();
+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\\"]}"
`);
});
});
+1 -1
View File
@@ -24,7 +24,7 @@ export class TestProject {
{
name: 'E2E Extension',
description: 'Example description',
version: '0.0.0-test',
version: '0.0.0',
dependencies: {
wxt: '../../..',
},
+28 -15
View File
@@ -1,10 +1,10 @@
{
"name": "wxt",
"type": "module",
"version": "0.7.4",
"version": "0.8.6",
"description": "Next gen framework for developing web extensions",
"engines": {
"node": ">=18.16.0",
"node": ">=18",
"pnpm": ">=8"
},
"repository": {
@@ -44,24 +44,34 @@
"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"
},
"./testing": {
"require": "./dist/testing.cjs",
"import": "./dist/testing.js",
"types": "./dist/testing.d.ts"
}
},
"scripts": {
"wxt": "tsx src/cli/index.ts",
"wxt": "tsx src/cli.ts",
"build": "tsx scripts/build.ts",
"format": "prettier --write .",
"format:check": "prettier --write .",
"compile": "tsc --noEmit",
"test": "vitest",
"test:coverage": "vitest run --coverage.enabled --coverage.exclude=e2e --coverage.exclude=src/testing",
"test:coverage": "vitest run --coverage",
"prepare": "simple-git-hooks",
"prepublish": "pnpm -s build",
"docs:dev": "vitepress dev docs",
"docs:build": "vitepress build docs",
"docs:preview": "vitepress preview docs",
"docs:gen": "typedoc --options docs/typedoc.json",
"docs:dev": "pnpm -s docs:gen && vitepress dev docs",
"docs:build": "pnpm -s docs:gen && vitepress build docs",
"docs:preview": "pnpm -s docs:gen && vitepress preview docs",
"sync-releases": "pnpx changelogen@latest gh release"
},
"dependencies": {
@@ -90,7 +100,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"
@@ -99,23 +109,26 @@
"@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",
"happy-dom": "^12.4.0",
"lint-staged": "^14.0.0",
"lodash.merge": "^4.6.2",
"npm-run-all": "^4.1.5",
"p-map": "^6.0.0",
"prettier": "^3.0.1",
"simple-git-hooks": "^2.9.0",
"ts-morph": "^20.0.0",
"tsup": "^7.1.0",
"tsup": "^7.2.0",
"tsx": "^3.12.7",
"typedoc": "^0.25.2",
"typedoc-plugin-markdown": "4.0.0-next.23",
"typedoc-vitepress-theme": "1.0.0-next.3",
"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"
},
+183 -399
View File
File diff suppressed because it is too large Load Diff
+83 -63
View File
@@ -1,82 +1,102 @@
import tsup from 'tsup';
import glob from 'fast-glob';
import { printFileList } from '../src/core/log/printFileList';
import { formatDuration } from '../src/core/utils/formatDuration';
import { printFileList } from '~/core/utils/log';
import { formatDuration } from '~/core/utils/time';
import ora from 'ora';
import fs from 'fs-extra';
import { consola } from 'consola';
import pMap from 'p-map';
import os from 'node:os';
import path from 'node:path';
const spinner = ora('Building WXT').start();
const spinnerText = 'Building WXT';
const spinner = ora(spinnerText).start();
const startTime = Date.now();
const outDir = 'dist';
const virtualEntrypoints = ['background', 'content-script'];
await fs.rm(path.join(outDir, '*'), { recursive: true, force: true });
await fs.rm(outDir, { recursive: true, force: true });
const preset: tsup.Options = {
dts: true,
silent: true,
sourcemap: false,
external: [
'vite',
'virtual:user-unlisted-script',
'virtual:user-content-script',
'virtual:user-background',
],
};
await Promise.all([
tsup.build({
function spinnerPMap(configs: tsup.Options[]) {
let completed = 0;
const updateSpinner = () => {
spinner.text = `${spinnerText} [${completed}/${configs.length}]`;
};
updateSpinner();
return pMap(
config,
async (config) => {
const res = await tsup.build(config);
completed++;
updateSpinner();
return res;
},
{
stopOnError: true,
concurrency: process.env.CI === 'true' ? os.cpus().length : Infinity,
},
);
}
const config: tsup.Options[] = [
// CJS/ESM
{
...preset,
entry: {
index: 'src/index.ts',
testing: 'src/testing/index.ts',
},
format: ['cjs', 'esm'],
sourcemap: true,
dts: true,
silent: true,
external: ['vite'],
}),
tsup.build({
entry: { cli: 'src/cli/index.ts' },
clean: true,
},
// ESM-only
{
...preset,
entry: {
browser: 'src/browser.ts',
sandbox: 'src/sandbox/index.ts',
client: 'src/client/index.ts',
},
format: ['esm'],
},
{
...preset,
entry: {
'virtual/background-entrypoint': 'src/virtual/background-entrypoint.ts',
'virtual/content-script-entrypoint':
'src/virtual/content-script-entrypoint.ts',
'virtual/mock-browser': 'src/virtual/mock-browser.ts',
'virtual/reload-html': 'src/virtual/reload-html.ts',
'virtual/unlisted-script-entrypoint':
'src/virtual/unlisted-script-entrypoint.ts',
},
format: ['esm'],
splitting: false,
dts: false,
},
// CJS-only
{
...preset,
entry: {
cli: 'src/cli.ts',
},
format: ['cjs'],
sourcemap: 'inline',
silent: true,
external: ['vite'],
}),
tsup.build({
entry: { client: 'src/client/index.ts' },
format: ['esm'],
sourcemap: 'inline',
dts: true,
silent: true,
external: ['vite'],
}),
tsup.build({
entry: { browser: 'src/client/browser.ts' },
format: ['esm'],
sourcemap: 'inline',
dts: true,
silent: true,
external: ['vite'],
}),
...virtualEntrypoints.map((entryName) =>
tsup.build({
entry: {
[`virtual-modules/${entryName}-entrypoint`]: `src/client/virtual-modules/${entryName}-entrypoint.ts`,
},
format: ['esm'],
sourcemap: true,
silent: true,
external: [`virtual:user-${entryName}`, 'vite'],
}),
),
tsup.build({
entry: {
'virtual-modules/reload-html': `src/client/virtual-modules/reload-html.ts`,
},
format: ['esm'],
sourcemap: true,
silent: true,
external: ['vite'],
}),
tsup.build({
entry: {
'virtual-modules/fake-browser': `src/client/virtual-modules/fake-browser.ts`,
},
format: ['esm', 'cjs'],
silent: true,
external: ['vite'],
}),
]).catch((err) => {
},
];
await spinnerPMap(config).catch((err) => {
spinner.fail();
console.error(err);
process.exit(1);
-16
View File
@@ -1,16 +0,0 @@
declare module 'zip-dir' {
// Represents the options object for zipdir function
interface ZipDirOptions {
saveTo?: string;
filter?: (path: string, stat: import('fs').Stats) => boolean;
each?: (path: string) => void;
}
function zipdir(
dirPath: string,
options?: ZipDirOptions,
callback?: (error: Error | null, buffer: Buffer) => void,
): Promise<Buffer>;
export = zipdir;
}
+3
View File
@@ -1,3 +1,6 @@
/**
* @module wxt/browser
*/
import originalBrowser, { Browser, Runtime, I18n } from 'webextension-polyfill';
export interface AugmentedBrowser extends Browser {
+164
View File
@@ -0,0 +1,164 @@
import cac from 'cac';
import { version } from '~/version';
import { build, clean, createServer, initialize, prepare, zip } from '~/core';
import consola, { LogLevels } from 'consola';
import { printHeader } from '~/core/utils/log';
import { formatDuration } from '~/core/utils/time';
const cli = cac('wxt');
cli.help();
cli.version(version);
cli.option('--debug', 'enable debug mode');
// DEV
cli
.command('[root]', 'start dev server')
.option('-c, --config <file>', 'use specified config file')
.option('-m, --mode <mode>', 'set env mode')
.option('-b, --browser <browser>', 'specify a browser')
.option('--mv3', 'target manifest v3')
.option('--mv2', 'target manifest v2')
.action(
wrapAction(async (root, flags) => {
const server = await createServer({
root,
mode: flags.mode,
browser: flags.browser,
manifestVersion: flags.mv3 ? 3 : flags.mv2 ? 2 : undefined,
configFile: flags.config,
debug: flags.debug,
});
await server.start();
return { isOngoing: true };
}),
);
// BUILD
cli
.command('build [root]', 'build for production')
.option('-c, --config <file>', 'use specified config file')
.option('-m, --mode <mode>', 'set env mode')
.option('-b, --browser <browser>', 'specify a browser')
.option('--mv3', 'target manifest v3')
.option('--mv2', 'target manifest v2')
.option('--analyze', 'visualize extension bundle')
.action(
wrapAction(async (root, flags) => {
await build({
root,
mode: flags.mode,
browser: flags.browser,
manifestVersion: flags.mv3 ? 3 : flags.mv2 ? 2 : undefined,
configFile: flags.config,
debug: flags.debug,
analysis: {
enabled: flags.analyze,
},
});
}),
);
// ZIP
cli
.command('zip [root]', 'build for production and zip output')
.option('-c, --config <file>', 'use specified config file')
.option('-m, --mode <mode>', 'set env mode')
.option('-b, --browser <browser>', 'specify a browser')
.option('--mv3', 'target manifest v3')
.option('--mv2', 'target manifest v2')
.action(
wrapAction(async (root, flags) => {
await zip({
root,
mode: flags.mode,
browser: flags.browser,
manifestVersion: flags.mv3 ? 3 : flags.mv2 ? 2 : undefined,
configFile: flags.config,
debug: flags.debug,
});
}),
);
// PREPARE
cli
.command('prepare [root]', 'prepare typescript project')
.option('-c, --config <file>', 'use specified config file')
.action(
wrapAction(async (root, flags) => {
await prepare({
root,
configFile: flags.config,
debug: flags.debug,
});
}),
);
// CLEAN
cli
.command('clean [root]', 'clean generated files and caches')
.alias('cleanup')
.action(
wrapAction(async (root, flags) => {
await clean(root);
}),
);
// INIT
cli
.command('init [directory]', 'initialize a new project')
.option('-t, --template <template>', 'template to use')
.option('--pm <packageManager>', 'which package manager to use')
.action(
wrapAction(
async (directory, flags) => {
await initialize({
directory,
template: flags.template,
packageManager: flags.pm,
});
},
{ disableFinishedLog: true },
),
);
cli.parse();
/**
* Wrap an action handler to add a timer, error handling, and maybe enable debug mode.
*/
function wrapAction(
cb: (
...args: any[]
) => void | { isOngoing?: boolean } | Promise<void | { isOngoing?: boolean }>,
options?: {
disableFinishedLog?: boolean;
},
) {
return async (...args: any[]) => {
// Enable consola's debug mode globally at the start of all commands when the `--debug` flag is
// passed
const isDebug = !!args.find((arg) => arg?.debug);
if (isDebug) {
consola.level = LogLevels.debug;
}
const startTime = Date.now();
try {
printHeader();
const status = await cb(...args);
if (!status?.isOngoing && !options?.disableFinishedLog)
consola.success(
`Finished in ${formatDuration(Date.now() - startTime)}`,
);
} catch (err) {
consola.fail(
`Command failed after ${formatDuration(Date.now() - startTime)}`,
);
consola.error(err);
process.exit(1);
}
};
}
-31
View File
@@ -1,31 +0,0 @@
import * as wxt from '../..';
import { defineCommand } from '../utils/defineCommand';
export const build = defineCommand<
[
root: string | undefined,
flags: {
mode?: string;
config?: string;
browser?: wxt.TargetBrowser;
mv3?: boolean;
mv2?: boolean;
debug?: boolean;
analyze?: boolean;
},
]
>(async (root, flags) => {
const cliConfig: wxt.InlineConfig = {
root,
mode: flags.mode,
browser: flags.browser,
manifestVersion: flags.mv3 ? 3 : flags.mv2 ? 2 : undefined,
configFile: flags.config,
debug: flags.debug,
analysis: {
enabled: flags.analyze,
},
};
await wxt.build(cliConfig);
});
-11
View File
@@ -1,11 +0,0 @@
import { defineCommand } from '../utils/defineCommand';
import * as wxt from '../..';
export const clean = defineCommand<
[
root: string | undefined,
flags: {
debug?: boolean;
},
]
>(wxt.clean);
-30
View File
@@ -1,30 +0,0 @@
import * as wxt from '../..';
import { defineCommand } from '../utils/defineCommand';
export const dev = defineCommand<
[
root: string | undefined,
flags: {
mode?: string;
config?: string;
browser?: wxt.TargetBrowser;
mv3?: boolean;
mv2?: boolean;
debug?: boolean;
},
]
>(async (root, flags) => {
const cliConfig: wxt.InlineConfig = {
root,
mode: flags.mode,
browser: flags.browser,
manifestVersion: flags.mv3 ? 3 : flags.mv2 ? 2 : undefined,
configFile: flags.config,
debug: flags.debug,
};
const server = await wxt.createServer(cliConfig);
await server.start();
return true;
});
-7
View File
@@ -1,7 +0,0 @@
export * from './build';
export * from './dev';
export * from './init';
export * from './prepare';
export * from './publish';
export * from './zip';
export * from './clean';
-27
View File
@@ -1,27 +0,0 @@
import { getInternalConfig } from '../../core/utils/getInternalConfig';
import { findEntrypoints } from '../../core/build/findEntrypoints';
import { generateTypesDir } from '../../core/build/generateTypesDir';
import { defineCommand } from '../utils/defineCommand';
import * as wxt from '../..';
export const prepare = defineCommand<
[
root: string | undefined,
flags: {
config?: string;
debug?: boolean;
},
]
>(async (root, flags) => {
const cliConfig: wxt.InlineConfig = {
root,
configFile: flags.config,
debug: flags.debug,
};
const config = await getInternalConfig(cliConfig, 'build');
config.logger.info('Generating types...');
const entrypoints = await findEntrypoints(config);
await generateTypesDir(entrypoints, config);
});
-11
View File
@@ -1,11 +0,0 @@
import { consola } from 'consola';
import { defineCommand } from '../utils/defineCommand';
export const publish = defineCommand(
async (
root: any,
{ config: configFile, debug }: { config?: string; debug?: string },
) => {
consola.warn('wxt publish: Not implemented');
},
);
-32
View File
@@ -1,32 +0,0 @@
import * as wxt from '../..';
import { buildInternal } from '../../core/build';
import { getInternalConfig } from '../../core/utils/getInternalConfig';
import { zipExtension } from '../../core/zip';
import { defineCommand } from '../utils/defineCommand';
export const zip = defineCommand<
[
root: string | undefined,
flags: {
mode?: string;
config?: string;
browser?: wxt.TargetBrowser;
mv3?: boolean;
mv2?: boolean;
debug?: boolean;
},
]
>(async (root, flags) => {
const cliConfig: wxt.InlineConfig = {
root,
mode: flags.mode,
browser: flags.browser,
manifestVersion: flags.mv3 ? 3 : flags.mv2 ? 2 : undefined,
configFile: flags.config,
debug: flags.debug,
};
const config = await getInternalConfig(cliConfig, 'build');
const output = await buildInternal(config);
await zipExtension(config, output);
});
-64
View File
@@ -1,64 +0,0 @@
import cac from 'cac';
import { version } from '../../package.json';
import * as commands from './commands';
const cli = cac('wxt');
cli.help();
cli.version(version);
cli.option('--debug', 'enable debug mode');
// DEV
cli
.command('[root]', 'start dev server')
.option('-c, --config <file>', 'use specified config file')
.option('-m, --mode <mode>', 'set env mode')
.option('-b, --browser <browser>', 'specify a browser')
.option('--mv3', 'target manifest v3')
.option('--mv2', 'target manifest v2')
.action(commands.dev);
// BUILD
cli
.command('build [root]', 'build for production')
.option('-c, --config <file>', 'use specified config file')
.option('-m, --mode <mode>', 'set env mode')
.option('-b, --browser <browser>', 'specify a browser')
.option('--mv3', 'target manifest v3')
.option('--mv2', 'target manifest v2')
.option('--analyze', 'visualize extension bundle')
.action(commands.build);
// ZIP
cli
.command('zip [root]', 'build for production and zip output')
.option('-c, --config <file>', 'use specified config file')
.option('-m, --mode <mode>', 'set env mode')
.option('-b, --browser <browser>', 'specify a browser')
.option('--mv3', 'target manifest v3')
.option('--mv2', 'target manifest v2')
.action(commands.zip);
// PREPARE
cli
.command('prepare [root]', 'prepare typescript project')
.option('-c, --config <file>', 'use specified config file')
.action(commands.prepare);
// CLEAN
cli
.command('clean [root]', 'clean generated files and caches')
.alias('cleanup')
.action(commands.clean);
// PUBLISH
cli.command('publish [root]', 'publish to stores').action(commands.publish);
// INIT
cli
.command('init [directory]', 'initialize a new project')
.option('-t, --template <template>', 'template to use')
.option('--pm <packageManager>', 'which package manager to use')
.action(commands.init);
cli.parse();
@@ -0,0 +1,25 @@
import { describe, expect, it, vi } from 'vitest';
import { defineBackground } from '~/client/define-background';
import { BackgroundDefinition } from '~/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 });
});
});
@@ -1,13 +1,10 @@
/** @vitest-environment jsdom */
/** @vitest-environment happy-dom */
import { describe, it, expect, vi, beforeEach } from 'vitest';
import { ContentScriptContext, createContentScriptUi } from '..';
import { createContentScriptUi } from '~/client/content-scripts/content-script-ui';
import { ContentScriptContext } from '~/client/content-scripts/content-script-context';
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'),
);
import { browser } from '~/browser';
vi.mock('@webext-core/isolated-element', async () => {
const { vi } = await import('vitest');
@@ -222,9 +219,11 @@ describe('createContentScriptUi', () => {
});
ui.mount();
expect(
document.querySelector('#parent > :nth-child(3)')?.tagName,
).toEqual('TEST-APP');
// Happy DOM doesn't work in this case, so we just make sure the element is added.
// expect(
// document.querySelector('#parent > :nth-child(3)')?.tagName,
// ).toEqual('TEST-APP');
expect(document.querySelector('test-app')).toBeDefined();
});
it('should apply a custom function', async () => {
@@ -0,0 +1,17 @@
import { describe, expect, it, vi } from 'vitest';
import { defineContentScript } from '~/client/content-scripts/define-content-script';
import { ContentScriptDefinition } from '~/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);
});
});
@@ -1,25 +1,25 @@
import { ContentScriptDefinition } from '../../core/types';
import { browser } from '../browser';
import { logger } from './logger';
import { ContentScriptDefinition } from '~/types';
import { browser } from '~/browser';
import { logger } from '~/client/utils/logger';
/**
* Extends [`AbortController`](https://developer.mozilla.org/en-US/docs/Web/API/AbortController).
* Implements [`AbortController`](https://developer.mozilla.org/en-US/docs/Web/API/AbortController).
* Used to detect and stop content script code when the script is invalidated.
*
* It also provides several utilities like `ctx.setTimeout` and `ctx.setInterval` that should be used in
* content scripts instead of `window.setTimeout` or `window.setInterval`.
*/
export class ContentScriptContext extends AbortController {
static SCRIPT_STARTED_MESSAGE_TYPE = 'wxt:content-script-started';
export class ContentScriptContext implements AbortController {
private static SCRIPT_STARTED_MESSAGE_TYPE = 'wxt:content-script-started';
#isTopFrame = window.self === window.top;
#abortController: AbortController;
constructor(
private readonly contentScriptName: string,
public readonly options?: Omit<ContentScriptDefinition, 'main'>,
) {
super();
this.#abortController = new AbortController();
if (this.#isTopFrame) {
this.#stopOldScripts();
}
@@ -29,6 +29,14 @@ export class ContentScriptContext extends AbortController {
});
}
get signal() {
return this.#abortController.signal;
}
abort(reason?: any): void {
return this.#abortController.abort(reason);
}
get isInvalid(): boolean {
if (browser.runtime.id == null) {
this.notifyInvalidated(); // Sets `signal.aborted` to true
@@ -150,6 +158,7 @@ export class ContentScriptContext extends AbortController {
}
/**
* @internal
* Abort the abort controller and execute all `onInvalidated` listeners.
*/
notifyInvalidated() {
@@ -1,13 +1,13 @@
import { createIsolatedElement } from '@webext-core/isolated-element';
import { browser } from './browser';
import { logger } from './utils/logger';
import { ContentScriptContext } from '.';
import { browser } from '~/browser';
import { logger } from '~/client/utils/logger';
import { ContentScriptContext } from './content-script-context';
/**
* 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.
* See https://wxt.dev/entrypoints/content-scripts.html#ui for full documentation.
*
* @example
* // entrypoints/example-ui.content/index.ts
@@ -31,10 +31,10 @@ import { ContentScriptContext } from '.';
* }
* })
*/
export async function createContentScriptUi<T>(
export async function createContentScriptUi<TApp>(
ctx: ContentScriptContext,
options: ContentScriptUiOptions<T>,
): Promise<ContentScriptUi<T>> {
options: ContentScriptUiOptions<TApp>,
): Promise<ContentScriptUi<TApp>> {
const css = [options.css ?? ''];
if (ctx.options?.cssInjectionMode === 'ui') {
css.push(await loadCss());
@@ -62,7 +62,7 @@ export async function createContentScriptUi<T>(
return resolved ?? undefined;
};
let mounted: T;
let mounted: TApp;
const mount = () => {
const anchor = getAnchor();
@@ -173,7 +173,7 @@ async function loadCss(): Promise<string> {
}
}
export interface ContentScriptUi<T> {
export interface ContentScriptUi<TApp> {
/**
* 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.
@@ -191,7 +191,7 @@ export interface ContentScriptUi<T> {
/**
* Custom data returned from the `options.mount` function.
*/
mounted: T;
mounted: TApp;
/**
* Function that mounts or remounts the UI on the page.
*/
@@ -202,7 +202,7 @@ export interface ContentScriptUi<T> {
remove: () => void;
}
interface BaseContentScriptUiOptions<T> {
export interface BaseContentScriptUiOptions<TApp> {
/**
* The name of the custom component used to host the ShadowRoot. Must be kebab-case.
*/
@@ -234,50 +234,53 @@ interface BaseContentScriptUiOptions<T> {
*
* Optionally return a value that can be accessed at `ui.mounted` or in the `onRemove` callback.
*/
mount: (container: Element) => T;
mount: (container: Element) => TApp;
/**
* 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;
onRemove?: (mounted: TApp) => 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.
* 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 OverlayContentScriptUiOptions<TApp> =
BaseContentScriptUiOptions<TApp> & {
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 ModalContentScriptUiOptions<TApp> =
BaseContentScriptUiOptions<TApp> & {
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 InlineContentScriptUiOptions<TApp> =
BaseContentScriptUiOptions<TApp> & {
type: 'inline';
};
export type ContentScriptUiOverlayAlignment =
| 'top-left'
@@ -292,7 +295,7 @@ export type ContentScriptAppendMode =
| 'before'
| 'after';
export type ContentScriptUiOptions<T> =
| OverlayContentScriptUiOptions<T>
| ModalContentScriptUiOptions<T>
| InlineContentScriptUiOptions<T>;
export type ContentScriptUiOptions<TApp> =
| OverlayContentScriptUiOptions<TApp>
| ModalContentScriptUiOptions<TApp>
| InlineContentScriptUiOptions<TApp>;
@@ -1,4 +1,4 @@
import { ContentScriptDefinition } from '../core/types';
import { ContentScriptDefinition } from '~/types';
export function defineContentScript(
definition: ContentScriptDefinition,
+3
View File
@@ -0,0 +1,3 @@
export * from './content-script-context';
export * from './content-script-ui';
export * from './define-content-script';
+12
View File
@@ -0,0 +1,12 @@
import { BackgroundDefinition } from '~/types';
export function defineBackground(main: () => void): BackgroundDefinition;
export function defineBackground(
definition: BackgroundDefinition,
): BackgroundDefinition;
export function defineBackground(
arg: (() => void) | BackgroundDefinition,
): BackgroundDefinition {
if (typeof arg === 'function') return { main: arg };
return arg;
}
-12
View File
@@ -1,12 +0,0 @@
import { BackgroundScriptDefintition } from '..';
export function defineBackground(main: () => void): BackgroundScriptDefintition;
export function defineBackground(
definition: BackgroundScriptDefintition,
): BackgroundScriptDefintition;
export function defineBackground(
arg: (() => void) | BackgroundScriptDefintition,
): BackgroundScriptDefintition {
if (typeof arg === 'function') return { main: arg };
return arg;
}
+5 -4
View File
@@ -1,4 +1,5 @@
export * from './defineContentScript';
export * from './defineBackground';
export * from './createContentScriptUi';
export * from './utils/ContentScriptContext';
/**
* @module wxt/client
*/
export * from './define-background';
export * from './content-scripts';
@@ -1,3 +0,0 @@
import { fakeBrowser as browser } from '@webext-core/fake-browser';
export default browser;
+14 -138
View File
@@ -1,144 +1,20 @@
import { Manifest } from 'webextension-polyfill';
import { BuildOutput } from './types';
import { buildEntrypoints } from './build/buildEntrypoints';
import { findEntrypoints } from './build/findEntrypoints';
import { generateTypesDir } from './build/generateTypesDir';
import { InternalConfig, EntrypointGroup } from './types';
import { generateMainfest, writeManifest } from './utils/manifest';
import pc from 'picocolors';
import * as vite from 'vite';
import fs from 'fs-extra';
import { groupEntrypoints } from './utils/groupEntrypoints';
import { formatDuration } from './utils/formatDuration';
import { printBuildSummary } from './log/printBuildSummary';
import { execaCommand } from 'execa';
import glob from 'fast-glob';
import { unnormalizePath } from './utils/paths';
import { BuildOutput, InlineConfig } from '~/types';
import { getInternalConfig, internalBuild } from './utils/building';
/**
* Builds the extension based on an internal config.
* Bundles the extension for production. Returns a promise of the build result. Discovers the `wxt.config.ts` file in
* the root directory, and merges that config with what is passed in.
*
* This function:
* 1. Cleans the output directory
* 2. Executes the rebuild function with a blank previous output so everything is built (see
* `rebuild` for more details)
* 3. Prints the summary
*/
export async function buildInternal(
config: InternalConfig,
): Promise<BuildOutput> {
const verb = config.command === 'serve' ? 'Pre-rendering' : 'Building';
const target = `${config.browser}-mv${config.manifestVersion}`;
config.logger.info(
`${verb} ${pc.cyan(target)} for ${pc.cyan(config.mode)} with ${pc.green(
`Vite ${vite.version}`,
)}`,
);
const startTime = Date.now();
// Cleanup
await fs.rm(config.outDir, { recursive: true, force: true });
await fs.ensureDir(config.outDir);
const entrypoints = await findEntrypoints(config);
config.logger.debug('Detected entrypoints:', entrypoints);
const groups = groupEntrypoints(entrypoints);
const { output } = await rebuild(config, groups, undefined);
// Post-build
await printBuildSummary(
config.logger.success,
`Built extension in ${formatDuration(Date.now() - startTime)}`,
output,
config,
);
if (config.analysis.enabled) {
await combineAnalysisStats(config);
config.logger.info(
`Analysis complete:\n ${pc.gray('└─')} ${pc.yellow('stats.html')}`,
);
}
return output;
}
/**
* Given a configuration, list of entrypoints, and an existing, partial output, build the
* entrypoints and merge the new output with the existing output.
* @example
* // Use config from `wxt.config.ts`
* const res = await build()
*
* This function will:
* 1. Generate the .wxt directory's types
* 2. Build the `entrypointGroups` (and copies public files)
* 3. Generate the latest manifest for all entrypoints
* 4. Write the new manifest to the file system
* // or override config `from wxt.config.ts`
* const res = await build({
* // Override config...
* })
*/
export async function rebuild(
config: InternalConfig,
entrypointGroups: EntrypointGroup[],
existingOutput: Omit<BuildOutput, 'manifest'> = {
steps: [],
publicAssets: [],
},
): Promise<{ output: BuildOutput; manifest: Manifest.WebExtensionManifest }> {
const { default: ora } = await import('ora');
const spinner = ora(`Preparing...`).start();
// Update types directory with new files and types
const allEntrypoints = await findEntrypoints(config);
await generateTypesDir(allEntrypoints, config).catch((err) => {
config.logger.warn('Failed to update .wxt directory:', err);
// Throw the error if doing a regular build, don't for dev mode.
if (config.command === 'build') throw err;
});
// Build and merge the outputs
const newOutput = await buildEntrypoints(entrypointGroups, config, spinner);
const mergedOutput: Omit<BuildOutput, 'manifest'> = {
steps: [...existingOutput.steps, ...newOutput.steps],
publicAssets: [...existingOutput.publicAssets, ...newOutput.publicAssets],
};
const newManifest = await generateMainfest(
allEntrypoints,
mergedOutput,
config,
);
const finalOutput: BuildOutput = {
manifest: newManifest,
...newOutput,
};
// Write manifest
await writeManifest(newManifest, finalOutput, config);
// Stop the spinner and remove it from the CLI output
spinner.clear().stop();
return {
output: {
manifest: newManifest,
steps: [...existingOutput.steps, ...finalOutput.steps],
publicAssets: [
...existingOutput.publicAssets,
...finalOutput.publicAssets,
],
},
manifest: newManifest,
};
}
async function combineAnalysisStats(config: InternalConfig): Promise<void> {
const unixFiles = await glob(`stats-*.json`, {
cwd: config.outDir,
absolute: true,
});
const absolutePaths = unixFiles.map(unnormalizePath);
await execaCommand(
`rollup-plugin-visualizer ${absolutePaths.join(' ')} --template ${
config.analysis.template
}`,
{ cwd: config.root, stdio: 'inherit' },
);
export async function build(config?: InlineConfig): Promise<BuildOutput> {
const internalConfig = await getInternalConfig(config ?? {}, 'build');
return await internalBuild(internalConfig);
}
+3
View File
@@ -8,6 +8,9 @@ import pc from 'picocolors';
* Remove generated/temp files from the directory.
*
* @param root The directory to look for generated/temp files in. Defaults to `process.cwd()`. Can be relative to `process.cwd()` or absolute.
*
* @example
* await clean();
*/
export async function clean(root = process.cwd()) {
consola.info('Cleaning Project');
+253
View File
@@ -0,0 +1,253 @@
import {
BuildStepOutput,
EntrypointGroup,
InlineConfig,
InternalConfig,
WxtDevServer,
} from '~/types';
import * as vite from 'vite';
import type { Scripting } from 'webextension-polyfill';
import {
getEntrypointBundlePath,
getEntrypointOutputFile,
resolvePerBrowserOption,
} from '~/core/utils/entrypoints';
import {
getContentScriptCssFiles,
getContentScriptsCssMap,
} from '~/core/utils/manifest';
import {
internalBuild,
getInternalConfig,
detectDevChanges,
rebuild,
} from '~/core/utils/building';
import { createExtensionRunner } from '~/core/runners';
import { consola } from 'consola';
import { Mutex } from 'async-mutex';
import pc from 'picocolors';
import { relative } from 'node:path';
/**
* Creates a dev server and pre-builds all the files that need to exist before loading the extension.
*
* @example
* const server = await wxt.createServer({
* // Enter config...
* });
* await server.start();
*/
export async function createServer(
config?: InlineConfig,
): Promise<WxtDevServer> {
const serverInfo = await getServerInfo();
const getLatestInternalConfig = async () => {
return getInternalConfig(
{
...config,
vite: () => serverInfo.viteServerConfig,
},
'serve',
);
};
let internalConfig = await getLatestInternalConfig();
const server = await setupServer(serverInfo, internalConfig);
internalConfig.server = server;
const fileChangedMutex = new Mutex();
const changeQueue: Array<[string, string]> = [];
server.ws.on('wxt:background-initialized', () => {
// Register content scripts for the first time since they're not listed in the manifest
reloadContentScripts(server.currentOutput.steps, internalConfig, server);
});
server.watcher.on('all', async (event, path, _stats) => {
// Here, "path" is a non-normalized path (ie: C:\\users\\... instead of C:/users/...)
if (path.startsWith(internalConfig.outBaseDir)) return;
changeQueue.push([event, path]);
await fileChangedMutex.runExclusive(async () => {
const fileChanges = changeQueue.splice(0, changeQueue.length);
if (fileChanges.length === 0) return;
const changes = detectDevChanges(fileChanges, server.currentOutput);
if (changes.type === 'no-change') return;
// Log the entrypoints that were effected
internalConfig.logger.info(
`Changed: ${Array.from(new Set(fileChanges.map((change) => change[1])))
.map((file) => pc.dim(relative(internalConfig.root, file)))
.join(', ')}`,
);
const rebuiltNames = changes.rebuildGroups
.flat()
.map((entry) => {
return pc.cyan(
relative(internalConfig.outDir, getEntrypointOutputFile(entry, '')),
);
})
.join(pc.dim(', '));
// Get latest config and Rebuild groups with changes
internalConfig = await getLatestInternalConfig();
internalConfig.server = server;
const { output: newOutput } = await rebuild(
internalConfig,
// TODO: this excludes new entrypoints, so they're not built until the dev command is restarted
changes.rebuildGroups,
changes.cachedOutput,
);
server.currentOutput = newOutput;
// Perform reloads
switch (changes.type) {
case 'extension-reload':
server.reloadExtension();
break;
case 'html-reload':
reloadHtmlPages(changes.rebuildGroups, server, internalConfig);
break;
case 'content-script-reload':
reloadContentScripts(changes.changedSteps, internalConfig, server);
break;
}
consola.success(`Reloaded: ${rebuiltNames}`);
});
});
return server;
}
async function getServerInfo(): Promise<ServerInfo> {
const { default: getPort, portNumbers } = await import('get-port');
const port = await getPort({ port: portNumbers(3000, 3010) });
const hostname = 'localhost';
const origin = `http://${hostname}:${port}`;
const serverConfig: vite.InlineConfig = {
server: {
origin,
},
};
return {
port,
hostname,
origin,
viteServerConfig: serverConfig,
};
}
async function setupServer(
serverInfo: ServerInfo,
config: InternalConfig,
): Promise<WxtDevServer> {
const runner = await createExtensionRunner(config);
const viteServer = await vite.createServer(
vite.mergeConfig(serverInfo, await config.vite(config.env)),
);
const start = async () => {
await viteServer.listen(server.port);
config.logger.success(`Started dev server @ ${serverInfo.origin}`);
server.currentOutput = await internalBuild(config);
await runner.openBrowser(config);
};
const reloadExtension = () => {
viteServer.ws.send('wxt:reload-extension');
};
const reloadPage = (path: string) => {
// Can't use Vite's built-in "full-reload" event because it doesn't like our paths, it expects
// paths ending in "/index.html"
viteServer.ws.send('wxt:reload-page', path);
};
const reloadContentScript = (
contentScript: Omit<Scripting.RegisteredContentScript, 'id'>,
) => {
viteServer.ws.send('wxt:reload-content-script', contentScript);
};
const server: WxtDevServer = {
...viteServer,
start,
currentOutput: {
manifest: {
manifest_version: 3,
name: '',
version: '',
},
publicAssets: [],
steps: [],
},
port: serverInfo.port,
hostname: serverInfo.hostname,
origin: serverInfo.origin,
reloadExtension,
reloadPage,
reloadContentScript,
};
return server;
}
/**
* From the server, tell the client to reload content scripts from the provided build step outputs.
*/
function reloadContentScripts(
steps: BuildStepOutput[],
config: InternalConfig,
server: WxtDevServer,
) {
if (config.manifestVersion === 3) {
steps.forEach((step) => {
const entry = step.entrypoints;
if (Array.isArray(entry) || entry.type !== 'content-script') return;
const js = [getEntrypointBundlePath(entry, config.outDir, '.js')];
const cssMap = getContentScriptsCssMap(server.currentOutput, [entry]);
const css = getContentScriptCssFiles([entry], cssMap);
server.reloadContentScript({
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,
});
});
} else {
server.reloadExtension();
}
}
function reloadHtmlPages(
groups: EntrypointGroup[],
server: WxtDevServer,
config: InternalConfig,
) {
groups.flat().forEach((entry) => {
const path = getEntrypointBundlePath(entry, config.outDir, '.html');
server.reloadPage(path);
});
}
interface ServerInfo {
port: number;
hostname: string;
origin: string;
viteServerConfig: vite.InlineConfig;
}
@@ -1,4 +1,4 @@
import { UserConfig } from '../types';
import { UserConfig } from '~/types';
export function defineConfig(config: UserConfig): UserConfig {
return config;
@@ -1,4 +1,4 @@
import { ExtensionRunnerConfig } from '../types';
import { ExtensionRunnerConfig } from '~/types';
export function defineRunnerConfig(
config: ExtensionRunnerConfig,
+8
View File
@@ -0,0 +1,8 @@
export * from './build';
export * from './clean';
export * from './define-config';
export * from './define-runner-config';
export * from './create-server';
export * from './initialize';
export * from './prepare';
export * from './zip';
@@ -1,4 +1,3 @@
import { defineCommand } from '../utils/defineCommand';
import prompts from 'prompts';
import { consola } from 'consola';
import { downloadTemplate } from 'giget';
@@ -7,76 +6,72 @@ import path from 'node:path';
import pc from 'picocolors';
import { Formatter } from 'picocolors/types';
export const init = defineCommand<
[
directory: string | undefined,
options: { template?: string; pm?: string; debug?: boolean },
]
>(
async (userDirectory, flags) => {
consola.info('Initalizing new project');
export async function initialize(options: {
directory: string;
template: string;
packageManager: string;
}) {
consola.info('Initalizing new project');
const templates = await listTemplates();
const defaultTemplate = templates.find(
(template) => template.name === flags.template?.toLowerCase().trim(),
);
const templates = await listTemplates();
const defaultTemplate = templates.find(
(template) => template.name === options.template?.toLowerCase().trim(),
);
const input = await prompts(
[
{
name: 'directory',
type: () => (userDirectory == null ? 'text' : undefined),
message: 'Project Directory',
initial: userDirectory,
},
{
name: 'template',
type: () => (defaultTemplate == null ? 'select' : undefined),
message: 'Choose a template',
choices: templates.map((template) => ({
title:
TEMPLATE_COLORS[template.name]?.(template.name) ?? template.name,
value: template,
})),
},
{
name: 'packageManager',
type: () => (flags.pm == null ? 'select' : undefined),
message: 'Package Manager',
choices: [
{ title: 'npm', value: 'npm' },
{ title: 'pnpm', value: 'pnpm' },
{ title: 'yarn', value: 'yarn' },
],
},
],
const input = await prompts(
[
{
onCancel: () => process.exit(1),
name: 'directory',
type: () => (options.directory == null ? 'text' : undefined),
message: 'Project Directory',
initial: options.directory,
},
);
input.directory ??= userDirectory;
input.template ??= defaultTemplate;
input.packageManager ??= flags.pm;
{
name: 'template',
type: () => (defaultTemplate == null ? 'select' : undefined),
message: 'Choose a template',
choices: templates.map((template) => ({
title:
TEMPLATE_COLORS[template.name]?.(template.name) ?? template.name,
value: template,
})),
},
{
name: 'packageManager',
type: () => (options.packageManager == null ? 'select' : undefined),
message: 'Package Manager',
choices: [
{ title: 'npm', value: 'npm' },
{ title: 'pnpm', value: 'pnpm' },
{ title: 'yarn', value: 'yarn' },
],
},
],
{
onCancel: () => process.exit(1),
},
);
input.directory ??= options.directory;
input.template ??= defaultTemplate;
input.packageManager ??= options.packageManager;
await cloneProject(input);
await cloneProject(input);
const cdPath = path.relative(process.cwd(), path.resolve(input.directory));
console.log();
consola.log(
`✨ WXT project created with the ${
TEMPLATE_COLORS[input.template.name]?.(input.template.name) ??
input.template.name
} template.`,
);
console.log();
consola.log('Next steps:');
let step = 0;
if (cdPath !== '') consola.log(` ${++step}.`, pc.cyan(`cd ${cdPath}`));
consola.log(` ${++step}.`, pc.cyan(`${input.packageManager} install`));
console.log();
},
{ disableFinishedLog: true },
);
const cdPath = path.relative(process.cwd(), path.resolve(input.directory));
console.log();
consola.log(
`✨ WXT project created with the ${
TEMPLATE_COLORS[input.template.name]?.(input.template.name) ??
input.template.name
} template.`,
);
console.log();
consola.log('Next steps:');
let step = 0;
if (cdPath !== '') consola.log(` ${++step}.`, pc.cyan(`cd ${cdPath}`));
consola.log(` ${++step}.`, pc.cyan(`${input.packageManager} install`));
console.log();
}
interface Template {
/**
+15
View File
@@ -0,0 +1,15 @@
import { InlineConfig } from '~/types';
import {
findEntrypoints,
generateTypesDir,
getInternalConfig,
} from '~/core/utils/building';
export async function prepare(config: InlineConfig) {
const internalConfig = await getInternalConfig(config, 'build');
internalConfig.logger.info('Generating types...');
const entrypoints = await findEntrypoints(internalConfig);
await generateTypesDir(entrypoints, internalConfig);
}
+2 -2
View File
@@ -1,13 +1,13 @@
import { describe, expect, it, vi } from 'vitest';
import { createExtensionRunner } from '..';
import { fakeInternalConfig } from '../../../testing/fake-objects';
import { fakeInternalConfig } from '~/core/utils/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';
import { ExtensionRunner } from '~/types';
vi.mock('../../utils/wsl');
const isWslMock = vi.mocked(isWsl);
-6
View File
@@ -1,6 +0,0 @@
import { InternalConfig } from '../types';
export interface ExtensionRunner {
openBrowser(config: InternalConfig): Promise<void>;
closeBrowser(): Promise<void>;
}
+2 -3
View File
@@ -1,10 +1,9 @@
import { InternalConfig } from '../types';
import { ExtensionRunner } from './extension-runner';
import { InternalConfig, ExtensionRunner } from '~/types';
import { createWslRunner } from './wsl';
import { createWebExtRunner } from './web-ext';
import { createSafariRunner } from './safari';
import { createManualRunner } from './manual';
import { isWsl } from '../utils/wsl';
import { isWsl } from '~/core/utils/wsl';
export async function createExtensionRunner(
config: InternalConfig,
+1 -1
View File
@@ -1,4 +1,4 @@
import { ExtensionRunner } from './extension-runner';
import { ExtensionRunner } from '~/types';
import { relative } from 'node:path';
/**
+1 -1
View File
@@ -1,4 +1,4 @@
import { ExtensionRunner } from './extension-runner';
import { ExtensionRunner } from '~/types';
import { relative } from 'node:path';
/**
+1 -1
View File
@@ -1,5 +1,5 @@
import type { WebExtRunInstance } from 'web-ext-run';
import { ExtensionRunner } from './extension-runner';
import { ExtensionRunner } from '~/types';
/**
* Create an `ExtensionRunner` backed by `web-ext`.
+1 -1
View File
@@ -1,4 +1,4 @@
import { ExtensionRunner } from './extension-runner';
import { ExtensionRunner } from '~/types';
import { relative } from 'node:path';
/**
-149
View File
@@ -1,149 +0,0 @@
import {
BuildStepOutput,
EntrypointGroup,
InternalConfig,
WxtDevServer,
} from './types';
import * as vite from 'vite';
import { Scripting } from 'webextension-polyfill';
import {
getEntrypointBundlePath,
resolvePerBrowserOption,
} from './utils/entrypoints';
import {
getContentScriptCssFiles,
getContentScriptsCssMap,
} from './utils/manifest';
import { buildInternal } from './build';
import { createExtensionRunner } from './runners';
export async function getServerInfo(): Promise<ServerInfo> {
const { default: getPort, portNumbers } = await import('get-port');
const port = await getPort({ port: portNumbers(3000, 3010) });
const hostname = 'localhost';
const origin = `http://${hostname}:${port}`;
const serverConfig: vite.InlineConfig = {
server: {
origin,
},
};
return {
port,
hostname,
origin,
viteServerConfig: serverConfig,
};
}
export async function setupServer(
serverInfo: ServerInfo,
config: InternalConfig,
): Promise<WxtDevServer> {
const runner = await createExtensionRunner(config);
const viteServer = await vite.createServer(
vite.mergeConfig(serverInfo, await config.vite(config.env)),
);
const start = async () => {
await viteServer.listen(server.port);
config.logger.success(`Started dev server @ ${serverInfo.origin}`);
server.currentOutput = await buildInternal(config);
await runner.openBrowser(config);
};
const reloadExtension = () => {
viteServer.ws.send('wxt:reload-extension');
};
const reloadPage = (path: string) => {
// Can't use Vite's built-in "full-reload" event because it doesn't like our paths, it expects
// paths ending in "/index.html"
viteServer.ws.send('wxt:reload-page', path);
};
const reloadContentScript = (
contentScript: Omit<Scripting.RegisteredContentScript, 'id'>,
) => {
viteServer.ws.send('wxt:reload-content-script', contentScript);
};
const server: WxtDevServer = {
...viteServer,
start,
currentOutput: {
manifest: {
manifest_version: 3,
name: '',
version: '',
},
publicAssets: [],
steps: [],
},
port: serverInfo.port,
hostname: serverInfo.hostname,
origin: serverInfo.origin,
reloadExtension,
reloadPage,
reloadContentScript,
};
return server;
}
/**
* From the server, tell the client to reload content scripts from the provided build step outputs.
*/
export function reloadContentScripts(
steps: BuildStepOutput[],
config: InternalConfig,
server: WxtDevServer,
) {
if (config.manifestVersion === 3) {
steps.forEach((step) => {
const entry = step.entrypoints;
if (Array.isArray(entry) || entry.type !== 'content-script') return;
const js = [getEntrypointBundlePath(entry, config.outDir, '.js')];
const cssMap = getContentScriptsCssMap(server.currentOutput, [entry]);
const css = getContentScriptCssFiles([entry], cssMap);
server.reloadContentScript({
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,
});
});
} else {
server.reloadExtension();
}
}
export function reloadHtmlPages(
groups: EntrypointGroup[],
server: WxtDevServer,
config: InternalConfig,
) {
groups.flat().forEach((entry) => {
const path = getEntrypointBundlePath(entry, config.outDir, '.html');
server.reloadPage(path);
});
}
interface ServerInfo {
port: number;
hostname: string;
origin: string;
viteServerConfig: vite.InlineConfig;
}
+1 -1
View File
@@ -1,5 +1,5 @@
import { describe, it, expect } from 'vitest';
import { every } from '../arrays';
import { every } from '~/core/utils/arrays';
describe('Array Utils', () => {
describe('every', () => {
@@ -1,26 +1,36 @@
import { describe, expect, it } from 'vitest';
import { hashContentScriptOptions } from '../content-scripts';
import { hashContentScriptOptions } from '~/core/utils/content-scripts';
import { fakeInternalConfig } from '~/core/utils/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);
});
@@ -1,5 +1,5 @@
import { describe, expect, it } from 'vitest';
import { ContentSecurityPolicy } from '../ContentSecurityPolicy';
import { ContentSecurityPolicy } from '~/core/utils/content-security-policy';
describe('Content Security Policy Builder', () => {
it('should add values to new directives correctly', () => {
+2 -2
View File
@@ -3,8 +3,8 @@ import {
getEntrypointName,
getEntrypointOutputFile,
resolvePerBrowserOption,
} from '../entrypoints';
import { Entrypoint } from '../../types';
} from '~/core/utils/entrypoints';
import { Entrypoint } from '~/types';
import { resolve } from 'path';
describe('Entrypoint Utils', () => {
+26
View File
@@ -0,0 +1,26 @@
import { describe, it, expect } from 'vitest';
import { getPackageJson } from '../package';
import { fakeInternalConfig } from '../testing/fake-objects';
import { mock } from 'vitest-mock-extended';
import { Logger } from '~/types';
describe('Package JSON Utils', () => {
describe('getPackageJson', () => {
it('should return the package.json inside <root>/package.json', async () => {
const root = process.cwd(); // WXT project directory
const actual = await getPackageJson(fakeInternalConfig({ root }));
expect(actual).toMatchObject({
name: 'wxt',
});
});
it("should return an empty object when <root>/package.json doesn't exist", async () => {
const root = '/some/path/that/does/not/exist';
const logger = mock<Logger>();
const actual = await getPackageJson(fakeInternalConfig({ root, logger }));
expect(actual).toEqual({});
});
});
});
+4 -1
View File
@@ -1,5 +1,8 @@
import { describe, expect, it } from 'vitest';
import { kebabCaseAlphanumeric, removeImportStatements } from '../strings';
import {
kebabCaseAlphanumeric,
removeImportStatements,
} from '~/core/utils/strings';
describe('String utils', () => {
describe('kebabCaseAlphanumeric', () => {
@@ -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() {},
});
@@ -0,0 +1,3 @@
import { defineUnlistedScript } from '~/sandbox';
export default defineUnlistedScript(() => {});
@@ -0,0 +1,3 @@
import { defineUnlistedScript } from '~/sandbox';
export default defineUnlistedScript(() => {});
@@ -0,0 +1,5 @@
import { defineBackground } from '~/client';
export const a = {};
export default defineBackground(() => {});
@@ -1,5 +1,5 @@
import { describe, expect, it } from 'vitest';
import { DevModeChange, detectDevChanges } from '../detectDevChanges';
import { DevModeChange, detectDevChanges } from '~/core/utils/building';
import {
fakeBackgroundEntrypoint,
fakeContentScriptEntrypoint,
@@ -10,8 +10,8 @@ import {
fakePopupEntrypoint,
fakeRollupOutputAsset,
fakeRollupOutputChunk,
} from '../../../testing/fake-objects';
import { BuildOutput, BuildStepOutput } from '../../types';
} from '~/core/utils/testing/fake-objects';
import { BuildOutput, BuildStepOutput } from '~/types';
describe('Detect Dev Changes', () => {
describe('No changes', () => {
@@ -5,16 +5,16 @@ import {
GenericEntrypoint,
OptionsEntrypoint,
PopupEntrypoint,
} from '../../types';
} from '~/types';
import { resolve } from 'path';
import { findEntrypoints } from '../findEntrypoints';
import { findEntrypoints } from '../find-entrypoints';
import fs from 'fs-extra';
import { importEntrypointFile } from '../../utils/importEntrypointFile';
import { importEntrypointFile } from '../import-entrypoint';
import glob from 'fast-glob';
import { fakeInternalConfig } from '../../../testing/fake-objects';
import { unnormalizePath } from '../../utils/paths';
import { fakeInternalConfig } from '~/core/utils/testing/fake-objects';
import { unnormalizePath } from '~/core/utils/paths';
vi.mock('../../utils/importEntrypointFile');
vi.mock('../import-entrypoint');
const importEntrypointFileMock = vi.mocked(importEntrypointFile);
vi.mock('fast-glob');
@@ -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',
@@ -1,6 +1,6 @@
import { describe, expect, it } from 'vitest';
import { Entrypoint } from '../../types';
import { groupEntrypoints } from '../groupEntrypoints';
import { Entrypoint } from '~/types';
import { groupEntrypoints } from '../group-entrypoints';
const background: Entrypoint = {
type: 'background',
@@ -0,0 +1,41 @@
import { describe, expect, it } from 'vitest';
import { importEntrypointFile } from '~/core/utils/building';
import { fakeInternalConfig } from '~/core/utils/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();
});
});
@@ -5,14 +5,14 @@ import {
Entrypoint,
EntrypointGroup,
InternalConfig,
} from '../types';
import * as wxtPlugins from '../vite-plugins';
import { removeEmptyDirs } from '../utils/removeEmptyDirs';
import { getEntrypointBundlePath } from '../utils/entrypoints';
} from '~/types';
import * as wxtPlugins from '~/core/vite-plugins';
import { removeEmptyDirs } from '~/core/utils/fs';
import { getPublicFiles } from '~/core/utils/fs';
import { getEntrypointBundlePath } from '~/core/utils/entrypoints';
import fs from 'fs-extra';
import { dirname, resolve } from 'path';
import { getPublicFiles } from '../utils/public';
import { getEntrypointGlobals } from '../utils/globals';
import { getEntrypointGlobals } from '~/core/utils/globals';
import type { Ora } from 'ora';
import pc from 'picocolors';
@@ -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;
@@ -1,7 +1,7 @@
import { BuildOutput, BuildStepOutput, EntrypointGroup } from '../types';
import { BuildOutput, BuildStepOutput, EntrypointGroup } from '~/types';
import * as vite from 'vite';
import { every } from './arrays';
import { normalizePath } from './paths';
import { every } from '~/core/utils/arrays';
import { normalizePath } from '~/core/utils/paths';
/**
* Compare the changed files vs the build output and determine what kind of reload needs to happen:
@@ -1,7 +1,7 @@
import { relative, resolve } from 'path';
import {
BackgroundEntrypoint,
BackgroundScriptDefintition,
BackgroundDefinition,
BaseEntrypointOptions,
ContentScriptDefinition,
ContentScriptEntrypoint,
@@ -10,19 +10,20 @@ import {
InternalConfig,
OptionsEntrypoint,
PopupEntrypoint,
} from '../types';
UnlistedScriptDefinition,
} from '~/types';
import fs from 'fs-extra';
import { minimatch } from 'minimatch';
import { parseHTML } from 'linkedom';
import JSON5 from 'json5';
import { importEntrypointFile } from '../utils/importEntrypointFile';
import { importEntrypointFile } from '~/core/utils/building';
import glob from 'fast-glob';
import {
getEntrypointName,
resolvePerBrowserOption,
} from '../utils/entrypoints';
import { VIRTUAL_NOOP_BACKGROUND_MODULE_ID } from '../vite-plugins/noopBackground';
import { CSS_EXTENSIONS_PATTERN } from '../utils/paths';
} from '~/core/utils/entrypoints';
import { VIRTUAL_NOOP_BACKGROUND_MODULE_ID } from '~/core/vite-plugins/noopBackground';
import { CSS_EXTENSIONS_PATTERN } from '~/core/utils/paths';
/**
* Return entrypoints and their configuration by looking through the project's files.
@@ -37,11 +38,10 @@ export async function findEntrypoints(
relativePaths.sort();
const pathGlobs = Object.keys(PATH_GLOB_TO_TYPE_MAP);
const existingNames: Record<string, Entrypoint | undefined> = {};
const entrypoints: Entrypoint[] = [];
let hasBackground = false;
await Promise.all(
// TODO: This parallelization is bad
const possibleEntrypoints: Array<Entrypoint | undefined> = await Promise.all(
relativePaths.map(async (relativePath) => {
const path = resolve(config.entrypointsDir, relativePath);
const matchingGlob = pathGlobs.find((glob) =>
@@ -49,42 +49,35 @@ export async function findEntrypoints(
);
if (matchingGlob == null) {
return config.logger.warn(
config.logger.warn(
`${relativePath} does not match any known entrypoint. Known entrypoints:\n${JSON.stringify(
PATH_GLOB_TO_TYPE_MAP,
null,
2,
)}`,
);
return;
}
const type = PATH_GLOB_TO_TYPE_MAP[matchingGlob];
if (type === 'ignored') return;
let entrypoint: Entrypoint;
switch (type) {
case 'popup':
entrypoint = await getPopupEntrypoint(config, path);
break;
return await getPopupEntrypoint(config, path);
case 'options':
entrypoint = await getOptionsEntrypoint(config, path);
break;
return await getOptionsEntrypoint(config, path);
case 'background':
entrypoint = await getBackgroundEntrypoint(config, path);
hasBackground = true;
break;
return await getBackgroundEntrypoint(config, path);
case 'content-script':
entrypoint = await getContentScriptEntrypoint(
config,
getEntrypointName(config.entrypointsDir, path),
path,
);
break;
return await getContentScriptEntrypoint(config, path);
case 'unlisted-page':
entrypoint = await getUnlistedPageEntrypoint(config, path);
break;
return await getUnlistedPageEntrypoint(config, path);
case 'unlisted-script':
return await getUnlistedScriptEntrypoint(config, path);
case 'content-script-style':
entrypoint = {
return {
type,
name: getEntrypointName(config.entrypointsDir, path),
inputPath: path,
@@ -94,9 +87,8 @@ export async function findEntrypoints(
exclude: undefined,
},
};
break;
default:
entrypoint = {
return {
type,
name: getEntrypointName(config.entrypointsDir, path),
inputPath: path,
@@ -107,22 +99,30 @@ export async function findEntrypoints(
},
};
}
const withSameName = existingNames[entrypoint.name];
if (withSameName) {
throw Error(
`Multiple entrypoints with the name "${
entrypoint.name
}" detected, but only one is allowed: ${[
relative(config.root, withSameName.inputPath),
relative(config.root, entrypoint.inputPath),
].join(', ')}`,
);
}
entrypoints.push(entrypoint);
existingNames[entrypoint.name] = entrypoint;
}),
);
const entrypoints = possibleEntrypoints.filter(
(entry) => !!entry,
) as Entrypoint[];
// Report duplicate entrypoint names
const existingNames: Record<string, Entrypoint | undefined> = {};
entrypoints.forEach((entrypoint) => {
const withSameName = existingNames[entrypoint.name];
if (withSameName) {
throw Error(
`Multiple entrypoints with the name "${
entrypoint.name
}" detected, but only one is allowed: ${[
relative(config.root, withSameName.inputPath),
relative(config.root, entrypoint.inputPath),
].join(', ')}`,
);
}
existingNames[entrypoint.name] = entrypoint;
});
if (config.command === 'serve' && !hasBackground) {
entrypoints.push(
await getBackgroundEntrypoint(config, VIRTUAL_NOOP_BACKGROUND_MODULE_ID),
@@ -201,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 {
@@ -281,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.
*/
@@ -288,19 +324,24 @@ 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: {
@@ -316,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,
@@ -1,15 +1,14 @@
import { UnimportOptions, createUnimport } from 'unimport';
import { Entrypoint, InternalConfig } from '../types';
import { Entrypoint, InternalConfig } from '~/types';
import fs from 'fs-extra';
import { relative, resolve } from 'path';
import { getEntrypointBundlePath } from '../utils/entrypoints';
import { getUnimportOptions } from '../utils/auto-imports';
import { getEntrypointGlobals, getGlobals } from '../utils/globals';
import { getPublicFiles } from '../utils/public';
import { normalizePath } from '../utils/paths';
import { getEntrypointBundlePath } from '~/core/utils/entrypoints';
import { getUnimportOptions } from '~/core/utils/unimport';
import { getEntrypointGlobals, getGlobals } from '~/core/utils/globals';
import { normalizePath } from '~/core/utils/paths';
import path from 'node:path';
import { Message, parseI18nMessages } from '../utils/i18n';
import { writeFileIfDifferent } from '../utils/fs';
import { Message, parseI18nMessages } from '~/core/utils/i18n';
import { writeFileIfDifferent, getPublicFiles } from '~/core/utils/fs';
/**
* Generate and write all the files inside the `InternalConfig.typesDir` directory.
@@ -8,13 +8,12 @@ import {
UserManifest,
WxtViteConfig,
ExtensionRunnerConfig,
} from '../types';
} from '~/types';
import path from 'node:path';
import * as vite from 'vite';
import { createFsCache } from './createFsCache';
import { createFsCache } from '~/core/utils/cache';
import consola, { LogLevels } from 'consola';
import * as plugins from '../vite-plugins';
import { getGlobals } from './globals';
import * as plugins from '~/core/vite-plugins';
/**
* Given an inline config, discover the config file if necessary, merge the results, resolve any
@@ -237,10 +236,13 @@ async function resolveInternalViteConfig(
internalVite.plugins.push(plugins.devHtmlPrerender(finalConfig));
internalVite.plugins.push(plugins.unimport(finalConfig));
internalVite.plugins.push(
plugins.virtualEntrypoin('background', finalConfig),
plugins.virtualEntrypoint('background', finalConfig),
);
internalVite.plugins.push(
plugins.virtualEntrypoin('content-script', finalConfig),
plugins.virtualEntrypoint('content-script', finalConfig),
);
internalVite.plugins.push(
plugins.virtualEntrypoint('unlisted-script', finalConfig),
);
internalVite.plugins.push(plugins.devServerGlobals(finalConfig));
internalVite.plugins.push(plugins.tsconfigPaths(finalConfig));
@@ -248,10 +250,7 @@ async function resolveInternalViteConfig(
if (finalConfig.analysis.enabled) {
internalVite.plugins.push(plugins.bundleAnalysis());
}
internalVite.plugins.push(plugins.globals(finalConfig));
internalVite.define ??= {};
for (const global of getGlobals(finalConfig)) {
internalVite.define[global.name] = JSON.stringify(global.value);
}
return internalVite;
}

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