Compare commits
33 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 145038c6a2 | |||
| 6e7184d98d | |||
| ee49837804 | |||
| 67f972eab8 | |||
| b29c3c6fdd | |||
| ef6001e0c0 | |||
| 636aa48e95 | |||
| ec66b6172c | |||
| 1edd94e8f4 | |||
| 2efc193b45 | |||
| 2e51e7349d | |||
| 28733df5f9 | |||
| 0110a2bd4e | |||
| afe838a348 | |||
| 0255028ce2 | |||
| 249aa5eccc | |||
| b7c078f4e4 | |||
| f6b6b8857d | |||
| 54eb118f8c | |||
| 75eb3de89e | |||
| e14f81d97a | |||
| cd714ea196 | |||
| 684197dbe3 | |||
| c51f0e055f | |||
| 7f3a1e8d91 | |||
| 37986bf230 | |||
| 13a713cc28 | |||
| a78aada96e | |||
| 3307fc42a0 | |||
| 8be53efd24 | |||
| f02abc5227 | |||
| 2dd7a99937 | |||
| a9af4d3b67 |
Binary file not shown.
|
Before Width: | Height: | Size: 280 KiB After Width: | Height: | Size: 150 KiB |
@@ -47,4 +47,4 @@ jobs:
|
||||
pnpm publish
|
||||
|
||||
- name: GitHub Release
|
||||
run: pnpx changelogen@latest gh release
|
||||
run: pnpx changelogen@latest gh release --token ${{ secrets.GITHUB_TOKEN }}
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
.output
|
||||
coverage
|
||||
dist
|
||||
e2e/project
|
||||
|
||||
+96
-1
@@ -1,5 +1,101 @@
|
||||
# Changelog
|
||||
|
||||
## v0.1.2
|
||||
|
||||
[compare changes](https://github.com/aklinker1/wxt/compare/v0.1.1...v0.1.2)
|
||||
|
||||
### 🚀 Enhancements
|
||||
|
||||
- Accept a function for `config.manifest` ([ee49837](https://github.com/aklinker1/wxt/commit/ee49837))
|
||||
|
||||
### 🩹 Fixes
|
||||
|
||||
- Add missing types for `webextension-polyfill` and the `manifest` option ([636aa48](https://github.com/aklinker1/wxt/commit/636aa48))
|
||||
- Only add imports to JS files ([b29c3c6](https://github.com/aklinker1/wxt/commit/b29c3c6))
|
||||
- Generate valid type for `EntrypointPath` when there are no entrypoints ([6e7184d](https://github.com/aklinker1/wxt/commit/6e7184d))
|
||||
|
||||
### 🌊 Types
|
||||
|
||||
- Change `config.vite` to `UserConfig` ([ef6001e](https://github.com/aklinker1/wxt/commit/ef6001e))
|
||||
|
||||
### ❤️ Contributors
|
||||
|
||||
- Aaron Klinker
|
||||
|
||||
## v0.1.1
|
||||
|
||||
[compare changes](https://github.com/aklinker1/wxt/compare/v0.1.0...v0.1.1)
|
||||
|
||||
### 🩹 Fixes
|
||||
|
||||
- Allow dashes in entrypoint names ([2e51e73](https://github.com/aklinker1/wxt/commit/2e51e73))
|
||||
- Unable to read entrypoint options ([#28](https://github.com/aklinker1/wxt/pull/28))
|
||||
|
||||
### ❤️ Contributors
|
||||
|
||||
- Aaron Klinker
|
||||
|
||||
## v0.1.0
|
||||
|
||||
Initial release of WXT. Full support for production builds and initial toolkit for development:
|
||||
|
||||
- HMR support when HTML page dependencies change
|
||||
- Reload extension when background changes
|
||||
- Reload HTML pages when saving them directly
|
||||
- Re-register and reload tabs when content scripts change
|
||||
|
||||
[compare changes](https://github.com/aklinker1/wxt/compare/v0.0.2...v0.1.0)
|
||||
|
||||
### 🚀 Enhancements
|
||||
|
||||
- Content scripts reloading ([#25](https://github.com/aklinker1/wxt/pull/25))
|
||||
|
||||
### 📖 Documentation
|
||||
|
||||
- Update feature list ([0255028](https://github.com/aklinker1/wxt/commit/0255028))
|
||||
|
||||
### 🤖 CI
|
||||
|
||||
- Create github release ([b7c078f](https://github.com/aklinker1/wxt/commit/b7c078f))
|
||||
|
||||
### ❤️ Contributors
|
||||
|
||||
- Aaron Klinker
|
||||
|
||||
## v0.0.2
|
||||
|
||||
[compare changes](https://github.com/aklinker1/wxt/compare/v0.0.1...v0.0.2)
|
||||
|
||||
### 🚀 Enhancements
|
||||
|
||||
- Reload extension when source code is changed ([#17](https://github.com/aklinker1/wxt/pull/17))
|
||||
- Setup background script web socket/reload ([#22](https://github.com/aklinker1/wxt/pull/22))
|
||||
- Reload HTML files individually ([#23](https://github.com/aklinker1/wxt/pull/23))
|
||||
|
||||
### 🩹 Fixes
|
||||
|
||||
- Output chunks to a chunks directory ([2dd7a99](https://github.com/aklinker1/wxt/commit/2dd7a99))
|
||||
- Remove hash from content script css outputs ([#20](https://github.com/aklinker1/wxt/pull/20))
|
||||
- Overwrite files with the same name when renaming entrypoints in dev mode ([37986bf](https://github.com/aklinker1/wxt/commit/37986bf))
|
||||
- Separate template builds to prevent sharing chunks ([7f3a1e8](https://github.com/aklinker1/wxt/commit/7f3a1e8))
|
||||
- Show Vite warnings and errors ([c51f0e0](https://github.com/aklinker1/wxt/commit/c51f0e0))
|
||||
|
||||
### 📖 Documentation
|
||||
|
||||
- Add milestone progress badge to README ([684197d](https://github.com/aklinker1/wxt/commit/684197d))
|
||||
- Fix milestone link in README ([e14f81d](https://github.com/aklinker1/wxt/commit/e14f81d))
|
||||
|
||||
### 🏡 Chore
|
||||
|
||||
- Refactor build output type ([#19](https://github.com/aklinker1/wxt/pull/19))
|
||||
- Refactor build outputs to support transpiled templates ([a78aada](https://github.com/aklinker1/wxt/commit/a78aada))
|
||||
- Rename `templates` to `virtual-modules` ([#24](https://github.com/aklinker1/wxt/pull/24))
|
||||
- Update cli screenshot ([54eb118](https://github.com/aklinker1/wxt/commit/54eb118))
|
||||
|
||||
### ❤️ Contributors
|
||||
|
||||
- Aaron Klinker
|
||||
|
||||
## v0.0.1
|
||||
|
||||
[compare changes](https://github.com/aklinker1/wxt/compare/v0.0.0...v0.0.1)
|
||||
@@ -73,4 +169,3 @@
|
||||
### ❤️ Contributors
|
||||
|
||||
- Aaron Klinker
|
||||
- Aaron
|
||||
|
||||
@@ -4,29 +4,22 @@
|
||||
|
||||

|
||||
|
||||
> **Warning**
|
||||
>
|
||||
> WXT is not ready for use yet. Production builds work, but dev mode is incomplete.
|
||||
>
|
||||
> See the [Initial Release Candidate](https://github.com/aklinker1/wxt/milestone/1) milestone for more details.
|
||||
|
||||
## Features
|
||||
|
||||
- 🌐 Supports all browsers
|
||||
- ✅ Supports both MV2 and MV3
|
||||
- 📂 Directory based entrypoints
|
||||
- ⚡ Dev mode with HMR & auto-reload
|
||||
- 🚔 TypeScript
|
||||
- 🦾 Auto-imports
|
||||
- ⚡ Dev mode with HMR
|
||||
- ⬇️ Download and bundle remote URL imports
|
||||
- 🎨 Frontend framework agnostic: works with Vue, React, Svelte, etc
|
||||
|
||||
### Todo
|
||||
|
||||
- 🤖 Automated publishing
|
||||
- 🎨 Frontend framework agnostic: works with Vue, React, Svelte, etc
|
||||
- 🖍️ Quickly bootstrap a new project
|
||||
- 📏 Bundle analysis
|
||||
- ⚡ Dev mode with HMR and **_auto-reload_**
|
||||
- 🤖 Automated publishing
|
||||
|
||||
## Get Started
|
||||
|
||||
|
||||
@@ -4,7 +4,7 @@ export default defineContentScript({
|
||||
matches: ['*://*/*'],
|
||||
async main() {
|
||||
console.log(browser.runtime.id);
|
||||
|
||||
logId();
|
||||
mountContentScriptUi();
|
||||
},
|
||||
});
|
||||
|
||||
@@ -191,21 +191,18 @@ describe('Manifest Content', () => {
|
||||
expect(manifest.content_scripts).toContainEqual({
|
||||
matches: ['*://duckduckgo.com/*'],
|
||||
run_at: 'document_end',
|
||||
css: [expect.stringContaining('assets/four-')],
|
||||
css: ['assets/four.css'],
|
||||
js: ['content-scripts/four.js'],
|
||||
});
|
||||
expect(manifest.content_scripts).toContainEqual({
|
||||
matches: ['*://google.com/*'],
|
||||
run_at: 'document_end',
|
||||
css: [
|
||||
expect.stringContaining('assets/three-'),
|
||||
expect.stringContaining('assets/two-'),
|
||||
],
|
||||
css: ['assets/three.css', 'assets/two.css'],
|
||||
js: ['content-scripts/three.js', 'content-scripts/two.js'],
|
||||
});
|
||||
expect(manifest.content_scripts).toContainEqual({
|
||||
matches: ['*://google.com/*'],
|
||||
css: [expect.stringContaining('assets/one-')],
|
||||
css: ['assets/one.css'],
|
||||
js: ['content-scripts/one.js'],
|
||||
});
|
||||
});
|
||||
|
||||
@@ -44,33 +44,53 @@ describe('Output Directory Structure', () => {
|
||||
await project.build();
|
||||
|
||||
expect(await project.serializeOutput()).toMatchInlineSnapshot(`
|
||||
".output/chrome-mv3/assets/one-dedc7a05.css
|
||||
".output/chrome-mv3/assets/one.css
|
||||
----------------------------------------
|
||||
body{color:#00f}
|
||||
|
||||
================================================================================
|
||||
.output/chrome-mv3/assets/two-74d94aed.css
|
||||
.output/chrome-mv3/assets/two.css
|
||||
----------------------------------------
|
||||
body{color:red}
|
||||
|
||||
================================================================================
|
||||
.output/chrome-mv3/content-scripts/one.js
|
||||
----------------------------------------
|
||||
(function(){\\"use strict\\";function c(n){return n}const e=\\"\\",t={matches:[\\"*://*/*\\"],main:()=>{}};(async()=>{try{await t.main()}catch(n){console.error(\`The content script crashed on startup!
|
||||
|
||||
\`,n)}})()})();
|
||||
(function(){\\"use strict\\";function i(n){return n}const s=\\"\\",o={matches:[\\"*://*/*\\"],main:()=>{}};function t(n,...e){if(typeof e[0]==\\"string\\"){const c=e.shift();n(\`[wxt] \${c}\`,...e)}else n(\\"[wxt]\\",...e)}var r={debug:(...n)=>t(console.debug,...n),log:(...n)=>t(console.log,...n),warn:(...n)=>t(console.warn,...n),error:(...n)=>t(console.error,...n)};(async()=>{try{await o.main()}catch(n){r.error(\\"The content script crashed on startup!\\",n)}})()})();
|
||||
|
||||
================================================================================
|
||||
.output/chrome-mv3/content-scripts/two.js
|
||||
----------------------------------------
|
||||
(function(){\\"use strict\\";function c(n){return n}const e=\\"\\",t={matches:[\\"*://*/*\\"],main:()=>{}};(async()=>{try{await t.main()}catch(n){console.error(\`The content script crashed on startup!
|
||||
|
||||
\`,n)}})()})();
|
||||
(function(){\\"use strict\\";function i(n){return n}const s=\\"\\",o={matches:[\\"*://*/*\\"],main:()=>{}};function t(n,...e){if(typeof e[0]==\\"string\\"){const c=e.shift();n(\`[wxt] \${c}\`,...e)}else n(\\"[wxt]\\",...e)}var r={debug:(...n)=>t(console.debug,...n),log:(...n)=>t(console.log,...n),warn:(...n)=>t(console.warn,...n),error:(...n)=>t(console.error,...n)};(async()=>{try{await o.main()}catch(n){r.error(\\"The content script crashed on startup!\\",n)}})()})();
|
||||
|
||||
================================================================================
|
||||
.output/chrome-mv3/manifest.json
|
||||
----------------------------------------
|
||||
{\\"manifest_version\\":3,\\"name\\":\\"E2E Extension\\",\\"version\\":\\"0.0.0\\",\\"version_name\\":\\"0.0.0-test\\",\\"content_scripts\\":[{\\"matches\\":[\\"*://*/*\\"],\\"css\\":[\\"assets/one-dedc7a05.css\\",\\"assets/two-74d94aed.css\\"],\\"js\\":[\\"content-scripts/one.js\\",\\"content-scripts/two.js\\"]}]}"
|
||||
{\\"manifest_version\\":3,\\"name\\":\\"E2E Extension\\",\\"version\\":\\"0.0.0\\",\\"version_name\\":\\"0.0.0-test\\",\\"content_scripts\\":[{\\"matches\\":[\\"*://*/*\\"],\\"css\\":[\\"assets/one.css\\",\\"assets/two.css\\"],\\"js\\":[\\"content-scripts/one.js\\",\\"content-scripts/two.js\\"]}]}"
|
||||
`);
|
||||
});
|
||||
|
||||
it('should allow inputs with invalid JS variable names, like dashes', async () => {
|
||||
const project = new TestProject();
|
||||
project.addFile(
|
||||
'entrypoints/overlay-one.content.ts',
|
||||
`export default defineContentScript({
|
||||
matches: ["*://*/*"],
|
||||
main: () => {},
|
||||
})`,
|
||||
);
|
||||
|
||||
await project.build();
|
||||
|
||||
expect(await project.serializeOutput()).toMatchInlineSnapshot(`
|
||||
".output/chrome-mv3/content-scripts/overlay-one.js
|
||||
----------------------------------------
|
||||
(function(){\\"use strict\\";function i(n){return n}const o={matches:[\\"*://*/*\\"],main:()=>{}};function t(n,...e){if(typeof e[0]==\\"string\\"){const c=e.shift();n(\`[wxt] \${c}\`,...e)}else n(\\"[wxt]\\",...e)}var r={debug:(...n)=>t(console.debug,...n),log:(...n)=>t(console.log,...n),warn:(...n)=>t(console.warn,...n),error:(...n)=>t(console.error,...n)};(async()=>{try{await o.main()}catch(n){r.error(\\"The content script crashed on startup!\\",n)}})()})();
|
||||
|
||||
================================================================================
|
||||
.output/chrome-mv3/manifest.json
|
||||
----------------------------------------
|
||||
{\\"manifest_version\\":3,\\"name\\":\\"E2E Extension\\",\\"version\\":\\"0.0.0\\",\\"version_name\\":\\"0.0.0-test\\",\\"content_scripts\\":[{\\"matches\\":[\\"*://*/*\\"],\\"js\\":[\\"content-scripts/overlay-one.js\\"]}]}"
|
||||
`);
|
||||
});
|
||||
});
|
||||
|
||||
File diff suppressed because one or more lines are too long
+17
-13
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"name": "wxt",
|
||||
"type": "module",
|
||||
"version": "0.0.1",
|
||||
"version": "0.1.2",
|
||||
"description": "Next gen framework for developing web extensions",
|
||||
"repository": {
|
||||
"type": "git",
|
||||
@@ -22,10 +22,9 @@
|
||||
},
|
||||
"license": "MIT",
|
||||
"files": [
|
||||
"dist",
|
||||
"templates"
|
||||
"dist"
|
||||
],
|
||||
"bin": "dist/cli/index.cjs",
|
||||
"bin": "dist/cli.cjs",
|
||||
"main": "./dist/index.cjs",
|
||||
"module": "./dist/index.js",
|
||||
"types": "./dist/index.d.ts",
|
||||
@@ -36,17 +35,14 @@
|
||||
"types": "./dist/index.d.ts"
|
||||
},
|
||||
"./client": {
|
||||
"require": "./dist/client/index.cjs",
|
||||
"import": "./dist/client/index.js",
|
||||
"types": "./dist/client/index.d.ts"
|
||||
"require": "./dist/client.cjs",
|
||||
"import": "./dist/client.js",
|
||||
"types": "./dist/client.d.ts"
|
||||
}
|
||||
},
|
||||
"scripts": {
|
||||
"wxt": "tsx src/cli/index.ts",
|
||||
"build": "run-s -s build:*",
|
||||
"build:js": "tsup src/index.ts --sourcemap --dts --format esm,cjs",
|
||||
"build:cli": "tsup src/cli/index.ts -d dist/cli --sourcemap",
|
||||
"build:client": "tsup src/client/index.ts -d dist/client --sourcemap --dts --format esm,cjs",
|
||||
"build": "tsx scripts/build.ts",
|
||||
"format": "prettier --write .",
|
||||
"format:check": "prettier --write .",
|
||||
"compile": "tsc --noEmit",
|
||||
@@ -56,6 +52,10 @@
|
||||
"prepublish": "pnpm -s build"
|
||||
},
|
||||
"dependencies": {
|
||||
"@types/webextension-polyfill": "^0.10.0",
|
||||
"@webext-core/fake-browser": "^1.2.2",
|
||||
"@webext-core/match-patterns": "^1.0.1",
|
||||
"async-mutex": "^0.4.0",
|
||||
"c12": "^1.4.2",
|
||||
"cac": "^6.7.14",
|
||||
"consola": "^3.1.0",
|
||||
@@ -73,19 +73,23 @@
|
||||
"webextension-polyfill": "^0.10.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@faker-js/faker": "^8.0.2",
|
||||
"@types/fs-extra": "^11.0.1",
|
||||
"@types/lodash.merge": "^4.6.7",
|
||||
"@types/node": "^20.3.1",
|
||||
"@types/picomatch": "^2.3.0",
|
||||
"@types/webextension-polyfill": "^0.10.0",
|
||||
"@vitest/coverage-v8": "^0.32.2",
|
||||
"lodash.merge": "^4.6.2",
|
||||
"npm-run-all": "^4.1.5",
|
||||
"ora": "^6.3.1",
|
||||
"prettier": "^2.8.8",
|
||||
"pretty-quick": "^3.1.3",
|
||||
"simple-git-hooks": "^2.8.1",
|
||||
"tsup": "^7.0.0",
|
||||
"tsx": "^3.12.7",
|
||||
"typescript": "^5.1.3",
|
||||
"vitest": "^0.32.2",
|
||||
"vitest": "^0.32.4",
|
||||
"vitest-mock-extended": "^1.1.4",
|
||||
"webextension-polyfill": "^0.10.0"
|
||||
},
|
||||
"peerDependencies": {
|
||||
|
||||
Generated
+346
-201
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,90 @@
|
||||
import tsup from 'tsup';
|
||||
import glob from 'fast-glob';
|
||||
import pc from 'picocolors';
|
||||
import path from 'path';
|
||||
import { formatDuration } from '../src/core/utils/formatDuration';
|
||||
import ora from 'ora';
|
||||
import fs from 'fs-extra';
|
||||
import { consola } from 'consola';
|
||||
|
||||
const spinner = ora('Building WXT').start();
|
||||
|
||||
const startTime = Date.now();
|
||||
const outDir = 'dist';
|
||||
const virtualEntrypoints = ['background', 'content-script'];
|
||||
|
||||
await fs.rm(outDir, { recursive: true, force: true });
|
||||
|
||||
await Promise.all([
|
||||
tsup.build({
|
||||
entry: {
|
||||
index: 'src/index.ts',
|
||||
},
|
||||
format: ['cjs', 'esm'],
|
||||
sourcemap: true,
|
||||
dts: true,
|
||||
silent: true,
|
||||
}),
|
||||
tsup.build({
|
||||
entry: { cli: 'src/cli/index.ts' },
|
||||
format: ['cjs'],
|
||||
sourcemap: 'inline',
|
||||
silent: true,
|
||||
}),
|
||||
tsup.build({
|
||||
entry: { client: 'src/client/index.ts' },
|
||||
format: ['esm'],
|
||||
sourcemap: 'inline',
|
||||
dts: true,
|
||||
silent: true,
|
||||
}),
|
||||
...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}`],
|
||||
}),
|
||||
),
|
||||
tsup.build({
|
||||
entry: {
|
||||
'virtual-modules/reload-html': `src/client/virtual-modules/reload-html.ts`,
|
||||
},
|
||||
format: ['esm'],
|
||||
sourcemap: true,
|
||||
silent: true,
|
||||
}),
|
||||
tsup.build({
|
||||
entry: {
|
||||
'virtual-modules/fake-browser': `src/client/virtual-modules/fake-browser.ts`,
|
||||
},
|
||||
format: ['esm', 'cjs'],
|
||||
silent: true,
|
||||
}),
|
||||
]).catch((err) => {
|
||||
spinner.fail();
|
||||
console.error(err);
|
||||
process.exit(1);
|
||||
});
|
||||
|
||||
spinner.succeed();
|
||||
|
||||
const duration = Date.now() - startTime;
|
||||
const outFiles = await glob(`${outDir}/**`);
|
||||
outFiles.forEach((file, i) => {
|
||||
const color = file.endsWith('.map')
|
||||
? pc.dim
|
||||
: file.endsWith('.d.ts')
|
||||
? pc.blue
|
||||
: pc.cyan;
|
||||
const prefix = i === outFiles.length - 1 ? ' └─' : ' ├─';
|
||||
console.log(
|
||||
`${pc.gray(prefix)} ${pc.dim(outDir + path.sep)}${color(
|
||||
path.relative(outDir, file),
|
||||
)}`,
|
||||
);
|
||||
});
|
||||
consola.success(`Finished in ${formatDuration(duration)}`);
|
||||
Vendored
+1
@@ -0,0 +1 @@
|
||||
declare const __TEST_SEED__: number;
|
||||
@@ -23,7 +23,7 @@ export const dev = defineCommand<
|
||||
};
|
||||
|
||||
const server = await wxt.createServer(cliConfig);
|
||||
await server.listen(server.port);
|
||||
await server.start();
|
||||
|
||||
return true;
|
||||
});
|
||||
|
||||
@@ -0,0 +1,11 @@
|
||||
import browser from 'webextension-polyfill';
|
||||
|
||||
/**
|
||||
* https://developer.chrome.com/blog/longer-esw-lifetimes/
|
||||
*/
|
||||
export function keepServiceWorkerAlive() {
|
||||
setInterval(async () => {
|
||||
// Calling an async browser API resets the service worker's timeout
|
||||
await browser.runtime.getPlatformInfo();
|
||||
}, 5e3);
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
function print(method: (...args: any[]) => void, ...args: any[]) {
|
||||
if (typeof args[0] === 'string') {
|
||||
const message = args.shift();
|
||||
method(`[wxt] ${message}`, ...args);
|
||||
} else {
|
||||
method('[wxt]', ...args);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Wrapper around `console` with a "[wxt]" prefix
|
||||
*/
|
||||
export const logger = {
|
||||
debug: (...args: any[]) => print(console.debug, ...args),
|
||||
log: (...args: any[]) => print(console.log, ...args),
|
||||
warn: (...args: any[]) => print(console.warn, ...args),
|
||||
error: (...args: any[]) => print(console.error, ...args),
|
||||
};
|
||||
@@ -0,0 +1,48 @@
|
||||
import browser, { Manifest } from 'webextension-polyfill';
|
||||
import { logger } from './logger';
|
||||
import { MatchPattern } from '@webext-core/match-patterns';
|
||||
|
||||
export function reloadContentScript(contentScript: Manifest.ContentScript) {
|
||||
const manifest = browser.runtime.getManifest();
|
||||
if (manifest.manifest_version == 2) {
|
||||
void reloadContentScriptMv2(contentScript);
|
||||
} else {
|
||||
void reloadContentScriptMv3(contentScript);
|
||||
}
|
||||
}
|
||||
|
||||
export async function reloadContentScriptMv3(
|
||||
contentScript: Manifest.ContentScript,
|
||||
) {
|
||||
const id = `wxt:${contentScript.js![0]}`;
|
||||
logger.log('Reloading content script:', contentScript);
|
||||
const registered = await browser.scripting.getRegisteredContentScripts();
|
||||
logger.debug('Existing scripts:', registered);
|
||||
|
||||
const existing = registered.find((cs) => cs.id === id);
|
||||
|
||||
if (existing) {
|
||||
logger.debug('Updating content script', existing);
|
||||
await browser.scripting.updateContentScripts([{ ...contentScript, id }]);
|
||||
} else {
|
||||
logger.debug('Registering new content script...');
|
||||
await browser.scripting.registerContentScripts([{ ...contentScript, id }]);
|
||||
}
|
||||
|
||||
const allTabs = await browser.tabs.query({});
|
||||
const matchPatterns = contentScript.matches.map(
|
||||
(match) => new MatchPattern(match),
|
||||
);
|
||||
const matchingTabs = allTabs.filter((tab) => {
|
||||
const url = tab.url;
|
||||
if (!url) return false;
|
||||
return !!matchPatterns.find((pattern) => pattern.includes(url));
|
||||
});
|
||||
await Promise.all(matchingTabs.map((tab) => browser.tabs.reload(tab.id)));
|
||||
}
|
||||
|
||||
export async function reloadContentScriptMv2(
|
||||
contentScript: Manifest.ContentScript,
|
||||
) {
|
||||
throw Error('TODO: reloadContentScriptMv2');
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
import { logger } from './logger';
|
||||
|
||||
interface WebSocketMessage {
|
||||
type: string;
|
||||
event: string;
|
||||
data?: any;
|
||||
}
|
||||
|
||||
/**
|
||||
* Connect to the websocket and listen for messages.
|
||||
*
|
||||
* @param onMessage Optional callback that is called when a message is recieved and we've verified
|
||||
* it's structure is what we expect.
|
||||
*/
|
||||
export function setupWebSocket(
|
||||
onMessage?: (message: WebSocketMessage) => void,
|
||||
) {
|
||||
const serverUrl = `${__DEV_SERVER_PROTOCOL__}//${__DEV_SERVER_HOSTNAME__}:${__DEV_SERVER_PORT__}`;
|
||||
logger.debug('Connecting to dev server @', serverUrl);
|
||||
const ws = new WebSocket(serverUrl, 'vite-hmr');
|
||||
|
||||
ws.addEventListener('open', () => {
|
||||
logger.debug('Connected to dev server');
|
||||
});
|
||||
ws.addEventListener('close', () => {
|
||||
logger.debug('Disconnected from dev server');
|
||||
});
|
||||
ws.addEventListener('error', (event) => {
|
||||
logger.error('Failed to connect to dev server', event);
|
||||
});
|
||||
|
||||
ws.addEventListener('message', (e) => {
|
||||
try {
|
||||
const message = JSON.parse(e.data) as WebSocketMessage;
|
||||
if (message.type === 'custom' && message.event?.startsWith?.('wxt:')) {
|
||||
onMessage?.(message);
|
||||
}
|
||||
} catch (err) {
|
||||
logger.error('Failed to handle message', err);
|
||||
}
|
||||
});
|
||||
|
||||
return ws;
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
import definition from 'virtual:user-background';
|
||||
import { setupWebSocket } from '../utils/setupWebSocket';
|
||||
import { logger } from '../utils/logger';
|
||||
import browser from 'webextension-polyfill';
|
||||
import { keepServiceWorkerAlive } from '../utils/keepServiceWorkerAlive';
|
||||
import { reloadContentScript } from '../utils/reloadContentScript';
|
||||
|
||||
if (__COMMAND__ === 'serve') {
|
||||
try {
|
||||
const ws = setupWebSocket((message) => {
|
||||
if (message.event === 'wxt:reload-extension') browser.runtime.reload();
|
||||
if (message.event === 'wxt:reload-content-script' && message.data != null)
|
||||
reloadContentScript(message.data);
|
||||
});
|
||||
|
||||
if (__MANIFEST_VERSION__ === 3) {
|
||||
// Tell the server the background script is loaded and ready to go
|
||||
ws.addEventListener('open', () => {
|
||||
const msg = { type: 'custom', event: 'wxt:background-initialized' };
|
||||
ws.send(JSON.stringify(msg));
|
||||
});
|
||||
|
||||
// Web Socket will disconnect if the service worker is killed
|
||||
keepServiceWorkerAlive();
|
||||
}
|
||||
} catch (err) {
|
||||
logger.error('Failed to setup web socket connection with dev server', err);
|
||||
}
|
||||
}
|
||||
|
||||
try {
|
||||
const res = definition.main();
|
||||
// @ts-expect-error: res shouldn't be a promise, but we're checking it anyways
|
||||
if (res instanceof Promise) {
|
||||
console.warn(
|
||||
"The background's main() function return a promise, but it must be synchonous",
|
||||
);
|
||||
}
|
||||
} catch (err) {
|
||||
logger.error('The background script crashed on startup!');
|
||||
throw err;
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
import definition from 'virtual:user-content-script';
|
||||
import { logger } from '../utils/logger';
|
||||
|
||||
(async () => {
|
||||
try {
|
||||
await definition.main();
|
||||
} catch (err) {
|
||||
logger.error('The content script crashed on startup!', err);
|
||||
}
|
||||
})();
|
||||
@@ -0,0 +1,3 @@
|
||||
import { fakeBrowser as browser } from '@webext-core/fake-browser';
|
||||
|
||||
export default browser;
|
||||
@@ -0,0 +1,20 @@
|
||||
/// <reference types="vite/client" />
|
||||
|
||||
import { logger } from '../utils/logger';
|
||||
import { setupWebSocket } from '../utils/setupWebSocket';
|
||||
|
||||
if (__COMMAND__ === 'serve') {
|
||||
try {
|
||||
setupWebSocket((message) => {
|
||||
if (message.event === 'wxt:reload-page') {
|
||||
// We need to remove the initial slash from the path to compare correctly
|
||||
// "popup.html" === "/popup.html".substring(1)
|
||||
if (message.data === location.pathname.substring(1)) {
|
||||
location.reload();
|
||||
}
|
||||
}
|
||||
});
|
||||
} catch (err) {
|
||||
logger.error('Failed to setup web socket connection with dev server', err);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
// Types required to make the virtual modules happy.
|
||||
|
||||
declare module '*?raw' {
|
||||
const content: any;
|
||||
export default content;
|
||||
}
|
||||
|
||||
declare module 'virtual:user-background' {
|
||||
const definition: import('../../').BackgroundScriptDefintition;
|
||||
export default definition;
|
||||
}
|
||||
|
||||
declare module 'virtual:user-content-script' {
|
||||
const definition: import('../../').ContentScriptDefinition;
|
||||
export default definition;
|
||||
}
|
||||
|
||||
// Globals defined by the vite-plugins/devServerGlobals.ts and utils/globals.ts
|
||||
declare const __COMMAND__: 'build' | 'serve';
|
||||
declare const __DEV_SERVER_PROTOCOL__: string;
|
||||
declare const __DEV_SERVER_HOSTNAME__: string;
|
||||
declare const __DEV_SERVER_PORT__: string;
|
||||
declare const __MANIFEST_VERSION__: 2 | 3;
|
||||
@@ -0,0 +1,106 @@
|
||||
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';
|
||||
|
||||
/**
|
||||
* Builds the extension based on an internal config.
|
||||
*
|
||||
* 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);
|
||||
const groups = groupEntrypoints(entrypoints);
|
||||
const { output } = await rebuild(config, groups);
|
||||
|
||||
// Post-build
|
||||
config.logger.success(
|
||||
`Built extension in ${formatDuration(Date.now() - startTime)}`,
|
||||
);
|
||||
await printBuildSummary(output, config);
|
||||
|
||||
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.
|
||||
*
|
||||
* 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
|
||||
*/
|
||||
export async function rebuild(
|
||||
config: InternalConfig,
|
||||
entrypointGroups: EntrypointGroup[],
|
||||
existingOutput: Omit<BuildOutput, 'manifest'> = {
|
||||
steps: [],
|
||||
publicAssets: [],
|
||||
},
|
||||
): Promise<{ output: BuildOutput; manifest: Manifest.WebExtensionManifest }> {
|
||||
// Update types directory with new files and types
|
||||
const allEntrypoints = await findEntrypoints(config);
|
||||
await generateTypesDir(allEntrypoints, config);
|
||||
|
||||
// Build and merge the outputs
|
||||
const newOutput = await buildEntrypoints(entrypointGroups, config);
|
||||
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);
|
||||
|
||||
return {
|
||||
output: {
|
||||
manifest: newManifest,
|
||||
steps: [...existingOutput.steps, ...finalOutput.steps],
|
||||
publicAssets: [
|
||||
...existingOutput.publicAssets,
|
||||
...finalOutput.publicAssets,
|
||||
],
|
||||
},
|
||||
manifest: newManifest,
|
||||
};
|
||||
}
|
||||
@@ -7,10 +7,11 @@ import {
|
||||
PopupEntrypoint,
|
||||
} from '../../types';
|
||||
import { resolve } from 'path';
|
||||
import { FindEntrypointsConfig, findEntrypoints } from '../findEntrypoints';
|
||||
import { findEntrypoints } from '../findEntrypoints';
|
||||
import fs from 'fs-extra';
|
||||
import { importTsFile } from '../../utils/importTsFile';
|
||||
import glob from 'fast-glob';
|
||||
import { fakeInternalConfig } from '../../../testing/fake-objects';
|
||||
|
||||
vi.mock('../../utils/importTsFile');
|
||||
const importTsFileMock = vi.mocked(importTsFile);
|
||||
@@ -24,24 +25,11 @@ const readFileMock = vi.mocked(
|
||||
);
|
||||
|
||||
describe('findEntrypoints', () => {
|
||||
const config: FindEntrypointsConfig = {
|
||||
const config = fakeInternalConfig({
|
||||
root: '/',
|
||||
entrypointsDir: resolve('/src/entrypoints'),
|
||||
outDir: resolve('.output'),
|
||||
logger: {
|
||||
debug: vi.fn(),
|
||||
error: vi.fn(),
|
||||
fatal: (...args) => {
|
||||
throw Error('logger.fatal called with: ' + JSON.stringify(args));
|
||||
},
|
||||
info: vi.fn(),
|
||||
log: vi.fn(),
|
||||
warn: vi.fn(),
|
||||
success: vi.fn(),
|
||||
},
|
||||
command: 'build',
|
||||
mode: 'production',
|
||||
};
|
||||
});
|
||||
|
||||
it.each<[string, string, PopupEntrypoint]>([
|
||||
[
|
||||
@@ -189,7 +177,7 @@ describe('findEntrypoints', () => {
|
||||
|
||||
expect(entrypoints).toHaveLength(1);
|
||||
expect(entrypoints[0]).toEqual({ ...expected, options });
|
||||
expect(importTsFileMock).toBeCalledWith(config.root, expected.inputPath);
|
||||
expect(importTsFileMock).toBeCalledWith(expected.inputPath, config);
|
||||
},
|
||||
);
|
||||
|
||||
@@ -216,7 +204,7 @@ describe('findEntrypoints', () => {
|
||||
|
||||
expect(entrypoints).toHaveLength(1);
|
||||
expect(entrypoints[0]).toEqual({ ...expected, options });
|
||||
expect(importTsFileMock).toBeCalledWith(config.root, expected.inputPath);
|
||||
expect(importTsFileMock).toBeCalledWith(expected.inputPath, config);
|
||||
},
|
||||
);
|
||||
|
||||
|
||||
@@ -1,6 +1,11 @@
|
||||
import * as vite from 'vite';
|
||||
import { BuildOutput, Entrypoint, InternalConfig } from '../types';
|
||||
import { groupEntrypoints } from '../utils/groupEntrypoints';
|
||||
import {
|
||||
BuildOutput,
|
||||
BuildStepOutput,
|
||||
Entrypoint,
|
||||
EntrypointGroup,
|
||||
InternalConfig,
|
||||
} from '../types';
|
||||
import * as plugins from '../vite-plugins';
|
||||
import { removeEmptyDirs } from '../utils/removeEmptyDirs';
|
||||
import { getEntrypointBundlePath } from '../utils/entrypoints';
|
||||
@@ -9,25 +14,22 @@ import fs from 'fs-extra';
|
||||
import { dirname, resolve } from 'path';
|
||||
|
||||
export async function buildEntrypoints(
|
||||
entrypoints: Entrypoint[],
|
||||
groups: EntrypointGroup[],
|
||||
config: InternalConfig,
|
||||
): Promise<BuildOutput> {
|
||||
const groups = groupEntrypoints(entrypoints);
|
||||
|
||||
const outputs: BuildOutput[] = [];
|
||||
): Promise<Omit<BuildOutput, 'manifest'>> {
|
||||
const steps: BuildStepOutput[] = [];
|
||||
for (const group of groups) {
|
||||
const output = Array.isArray(group)
|
||||
const step = Array.isArray(group)
|
||||
? await buildMultipleEntrypoints(group, config)
|
||||
: await buildSingleEntrypoint(group, config);
|
||||
outputs.push(output);
|
||||
steps.push(step);
|
||||
}
|
||||
const publicOutput = await copyPublicDirectory(config);
|
||||
outputs.push(publicOutput);
|
||||
const publicAssets = await copyPublicDirectory(config);
|
||||
|
||||
// Remove any empty directories from moving outputs around
|
||||
await removeEmptyDirs(config.outDir);
|
||||
|
||||
return outputs.flat();
|
||||
return { publicAssets, steps };
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -36,23 +38,25 @@ export async function buildEntrypoints(
|
||||
async function buildSingleEntrypoint(
|
||||
entrypoint: Entrypoint,
|
||||
config: InternalConfig,
|
||||
): Promise<BuildOutput> {
|
||||
): Promise<BuildStepOutput> {
|
||||
// Should this entrypoint be wrapped by the vite-plugins/virtualEntrypoint plugin?
|
||||
const isVirtual = ['background', 'content-script'].includes(entrypoint.type);
|
||||
const entry = isVirtual
|
||||
? `virtual:wxt-${entrypoint.type}?${entrypoint.inputPath}`
|
||||
: entrypoint.inputPath;
|
||||
|
||||
const libMode: vite.InlineConfig = {
|
||||
const libMode: vite.UserConfig = {
|
||||
build: {
|
||||
lib: {
|
||||
entry,
|
||||
formats: ['iife'],
|
||||
name: entrypoint.name,
|
||||
name: '_',
|
||||
fileName: entrypoint.name,
|
||||
},
|
||||
rollupOptions: {
|
||||
output: {
|
||||
// There's only a single output for this build, so we use the desired bundle path for the
|
||||
// entry output (like "content-scripts/overlay.js")
|
||||
entryFileNames: getEntrypointBundlePath(
|
||||
entrypoint,
|
||||
config.outDir,
|
||||
@@ -61,7 +65,7 @@ async function buildSingleEntrypoint(
|
||||
// Output content script CSS to assets/ with a hash to prevent conflicts. Defaults to
|
||||
// "[name].[ext]" in lib mode, which usually results in "style.css". That means multiple
|
||||
// content scripts with styles would overwrite each other if it weren't changed below.
|
||||
assetFileNames: `assets/${entrypoint.name}-[hash].[ext]`,
|
||||
assetFileNames: `assets/${entrypoint.name}.[ext]`,
|
||||
},
|
||||
},
|
||||
},
|
||||
@@ -72,7 +76,10 @@ async function buildSingleEntrypoint(
|
||||
) as vite.InlineConfig;
|
||||
|
||||
const result = await vite.build(entryConfig);
|
||||
return getBuildOutput(result);
|
||||
return {
|
||||
entrypoints: entrypoint,
|
||||
chunks: getBuildOutputChunks(result),
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -81,8 +88,8 @@ async function buildSingleEntrypoint(
|
||||
async function buildMultipleEntrypoints(
|
||||
entrypoints: Entrypoint[],
|
||||
config: InternalConfig,
|
||||
): Promise<BuildOutput> {
|
||||
const multiPage: vite.InlineConfig = {
|
||||
): Promise<BuildStepOutput> {
|
||||
const multiPage: vite.UserConfig = {
|
||||
plugins: [plugins.multipageMove(entrypoints, config)],
|
||||
build: {
|
||||
rollupOptions: {
|
||||
@@ -90,6 +97,14 @@ async function buildMultipleEntrypoints(
|
||||
input[entry.name] = entry.inputPath;
|
||||
return input;
|
||||
}, {}),
|
||||
output: {
|
||||
// Include a hash to prevent conflicts
|
||||
chunkFileNames: 'chunks/[name]-[hash].js',
|
||||
// Include a hash to prevent conflicts
|
||||
entryFileNames: 'chunks/[name]-[hash].js',
|
||||
// We can't control the "name", so we need a hash to prevent conflicts
|
||||
assetFileNames: 'assets/[name]-[hash].[ext]',
|
||||
},
|
||||
},
|
||||
},
|
||||
};
|
||||
@@ -97,15 +112,18 @@ async function buildMultipleEntrypoints(
|
||||
const entryConfig = vite.mergeConfig(
|
||||
multiPage,
|
||||
config.vite,
|
||||
) as vite.InlineConfig;
|
||||
) as vite.UserConfig;
|
||||
|
||||
const result = await vite.build(entryConfig);
|
||||
return getBuildOutput(result);
|
||||
return {
|
||||
entrypoints,
|
||||
chunks: getBuildOutputChunks(result),
|
||||
};
|
||||
}
|
||||
|
||||
function getBuildOutput(
|
||||
function getBuildOutputChunks(
|
||||
result: Awaited<ReturnType<typeof vite.build>>,
|
||||
): BuildOutput {
|
||||
): BuildStepOutput['chunks'] {
|
||||
if ('on' in result) throw Error('wxt does not support vite watch mode.');
|
||||
if (Array.isArray(result)) return result.flatMap(({ output }) => output);
|
||||
return result.output;
|
||||
@@ -113,19 +131,19 @@ function getBuildOutput(
|
||||
|
||||
async function copyPublicDirectory(
|
||||
config: InternalConfig,
|
||||
): Promise<BuildOutput> {
|
||||
if (!(await fs.exists(config.publicDir))) return [];
|
||||
): Promise<BuildOutput['publicAssets']> {
|
||||
const publicAssets: BuildOutput['publicAssets'] = [];
|
||||
if (!(await fs.exists(config.publicDir))) return publicAssets;
|
||||
|
||||
const files = await glob('**/*', { cwd: config.publicDir });
|
||||
|
||||
const outputs: BuildOutput = [];
|
||||
for (const file of files) {
|
||||
const srcPath = resolve(config.publicDir, file);
|
||||
const outPath = resolve(config.outDir, file);
|
||||
|
||||
await fs.ensureDir(dirname(outPath));
|
||||
await fs.copyFile(srcPath, outPath);
|
||||
outputs.push({
|
||||
publicAssets.push({
|
||||
type: 'asset',
|
||||
fileName: file,
|
||||
name: file,
|
||||
@@ -133,5 +151,6 @@ async function copyPublicDirectory(
|
||||
source: await fs.readFile(srcPath),
|
||||
});
|
||||
}
|
||||
return outputs;
|
||||
|
||||
return publicAssets;
|
||||
}
|
||||
|
||||
@@ -21,7 +21,7 @@ import { getEntrypointName } from '../utils/entrypoints';
|
||||
* Return entrypoints and their configuration by looking through the
|
||||
*/
|
||||
export async function findEntrypoints(
|
||||
config: FindEntrypointsConfig,
|
||||
config: InternalConfig,
|
||||
): Promise<Entrypoint[]> {
|
||||
const relativePaths = await glob('**/*', {
|
||||
cwd: config.entrypointsDir,
|
||||
@@ -103,7 +103,7 @@ export async function findEntrypoints(
|
||||
* @param content String contents of the file at the path.
|
||||
*/
|
||||
async function getPopupEntrypoint(
|
||||
config: FindEntrypointsConfig,
|
||||
config: InternalConfig,
|
||||
path: string,
|
||||
): Promise<PopupEntrypoint> {
|
||||
const options: PopupEntrypoint['options'] = {};
|
||||
@@ -150,7 +150,7 @@ async function getPopupEntrypoint(
|
||||
* @param content String contents of the file at the path.
|
||||
*/
|
||||
async function getOptionsEntrypoint(
|
||||
config: FindEntrypointsConfig,
|
||||
config: InternalConfig,
|
||||
path: string,
|
||||
): Promise<OptionsEntrypoint> {
|
||||
const options: OptionsEntrypoint['options'] = {};
|
||||
@@ -192,11 +192,11 @@ async function getOptionsEntrypoint(
|
||||
* @param path Absolute path to the background's TS file.
|
||||
*/
|
||||
async function getBackgroundEntrypoint(
|
||||
config: FindEntrypointsConfig,
|
||||
config: InternalConfig,
|
||||
path: string,
|
||||
): Promise<BackgroundEntrypoint> {
|
||||
const { main: _, ...options } =
|
||||
await importTsFile<BackgroundScriptDefintition>(config.root, path);
|
||||
await importTsFile<BackgroundScriptDefintition>(path, config);
|
||||
if (options == null) {
|
||||
throw Error('Background script does not have a default export');
|
||||
}
|
||||
@@ -213,13 +213,13 @@ async function getBackgroundEntrypoint(
|
||||
* @param path Absolute path to the content script's TS file.
|
||||
*/
|
||||
async function getContentScriptEntrypoint(
|
||||
config: FindEntrypointsConfig,
|
||||
config: InternalConfig,
|
||||
name: string,
|
||||
path: string,
|
||||
): Promise<ContentScriptEntrypoint> {
|
||||
const { main: _, ...options } = await importTsFile<ContentScriptDefinition>(
|
||||
config.root,
|
||||
path,
|
||||
config,
|
||||
);
|
||||
if (options == null) {
|
||||
throw Error(`Content script ${name} does not have a default export`);
|
||||
@@ -274,8 +274,3 @@ const PATH_GLOB_TO_TYPE_MAP: Record<string, Entrypoint['type'] | 'ignored'> = {
|
||||
// Don't warn about any files in subdirectories, like CSS or JS entrypoints for HTML files
|
||||
'*/*': 'ignored',
|
||||
};
|
||||
|
||||
export type FindEntrypointsConfig = Pick<
|
||||
InternalConfig,
|
||||
'root' | 'entrypointsDir' | 'outDir' | 'logger' | 'mode' | 'command'
|
||||
>;
|
||||
|
||||
@@ -48,22 +48,23 @@ async function writePathsDeclarationFile(
|
||||
config: InternalConfig,
|
||||
): Promise<string> {
|
||||
const filePath = resolve(config.typesDir, 'paths.d.ts');
|
||||
const unions = entrypoints
|
||||
.map((entry) => {
|
||||
const path = getEntrypointBundlePath(
|
||||
entry,
|
||||
config.outDir,
|
||||
entry.inputPath.endsWith('.html') ? '.html' : '.js',
|
||||
);
|
||||
return ` | "/${path}"`;
|
||||
})
|
||||
.sort();
|
||||
|
||||
await fs.writeFile(
|
||||
filePath,
|
||||
[
|
||||
'// Generated by wxt',
|
||||
'type EntrypointPath =',
|
||||
...entrypoints
|
||||
.map((entry) => {
|
||||
const path = getEntrypointBundlePath(
|
||||
entry,
|
||||
config.outDir,
|
||||
entry.inputPath.endsWith('.html') ? '.html' : '.js',
|
||||
);
|
||||
return ` | "/${path}"`;
|
||||
})
|
||||
.sort(),
|
||||
...(unions.length === 0 ? [' never'] : unions),
|
||||
].join('\n') + '\n',
|
||||
);
|
||||
|
||||
|
||||
@@ -9,7 +9,10 @@ export async function printBuildSummary(
|
||||
output: BuildOutput,
|
||||
config: InternalConfig,
|
||||
) {
|
||||
const chunks = output.sort((l, r) => {
|
||||
const chunks = [
|
||||
...output.steps.flatMap((step) => step.chunks),
|
||||
...output.publicAssets,
|
||||
].sort((l, r) => {
|
||||
const lWeight =
|
||||
CHUNK_SORT_WEIGHTS[l.fileName] ??
|
||||
CHUNK_SORT_WEIGHTS[extname(l.fileName)] ??
|
||||
|
||||
@@ -0,0 +1,131 @@
|
||||
import {
|
||||
BuildStepOutput,
|
||||
EntrypointGroup,
|
||||
InternalConfig,
|
||||
WxtDevServer,
|
||||
} from './types';
|
||||
import * as vite from 'vite';
|
||||
import { findOpenPort } from './utils/findOpenPort';
|
||||
import { Manifest } from 'webextension-polyfill';
|
||||
import { getEntrypointBundlePath } from './utils/entrypoints';
|
||||
import { getContentScriptCssFiles } from './utils/manifest';
|
||||
import { createWebExtRunner } from './runners/createWebExtRunner';
|
||||
import { buildInternal } from './build';
|
||||
|
||||
export async function getServerInfo(): Promise<ServerInfo> {
|
||||
const port = await findOpenPort(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 = createWebExtRunner();
|
||||
|
||||
const viteServer = await vite.createServer(
|
||||
vite.mergeConfig(serverInfo, config.vite),
|
||||
);
|
||||
|
||||
const start = async () => {
|
||||
await viteServer.listen(server.port);
|
||||
config.logger.success(`Started dev server @ ${serverInfo.origin}`);
|
||||
|
||||
server.currentOutput = await buildInternal(config);
|
||||
config.logger.info('Opening browser...');
|
||||
await runner.openBrowser(config);
|
||||
config.logger.success('Opened!');
|
||||
};
|
||||
|
||||
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: Manifest.ContentScript) => {
|
||||
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 css = getContentScriptCssFiles([entry], server.currentOutput);
|
||||
|
||||
server.reloadContentScript({
|
||||
js,
|
||||
css,
|
||||
...entry.options,
|
||||
});
|
||||
});
|
||||
} 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,6 +1,7 @@
|
||||
import * as vite from 'vite';
|
||||
import { Manifest } from 'webextension-polyfill';
|
||||
import { UnimportOptions } from 'unimport';
|
||||
import { EntrypointGroup } from '.';
|
||||
|
||||
export interface InlineConfig {
|
||||
root?: string;
|
||||
@@ -18,8 +19,8 @@ export interface InlineConfig {
|
||||
browser?: TargetBrowser;
|
||||
manifestVersion?: TargetManifestVersion;
|
||||
logger?: Logger;
|
||||
vite?: Omit<vite.InlineConfig, 'root' | 'configFile' | 'mode'>;
|
||||
manifest?: UserManifest;
|
||||
vite?: Omit<vite.UserConfig, 'root' | 'configFile' | 'mode'>;
|
||||
manifest?: UserManifest | Promise<UserManifest> | UserManifestFn;
|
||||
server?: WxtDevServer;
|
||||
runner?: ExtensionRunnerConfig;
|
||||
}
|
||||
@@ -29,13 +30,60 @@ export interface WxtInlineViteConfig
|
||||
build?: Omit<vite.BuildOptions, 'outDir'>;
|
||||
}
|
||||
|
||||
export type BuildOutput = (vite.Rollup.OutputChunk | vite.Rollup.OutputAsset)[];
|
||||
export interface BuildOutput {
|
||||
manifest: Manifest.WebExtensionManifest;
|
||||
publicAssets: vite.Rollup.OutputAsset[];
|
||||
steps: BuildStepOutput[];
|
||||
}
|
||||
|
||||
export interface BuildStepOutput {
|
||||
entrypoints: EntrypointGroup;
|
||||
chunks: (vite.Rollup.OutputChunk | vite.Rollup.OutputAsset)[];
|
||||
}
|
||||
|
||||
export interface WxtDevServer extends vite.ViteDevServer {
|
||||
logger: Logger;
|
||||
/**
|
||||
* Ex: `3000`
|
||||
*/
|
||||
port: number;
|
||||
/**
|
||||
* Ex: `"localhost"`
|
||||
*/
|
||||
hostname: string;
|
||||
/**
|
||||
* Ex: `"http://localhost:3000"`
|
||||
*/
|
||||
origin: string;
|
||||
/**
|
||||
* Stores the current build output of the server.
|
||||
*/
|
||||
currentOutput: BuildOutput;
|
||||
/**
|
||||
* Start the server on the first open port.
|
||||
*/
|
||||
start(): Promise<void>;
|
||||
/**
|
||||
* Tell the extension to reload by running `browser.runtime.reload`.
|
||||
*/
|
||||
reloadExtension: () => void;
|
||||
/**
|
||||
* Tell an extension page to reload.
|
||||
*
|
||||
* The path is the bundle path, not the input paths, so if the input paths is
|
||||
* "src/options/index.html", you would pass "options.html" because that's where it is written to
|
||||
* in the dist directory, and where it's available at in the actual extension.
|
||||
*
|
||||
* @example
|
||||
* server.reloadPage("popup.html")
|
||||
* server.reloadPage("sandbox.html")
|
||||
*/
|
||||
reloadPage: (path: string) => void;
|
||||
/**
|
||||
* Tell the extension to restart a content script.
|
||||
*
|
||||
* @param contentScript The manifest definition for a content script
|
||||
*/
|
||||
reloadContentScript: (contentScript: Manifest.ContentScript) => void;
|
||||
}
|
||||
|
||||
export type TargetBrowser = 'chrome' | 'firefox' | 'safari' | 'edge' | 'opera';
|
||||
@@ -91,7 +139,6 @@ export interface GenericEntrypoint extends BaseEntrypoint {
|
||||
| 'sidepanel'
|
||||
| 'devtools'
|
||||
| 'unlisted-page'
|
||||
| 'unlisted-page'
|
||||
| 'unlisted-script';
|
||||
}
|
||||
|
||||
@@ -144,7 +191,7 @@ export interface ContentScriptDefinition {
|
||||
matchAboutBlank?: boolean;
|
||||
matchOriginAsFallback?: boolean;
|
||||
world?: 'ISOLATED' | 'MAIN';
|
||||
main(onStopped: OnContentScriptStopped): void | Promise<void>;
|
||||
main(): void | Promise<void>;
|
||||
}
|
||||
|
||||
export interface BackgroundScriptDefintition {
|
||||
@@ -179,6 +226,23 @@ export type UserManifest = Omit<
|
||||
| 'version_name'
|
||||
>;
|
||||
|
||||
export type UserManifestFn = (
|
||||
env: ConfigEnv,
|
||||
) => UserManifest | Promise<UserManifest>;
|
||||
|
||||
export interface ConfigEnv {
|
||||
mode: string;
|
||||
command: 'build' | 'serve';
|
||||
/**
|
||||
* Browser passed in from the CLI
|
||||
*/
|
||||
browser: TargetBrowser;
|
||||
/**
|
||||
* Manifest version passed in from the CLI
|
||||
*/
|
||||
manifestVersion: 2 | 3;
|
||||
}
|
||||
|
||||
/**
|
||||
* Configure how the browser starts up.
|
||||
*/
|
||||
|
||||
@@ -0,0 +1,18 @@
|
||||
import { describe, it, expect } from 'vitest';
|
||||
import { every } from '../arrays';
|
||||
|
||||
describe('Array Utils', () => {
|
||||
describe('every', () => {
|
||||
it('should return true when the array is empty', () => {
|
||||
expect(every([], () => false)).toBe(true);
|
||||
});
|
||||
|
||||
it("should return true when all item predicate's return true", () => {
|
||||
expect(every([1, 1, 1], (item) => item === 1)).toBe(true);
|
||||
});
|
||||
|
||||
it("should return false when a single item predicate's return false", () => {
|
||||
expect(every([1, 2, 1], (item) => item === 1)).toBe(false);
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,251 @@
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { DevModeChange, detectDevChanges } from '../detectDevChanges';
|
||||
import {
|
||||
fakeBackgroundEntrypoint,
|
||||
fakeContentScriptEntrypoint,
|
||||
fakeFile,
|
||||
fakeGenericEntrypoint,
|
||||
fakeManifest,
|
||||
fakeOptionsEntrypoint,
|
||||
fakePopupEntrypoint,
|
||||
fakeRollupOutputAsset,
|
||||
fakeRollupOutputChunk,
|
||||
} from '../../../testing/fake-objects';
|
||||
import { BuildOutput, BuildStepOutput } from '../../types';
|
||||
|
||||
describe('Detect Dev Changes', () => {
|
||||
describe('No changes', () => {
|
||||
it("should return 'no-change' when a build hasn't finished", () => {
|
||||
const actual = detectDevChanges(
|
||||
[['unknown', '/path/to/file.ts']],
|
||||
undefined,
|
||||
);
|
||||
|
||||
expect(actual).toEqual({ type: 'no-change' });
|
||||
});
|
||||
|
||||
it("should return 'no-change' when the changed file isn't used by any of the entrypoints", () => {
|
||||
const change: [string, string] = ['unknown', '/some/path.ts'];
|
||||
const currentOutput: BuildOutput = {
|
||||
manifest: fakeManifest(),
|
||||
publicAssets: [],
|
||||
steps: [
|
||||
{
|
||||
entrypoints: fakeContentScriptEntrypoint(),
|
||||
chunks: [fakeRollupOutputChunk(), fakeRollupOutputChunk()],
|
||||
},
|
||||
{
|
||||
entrypoints: fakeContentScriptEntrypoint(),
|
||||
chunks: [
|
||||
fakeRollupOutputChunk(),
|
||||
fakeRollupOutputChunk(),
|
||||
fakeRollupOutputChunk(),
|
||||
],
|
||||
},
|
||||
],
|
||||
};
|
||||
|
||||
const actual = detectDevChanges([change], currentOutput);
|
||||
|
||||
expect(actual).toEqual({ type: 'no-change' });
|
||||
});
|
||||
});
|
||||
|
||||
describe('Public Assets', () => {
|
||||
it("should return 'extension-reload' without any groups to rebuild when the changed file is a public asset", () => {
|
||||
const change: [string, string] = [
|
||||
'unknown',
|
||||
'/root/src/public/image.svg',
|
||||
];
|
||||
const asset1 = fakeRollupOutputAsset({
|
||||
fileName: 'image.svg',
|
||||
});
|
||||
const asset2 = fakeRollupOutputAsset({
|
||||
fileName: 'some-other-image.svg',
|
||||
});
|
||||
const currentOutput: BuildOutput = {
|
||||
manifest: fakeManifest(),
|
||||
publicAssets: [asset1, asset2],
|
||||
steps: [],
|
||||
};
|
||||
const expected: DevModeChange = {
|
||||
type: 'extension-reload',
|
||||
rebuildGroups: [],
|
||||
cachedOutput: {
|
||||
...currentOutput,
|
||||
publicAssets: [asset2],
|
||||
},
|
||||
};
|
||||
|
||||
const actual = detectDevChanges([change], currentOutput);
|
||||
|
||||
expect(actual).toEqual(expected);
|
||||
});
|
||||
});
|
||||
|
||||
describe('Background', () => {
|
||||
it("should rebuild the background and reload the extension when the changed file in it's chunks' `moduleIds` field", () => {
|
||||
const changedPath = '/root/utils/shared.ts';
|
||||
const contentScript = fakeContentScriptEntrypoint({
|
||||
inputPath: '/root/overlay.content.ts',
|
||||
});
|
||||
const background = fakeBackgroundEntrypoint({
|
||||
inputPath: '/root/background.ts',
|
||||
});
|
||||
|
||||
const step1: BuildStepOutput = {
|
||||
entrypoints: contentScript,
|
||||
chunks: [
|
||||
fakeRollupOutputChunk({
|
||||
moduleIds: [fakeFile(), fakeFile()],
|
||||
}),
|
||||
],
|
||||
};
|
||||
const step2: BuildStepOutput = {
|
||||
entrypoints: background,
|
||||
chunks: [
|
||||
fakeRollupOutputChunk({
|
||||
moduleIds: [fakeFile(), changedPath, fakeFile()],
|
||||
}),
|
||||
],
|
||||
};
|
||||
|
||||
const currentOutput: BuildOutput = {
|
||||
manifest: fakeManifest(),
|
||||
publicAssets: [],
|
||||
steps: [step1, step2],
|
||||
};
|
||||
const expected: DevModeChange = {
|
||||
type: 'extension-reload',
|
||||
cachedOutput: {
|
||||
...currentOutput,
|
||||
steps: [step1],
|
||||
},
|
||||
rebuildGroups: [background],
|
||||
};
|
||||
|
||||
const actual = detectDevChanges(
|
||||
[['unknown', changedPath]],
|
||||
currentOutput,
|
||||
);
|
||||
|
||||
expect(actual).toEqual(expected);
|
||||
});
|
||||
});
|
||||
|
||||
describe('HTML Pages', () => {
|
||||
it('should rebuild then reload only the effected pages', async () => {
|
||||
const changedPath = '/root/page1/index.html';
|
||||
const htmlPage1 = fakePopupEntrypoint({
|
||||
inputPath: changedPath,
|
||||
});
|
||||
const htmlPage2 = fakeOptionsEntrypoint({
|
||||
inputPath: '/root/page2.html',
|
||||
});
|
||||
const htmlPage3 = fakeGenericEntrypoint({
|
||||
type: 'sandbox',
|
||||
inputPath: '/root/page3.html',
|
||||
});
|
||||
|
||||
const step1: BuildStepOutput = {
|
||||
entrypoints: [htmlPage1, htmlPage2],
|
||||
chunks: [
|
||||
fakeRollupOutputChunk({
|
||||
moduleIds: [fakeFile(), changedPath],
|
||||
}),
|
||||
],
|
||||
};
|
||||
const step2: BuildStepOutput = {
|
||||
entrypoints: [htmlPage3],
|
||||
chunks: [
|
||||
fakeRollupOutputChunk({
|
||||
moduleIds: [fakeFile(), fakeFile(), fakeFile()],
|
||||
}),
|
||||
],
|
||||
};
|
||||
|
||||
const currentOutput: BuildOutput = {
|
||||
manifest: fakeManifest(),
|
||||
publicAssets: [],
|
||||
steps: [step1, step2],
|
||||
};
|
||||
const expected: DevModeChange = {
|
||||
type: 'html-reload',
|
||||
cachedOutput: {
|
||||
...currentOutput,
|
||||
steps: [step2],
|
||||
},
|
||||
rebuildGroups: [[htmlPage1, htmlPage2]],
|
||||
};
|
||||
|
||||
const actual = detectDevChanges(
|
||||
[['unknown', changedPath]],
|
||||
currentOutput,
|
||||
);
|
||||
|
||||
expect(actual).toEqual(expected);
|
||||
});
|
||||
});
|
||||
|
||||
describe('Content Scripts', () => {
|
||||
it('should rebuild then reload only the effected content scripts', async () => {
|
||||
const changedPath = '/root/utils/shared.ts';
|
||||
const script1 = fakeContentScriptEntrypoint({
|
||||
inputPath: '/root/overlay1.content/index.ts',
|
||||
});
|
||||
const script2 = fakeContentScriptEntrypoint({
|
||||
inputPath: '/root/overlay2.ts',
|
||||
});
|
||||
const script3 = fakeContentScriptEntrypoint({
|
||||
inputPath: '/root/overlay3.content/index.ts',
|
||||
});
|
||||
|
||||
const step1: BuildStepOutput = {
|
||||
entrypoints: script1,
|
||||
chunks: [
|
||||
fakeRollupOutputChunk({
|
||||
moduleIds: [fakeFile(), changedPath],
|
||||
}),
|
||||
],
|
||||
};
|
||||
const step2: BuildStepOutput = {
|
||||
entrypoints: script2,
|
||||
chunks: [
|
||||
fakeRollupOutputChunk({
|
||||
moduleIds: [fakeFile(), fakeFile(), fakeFile()],
|
||||
}),
|
||||
],
|
||||
};
|
||||
const step3: BuildStepOutput = {
|
||||
entrypoints: script3,
|
||||
chunks: [
|
||||
fakeRollupOutputChunk({
|
||||
moduleIds: [changedPath, fakeFile(), fakeFile()],
|
||||
}),
|
||||
],
|
||||
};
|
||||
|
||||
const currentOutput: BuildOutput = {
|
||||
manifest: fakeManifest(),
|
||||
publicAssets: [],
|
||||
steps: [step1, step2, step3],
|
||||
};
|
||||
const expected: DevModeChange = {
|
||||
type: 'content-script-reload',
|
||||
cachedOutput: {
|
||||
...currentOutput,
|
||||
steps: [step2],
|
||||
},
|
||||
changedSteps: [step1, step3],
|
||||
rebuildGroups: [script1, script3],
|
||||
};
|
||||
|
||||
const actual = detectDevChanges(
|
||||
[['unknown', changedPath]],
|
||||
currentOutput,
|
||||
);
|
||||
|
||||
expect(actual).toEqual(expected);
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,11 @@
|
||||
/**
|
||||
* Checks if `predicate` returns truthy for all elements of the array.
|
||||
*/
|
||||
export function every<T>(
|
||||
array: T[],
|
||||
predicate: (item: T, index: number) => boolean,
|
||||
): boolean {
|
||||
for (let i = 0; i < array.length; i++)
|
||||
if (!predicate(array[i], i)) return false;
|
||||
return true;
|
||||
}
|
||||
@@ -0,0 +1,177 @@
|
||||
import { BuildOutput, BuildStepOutput, EntrypointGroup } from '../types';
|
||||
import * as vite from 'vite';
|
||||
import { every } from './arrays';
|
||||
|
||||
/**
|
||||
* Compare the changed files vs the build output and determine what kind of reload needs to happen:
|
||||
*
|
||||
* - Do nothing
|
||||
* - CSS or JS file associated with an HTML page is changed - this is handled automatically by the
|
||||
* dev server
|
||||
* - Change isn't used by any of the entrypoints
|
||||
* - Reload Content script
|
||||
* - CSS or JS file associated with a content script
|
||||
* - Background script will be told to reload the content script
|
||||
* - Reload HTML file
|
||||
* - HTML file itself is saved - HMR doesn't handle this because the HTML pages are pre-rendered
|
||||
* - Chrome is OK reloading the page when the HTML file is changed without reloading the whole
|
||||
* extension. Not sure about firefox, this might need to change to an extension reload
|
||||
* - Reload extension
|
||||
* - Background script is changed
|
||||
* - Manifest is different
|
||||
* - Restart browser
|
||||
* - Config file changed (wxt.config.ts, .env, web-ext.config.ts, etc)
|
||||
*/
|
||||
export function detectDevChanges(
|
||||
changedFiles: [event: string, path: string][],
|
||||
currentOutput: BuildOutput | undefined,
|
||||
): DevModeChange {
|
||||
if (currentOutput == null) return { type: 'no-change' };
|
||||
|
||||
const changedSteps = new Set(
|
||||
changedFiles.flatMap((changedFile) =>
|
||||
findEffectedSteps(changedFile, currentOutput),
|
||||
),
|
||||
);
|
||||
if (changedSteps.size === 0) return { type: 'no-change' };
|
||||
|
||||
const unchangedOutput: BuildOutput = {
|
||||
manifest: currentOutput.manifest,
|
||||
steps: [],
|
||||
publicAssets: [],
|
||||
};
|
||||
const changedOutput: BuildOutput = {
|
||||
manifest: currentOutput.manifest,
|
||||
steps: [],
|
||||
publicAssets: [],
|
||||
};
|
||||
|
||||
for (const step of currentOutput.steps) {
|
||||
if (changedSteps.has(step)) {
|
||||
changedOutput.steps.push(step);
|
||||
} else {
|
||||
unchangedOutput.steps.push(step);
|
||||
}
|
||||
}
|
||||
for (const asset of currentOutput.publicAssets) {
|
||||
if (changedSteps.has(asset)) {
|
||||
changedOutput.publicAssets.push(asset);
|
||||
} else {
|
||||
unchangedOutput.publicAssets.push(asset);
|
||||
}
|
||||
}
|
||||
|
||||
const isOnlyHtmlChanges =
|
||||
changedFiles.length > 0 &&
|
||||
every(changedFiles, ([_, file]) => file.endsWith('.html'));
|
||||
if (isOnlyHtmlChanges) {
|
||||
return {
|
||||
type: 'html-reload',
|
||||
cachedOutput: unchangedOutput,
|
||||
rebuildGroups: changedOutput.steps.map((step) => step.entrypoints),
|
||||
};
|
||||
}
|
||||
|
||||
const isOnlyContentScripts =
|
||||
changedOutput.steps.length > 0 &&
|
||||
every(
|
||||
changedOutput.steps.flatMap((step) => step.entrypoints),
|
||||
(entry) => entry.type === 'content-script',
|
||||
);
|
||||
if (isOnlyContentScripts) {
|
||||
return {
|
||||
type: 'content-script-reload',
|
||||
cachedOutput: unchangedOutput,
|
||||
changedSteps: changedOutput.steps,
|
||||
rebuildGroups: changedOutput.steps.map((step) => step.entrypoints),
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
type: 'extension-reload',
|
||||
cachedOutput: unchangedOutput,
|
||||
rebuildGroups: changedOutput.steps.map((step) => step.entrypoints),
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* For a single change, return all the step of the build output that were effected by it.
|
||||
*/
|
||||
function findEffectedSteps(
|
||||
changedFile: [event: string, path: string],
|
||||
currentOutput: BuildOutput,
|
||||
): DetectedChange[] {
|
||||
const changes: DetectedChange[] = [];
|
||||
const changedPath = changedFile[1];
|
||||
|
||||
const isChunkEffected = (
|
||||
chunk: vite.Rollup.OutputChunk | vite.Rollup.OutputAsset,
|
||||
): boolean =>
|
||||
// If it's an HTML file with the same path, is is effected because HTML files need to be pre-rendered
|
||||
// TODO: use bundle path to support `<name>/index.html`?
|
||||
(chunk.type === 'asset' && changedPath.endsWith(chunk.fileName)) ||
|
||||
// If it's a chunk that depends on the changed file, it is effected
|
||||
(chunk.type === 'chunk' && chunk.moduleIds.includes(changedPath));
|
||||
|
||||
for (const step of currentOutput.steps) {
|
||||
const effectedChunk = step.chunks.find((chunk) => isChunkEffected(chunk));
|
||||
if (effectedChunk) changes.push(step);
|
||||
}
|
||||
|
||||
const effectedAsset = currentOutput.publicAssets.find((chunk) =>
|
||||
isChunkEffected(chunk),
|
||||
);
|
||||
if (effectedAsset) changes.push(effectedAsset);
|
||||
|
||||
return changes;
|
||||
}
|
||||
|
||||
/**
|
||||
* Contains information about what files changed, what needs rebuilt, and the type of reload that is
|
||||
* required.
|
||||
*/
|
||||
export type DevModeChange =
|
||||
| NoChange
|
||||
| HtmlReload
|
||||
| ExtensionReload
|
||||
| ContentScriptReload;
|
||||
// | BrowserRestart
|
||||
|
||||
interface NoChange {
|
||||
type: 'no-change';
|
||||
}
|
||||
|
||||
interface RebuildChange {
|
||||
/**
|
||||
* The list of entrypoints that need rebuilt.
|
||||
*/
|
||||
rebuildGroups: EntrypointGroup[];
|
||||
/**
|
||||
* The previous output stripped of any files are going to change.
|
||||
*/
|
||||
cachedOutput: BuildOutput;
|
||||
}
|
||||
|
||||
interface HtmlReload extends RebuildChange {
|
||||
type: 'html-reload';
|
||||
}
|
||||
|
||||
interface ExtensionReload extends RebuildChange {
|
||||
type: 'extension-reload';
|
||||
}
|
||||
|
||||
// interface BrowserRestart extends RebuildChange {
|
||||
// type: 'browser-restart';
|
||||
// }
|
||||
|
||||
interface ContentScriptReload extends RebuildChange {
|
||||
type: 'content-script-reload';
|
||||
changedSteps: BuildStepOutput[];
|
||||
}
|
||||
|
||||
/**
|
||||
* When figuring out what needs reloaded, this stores the step that was changed, or the public
|
||||
* directory asset that was changed. It doesn't know what type of change is required yet. Just an
|
||||
* intermediate type.
|
||||
*/
|
||||
type DetectedChange = BuildStepOutput | vite.Rollup.OutputAsset;
|
||||
@@ -3,11 +3,11 @@ import {
|
||||
InlineConfig,
|
||||
InternalConfig,
|
||||
UserConfig,
|
||||
UserManifest,
|
||||
} from '../types';
|
||||
import path, { resolve } from 'node:path';
|
||||
import * as vite from 'vite';
|
||||
import { consola } from 'consola';
|
||||
import { importTsFile } from './importTsFile';
|
||||
import * as plugins from '../vite-plugins';
|
||||
import { createFsCache } from './createFsCache';
|
||||
import { getGlobals } from './globals';
|
||||
@@ -32,6 +32,15 @@ export async function getInternalConfig(
|
||||
const outDir = path.resolve(outBaseDir, `${browser}-mv${manifestVersion}`);
|
||||
const logger = config.logger ?? consola;
|
||||
|
||||
const manifest: UserManifest = await (typeof config.manifest === 'function'
|
||||
? config.manifest({
|
||||
browser,
|
||||
command,
|
||||
manifestVersion,
|
||||
mode,
|
||||
})
|
||||
: config.manifest ?? {});
|
||||
|
||||
const baseConfig: InternalConfigNoUserDirs = {
|
||||
root,
|
||||
outDir,
|
||||
@@ -43,7 +52,7 @@ export async function getInternalConfig(
|
||||
command,
|
||||
logger,
|
||||
vite: config.vite ?? {},
|
||||
manifest: config.manifest ?? {},
|
||||
manifest,
|
||||
imports: config.imports ?? {},
|
||||
runnerConfig: await loadConfig<ExtensionRunnerConfig>({
|
||||
name: 'web-ext',
|
||||
@@ -59,10 +68,12 @@ export async function getInternalConfig(
|
||||
mode,
|
||||
};
|
||||
if (config.configFile !== false) {
|
||||
userConfig = await importTsFile<UserConfig>(
|
||||
root,
|
||||
path.resolve(root, config.configFile ?? 'wxt.config.ts'),
|
||||
);
|
||||
const loaded = await loadConfig<UserConfig>({
|
||||
name: 'wxt',
|
||||
cwd: root,
|
||||
rcFile: false,
|
||||
});
|
||||
userConfig = loaded.config ?? {};
|
||||
}
|
||||
|
||||
// Merge inline and user configs
|
||||
@@ -94,7 +105,7 @@ export async function getInternalConfig(
|
||||
// Customize the default vite config
|
||||
finalConfig.vite.root = root;
|
||||
finalConfig.vite.configFile = false;
|
||||
finalConfig.vite.logLevel = 'silent';
|
||||
finalConfig.vite.logLevel = 'warn';
|
||||
|
||||
finalConfig.vite.build ??= {};
|
||||
finalConfig.vite.build.outDir = outDir;
|
||||
@@ -110,6 +121,7 @@ export async function getInternalConfig(
|
||||
finalConfig.vite.plugins.push(
|
||||
plugins.virtualEntrypoin('content-script', finalConfig),
|
||||
);
|
||||
finalConfig.vite.plugins.push(plugins.devServerGlobals(finalConfig));
|
||||
|
||||
finalConfig.vite.define ??= {};
|
||||
getGlobals(finalConfig).forEach((global) => {
|
||||
|
||||
@@ -39,5 +39,10 @@ export function getGlobals(
|
||||
value: config.browser === 'opera',
|
||||
type: `boolean`,
|
||||
},
|
||||
{
|
||||
name: '__COMMAND__',
|
||||
value: config.command,
|
||||
type: `"build" | "serve"`,
|
||||
},
|
||||
];
|
||||
}
|
||||
|
||||
@@ -1,44 +1,67 @@
|
||||
import { consola } from 'consola';
|
||||
import createJITI from 'jiti';
|
||||
import transform from 'jiti/dist/babel';
|
||||
import { InternalConfig } from '../types';
|
||||
import { createUnimport } from 'unimport';
|
||||
import fs from 'fs-extra';
|
||||
import { resolve } from 'path';
|
||||
import { scanExports } from 'unimport';
|
||||
import transform from 'jiti/dist/babel';
|
||||
import { getUnimportOptions } from './auto-imports';
|
||||
|
||||
export async function importTsFile<T>(root: string, path: string): Promise<T> {
|
||||
const clientImports = await scanExports(
|
||||
resolve(root, 'node_modules/wxt/dist/client/index.js'),
|
||||
/**
|
||||
* Get the value from the default export of a `path`.
|
||||
*
|
||||
* It works by:
|
||||
*
|
||||
* 1. Reading the file text
|
||||
* 2. Stripping all imports from it via regex
|
||||
* 3. Auto-import only the client helper functions
|
||||
*
|
||||
* This prevents resolving imports of imports, speeding things up and preventing "xxx is not
|
||||
* defined" errors.
|
||||
*
|
||||
* Downside is that code cannot be executed outside of the main fucntion for the entrypoint,
|
||||
* otherwise you will see "xxx is not defined" errors for any imports used outside of main function.
|
||||
*/
|
||||
export async function importTsFile<T>(
|
||||
path: string,
|
||||
config: InternalConfig,
|
||||
): Promise<T> {
|
||||
config.logger.debug('Loading file metadata:', path);
|
||||
|
||||
const unimport = createUnimport({
|
||||
...getUnimportOptions(config),
|
||||
// Only allow specific imports, not all from the project
|
||||
imports: [{ name: '*', as: 'browser', from: 'webextension-polyfill' }],
|
||||
dirs: [],
|
||||
});
|
||||
await unimport.init();
|
||||
|
||||
const text = await fs.readFile(path, 'utf-8');
|
||||
const textNoImports = text.replace(/import.*[\n;]/gm, '');
|
||||
const { code } = await unimport.injectImports(textNoImports);
|
||||
config.logger.debug(
|
||||
['Text:', text, 'No imports:', textNoImports, 'Code:', code].join('\n'),
|
||||
);
|
||||
|
||||
const jiti = createJITI(__filename, {
|
||||
cache: false,
|
||||
esmResolve: true,
|
||||
interopDefault: true,
|
||||
|
||||
alias: {
|
||||
'webextension-polyfill': resolve(
|
||||
config.root,
|
||||
'node_modules/wxt/dist/virtual-modules/fake-browser.js',
|
||||
),
|
||||
},
|
||||
transform(opts) {
|
||||
// Remove CSS imports from the source code - Jiti can't handle them.
|
||||
opts.source = opts.source.replace(/^import ['"].*\.css['"];?$/gm, '');
|
||||
opts.source = opts.source.replace(
|
||||
/^import\s+.*\s+from ['"]webextension-polyfill['"];?$/gm,
|
||||
'',
|
||||
);
|
||||
|
||||
// Append any wxt/client functions so babel doesn't complain about undefined variables
|
||||
if (opts.filename === path) {
|
||||
// TODO: Only append import if it isn't already imported
|
||||
const imports =
|
||||
clientImports
|
||||
.map((i) => `import { ${i.name} } from "${i.from}";`)
|
||||
.join('\n') + '\n';
|
||||
opts.source = imports + opts.source;
|
||||
}
|
||||
|
||||
// Call the default babel transformer with our modified source code
|
||||
return transform(opts);
|
||||
if (opts.filename === path) return transform({ ...opts, source: code });
|
||||
else return transform(opts);
|
||||
},
|
||||
});
|
||||
|
||||
try {
|
||||
return await jiti(path);
|
||||
} catch (err) {
|
||||
consola.error(`Failed to import file: ${path}`);
|
||||
config.logger.error(err);
|
||||
throw err;
|
||||
}
|
||||
}
|
||||
|
||||
+51
-24
@@ -29,7 +29,7 @@ export async function writeManifest(
|
||||
await fs.ensureDir(config.outDir);
|
||||
await fs.writeFile(resolve(config.outDir, 'manifest.json'), str, 'utf-8');
|
||||
|
||||
output.unshift({
|
||||
output.publicAssets.unshift({
|
||||
type: 'asset',
|
||||
fileName: 'manifest.json',
|
||||
name: 'manifest',
|
||||
@@ -43,7 +43,7 @@ export async function writeManifest(
|
||||
*/
|
||||
export async function generateMainfest(
|
||||
entrypoints: Entrypoint[],
|
||||
buildOutput: BuildOutput,
|
||||
buildOutput: Omit<BuildOutput, 'manifest'>,
|
||||
config: InternalConfig,
|
||||
): Promise<Manifest.WebExtensionManifest> {
|
||||
const pkg = await getPackageJson(config);
|
||||
@@ -65,6 +65,7 @@ export async function generateMainfest(
|
||||
addEntrypoints(manifest, entrypoints, buildOutput, config);
|
||||
|
||||
if (config.command === 'serve') addDevModeCsp(manifest, config);
|
||||
if (config.command === 'serve') addDevModePermissions(manifest, config);
|
||||
|
||||
return manifest;
|
||||
}
|
||||
@@ -100,7 +101,7 @@ function simplifyVersion(versionName: string): string {
|
||||
function addEntrypoints(
|
||||
manifest: Manifest.WebExtensionManifest,
|
||||
entrypoints: Entrypoint[],
|
||||
buildOutput: BuildOutput,
|
||||
buildOutput: Omit<BuildOutput, 'manifest'>,
|
||||
config: InternalConfig,
|
||||
): void {
|
||||
const entriesByType = entrypoints.reduce<
|
||||
@@ -270,24 +271,23 @@ function addEntrypoints(
|
||||
}
|
||||
|
||||
if (contentScripts?.length) {
|
||||
if (config.command === 'serve') {
|
||||
const permissionsKey =
|
||||
config.manifestVersion === 2 ? 'permissions' : 'host_permissions';
|
||||
const hostPermissions = new Set<string>(manifest[permissionsKey] ?? []);
|
||||
// Don't add content scripts to the manifest in dev mode for MV3 - they're managed and reloaded
|
||||
// at runtime
|
||||
if (config.command === 'serve' && config.manifestVersion === 3) {
|
||||
const hostPermissions = new Set<string>(manifest.host_permissions ?? []);
|
||||
contentScripts.forEach((script) => {
|
||||
script.options.matches.forEach((matchPattern) => {
|
||||
hostPermissions.add(matchPattern);
|
||||
});
|
||||
});
|
||||
manifest[permissionsKey] = Array.from(hostPermissions).sort();
|
||||
hostPermissions.forEach((permission) =>
|
||||
addHostPermission(manifest, permission),
|
||||
);
|
||||
} else {
|
||||
const hashToEntrypointsMap = contentScripts.reduce((map, script) => {
|
||||
const hash = JSON.stringify(script.options);
|
||||
if (!map.has(hash)) {
|
||||
map.set(hash, [script]);
|
||||
} else {
|
||||
map.get(hash)?.push(script);
|
||||
}
|
||||
if (map.has(hash)) map.get(hash)?.push(script);
|
||||
else map.set(hash, [script]);
|
||||
return map;
|
||||
}, new Map<string, ContentScriptEntrypoint[]>());
|
||||
|
||||
@@ -316,13 +316,9 @@ function addDevModeCsp(
|
||||
const allowedCsp = config.server?.origin ?? 'http://localhost:*';
|
||||
|
||||
if (manifest.manifest_version === 3) {
|
||||
manifest.host_permissions ??= [];
|
||||
if (!manifest.host_permissions.includes(permission))
|
||||
manifest.host_permissions.push(permission);
|
||||
addHostPermission(manifest, permission);
|
||||
} else {
|
||||
manifest.permissions ??= [];
|
||||
if (!manifest.permissions.includes(permission))
|
||||
manifest.permissions.push(permission);
|
||||
addPermission(manifest, permission);
|
||||
}
|
||||
|
||||
const csp = new ContentSecurityPolicy(
|
||||
@@ -345,20 +341,33 @@ function addDevModeCsp(
|
||||
}
|
||||
}
|
||||
|
||||
function addDevModePermissions(
|
||||
manifest: Manifest.WebExtensionManifest,
|
||||
config: InternalConfig,
|
||||
) {
|
||||
// For reloading the page
|
||||
addPermission(manifest, 'tabs');
|
||||
|
||||
// For registering content scripts
|
||||
if (config.manifestVersion === 3) addPermission(manifest, 'scripting');
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the bundle paths to CSS files associated with a list of content scripts, or undefined if
|
||||
* there is no associated CSS.
|
||||
*/
|
||||
function getContentScriptCssFiles(
|
||||
export function getContentScriptCssFiles(
|
||||
contentScripts: ContentScriptEntrypoint[],
|
||||
buildOutput: BuildOutput,
|
||||
buildOutput: Omit<BuildOutput, 'manifest'>,
|
||||
): string[] | undefined {
|
||||
const css: string[] = [];
|
||||
|
||||
const allChunks = buildOutput.steps.flatMap((step) => step.chunks);
|
||||
|
||||
contentScripts.forEach((script) => {
|
||||
const cssRegex = new RegExp(`^assets/${script.name}-[a-f0-9]{8}.css$`);
|
||||
const relatedCss = buildOutput.find((chunk) =>
|
||||
chunk.fileName.match(cssRegex),
|
||||
// TODO: optimize and remove loop with a map
|
||||
const relatedCss = allChunks.find(
|
||||
(chunk) => chunk.fileName === `assets/${script.name}.css`,
|
||||
);
|
||||
if (relatedCss) css.push(relatedCss.fileName);
|
||||
});
|
||||
@@ -366,3 +375,21 @@ function getContentScriptCssFiles(
|
||||
if (css.length > 0) return css;
|
||||
return undefined;
|
||||
}
|
||||
|
||||
function addPermission(
|
||||
manifest: Manifest.WebExtensionManifest,
|
||||
permission: string,
|
||||
): void {
|
||||
manifest.permissions ??= [];
|
||||
if (manifest.permissions.includes(permission)) return;
|
||||
manifest.permissions.push(permission);
|
||||
}
|
||||
|
||||
function addHostPermission(
|
||||
manifest: Manifest.WebExtensionManifest,
|
||||
hostPermission: string,
|
||||
): void {
|
||||
manifest.host_permissions ??= [];
|
||||
if (manifest.host_permissions.includes(hostPermission)) return;
|
||||
manifest.host_permissions.push(hostPermission);
|
||||
}
|
||||
|
||||
@@ -11,6 +11,21 @@ export function devHtmlPrerender(config: InternalConfig): vite.Plugin {
|
||||
return {
|
||||
apply: 'build',
|
||||
name: 'wxt:dev-html-prerender',
|
||||
config(userConfig) {
|
||||
return vite.mergeConfig(
|
||||
{
|
||||
resolve: {
|
||||
alias: {
|
||||
'@wxt/reload-html': resolve(
|
||||
config.root,
|
||||
'node_modules/wxt/dist/virtual-modules/reload-html.js',
|
||||
),
|
||||
},
|
||||
},
|
||||
},
|
||||
userConfig,
|
||||
);
|
||||
},
|
||||
async transform(html, id) {
|
||||
const server = config.server;
|
||||
if (config.command !== 'serve' || server == null || !id.endsWith('.html'))
|
||||
@@ -43,6 +58,12 @@ export function devHtmlPrerender(config: InternalConfig): vite.Plugin {
|
||||
pointToDevServer('script[type=module]', 'src');
|
||||
pointToDevServer('link[rel=stylesheet]', 'href');
|
||||
|
||||
// Add a script to add page reloading
|
||||
const reloader = document.createElement('script');
|
||||
reloader.src = '@wxt/reload-html';
|
||||
reloader.type = 'module';
|
||||
document.head.appendChild(reloader);
|
||||
|
||||
const newHtml = document.toString();
|
||||
config.logger.debug('Transformed ' + id);
|
||||
config.logger.debug('Old HTML:\n' + html);
|
||||
|
||||
@@ -0,0 +1,24 @@
|
||||
import { Plugin } from 'vite';
|
||||
import { InternalConfig } from '../types';
|
||||
|
||||
/**
|
||||
* Defines global constants about the dev server. Helps scripts connect to the server's web socket.
|
||||
*/
|
||||
export function devServerGlobals(internalConfig: InternalConfig): Plugin {
|
||||
return {
|
||||
name: 'wxt:dev-server-globals',
|
||||
config(config) {
|
||||
if (internalConfig.server == null || internalConfig.command == 'build')
|
||||
return;
|
||||
|
||||
config.define ??= {};
|
||||
config.define.__DEV_SERVER_PROTOCOL__ = JSON.stringify('ws:');
|
||||
config.define.__DEV_SERVER_HOSTNAME__ = JSON.stringify(
|
||||
internalConfig.server.hostname,
|
||||
);
|
||||
config.define.__DEV_SERVER_PORT__ = JSON.stringify(
|
||||
internalConfig.server.port,
|
||||
);
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -1,5 +1,6 @@
|
||||
export * from './download';
|
||||
export * from './unimport';
|
||||
export * from './multipageMove';
|
||||
export * from './devHtmlPrerender';
|
||||
export * from './devServerGlobals';
|
||||
export * from './download';
|
||||
export * from './multipageMove';
|
||||
export * from './unimport';
|
||||
export * from './virtualEntrypoint';
|
||||
|
||||
@@ -53,7 +53,7 @@ export function multipageMove(
|
||||
const oldAbsPath = resolve(config.outDir, oldBundlePath);
|
||||
const newAbsPath = resolve(config.outDir, newBundlePath);
|
||||
await ensureDir(dirname(newAbsPath));
|
||||
await fs.move(oldAbsPath, newAbsPath);
|
||||
await fs.move(oldAbsPath, newAbsPath, { overwrite: true });
|
||||
|
||||
const renamedChunk = {
|
||||
...bundle[oldBundlePath],
|
||||
|
||||
@@ -2,6 +2,16 @@ import { createUnimport } from 'unimport';
|
||||
import { InternalConfig } from '../types';
|
||||
import { getUnimportOptions } from '../utils/auto-imports';
|
||||
import { Plugin } from 'vite';
|
||||
import { extname } from 'path';
|
||||
|
||||
const ENABLED_EXTENSIONS: Record<string, boolean | undefined> = {
|
||||
'.js': true,
|
||||
'.jsx': true,
|
||||
'.ts': true,
|
||||
'.tsx': true,
|
||||
'.vue': true,
|
||||
'.svelte': true,
|
||||
};
|
||||
|
||||
/**
|
||||
* Inject any global imports defined by unimport
|
||||
@@ -16,7 +26,8 @@ export function unimport(config: InternalConfig): Plugin {
|
||||
await unimport.scanImportsFromDir(undefined, { cwd: config.srcDir });
|
||||
},
|
||||
async transform(code, id) {
|
||||
return unimport.injectImports(code, id);
|
||||
const ext = extname(id);
|
||||
if (ENABLED_EXTENSIONS[ext]) return unimport.injectImports(code, id);
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
@@ -29,10 +29,13 @@ export function virtualEntrypoin(
|
||||
|
||||
const inputPath = id.replace(resolvedVirtualId, '');
|
||||
const template = await fs.readFile(
|
||||
resolve(config.root, `node_modules/wxt/templates/virtual-${type}.ts`),
|
||||
resolve(
|
||||
config.root,
|
||||
`node_modules/wxt/dist/virtual-modules/${type}-entrypoint.js`,
|
||||
),
|
||||
'utf-8',
|
||||
);
|
||||
return template.replaceAll('{{moduleId}}', inputPath);
|
||||
return template.replace(`virtual:user-${type}`, inputPath);
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
+83
-83
@@ -1,21 +1,19 @@
|
||||
import {
|
||||
BuildOutput,
|
||||
WxtDevServer,
|
||||
InlineConfig,
|
||||
InternalConfig,
|
||||
} from './core/types';
|
||||
import { BuildOutput, WxtDevServer, InlineConfig } from './core/types';
|
||||
import { getInternalConfig } from './core/utils/getInternalConfig';
|
||||
import { findEntrypoints } from './core/build/findEntrypoints';
|
||||
import { buildEntrypoints } from './core/build/buildEntrypoints';
|
||||
import { generateMainfest, writeManifest } from './core/utils/manifest';
|
||||
import { printBuildSummary } from './core/log/printBuildSummary';
|
||||
import fs from 'fs-extra';
|
||||
import { generateTypesDir } from './core/build/generateTypesDir';
|
||||
import pc from 'picocolors';
|
||||
import * as vite from 'vite';
|
||||
import { findOpenPort } from './core/utils/findOpenPort';
|
||||
import { formatDuration } from './core/utils/formatDuration';
|
||||
import { createWebExtRunner } from './core/runners/createWebExtRunner';
|
||||
import { detectDevChanges } from './core/utils/detectDevChanges';
|
||||
import { Mutex } from 'async-mutex';
|
||||
import { consola } from 'consola';
|
||||
import { relative } from 'node:path';
|
||||
import { getEntrypointOutputFile } from './core/utils/entrypoints';
|
||||
import { buildInternal, rebuild } from './core/build';
|
||||
import {
|
||||
getServerInfo,
|
||||
reloadContentScripts,
|
||||
reloadHtmlPages,
|
||||
setupServer,
|
||||
} from './core/server';
|
||||
|
||||
export { version } from '../package.json';
|
||||
export * from './core/types/external';
|
||||
@@ -33,77 +31,79 @@ export async function build(config: InlineConfig): Promise<BuildOutput> {
|
||||
export async function createServer(
|
||||
config?: InlineConfig,
|
||||
): Promise<WxtDevServer> {
|
||||
const port = await findOpenPort(3000, 3010);
|
||||
const hostname = 'localhost';
|
||||
const origin = `http://${hostname}:${port}`;
|
||||
const serverConfig: vite.InlineConfig = {
|
||||
server: {
|
||||
origin,
|
||||
},
|
||||
const serverInfo = await getServerInfo();
|
||||
|
||||
const getLatestInternalConfig = () => {
|
||||
const viteConfig: vite.InlineConfig = vite.mergeConfig(
|
||||
serverInfo.viteServerConfig,
|
||||
config?.vite ?? {},
|
||||
);
|
||||
return getInternalConfig({ ...config, vite: viteConfig }, 'serve');
|
||||
};
|
||||
const internalConfig = await getInternalConfig(
|
||||
vite.mergeConfig(serverConfig, config ?? {}),
|
||||
'serve',
|
||||
);
|
||||
const runner = createWebExtRunner();
|
||||
|
||||
const viteServer = await vite.createServer(internalConfig.vite);
|
||||
const server: WxtDevServer = {
|
||||
...viteServer,
|
||||
async listen(port, isRestart) {
|
||||
const res = await viteServer.listen(port, isRestart);
|
||||
|
||||
if (!isRestart) {
|
||||
internalConfig.logger.success(`Started dev server @ ${origin}`);
|
||||
|
||||
internalConfig.logger.info('Opening browser...');
|
||||
await runner.openBrowser(internalConfig);
|
||||
internalConfig.logger.success('Opened!');
|
||||
}
|
||||
|
||||
return res;
|
||||
},
|
||||
logger: internalConfig.logger,
|
||||
port,
|
||||
hostname,
|
||||
origin,
|
||||
};
|
||||
internalConfig.logger.info('Created dev server');
|
||||
|
||||
let internalConfig = await getLatestInternalConfig();
|
||||
const server = await setupServer(serverInfo, internalConfig);
|
||||
internalConfig.server = server;
|
||||
await buildInternal(internalConfig);
|
||||
|
||||
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) => {
|
||||
if (path.startsWith(internalConfig.outBaseDir)) return;
|
||||
changeQueue.push([event, path]);
|
||||
|
||||
await fileChangedMutex.runExclusive(async () => {
|
||||
const fileChanges = changeQueue.splice(0, changeQueue.length);
|
||||
const changes = detectDevChanges(fileChanges, server.currentOutput);
|
||||
|
||||
if (changes.type === 'no-change') return;
|
||||
|
||||
// Log the entrypoints that were effected
|
||||
consola.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 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);
|
||||
|
||||
// Build
|
||||
const entrypoints = await findEntrypoints(config);
|
||||
await generateTypesDir(entrypoints, config);
|
||||
const output = await buildEntrypoints(entrypoints, config);
|
||||
|
||||
// Write manifest
|
||||
const manifest = await generateMainfest(entrypoints, output, config);
|
||||
await writeManifest(manifest, output, config);
|
||||
|
||||
// Post-build
|
||||
config.logger.success(
|
||||
`Built extension in ${formatDuration(Date.now() - startTime)}`,
|
||||
);
|
||||
await printBuildSummary(output, config);
|
||||
|
||||
return output;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,221 @@
|
||||
/**
|
||||
* SHOULD ONLY BE IMPORTED IN TESTS.
|
||||
*/
|
||||
import { resolve } from 'path';
|
||||
import {
|
||||
BackgroundEntrypoint,
|
||||
ContentScriptEntrypoint,
|
||||
GenericEntrypoint,
|
||||
OptionsEntrypoint,
|
||||
PopupEntrypoint,
|
||||
} from '..';
|
||||
import { faker } from '@faker-js/faker';
|
||||
import merge from 'lodash.merge';
|
||||
import { Rollup } from 'vite';
|
||||
import { Manifest } from 'webextension-polyfill';
|
||||
import { FsCache, InternalConfig, WxtDevServer } from '../core/types';
|
||||
import { mock } from 'vitest-mock-extended';
|
||||
|
||||
faker.seed(__TEST_SEED__);
|
||||
|
||||
type DeepPartial<T> = { [key in keyof T]+?: Partial<T[key]> };
|
||||
function fakeObjectCreator<T>(base: () => T) {
|
||||
return (overrides?: DeepPartial<T>): T => merge(base(), overrides);
|
||||
}
|
||||
|
||||
export function fakeFileName(): string {
|
||||
return faker.string.alphanumeric() + '.' + faker.string.alpha({ length: 3 });
|
||||
}
|
||||
|
||||
export function fakeFile(root = process.cwd()): string {
|
||||
return resolve(root, fakeFileName());
|
||||
}
|
||||
|
||||
export function fakeDir(root = process.cwd()): string {
|
||||
return resolve(root, faker.string.alphanumeric());
|
||||
}
|
||||
|
||||
export const fakeContentScriptEntrypoint =
|
||||
fakeObjectCreator<ContentScriptEntrypoint>(() => ({
|
||||
type: 'content-script',
|
||||
inputPath: fakeFile('src'),
|
||||
name: faker.string.alpha(),
|
||||
options: {
|
||||
matches: [],
|
||||
matchAboutBlank: faker.helpers.arrayElement([true, false, undefined]),
|
||||
matchOriginAsFallback: faker.helpers.arrayElement([
|
||||
true,
|
||||
false,
|
||||
undefined,
|
||||
]),
|
||||
runAt: faker.helpers.arrayElement([
|
||||
'document_start',
|
||||
'document_end',
|
||||
'document_idle',
|
||||
undefined,
|
||||
]),
|
||||
},
|
||||
outputDir: fakeDir('.output'),
|
||||
}));
|
||||
|
||||
export const fakeBackgroundEntrypoint = fakeObjectCreator<BackgroundEntrypoint>(
|
||||
() => ({
|
||||
type: 'background',
|
||||
inputPath: fakeFile('src'),
|
||||
name: faker.string.alpha(),
|
||||
options: {
|
||||
persistent: faker.helpers.arrayElement([true, false, undefined]),
|
||||
type: faker.helpers.maybe(() => 'module'),
|
||||
},
|
||||
outputDir: fakeDir('.output'),
|
||||
}),
|
||||
);
|
||||
|
||||
export const fakeUnlistedScriptEntrypoint =
|
||||
fakeObjectCreator<GenericEntrypoint>(() => ({
|
||||
type: 'unlisted-script',
|
||||
inputPath: fakeFile('src'),
|
||||
name: faker.string.alpha(),
|
||||
outputDir: fakeDir('.output'),
|
||||
}));
|
||||
|
||||
export const fakeOptionsEntrypoint = fakeObjectCreator<OptionsEntrypoint>(
|
||||
() => ({
|
||||
type: 'options',
|
||||
inputPath: fakeFile('src'),
|
||||
name: faker.string.alpha(),
|
||||
outputDir: fakeDir('.output'),
|
||||
options: {
|
||||
browserStyle: faker.helpers.arrayElement([true, false, undefined]),
|
||||
chromeStyle: faker.helpers.arrayElement([true, false, undefined]),
|
||||
openInTab: faker.helpers.arrayElement([true, false, undefined]),
|
||||
},
|
||||
}),
|
||||
);
|
||||
|
||||
export const fakePopupEntrypoint = fakeObjectCreator<PopupEntrypoint>(() => ({
|
||||
type: 'popup',
|
||||
inputPath: fakeFile('src'),
|
||||
name: faker.string.alpha(),
|
||||
outputDir: fakeDir('.output'),
|
||||
options: {
|
||||
defaultTitle: faker.helpers.arrayElement([
|
||||
faker.person.fullName(),
|
||||
undefined,
|
||||
]),
|
||||
defaultIcon: faker.helpers.arrayElement([
|
||||
{
|
||||
'16': 'icon/16.png',
|
||||
'24': 'icon/24.png',
|
||||
'64': 'icon/64.png',
|
||||
},
|
||||
]),
|
||||
mv2Key: faker.helpers.arrayElement([
|
||||
'browser_action',
|
||||
'page_action',
|
||||
undefined,
|
||||
]),
|
||||
},
|
||||
}));
|
||||
|
||||
export const fakeGenericEntrypoint = fakeObjectCreator<GenericEntrypoint>(
|
||||
() => ({
|
||||
type: faker.helpers.arrayElement([
|
||||
'sandbox',
|
||||
'bookmarks',
|
||||
'history',
|
||||
'newtab',
|
||||
'sidepanel',
|
||||
'devtools',
|
||||
'unlisted-page',
|
||||
'unlisted-script',
|
||||
]),
|
||||
inputPath: fakeFile('src'),
|
||||
name: faker.string.alpha(),
|
||||
outputDir: fakeDir('.output'),
|
||||
}),
|
||||
);
|
||||
|
||||
export const fakeRollupOutputChunk = fakeObjectCreator<Rollup.OutputChunk>(
|
||||
() => ({
|
||||
type: 'chunk',
|
||||
code: '',
|
||||
dynamicImports: [],
|
||||
exports: [],
|
||||
facadeModuleId: faker.helpers.arrayElement([null, fakeFile()]),
|
||||
fileName: faker.string.alphanumeric(),
|
||||
implicitlyLoadedBefore: [],
|
||||
importedBindings: {},
|
||||
imports: [],
|
||||
isDynamicEntry: faker.datatype.boolean(),
|
||||
isEntry: faker.datatype.boolean(),
|
||||
isImplicitEntry: faker.datatype.boolean(),
|
||||
map: null,
|
||||
moduleIds: [],
|
||||
modules: {},
|
||||
name: faker.string.alpha(),
|
||||
referencedFiles: [],
|
||||
viteMetadata: {
|
||||
importedAssets: new Set(),
|
||||
importedCss: new Set(),
|
||||
},
|
||||
}),
|
||||
);
|
||||
|
||||
export const fakeRollupOutputAsset = fakeObjectCreator<Rollup.OutputAsset>(
|
||||
() => ({
|
||||
type: 'asset',
|
||||
fileName: fakeFileName(),
|
||||
name: faker.string.alpha(),
|
||||
needsCodeReference: faker.datatype.boolean(),
|
||||
source: '',
|
||||
}),
|
||||
);
|
||||
|
||||
export function fakeRollupOutput(): Rollup.OutputAsset | Rollup.OutputChunk {
|
||||
return faker.helpers.arrayElement([
|
||||
fakeRollupOutputAsset(),
|
||||
fakeRollupOutputChunk(),
|
||||
]);
|
||||
}
|
||||
|
||||
export const fakeManifest = fakeObjectCreator<Manifest.WebExtensionManifest>(
|
||||
() => ({
|
||||
manifest_version: faker.helpers.arrayElement([2, 3]),
|
||||
name: faker.string.alphanumeric(),
|
||||
version: `${faker.number.int()}.${faker.number.int()}.${faker.number.int()}`,
|
||||
}),
|
||||
);
|
||||
|
||||
export function fakeArray<T>(createItem: () => T, count = 3): T[] {
|
||||
const array: T[] = [];
|
||||
for (let i = 0; i < count; i++) {
|
||||
array.push(createItem());
|
||||
}
|
||||
return array;
|
||||
}
|
||||
|
||||
export const fakeInternalConfig = fakeObjectCreator<InternalConfig>(() => ({
|
||||
browser: faker.helpers.arrayElement(['chrome', 'firefox']),
|
||||
command: faker.helpers.arrayElement(['build', 'serve']),
|
||||
entrypointsDir: fakeDir(),
|
||||
fsCache: mock<FsCache>(),
|
||||
imports: {},
|
||||
logger: mock(),
|
||||
manifest: fakeManifest(),
|
||||
manifestVersion: faker.helpers.arrayElement([2, 3]),
|
||||
mode: faker.helpers.arrayElement(['development', 'production']),
|
||||
outBaseDir: fakeDir(),
|
||||
outDir: fakeDir(),
|
||||
publicDir: fakeDir(),
|
||||
root: fakeDir(),
|
||||
runnerConfig: {
|
||||
config: {},
|
||||
},
|
||||
srcDir: fakeDir(),
|
||||
storeIds: {},
|
||||
typesDir: fakeDir(),
|
||||
vite: {},
|
||||
wxtDir: fakeDir(),
|
||||
server: mock<WxtDevServer>(),
|
||||
}));
|
||||
Vendored
-11
@@ -1,11 +0,0 @@
|
||||
// Types required to make templates happy.
|
||||
|
||||
declare module '*?raw' {
|
||||
const content: any;
|
||||
export default content;
|
||||
}
|
||||
|
||||
declare module '{{moduleId}}' {
|
||||
const variable: any;
|
||||
export default variable;
|
||||
}
|
||||
@@ -1,13 +0,0 @@
|
||||
import definition from '{{moduleId}}';
|
||||
|
||||
try {
|
||||
const res = definition.main();
|
||||
if (res instanceof Promise) {
|
||||
console.warn(
|
||||
"The background's main() function return a promise, but it must be synchonous",
|
||||
);
|
||||
}
|
||||
} catch (err) {
|
||||
console.error('The background script crashed on startup!');
|
||||
throw err;
|
||||
}
|
||||
@@ -1,9 +0,0 @@
|
||||
import definition from '{{moduleId}}';
|
||||
|
||||
(async () => {
|
||||
try {
|
||||
await definition.main();
|
||||
} catch (err) {
|
||||
console.error('The content script crashed on startup!\n\n', err);
|
||||
}
|
||||
})();
|
||||
@@ -1,6 +1,21 @@
|
||||
import { defineWorkspace } from 'vitest/config';
|
||||
import fs from 'fs-extra';
|
||||
import pc from 'picocolors';
|
||||
import { Plugin } from 'vite';
|
||||
|
||||
const seed = Math.round(Math.random() * Number.MAX_SAFE_INTEGER);
|
||||
console.info('Test seed: ' + pc.cyan(seed));
|
||||
|
||||
// config.define doesn't work with workspaces, so we have to set it inisde a plugin
|
||||
const testSeed = (): Plugin => ({
|
||||
name: 'test-seed',
|
||||
config(config) {
|
||||
config.define ??= {};
|
||||
config.define.__TEST_SEED__ = JSON.stringify(seed);
|
||||
},
|
||||
});
|
||||
|
||||
// Clear e2e test projects
|
||||
await fs.rm('e2e/project', { recursive: true, force: true });
|
||||
|
||||
export default defineWorkspace([
|
||||
@@ -11,6 +26,7 @@ export default defineWorkspace([
|
||||
mockReset: true,
|
||||
restoreMocks: true,
|
||||
},
|
||||
plugins: [testSeed()],
|
||||
},
|
||||
{
|
||||
test: {
|
||||
@@ -18,5 +34,6 @@ export default defineWorkspace([
|
||||
dir: 'e2e',
|
||||
singleThread: true,
|
||||
},
|
||||
plugins: [testSeed()],
|
||||
},
|
||||
]);
|
||||
|
||||
Reference in New Issue
Block a user