Compare commits
58 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| a0e9733335 | |||
| 1045092ab5 | |||
| ebe1f9da7e | |||
| acc4cdec07 | |||
| 8570ce29b0 | |||
| f7cce3e269 | |||
| 315912ebf3 | |||
| 574c3bd90a | |||
| 8dc8fa6f51 | |||
| 1e841ebad7 | |||
| 925e97d4fc | |||
| 859d654611 | |||
| 466ae8a33c | |||
| d1ab2d923d | |||
| 718b063ed7 | |||
| 87a96d4661 | |||
| d8a86e7633 | |||
| c3eaef6fb4 | |||
| d1a956342d | |||
| 0fdac0d4e4 | |||
| 7965ab0592 | |||
| 54d10af1fd | |||
| 7dbe18ba0c | |||
| d4f78b623e | |||
| 7d6caad9b5 | |||
| 0b352f6eff | |||
| 885f8f0b76 | |||
| eae835fa80 | |||
| 782a5b85f1 | |||
| 961cfa5f2a | |||
| ada0c86877 | |||
| 13151509b6 | |||
| b7bdb11a15 | |||
| ab679ba413 | |||
| f69b594401 | |||
| be3af14f9d | |||
| 3679bc772e | |||
| 9da43b6b75 | |||
| 008f5a66c9 | |||
| cffacffe34 | |||
| 3bd7aea9ee | |||
| 4b26d872ec | |||
| c10d09fbdb | |||
| 9698f2fdd9 | |||
| 299b0add80 | |||
| ec3d3196a9 | |||
| 13be7c5bfd | |||
| 575240aaf1 | |||
| b124c82ed4 | |||
| 6c5a1b0d2e | |||
| eb93fa4535 | |||
| 5bd36e90bf | |||
| 172d37193e | |||
| d92d5a4892 | |||
| 40c6c19802 | |||
| 653fccc8eb | |||
| 95657939a8 | |||
| a578dbf633 |
@@ -27,6 +27,7 @@ jobs:
|
||||
github.event.pull_request.user.login != 'aklinker1' &&
|
||||
github.event.pull_request.user.login != 'Timeraa' &&
|
||||
github.event.pull_request.user.login != 'PatrykKuniczak' &&
|
||||
github.event.pull_request.user.login != 'nishu-murmu' &&
|
||||
github.event.pull_request.user.login != 'dependabot[bot]' &&
|
||||
github.event.pull_request.user.login != 'copilot-swe-agent[bot]'
|
||||
uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0
|
||||
|
||||
@@ -20,6 +20,13 @@ on:
|
||||
- unocss
|
||||
- webextension-polyfill
|
||||
- wxt
|
||||
bump:
|
||||
description: Blank (auto), a version (1.4.1), or major/minor/patch
|
||||
type: string
|
||||
dryRun:
|
||||
description: Do a dry-run and don't publish anything
|
||||
type: boolean
|
||||
default: false
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
@@ -29,15 +36,20 @@ jobs:
|
||||
name: Validate
|
||||
uses: './.github/workflows/validate.yml'
|
||||
secrets: inherit
|
||||
if: ${{ inputs.dryRun != true }}
|
||||
|
||||
publish:
|
||||
name: Publish
|
||||
name: Publish ${{ case(inputs.dryRun, ' (dry-run)', '') }}
|
||||
runs-on: ubuntu-24.04
|
||||
permissions:
|
||||
contents: write # Push version changes
|
||||
id-token: write # OIDC for NPM publishing
|
||||
needs:
|
||||
- validate
|
||||
# Allow dry runs to skip validation but still run this job
|
||||
if: |
|
||||
always() &&
|
||||
(needs.validate.result == 'success' || needs.validate.result == 'skipped')
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7.0.0
|
||||
@@ -52,22 +64,42 @@ jobs:
|
||||
run: |
|
||||
git config user.name 'github-actions[bot]'
|
||||
git config user.email 'github-actions[bot]@users.noreply.github.com'
|
||||
git config --global push.followTags true
|
||||
|
||||
- name: Bump and Tag
|
||||
run: |
|
||||
bun run scripts/bump-package-version.ts ${{ inputs.package }}
|
||||
git push
|
||||
git push --tags
|
||||
- name: Upgrade NPM for Provence
|
||||
run: sudo npm i -g npm@latest
|
||||
|
||||
- name: Publish to NPM
|
||||
working-directory: packages/${{ inputs.package }}
|
||||
run: |
|
||||
bun pm pack
|
||||
sudo npm i -g npm@latest
|
||||
npm publish *.tgz
|
||||
|
||||
- name: Create GitHub release
|
||||
run: bun run scripts/create-github-release.ts ${{ inputs.package }}
|
||||
env:
|
||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
- name: Bump and Release
|
||||
uses: aklinker1/zero-changelog/actions/release@b6fcca17cebfc45f996b80fe5926da924d8441f8 # 0.2.1
|
||||
with:
|
||||
bump: ${{ inputs.bump }}
|
||||
path: packages/${{ inputs.package }}
|
||||
# Include documentation updates in WXT's releases
|
||||
additionalDirs: |-
|
||||
${{ case(
|
||||
inputs.package == 'wxt', 'docs',
|
||||
''
|
||||
) }}
|
||||
# Use package name in commit message
|
||||
commitTemplate: |-
|
||||
${{ case(
|
||||
inputs.package == 'wxt', 'chore(release): wxt v{{version}}',
|
||||
'chore(release): @wxt-dev/{{dirname}} v{{version}}'
|
||||
) }}
|
||||
# Use package name in release name
|
||||
releaseNameTemplate: |-
|
||||
${{ case(
|
||||
inputs.package == 'wxt', 'wxt v{{version}}',
|
||||
'@wxt-dev/{{dirname}} v{{version}}'
|
||||
) }}
|
||||
# Update lockfile with new versions since it includes the package versions
|
||||
preCommitCommands: |-
|
||||
bun i
|
||||
publishCommands: |-
|
||||
bun pm pack
|
||||
npm publish *.tgz
|
||||
dryRun: ${{ inputs.dryRun }}
|
||||
dryRunPublishCommands: |-
|
||||
bun pm pack
|
||||
npm publish *.tgz --dry-run
|
||||
githubToken: ${{ secrets.GITHUB_TOKEN }}
|
||||
latestRelease: ${{ inputs.package == 'wxt' }}
|
||||
|
||||
@@ -1,44 +0,0 @@
|
||||
name: 🔄 Sync Releases
|
||||
on:
|
||||
workflow_dispatch:
|
||||
inputs:
|
||||
package:
|
||||
description: Package to sync
|
||||
default: wxt
|
||||
type: choice
|
||||
options:
|
||||
- analytics
|
||||
- auto-icons
|
||||
- i18n
|
||||
- is-background
|
||||
- module-react
|
||||
- module-solid
|
||||
- module-svelte
|
||||
- module-vue
|
||||
- runner
|
||||
- storage
|
||||
- webextension-polyfill
|
||||
- wxt
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
jobs:
|
||||
sync:
|
||||
name: Sync Releases
|
||||
runs-on: ubuntu-22.04
|
||||
permissions:
|
||||
contents: write
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7.0.0
|
||||
|
||||
- name: Setup
|
||||
uses: ./.github/actions/setup
|
||||
with:
|
||||
installArgs: --ignore-scripts
|
||||
|
||||
- name: Sync Releases
|
||||
run: bun run scripts/sync-releases.ts ${{ inputs.package }}
|
||||
env:
|
||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
@@ -2,7 +2,12 @@ name: 📼 VHS
|
||||
on:
|
||||
push:
|
||||
paths:
|
||||
- 'docs/tapes/*.tape'
|
||||
- docs/tapes/*.tape
|
||||
- .github/workflows/vhs.yml
|
||||
pull_request:
|
||||
paths:
|
||||
- docs/tapes/*.tape
|
||||
- .github/workflows/vhs.yml
|
||||
workflow_dispatch:
|
||||
|
||||
permissions:
|
||||
@@ -18,6 +23,8 @@ jobs:
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7.0.0
|
||||
with:
|
||||
ssh-key: ${{ secrets.DEPLOY_KEY }}
|
||||
|
||||
- name: Setup
|
||||
uses: ./.github/actions/setup
|
||||
|
||||
@@ -53,7 +53,6 @@ Or see the [installation guide](https://wxt.dev/guide/installation.html) to get
|
||||
- 📦 [Module system](https://wxt.dev/guide/essentials/wxt-modules.html#overview) for reusing code between extensions
|
||||
- 🖍️ Quickly bootstrap a new project
|
||||
- 📏 Bundle analysis
|
||||
- ⬇️ Download and bundle remote URL imports
|
||||
|
||||
## Sponsors
|
||||
|
||||
|
||||
@@ -19,6 +19,7 @@ words:
|
||||
- automount
|
||||
- avenir
|
||||
- bidi
|
||||
- blocklists
|
||||
- buildc
|
||||
- bunx
|
||||
- cachable
|
||||
@@ -29,6 +30,7 @@ words:
|
||||
- comctx
|
||||
- confbox
|
||||
- configfile
|
||||
- consola
|
||||
- consolas
|
||||
- Cpath
|
||||
- crbug
|
||||
@@ -89,6 +91,7 @@ words:
|
||||
- pbbf
|
||||
- personaltoolbar
|
||||
- portaling
|
||||
- posthog
|
||||
- prebundled
|
||||
- prefs
|
||||
- proxified
|
||||
@@ -103,8 +106,10 @@ words:
|
||||
- solidjs
|
||||
- styl
|
||||
- subdependency
|
||||
- superlock
|
||||
- tabstrip
|
||||
- teleporting
|
||||
- topcli
|
||||
- treemap
|
||||
- triaging
|
||||
- umami
|
||||
|
||||
@@ -243,7 +243,6 @@ export default defineConfig({
|
||||
menuItem('WXT Modules', 'wxt-modules.md'),
|
||||
menuItem('Frontend Frameworks', 'frontend-frameworks.md'),
|
||||
menuItem('ES Modules', 'es-modules.md'),
|
||||
menuItem('Remote Code', 'remote-code.md'),
|
||||
menuItem('Unit Testing', 'unit-testing.md'),
|
||||
menuItem('E2E Testing', 'e2e-testing.md'),
|
||||
menuItem('Publishing', 'publishing.md'),
|
||||
|
||||
@@ -81,3 +81,7 @@ body {
|
||||
.item {
|
||||
z-index: 1;
|
||||
}
|
||||
|
||||
.VPSidebar .curtain {
|
||||
z-index: 2;
|
||||
}
|
||||
|
||||
@@ -401,6 +401,7 @@
|
||||
- # Teams Chat Exporter
|
||||
chromeId: jmghclbfbbapimhbgnpffbimphlpolnm
|
||||
firefoxSlug: teams-chat-exporter
|
||||
edgeId: phlomfiieaggnbfpacmjmidcjdlaiplp
|
||||
|
||||
- # Lofi BGM Player - Free lofi focus music for work & study
|
||||
chromeId: jdcppdokgfbnhiacbeplahgnciahnhck
|
||||
@@ -518,3 +519,15 @@
|
||||
|
||||
- # Leetcode Enhancer
|
||||
chromeId: cpoclfijojgjiafnlgnhjalkaiabcjch
|
||||
|
||||
- # Adaptive Tab Bar Colour
|
||||
firefoxSlug: adaptive-tab-bar-colour
|
||||
|
||||
- #ArcPort - Tab Checkpoint
|
||||
chromeId: kajmnfhpmkimleehomeioondgfcjjnbp
|
||||
|
||||
- #ArcPort - Tab Rebrand
|
||||
chromeId: pgmohcikgaeddapienpncpbiklbmfkgp
|
||||
|
||||
- #MindSnap
|
||||
chromeId: mdcpckfcphpicfpiopfcpeambjknjabl
|
||||
|
||||
Binary file not shown.
|
Before Width: | Height: | Size: 132 KiB After Width: | Height: | Size: 138 KiB |
@@ -43,7 +43,7 @@ ESLint doesn't know about the auto-imported variables unless they are explicitly
|
||||
|
||||
:::code-group
|
||||
|
||||
```ts [ESLint 9]
|
||||
```ts [ESLint >=9]
|
||||
export default defineConfig({
|
||||
imports: {
|
||||
eslintrc: {
|
||||
@@ -53,7 +53,7 @@ export default defineConfig({
|
||||
});
|
||||
```
|
||||
|
||||
```ts [ESLint 8]
|
||||
```ts [ESLint <=8]
|
||||
export default defineConfig({
|
||||
imports: {
|
||||
eslintrc: {
|
||||
@@ -69,7 +69,7 @@ Then in your ESLint config, import and use the generated file:
|
||||
|
||||
:::code-group
|
||||
|
||||
```js [ESLint 9]
|
||||
```js [ESLint >=9]
|
||||
// eslint.config.mjs
|
||||
import autoImports from './.wxt/eslint-auto-imports.mjs';
|
||||
|
||||
@@ -81,7 +81,7 @@ export default [
|
||||
];
|
||||
```
|
||||
|
||||
```js [ESLint 8]
|
||||
```js [ESLint <=8]
|
||||
// .eslintrc.mjs
|
||||
export default {
|
||||
extends: ['./.wxt/eslintrc-auto-import.json'],
|
||||
|
||||
@@ -4,11 +4,17 @@ outline: deep
|
||||
|
||||
# Browser Startup
|
||||
|
||||
During development, WXT will use any of the below packages to automatically open a browser with your extension installed.
|
||||
|
||||
- [`web-ext` by Mozilla](https://www.npmjs.com/package/web-ext)
|
||||
|
||||
Just install the dependency you want WXT to use to open the browser.
|
||||
|
||||
## `web-ext` Usage
|
||||
|
||||
> See the [API Reference](/api/reference/wxt/interfaces/WebExtConfig) for a full list of config.
|
||||
|
||||
During development, WXT uses [`web-ext` by Mozilla](https://www.npmjs.com/package/web-ext) to automatically open a browser window with your extension installed.
|
||||
|
||||
## Config Files
|
||||
### Config Files
|
||||
|
||||
You can configure browser startup in 3 places:
|
||||
|
||||
@@ -25,9 +31,9 @@ You can configure browser startup in 3 places:
|
||||
2. `<rootDir>/wxt.config.ts`: Via the [`webExt` config](/api/reference/wxt/interfaces/InlineConfig#webext), included in version control
|
||||
3. `$HOME/web-ext.config.ts`: Provide default values for all WXT projects on your computer
|
||||
|
||||
## Recipes
|
||||
### Recipes
|
||||
|
||||
### Set Browser Binaries
|
||||
#### Set Browser Binaries
|
||||
|
||||
To set or customize the browser opened during development:
|
||||
|
||||
@@ -57,7 +63,7 @@ export default defineConfig({
|
||||
|
||||
By default, WXT will try to automatically discover where Chrome/Firefox are installed. However, if you have chrome installed in a non-standard location, you need to set it manually as shown above.
|
||||
|
||||
### Persist Data
|
||||
#### Persist Data
|
||||
|
||||
By default, to keep from modifying your browser's existing profiles, `web-ext` creates a brand new profile every time you run the `dev` script.
|
||||
|
||||
@@ -94,9 +100,9 @@ Now, next time you run the `dev` script, a persistent profile will be created in
|
||||
You can use any directory you'd like for `--user-data-dir`, the examples above create a persistent profile for each WXT project. To create a profile for all WXT projects, you can put the `chrome-data` directory inside your user's home directory.
|
||||
:::
|
||||
|
||||
### Disable Opening Browser
|
||||
#### Disable Opening Browser
|
||||
|
||||
If you prefer to load the extension into your browser manually, you can disable the auto-open behavior:
|
||||
If you don't want to uninstall `web-ext`, like to test in your normal profile, you can do so via `disabled: true`:
|
||||
|
||||
```ts [web-ext.config.ts]
|
||||
import { defineWebExtConfig } from 'wxt';
|
||||
|
||||
@@ -76,27 +76,33 @@ Alternatively, if you're trying to use similar APIs under different names (to su
|
||||
});
|
||||
```
|
||||
|
||||
### Augmenting the Browser Type
|
||||
## Add Firefox Types
|
||||
|
||||
WXT's `browser` types are based on the `@types/chrome` package. That means some Firefox-specific APIs may not be typed, like `browser.sidebarAction`. If you want to add types for these APIs, you can augment the browser type to add them yourself:
|
||||
WXT's `browser` types are based on the `@types/chrome` package. That means some Firefox-specific APIs may not be typed, like `browser.sidebarAction`. If you want to add types for these APIs, you can augment the browser type by:
|
||||
|
||||
```ts
|
||||
// <srcDir>/browser-types.d.ts
|
||||
import '@wxt-dev/browser';
|
||||
import type { SidebarAction } from 'webextension-polyfill';
|
||||
1. Installing `@wxt-dev/browser` as a direct dependency
|
||||
|
||||
declare module '@wxt-dev/browser' {
|
||||
namespace Browser {
|
||||
export const sidebarAction: SidebarAction.Static;
|
||||
}
|
||||
}
|
||||
```
|
||||
```sh
|
||||
pnpm add @wxt-dev/browser
|
||||
```
|
||||
|
||||
> For this to work, you may need to install `@wxt-dev/browser` as a direct dependency.
|
||||
>
|
||||
> ```sh
|
||||
> pnpm add @wxt-dev/browser
|
||||
> ```
|
||||
2. Augmenting the `Browser` type:
|
||||
|
||||
```ts
|
||||
// <srcDir>/browser-types.d.ts
|
||||
import '@wxt-dev/browser';
|
||||
import type { SidebarAction } from 'webextension-polyfill';
|
||||
|
||||
declare module '@wxt-dev/browser' {
|
||||
namespace Browser {
|
||||
export const sidebarAction: SidebarAction.Static;
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
You can add types from any source: `webextension-polyfill`, `@types/firefox-webext-browser`, or your own custom types.
|
||||
|
||||
See TypeScript's documentation on [declaration merging](https://www.typescriptlang.org/docs/handbook/declaration-merging.html) for more information.
|
||||
|
||||
## Entrypoint Limitations
|
||||
|
||||
@@ -116,41 +122,32 @@ The fix is simple, just move your API usage into the entrypoint's main function:
|
||||
|
||||
:::code-group
|
||||
|
||||
<!-- prettier-ignore -->
|
||||
```ts [background.ts]
|
||||
browser.action.onClicked.addListener(() => {
|
||||
/* ... */
|
||||
}); // [!code --]
|
||||
browser.action.onClicked.addListener(() => { /* ... */ }); // [!code --]
|
||||
|
||||
export default defineBackground(() => {
|
||||
browser.action.onClicked.addListener(() => {
|
||||
/* ... */
|
||||
}); // [!code ++]
|
||||
browser.action.onClicked.addListener(() => { /* ... */ }); // [!code ++]
|
||||
});
|
||||
```
|
||||
|
||||
<!-- prettier-ignore -->
|
||||
```ts [content.ts]
|
||||
browser.runtime.onMessage.addListener(() => {
|
||||
/* ... */
|
||||
}); // [!code --]
|
||||
browser.runtime.onMessage.addListener(() => { /* ... */ }); // [!code --]
|
||||
|
||||
export default defineContentScript({
|
||||
main() {
|
||||
browser.runtime.onMessage.addListener(() => {
|
||||
/* ... */
|
||||
}); // [!code ++]
|
||||
browser.runtime.onMessage.addListener(() => { /* ... */ }); // [!code ++]
|
||||
},
|
||||
});
|
||||
```
|
||||
|
||||
<!-- prettier-ignore -->
|
||||
```ts [unlisted.ts]
|
||||
browser.runtime.onMessage.addListener(() => {
|
||||
/* ... */
|
||||
}); // [!code --]
|
||||
browser.runtime.onMessage.addListener(() => { /* ... */ }); // [!code --]
|
||||
|
||||
export default defineUnlistedScript(() => {
|
||||
browser.runtime.onMessage.addListener(() => {
|
||||
/* ... */
|
||||
}); // [!code ++]
|
||||
browser.runtime.onMessage.addListener(() => { /* ... */ }); // [!code ++]
|
||||
});
|
||||
```
|
||||
|
||||
|
||||
@@ -1,31 +0,0 @@
|
||||
# Remote Code
|
||||
|
||||
WXT will automatically download and bundle imports with the `url:` prefix so the extension does not depend on remote code, [a requirement from Google for MV3](https://developer.chrome.com/docs/extensions/migrating/improve-security/#remove-remote-code).
|
||||
|
||||
## Google Analytics
|
||||
|
||||
For example, you can import Google Analytics:
|
||||
|
||||
```ts
|
||||
// utils/google-analytics.ts
|
||||
import 'url:https://www.googletagmanager.com/gtag/js?id=G-XXXXXX';
|
||||
|
||||
window.dataLayer = window.dataLayer || [];
|
||||
// NOTE: This line is different from Google's documentation
|
||||
window.gtag = function () {
|
||||
dataLayer.push(arguments);
|
||||
};
|
||||
gtag('js', new Date());
|
||||
gtag('config', 'G-XXXXXX');
|
||||
```
|
||||
|
||||
Then you can import this in your HTML files to enable Google Analytics:
|
||||
|
||||
```ts
|
||||
// popup/main.ts
|
||||
import '~/utils/google-analytics';
|
||||
|
||||
gtag('event', 'event_name', {
|
||||
key: 'value',
|
||||
});
|
||||
```
|
||||
@@ -21,7 +21,6 @@ This plugin does several things:
|
||||
- Polyfills the extension API, `browser`, with an in-memory implementation using [`@webext-core/fake-browser`](https://webext-core.aklinker1.io/fake-browser/installation)
|
||||
- Adds all vite config or plugins in `wxt.config.ts`
|
||||
- Configures auto-imports (if enabled)
|
||||
- Applies internal WXT vite plugins for things like [bundling remote code](/guide/essentials/remote-code)
|
||||
- Sets up global variables provided by WXT (`import.meta.env.BROWSER`, `import.meta.env.MANIFEST_VERSION`, `import.meta.env.IS_CHROME`, etc)
|
||||
- Configures aliases (`@/*`, `@@/*`, etc) so imports can be resolved
|
||||
|
||||
|
||||
@@ -24,7 +24,6 @@ Lets compare the features of WXT vs [Plasmo](https://docs.plasmo.com/framework)
|
||||
| Supports all frontend frameworks | ✅ | 🟡 [^c] | ✅ |
|
||||
| Framework specific entrypoints (like `Popup.tsx`) | 🟡 [^d] | ✅ [^e] | ❌ |
|
||||
| Automated publishing | ✅ | ✅ | ❌ |
|
||||
| Remote Code Bundling (Google Analytics) | ✅ | ✅ | ❌ |
|
||||
| Unlisted HTML Pages | ✅ | ✅ | ✅ |
|
||||
| Unlisted Scripts | ✅ | ❌ | ❌ |
|
||||
| ESM Content Scripts | ❌ [^l] | ❌ | ✅ |
|
||||
|
||||
@@ -51,7 +51,7 @@ Here's specific steps for other popular frameworks/build tools.
|
||||
3. Move public `assets/*` into the `public/` directory
|
||||
4. If you use CSUI, migrate to WXT's `createContentScriptUi`
|
||||
5. Convert Plasmo's custom import resolutions to Vite's
|
||||
6. If importing remote code via a URL, add a `url:` prefix so it works with WXT
|
||||
6. Importing remote code via a URL is not supported in WXT, see [this issue](https://github.com/wxt-dev/wxt/issues/2262) for alternatives
|
||||
7. Replace your [Plasmo tags](https://docs.plasmo.com/framework/workflows/build#with-a-custom-tag) (`--tag`) with [WXT build modes](/guide/essentials/config/build-mode) (`--mode`)
|
||||
8. ⚠️ Compare the old production manifest to `.output/*/manifest.json`. They should have the same content as before. If not, tweak your entrypoints and config until they are the same.
|
||||
|
||||
|
||||
@@ -15,7 +15,7 @@ To upgrade WXT to the latest major version:
|
||||
```
|
||||
|
||||
2. Follow the upgrade steps below to fix any breaking changes.
|
||||
3. Run `wxt prepare`. It should succeed and type errors will go away afterwords.
|
||||
3. Run `wxt prepare`. It should succeed and type errors will go away afterwards.
|
||||
|
||||
```sh
|
||||
pnpm wxt prepare
|
||||
@@ -35,6 +35,340 @@ Listed below are all the breaking changes you should address when upgrading to a
|
||||
|
||||
Currently, WXT is in pre-release. This means changes to the second digit, `v0.X`, are considered major and have breaking changes. Once v1 is released, only major version bumps will have breaking changes.
|
||||
|
||||
## v0.20.0 → v0.21.0
|
||||
|
||||
This release focuses on trimming WXT's install footprint and simplifying project configuration.
|
||||
|
||||
:::tip
|
||||
Read through all the changes once before updating your code.
|
||||
:::
|
||||
|
||||
### Install Footprint
|
||||
|
||||
When installing `wxt` v0.20, it downloaded 98 MB and 366 packages to your `node_modules`. v0.21 cuts this down to 22MB / 156 packages - that's 22.4% the previous size! This is a good improvement, but frankly, not good enough. Why?
|
||||
|
||||
- `wxt init` is slow for new developers trying it out
|
||||
- Less exposure to supply chain attacks
|
||||
- More compute and storage used by servers hosting the package and clients downloading it degrades hardware and shortens their life-cycle
|
||||
|
||||
If you want to explore WXT's dependencies and why it's so large, here's a few links:
|
||||
|
||||
- <https://pkg-size.dev/wxt@%5E0.21?no-peers>
|
||||
- <https://npmgraph.js.org/?q=wxt@^0.21>
|
||||
- <https://node-modules.dev/grid/depth#install=wxt@^0.21>
|
||||
|
||||
We'll continue working on minimizing WXT's install footprint.
|
||||
|
||||
### Minimum Node.js, Vite, and TypeScript Versions
|
||||
|
||||
| Tool | Old requirement | New requirement |
|
||||
| ---------- | --------------------------------- | ---------------------------------- |
|
||||
| Node.js | `>=20.12.0` | `>=22` |
|
||||
| Vite | `^5.4.19 \|\| ^6.3.4 \|\| ^7.0.0` | `^6.3.4 \|\| ^7.0.0 \|\| ^8.0.0-0` |
|
||||
| TypeScript | Not enforced | `>=5.4` |
|
||||
|
||||
Vite 5 support was dropped as part of moving WXT's dev server off `vite-node` and onto Vite's native `ModuleRunner`/Environment API, which requires Vite ≥6.3.4.
|
||||
|
||||
### `vite`, `web-ext`, and `typescript` Are Now Peer Dependencies
|
||||
|
||||
Previously, WXT installed its own copies of `vite` and `web-ext` for you (you never had to add them to your `package.json`). Now, all three are declared as [`peerDependencies`](https://docs.npmjs.com/cli/v10/configuring-npm/package-json#peerdependencies) instead of regular dependencies, so **your project controls the exact version that gets used**, and WXT's install size shrinks.
|
||||
|
||||
- `vite` is a **required** peer, add it to your `devDependencies`.
|
||||
- `web-ext` and `typescript` are **optional** peers, only needed if you use the corresponding features (see [below](#opt-into-opening-the-browser-during-dev-mode) for `web-ext`).
|
||||
|
||||
```sh
|
||||
pnpm add -D vite typescript
|
||||
```
|
||||
|
||||
### Opt Into Opening the Browser During Dev Mode
|
||||
|
||||
In v0.21, `web-ext` is now an optional peer dependency - if it's installed, the browser will be opened automatically. If not, the feature is disabled.
|
||||
|
||||
- **To continue opening the browser automatically**: Install `web-ext` as a dependency
|
||||
|
||||
```sh
|
||||
pnpm add -D web-ext
|
||||
```
|
||||
|
||||
- **If you don't use this feature**: Don't install it and you can delete any `web-ext.config.ts` options and/or remove any `webExt.enabled: false` config
|
||||
|
||||
You can still disable this behavior by setting `webExt.enabled: false` in your `wxt.config.ts` file or `web-ext.config.ts` file if the package is present.
|
||||
|
||||
> Projects created with `wxt init` will include `web-ext` in their `package.json`, opting new projects into this feature by default.
|
||||
|
||||
### `.wxt/tsconfig.json` Compiler Option Changes
|
||||
|
||||
The generated `.wxt/tsconfig.json` was updated to match Vite's current recommended TypeScript settings, and now requires **TypeScript ≥5.4**.
|
||||
|
||||
```jsonc
|
||||
{
|
||||
"compilerOptions": {
|
||||
"lib": ["ESNext", "DOM", "DOM.Iterable"], // [!code ++]
|
||||
"target": "ESNext",
|
||||
"module": "ESNext", // [!code --]
|
||||
"module": "Preserve", // [!code ++]
|
||||
"moduleDetection": "force", // [!code ++]
|
||||
"moduleResolution": "Bundler",
|
||||
"allowImportingTsExtensions": true, // [!code ++]
|
||||
"verbatimModuleSyntax": true, // [!code ++]
|
||||
"noEmit": true,
|
||||
"esModuleInterop": true, // [!code --]
|
||||
"forceConsistentCasingInFileNames": true, // [!code --]
|
||||
"resolveJsonModule": true, // [!code --]
|
||||
"strict": true,
|
||||
"skipLibCheck": true,
|
||||
"noFallthroughCasesInSwitch": true, // [!code ++]
|
||||
"noUncheckedIndexedAccess": true, // [!code ++]
|
||||
"noImplicitOverride": true, // [!code ++]
|
||||
},
|
||||
}
|
||||
```
|
||||
|
||||
If these changes do cause problems, `verbatimModuleSyntax` and `noUncheckedIndexedAccess` are the two most likely culprits. It's recommended you fix the issues and leave the new settings enabled.
|
||||
|
||||
However, if you want to revert the config back and upgrade to the recommended options at a later time, you can add the following to your `wxt.config.ts` file:
|
||||
|
||||
<details>
|
||||
|
||||
```ts
|
||||
export default defineConfig({
|
||||
hooks: {
|
||||
'prepare:tsconfig': (_, { tsconfig }) => {
|
||||
// Reverts TSConfig back to WXT v0.20
|
||||
// - https://wxt.dev/guide/resources/upgrading.html#wxttsconfigjson-compiler-option-changes
|
||||
delete tsconfig.lib;
|
||||
tsconfig.module = 'ESNext';
|
||||
delete tsconfig.moduleDetection;
|
||||
delete tsconfig.allowImportingTsExtensions;
|
||||
delete tsconfig.verbatimModuleSyntax;
|
||||
tsconfig.esModuleInterop = true;
|
||||
tsconfig.forceConsistentCasingInFileNames = true;
|
||||
tsconfig.resolveJsonModule = true;
|
||||
delete tsconfig.noFallthroughCasesInSwitch;
|
||||
delete tsconfig.noUncheckedIndexedAccess;
|
||||
delete tsconfig.noImplicitOverride;
|
||||
},
|
||||
},
|
||||
});
|
||||
```
|
||||
|
||||
</details>
|
||||
|
||||
### `url:` Imports Removed
|
||||
|
||||
The `url:` import feature (importing and bundling remote code by URL, e.g. `import 'url:https://code.jquery.com/jquery.js'`) has been removed due to the supply-chain risk of a compromised CDN silently injecting code into your build.
|
||||
|
||||
There is no config flag to restore this behavior. If you relied on it:
|
||||
|
||||
- **Prefer an NPM package** if one exists for the library you need.
|
||||
- **Vendor the file**: download it once, commit it to your repo, and import it locally like any other file. This lets you review the code and track changes via version control, instead of trusting a URL to never change.
|
||||
|
||||
:::details Why was this removed?
|
||||
See <https://github.com/wxt-dev/wxt/issues/2262> and <https://github.com/wxt-dev/wxt/issues/2229> for the full discussion. A proposal to restore this behind a mandatory integrity hash is being tracked in [#2514](https://github.com/wxt-dev/wxt/pull/2514); if there's enough demand, it may come back as a separate, opt-in WXT module instead of core.
|
||||
:::
|
||||
|
||||
### Zip Filename Template Changes
|
||||
|
||||
The default filename templates for `zip.artifactTemplate` and `zip.sourcesTemplate` changed, and the <span v-pre>`{{version}}`</span> template variable's meaning changed:
|
||||
|
||||
- <span v-pre>`{{version}}`</span> now always resolves to `manifest.version` (previously it resolved to `manifest.version_name ?? manifest.version`).
|
||||
- A new <span v-pre>`{{versionName}}`</span> variable was added with the old <span v-pre>`{{version}}`</span> behavior (`manifest.version_name ?? manifest.version`).
|
||||
- A new <span v-pre>`{{packageVersion}}`</span> variable was added, resolving to your `package.json`'s version.
|
||||
- A new <span v-pre>`{{modeSuffix}}`</span> variable was added (`-dev` for development builds, `''` for production).
|
||||
|
||||
The defaults themselves changed to use these new variables:
|
||||
|
||||
```diff
|
||||
- artifactTemplate: '{{name}}-{{version}}-{{browser}}.zip'
|
||||
+ artifactTemplate: '{{name}}-{{packageVersion}}-{{browser}}{{modeSuffix}}.zip'
|
||||
|
||||
- sourcesTemplate: '{{name}}-{{version}}-sources.zip'
|
||||
+ sourcesTemplate: '{{name}}-{{packageVersion}}-sources{{modeSuffix}}.zip'
|
||||
```
|
||||
|
||||
- **If you don't customize `artifactTemplate`/`sourcesTemplate`**: your production zip filenames will not change, but dev and other build modes will be output to separate directories.
|
||||
|
||||
> If you previously install the dev version of your extension in your browser, note that the output directory has changed and you'll need to re-install it next time you run the dev command.
|
||||
|
||||
- **If you have a custom template**: replace any <span v-pre>`{{version}}`</span> usage with <span v-pre>`{{versionName}}`</span> to keep the old value, or explicitly opt back into the old defaults:
|
||||
|
||||
```ts [wxt.config.ts]
|
||||
export default defineConfig({
|
||||
zip: {
|
||||
artifactTemplate: '{{name}}-{{versionName}}-{{browser}}.zip',
|
||||
sourcesTemplate: '{{name}}-{{versionName}}-sources.zip',
|
||||
},
|
||||
});
|
||||
```
|
||||
|
||||
For more info on the difference between `manifest.version` and `manifest.version_name`, see the [Manifest Config docs](/guide/essentials/config/manifest#version-and-version-name).
|
||||
|
||||
### Sources ZIP: `includeSources`/`excludeSources` Now Behave Like a Standard Allowlist
|
||||
|
||||
Previously, `includeSources`/`excludeSources` behaved counterintuitively: `all files - excludeSources + includedSources = zipped files`. This is not the standard behavior for allowlist/blocklists.
|
||||
|
||||
As of v0.21, these options behave as expected: `includedSources - excludeSources = zipped files`.
|
||||
|
||||
Additionally, a new `zip.dotSources` option (default `false`) was added to control whether hidden files/directories can be included in the zip.
|
||||
|
||||
This will likely be the biggest pain point of the upgrade. You will need to rebuild your included and excluded sources lists from scratch. Luckily, it's simpler than before!
|
||||
|
||||
1. Do you need any hidden files? If so, set `zip.dotSources` to `true`
|
||||
1. Add base files and directories that need to be in the ZIP to `zip.includeSources`
|
||||
1. Run `wxt zip -b firefox` and confirm all the files you need are included
|
||||
1. Remove files from the zip by adding them to `zip.excludeSources`
|
||||
1. Run `wxt zip -b firefox` and confirm only the files you need are in the zip
|
||||
|
||||
:::tip
|
||||
`wxt zip -b firefox` now prints every file included in the sources ZIP. This will help you identify missing or unwanted files more quickly.
|
||||
:::
|
||||
|
||||
Here's an example configuration:
|
||||
|
||||
```ts
|
||||
// wxt.config.ts
|
||||
export default defineConfig({
|
||||
srcDir: 'src',
|
||||
zip: {
|
||||
// Say I have a .tool-versions file I want to include
|
||||
dotSources: true,
|
||||
// Specify base folders and files to include
|
||||
includeSources: [
|
||||
'src',
|
||||
'public',
|
||||
'package.json',
|
||||
'bun.lock',
|
||||
'README.md',
|
||||
'.tool-versions',
|
||||
],
|
||||
// Exclude any folders inside the base folders that are not needed, like test data
|
||||
excludeSources: ['**/__fixtures__'],
|
||||
},
|
||||
});
|
||||
```
|
||||
|
||||
### `createShadowRootUi` DOM Changes
|
||||
|
||||
`@webext-core/isolated-element` was upgraded from v1 to v3. The only breaking change relevant to WXT projects is that the internal structure of the shadow root's is simpler:
|
||||
|
||||
:::code-group
|
||||
|
||||
```html [Before]
|
||||
<html>
|
||||
<head>
|
||||
<style>
|
||||
...
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
...your app
|
||||
</body>
|
||||
</html>
|
||||
```
|
||||
|
||||
```html [After]
|
||||
<style>
|
||||
...
|
||||
</style>
|
||||
<div>...your app</div>
|
||||
```
|
||||
|
||||
:::
|
||||
|
||||
Historically, CSS frameworks haven't had good support for shadow roots, so we needed a full `<html>` structure for styles to be applied correctly. But that has change this past few years, frameworks have started to include the `host:` selector alongside `root:` (which is required for base styles to be applied to the shadow root's host element):
|
||||
|
||||
```css
|
||||
:root { /* [!code --] */
|
||||
:root, :host { /* [!code ++] */
|
||||
/* base styles... */
|
||||
}
|
||||
```
|
||||
|
||||
If you use `createShadowRootUi`, see if your UI looks the same after this update without any changes.
|
||||
|
||||
If the styles are broken, you can continue using the full `<html>` structure by installing the v1 of `@webext-core/isolated-element` - WXT will respect whatever version of the package is listed in your `package.json`.
|
||||
|
||||
```sh
|
||||
pnpm add @webext-core/isolated-element@^1
|
||||
```
|
||||
|
||||
In the next major version, support for `@webext-core/isolated-element` v1 will be dropped, so you have some time to migrate.
|
||||
|
||||
### Content & Unlisted Script `globalName` Now Defaults to `false`
|
||||
|
||||
Content scripts and unlisted scripts are built as an IIFE. Previously, WXT generated a global variable to hold the IIFE's return value for all scripts by default. Now, no global variable is generated by default, producing a smaller, anonymous IIFE that prevents variable collisions with the page.
|
||||
|
||||
If you rely on the return value of your script, for example when injecting it with `browser.scripting.executeScript` and reading `InjectionResult.result`, set `globalName: true` to restore the old behavior:
|
||||
|
||||
```ts
|
||||
export default defineUnlistedScript({
|
||||
globalName: true, // [!code ++]
|
||||
main() {
|
||||
return 'some value';
|
||||
},
|
||||
});
|
||||
```
|
||||
|
||||
This applies per-entrypoint, to both `defineContentScript` and `defineUnlistedScript`.
|
||||
|
||||
### ESLint Auto-Import Config Now Detects Your Installed ESLint Version
|
||||
|
||||
Setting `imports.eslintrc.enabled: true` used to always assume you wanted the legacy ESLint 8 config format, regardless of which ESLint version you actually had installed.
|
||||
|
||||
Now, `true` behaves the same as `'auto'`: WXT detects your installed ESLint version and generates the matching file automatically (ESLint 9+ → `eslint-auto-imports.mjs`, ESLint ≤8 → `eslintrc-auto-import.json`).
|
||||
|
||||
- If you're on ESLint 9+ but never explicitly set `enabled: 9`, you'll now get the new flat-config file instead of the legacy one.
|
||||
- To force the old ESLint 8 format regardless of your installed version, set `enabled: 8` explicitly.
|
||||
|
||||
See the [ESLint config docs](/guide/essentials/config/auto-imports#eslint) for the full set of options and how to wire up the generated file.
|
||||
|
||||
### Deprecated APIs Removed From v0.21
|
||||
|
||||
APIs deprecated in v0.20 have been removed:
|
||||
|
||||
- `wxt.config.runner` / `ExtensionRunnerConfig` / `defineRunnerConfig` → use `wxt.config.webExt` / `defineWebExtConfig` instead.
|
||||
- `dev.server.hostname` → use `dev.server.host` instead.
|
||||
- The `wxt/testing` barrel export → import from the specific submodule instead:
|
||||
|
||||
```ts
|
||||
import { fakeBrowser, WxtVitest } from 'wxt/testing'; // [!code --]
|
||||
import { fakeBrowser } from 'wxt/testing/fake-browser'; // [!code ++]
|
||||
import { WxtVitest } from 'wxt/testing/vitest-plugin'; // [!code ++]
|
||||
```
|
||||
|
||||
- The `clean(root: string)` JS API overload → Pass a root like this instead `clean({ root: './my-extension' })`
|
||||
|
||||
### CWS v2 API Support
|
||||
|
||||
`publish-browser-extension` was upgraded to v5, which adds support for the new Chrome Web Store v2 API to `wxt submit`! Instead of using a refresh token for auth, it uses a service account, which is much easier to setup and never expires. It also supports a few other features: <https://developer.chrome.com/blog/cws-api-v2>
|
||||
|
||||
To setup your project to use v2, run `wxt submit init` and go through the setup process for the CWS, selecting v2 when prompted.
|
||||
|
||||
v1 will stop working **15th October 2026**, so you have a few months to migrate.
|
||||
|
||||
### `@webext-core/fake-browser` v2
|
||||
|
||||
If you use `wxt/testing/fake-browser` (or `@webext-core/fake-browser` directly) in unit tests, note that its types now match `@wxt-dev/browser` instead of `webextension-polyfill`. This is the same change WXT's own `browser` went through in [v0.20](#webextension-polyfill-removed).
|
||||
|
||||
Most notably, **mocking `browser.runtime.onMessage` listeners that return a promise no longer works**, use `sendResponse` instead:
|
||||
|
||||
```ts
|
||||
fakeBrowser.runtime.onMessage.addListener(async () => { // [!code --]
|
||||
return await someAsyncWork(); // [!code --]
|
||||
fakeBrowser.runtime.onMessage.addListener((_message, _sender, sendResponse) => { // [!code ++]
|
||||
someAsyncWork().then(sendResponse); // [!code ++]
|
||||
return true; // [!code ++]
|
||||
});
|
||||
```
|
||||
|
||||
If you use use a messaging library, it will likely continue working as-is.
|
||||
|
||||
### New Deprecations in v0.20
|
||||
|
||||
Deprecated APIs will be removed in the next major release.
|
||||
|
||||
- `useAppConfig` deprecated in favor of `getAppConfig` - same function, just renamed. This avoids react linters mistaking it as a hook.
|
||||
|
||||
## v0.19.0 → v0.20.0
|
||||
|
||||
v0.20 is a big release! There are lots of breaking changes because this version is intended to be a release candidate for v1.0. If all goes well, v1.0 will be released with no additional breaking changes.
|
||||
|
||||
@@ -66,11 +66,6 @@ features:
|
||||
- icon: 📏
|
||||
title: Bundle Analysis
|
||||
details: Tools for analyzing the final extension bundle and minimizing your extension's size.
|
||||
- icon: ⬇️
|
||||
title: Bundle Remote Code
|
||||
details: Downloads and bundles remote code imported from URLs.
|
||||
link: /guide/essentials/remote-code
|
||||
linkText: Read docs
|
||||
---
|
||||
|
||||
## Sponsors
|
||||
|
||||
@@ -38,6 +38,10 @@
|
||||
# 0.19.0
|
||||
/guide/go-further/entrypoint-side-effects.html /guide/go-further/entrypoint-loaders.html
|
||||
|
||||
# 0.21.0
|
||||
# The `url:` import feature was removed, along with its docs page.
|
||||
/guide/essentials/remote-code.html /guide/resources/upgrading.html#url-imports-removed
|
||||
|
||||
# https://github.com/wxt-dev/wxt/issues/704
|
||||
# Generated via `pnpm docs:build && find docs/.vitepress/dist -type f -name "*.html"`
|
||||
|
||||
@@ -59,7 +63,7 @@
|
||||
/guide/go-further/handling-updates.html /guide/essentials/testing-updates.html
|
||||
/guide/go-further/custom-events.html /guide/essentials/content-scripts.html#dealing-with-spas
|
||||
/guide/go-further/debugging.html /TODO
|
||||
/guide/go-further/remote-code.html /guide/essentials/remote-code.html
|
||||
/guide/go-further/remote-code.html /guide/resources/upgrading.html#url-imports-removed
|
||||
/guide/go-further/vite.html /guide/essentials/config/vite.html
|
||||
/guide/go-further/testing.html /guide/essentials/unit-testing.html
|
||||
/guide/go-further/how-wxt-works.html /guide/resources/how-wxt-works.html
|
||||
|
||||
@@ -37,6 +37,9 @@ Hide
|
||||
# Create a temporary folder for demo
|
||||
Type 'mkdir packages/wxt/init-demo' Enter
|
||||
Type 'cd packages/wxt/init-demo' Enter
|
||||
# Unset CI variables inherited from the GitHub Actions runner so consola
|
||||
# picks its fancy reporter instead of the basic one (#2461)
|
||||
Type 'unset CI GITHUB_ACTIONS' Enter
|
||||
Type 'clear' Enter
|
||||
Show
|
||||
|
||||
|
||||
+2
-2
@@ -21,7 +21,7 @@
|
||||
"@aklinker1/buildc": "^1.1.7",
|
||||
"@aklinker1/check": "^2.4.0",
|
||||
"@types/bun": "^1.3.5",
|
||||
"@types/node": "^20.17.6",
|
||||
"@types/node": "^22",
|
||||
"@types/react": "^19.2.14",
|
||||
"@types/react-dom": "^19.2.3",
|
||||
"@webext-core/fake-browser": "^1.3.4",
|
||||
@@ -31,6 +31,7 @@
|
||||
"tsdown": "^0.21.0",
|
||||
"typescript": "^6.0.3",
|
||||
"unocss": "^66.6.8",
|
||||
"vite": "^7.3.1",
|
||||
"vitest": "^4.1.5",
|
||||
"vitest-plugin-random-seed": "^1.1.2"
|
||||
},
|
||||
@@ -42,7 +43,6 @@
|
||||
"@types/bun": "catalog:",
|
||||
"@types/semver": "^7.7.1",
|
||||
"@vitest/coverage-v8": "^4.1.6",
|
||||
"changelogen": "^0.6.2",
|
||||
"consola": "^3.4.2",
|
||||
"cspell": "^9.7.0",
|
||||
"feed": "^5.2.1",
|
||||
|
||||
@@ -6,6 +6,7 @@ Report analytics events from your web extension extension.
|
||||
|
||||
- [Google Analytics 4 (Measurement Protocol)](#google-analytics-4-measurement-protocol)
|
||||
- [Moderok](#moderok)
|
||||
- [PostHog](#posthog)
|
||||
- [Umami](#umami)
|
||||
|
||||
## Install With WXT
|
||||
@@ -156,6 +157,35 @@ export default defineAppConfig({
|
||||
|
||||
For a full walkthrough — module setup, sending events, and all provider options — see the [Moderok WXT guide](https://docs.moderok.dev/guide/wxt).
|
||||
|
||||
### PostHog
|
||||
|
||||
[PostHog](https://posthog.com/) is an open source product analytics platform. It supports event tracking, session recording, feature flags, surveys, and more.
|
||||
|
||||
In your PostHog project settings, find your **Project API key** and save it to your `.env` file:
|
||||
|
||||
```dotenv
|
||||
WXT_POSTHOG_API_KEY='phc_...'
|
||||
```
|
||||
|
||||
Then add the `posthog` provider to your `<srcDir>/app.config.ts` file:
|
||||
|
||||
```ts
|
||||
import { posthog } from '@wxt-dev/analytics/providers/posthog';
|
||||
|
||||
export default defineAppConfig({
|
||||
analytics: {
|
||||
providers: [
|
||||
posthog({
|
||||
apiKey: import.meta.env.WXT_POSTHOG_API_KEY,
|
||||
// apiHost defaults to 'https://us.i.posthog.com'.
|
||||
// Change to 'https://eu.i.posthog.com' for EU Cloud, or your self-hosted URL.
|
||||
apiHost: 'https://eu.i.posthog.com',
|
||||
}),
|
||||
],
|
||||
},
|
||||
});
|
||||
```
|
||||
|
||||
### Umami
|
||||
|
||||
[Umami](https://umami.is/) is a privacy-first, open source analytics platform.
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { defineAppConfig } from 'wxt/utils/define-app-config';
|
||||
import { googleAnalytics4 } from './modules/analytics/providers/google-analytics-4';
|
||||
import { posthog } from './modules/analytics/providers/posthog';
|
||||
import { umami } from './modules/analytics/providers/umami';
|
||||
|
||||
export default defineAppConfig({
|
||||
@@ -10,6 +11,9 @@ export default defineAppConfig({
|
||||
apiSecret: '...',
|
||||
measurementId: '...',
|
||||
}),
|
||||
posthog({
|
||||
apiKey: '...',
|
||||
}),
|
||||
umami({
|
||||
apiUrl: 'https://umami.aklinker1.io/api',
|
||||
domain: 'analytics.wxt.dev',
|
||||
|
||||
@@ -18,7 +18,7 @@ export const googleAnalytics4 =
|
||||
eventProperties: Record<string, string | undefined> | undefined,
|
||||
): Promise<void> => {
|
||||
const url = new URL(
|
||||
config?.debug ? '/debug/mp/collect' : '/mp/collect',
|
||||
config.debug ? '/debug/mp/collect' : '/mp/collect',
|
||||
options.apiUrl ?? 'https://www.google-analytics.com',
|
||||
);
|
||||
if (options.apiSecret)
|
||||
@@ -38,6 +38,12 @@ export const googleAnalytics4 =
|
||||
]),
|
||||
);
|
||||
|
||||
if (config.debug) {
|
||||
console.debug(
|
||||
'[@wxt-dev/analytics] Sending event to Google Analytics 4:',
|
||||
{ eventName, eventProperties },
|
||||
);
|
||||
}
|
||||
await fetch(url.href, {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({
|
||||
|
||||
@@ -0,0 +1,83 @@
|
||||
import { defineAnalyticsProvider } from '../client';
|
||||
|
||||
export interface PostHogProviderOptions {
|
||||
/** Your PostHog project API key. */
|
||||
apiKey: string;
|
||||
/**
|
||||
* PostHog API host URL.
|
||||
*
|
||||
* @default 'https://us.i.posthog.com'
|
||||
*/
|
||||
apiHost?: string;
|
||||
}
|
||||
|
||||
export const posthog = defineAnalyticsProvider<PostHogProviderOptions>(
|
||||
(_, config, options) => {
|
||||
const apiHost = (options.apiHost ?? 'https://us.i.posthog.com').replace(
|
||||
/\/$/,
|
||||
'',
|
||||
);
|
||||
|
||||
const capture = async (
|
||||
distinctId: string,
|
||||
event: string,
|
||||
properties: Record<string, unknown>,
|
||||
): Promise<void> => {
|
||||
if (config.debug) {
|
||||
console.debug('[@wxt-dev/analytics] Sending event to PostHog:', {
|
||||
event,
|
||||
properties,
|
||||
});
|
||||
}
|
||||
const body: PostHogCaptureBody = {
|
||||
api_key: options.apiKey,
|
||||
distinct_id: distinctId,
|
||||
event,
|
||||
properties,
|
||||
timestamp: new Date().toISOString(),
|
||||
};
|
||||
await fetch(`${apiHost}/i/v0/e/`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify(body),
|
||||
});
|
||||
};
|
||||
|
||||
return {
|
||||
identify: async (event) => {
|
||||
await capture(event.user.id, '$identify', {
|
||||
$set: event.user.properties,
|
||||
});
|
||||
},
|
||||
page: async (event) => {
|
||||
await capture(event.user.id, '$pageview', {
|
||||
$current_url: event.page.url,
|
||||
$title: event.page.title,
|
||||
$session_id: event.meta.sessionId,
|
||||
$screen: event.meta.screen,
|
||||
$language: event.meta.language,
|
||||
$referrer: event.meta.referrer,
|
||||
$set: event.user.properties,
|
||||
});
|
||||
},
|
||||
track: async (event) => {
|
||||
await capture(event.user.id, event.event.name, {
|
||||
...event.event.properties,
|
||||
$screen: event.meta.screen,
|
||||
$language: event.meta.language,
|
||||
$referrer: event.meta.referrer,
|
||||
$set: event.user.properties,
|
||||
});
|
||||
},
|
||||
};
|
||||
},
|
||||
);
|
||||
|
||||
/** @see https://posthog.com/docs/api/capture */
|
||||
interface PostHogCaptureBody {
|
||||
api_key: string;
|
||||
distinct_id: string;
|
||||
event: string;
|
||||
properties: Record<string, unknown>;
|
||||
timestamp: string;
|
||||
}
|
||||
@@ -62,6 +62,10 @@
|
||||
"./providers/umami": {
|
||||
"types": "./dist/providers/umami.d.mts",
|
||||
"default": "./dist/providers/umami.mjs"
|
||||
},
|
||||
"./providers/posthog": {
|
||||
"types": "./dist/providers/posthog.d.mts",
|
||||
"default": "./dist/providers/posthog.mjs"
|
||||
}
|
||||
},
|
||||
"module": "./dist/index.mjs",
|
||||
|
||||
@@ -10,6 +10,7 @@ export default defineConfig({
|
||||
'./modules/analytics/providers/google-analytics-4.ts',
|
||||
'providers/umami': './modules/analytics/providers/umami.ts',
|
||||
'providers/moderok': './modules/analytics/providers/moderok.ts',
|
||||
'providers/posthog': './modules/analytics/providers/posthog.ts',
|
||||
},
|
||||
deps: {
|
||||
neverBundle: ['#analytics'],
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"name": "@wxt-dev/browser",
|
||||
"description": "Provides a cross-browser API for using extension APIs and types based on @types/chrome",
|
||||
"version": "0.2.0",
|
||||
"version": "0.2.2",
|
||||
"type": "module",
|
||||
"main": "src/index.mjs",
|
||||
"types": "src/index.d.ts",
|
||||
@@ -25,7 +25,7 @@
|
||||
"src"
|
||||
],
|
||||
"devDependencies": {
|
||||
"@types/chrome": "0.2.0",
|
||||
"@types/chrome": "0.2.2",
|
||||
"@types/node": "catalog:",
|
||||
"nano-spawn": "catalog:",
|
||||
"typescript": "catalog:",
|
||||
|
||||
+48
-15
@@ -383,22 +383,53 @@ export namespace Browser {
|
||||
* Permissions: "alarms"
|
||||
*/
|
||||
export namespace alarms {
|
||||
interface AlarmCreateInfo {
|
||||
/** Length of time in minutes after which the {@link onAlarm} event should fire. */
|
||||
delayInMinutes?: number | undefined;
|
||||
/** If set, the onAlarm event should fire every `periodInMinutes` minutes after the initial event specified by `when` or `delayInMinutes`. If not set, the alarm will only fire once. */
|
||||
periodInMinutes?: number | undefined;
|
||||
/** Time at which the alarm should fire, in milliseconds past the epoch (e.g. `Date.now() + n`). */
|
||||
when?: number | undefined;
|
||||
}
|
||||
type AlarmCreateInfo =
|
||||
& {
|
||||
/**
|
||||
* Whether the alarm should persist across sessions (browser restarts). In Chrome, this defaults to true to match historical behavior, but you should set this explicitly to maximize compatibility across browsers.
|
||||
* @since Chrome 150
|
||||
*/
|
||||
persistAcrossSessions?: boolean | undefined;
|
||||
}
|
||||
& (
|
||||
| {
|
||||
/** Length of time in minutes after which the {@link onAlarm} event should fire. */
|
||||
delayInMinutes: number;
|
||||
/** If set, the onAlarm event should fire every `periodInMinutes` minutes after the initial event specified by `when` or `delayInMinutes`. If not set, the alarm will only fire once. */
|
||||
periodInMinutes?: number | undefined;
|
||||
/** Time at which the alarm should fire, in milliseconds past the epoch (e.g. `Date.now() + n`). */
|
||||
when?: never | undefined;
|
||||
}
|
||||
| {
|
||||
/** Length of time in minutes after which the {@link onAlarm} event should fire. */
|
||||
delayInMinutes?: number | undefined;
|
||||
/** If set, the onAlarm event should fire every `periodInMinutes` minutes after the initial event specified by `when` or `delayInMinutes`. If not set, the alarm will only fire once. */
|
||||
periodInMinutes: number;
|
||||
/** Time at which the alarm should fire, in milliseconds past the epoch (e.g. `Date.now() + n`). */
|
||||
when?: number | undefined;
|
||||
}
|
||||
| {
|
||||
/** Length of time in minutes after which the {@link onAlarm} event should fire. */
|
||||
delayInMinutes?: never | undefined;
|
||||
/** If set, the onAlarm event should fire every `periodInMinutes` minutes after the initial event specified by `when` or `delayInMinutes`. If not set, the alarm will only fire once. */
|
||||
periodInMinutes?: number | undefined;
|
||||
/** Time at which the alarm should fire, in milliseconds past the epoch (e.g. `Date.now() + n`). */
|
||||
when: number;
|
||||
}
|
||||
);
|
||||
|
||||
interface Alarm {
|
||||
/** If not null, the alarm is a repeating alarm and will fire again in `periodInMinutes` minutes. */
|
||||
periodInMinutes?: number;
|
||||
/** Time at which this alarm was scheduled to fire, in milliseconds past the epoch (e.g. `Date.now() + n`). For performance reasons, the alarm may have been delayed an arbitrary amount beyond this. */
|
||||
scheduledTime: number;
|
||||
/** Name of this alarm. */
|
||||
name: string;
|
||||
/** If not null, the alarm is a repeating alarm and will fire again in `periodInMinutes` minutes. */
|
||||
periodInMinutes?: number;
|
||||
/**
|
||||
* Whether the alarm should persist across sessions (browser restarts).
|
||||
* @since Chrome 150
|
||||
*/
|
||||
persistAcrossSessions: boolean;
|
||||
/** Time at which this alarm was scheduled to fire, in milliseconds past the epoch (e.g. `Date.now() + n`). For performance reasons, the alarm may have been delayed an arbitrary amount beyond this. */
|
||||
scheduledTime: number;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -7606,7 +7637,7 @@ export namespace Browser {
|
||||
* Creates a new offscreen document for the extension.
|
||||
* @param parameters The parameters describing the offscreen document to create.
|
||||
*
|
||||
* Can return its result via Promise in Manifest V3.
|
||||
* Can return its result via Promise.
|
||||
*/
|
||||
function createDocument(parameters: CreateParameters): Promise<void>;
|
||||
function createDocument(parameters: CreateParameters, callback: () => void): void;
|
||||
@@ -7614,7 +7645,7 @@ export namespace Browser {
|
||||
/**
|
||||
* Closes the currently-open offscreen document for the extension.
|
||||
*
|
||||
* Can return its result via Promise in Manifest V3.
|
||||
* Can return its result via Promise.
|
||||
*/
|
||||
function closeDocument(): Promise<void>;
|
||||
function closeDocument(callback: () => void): void;
|
||||
@@ -7622,7 +7653,8 @@ export namespace Browser {
|
||||
/**
|
||||
* Determines whether the extension has an active document.
|
||||
*
|
||||
* Can return its result via Promise in Manifest V3.
|
||||
* Can return its result via Promise.
|
||||
* @since Chrome 150
|
||||
*/
|
||||
function hasDocument(): Promise<boolean>;
|
||||
function hasDocument(callback: (result: boolean) => void): void;
|
||||
@@ -9184,6 +9216,7 @@ export namespace Browser {
|
||||
| "identity"
|
||||
| "identity.email"
|
||||
| "idle"
|
||||
| "input"
|
||||
| "loginState"
|
||||
| "management"
|
||||
| "nativeMessaging"
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import 'wxt';
|
||||
import { addImportPreset, addViteConfig, defineWxtModule } from 'wxt/modules';
|
||||
import react, { Options as PluginOptions } from '@vitejs/plugin-react';
|
||||
import react, { type Options as PluginOptions } from '@vitejs/plugin-react';
|
||||
import type { PluginOption } from 'vite';
|
||||
|
||||
export default defineWxtModule<ReactModuleOptions>({
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { Component } from 'solid-js';
|
||||
import type { Component } from 'solid-js';
|
||||
|
||||
export const App: Component = () => {
|
||||
const [count, setCount] = createSignal(0);
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import 'wxt';
|
||||
import { addImportPreset, addViteConfig, defineWxtModule } from 'wxt/modules';
|
||||
import solid, { Options as PluginOptions } from 'vite-plugin-solid';
|
||||
import solid, { type Options as PluginOptions } from 'vite-plugin-solid';
|
||||
|
||||
export default defineWxtModule<SolidModuleOptions>({
|
||||
name: '@wxt-dev/module-solid',
|
||||
|
||||
@@ -33,8 +33,8 @@
|
||||
},
|
||||
"dependencies": {
|
||||
"@wxt-dev/browser": "workspace:^",
|
||||
"async-mutex": "^0.5.0",
|
||||
"dequal": "^2.0.3"
|
||||
"dequal": "^2.0.3",
|
||||
"superlock": "^1.3.2"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@aklinker1/buildc": "catalog:",
|
||||
|
||||
@@ -7,7 +7,7 @@
|
||||
* @module @wxt-dev/storage
|
||||
*/
|
||||
import { browser, type Browser } from '@wxt-dev/browser';
|
||||
import { Mutex } from 'async-mutex';
|
||||
import { withLock } from 'superlock';
|
||||
import { dequal } from 'dequal/lite';
|
||||
|
||||
export const storage = createStorage();
|
||||
@@ -487,12 +487,12 @@ function createStorage(): WxtStorage {
|
||||
);
|
||||
});
|
||||
|
||||
const initMutex = new Mutex();
|
||||
const initLock = withLock();
|
||||
|
||||
const getFallback = () => opts?.fallback ?? opts?.defaultValue ?? null;
|
||||
|
||||
const getOrInitValue = () =>
|
||||
initMutex.runExclusive(async () => {
|
||||
initLock(async () => {
|
||||
const value = await driver.getItem<any>(driverKey);
|
||||
// Don't init value if it already exists or the init function isn't provided
|
||||
if (value != null || opts?.init == null) return value;
|
||||
|
||||
@@ -1,6 +1,3 @@
|
||||
// @ts-expect-error: URL imports not typed
|
||||
import 'url:https://code.jquery.com/jquery-3.7.1.slim.min.js';
|
||||
|
||||
console.log(browser.runtime.id);
|
||||
logId();
|
||||
console.log(2);
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { defineProject } from 'vitest/config';
|
||||
import { WxtVitest } from 'wxt/testing';
|
||||
import { WxtVitest } from 'wxt/testing/vitest-plugin';
|
||||
|
||||
export default defineProject({
|
||||
test: {
|
||||
|
||||
+145
-1
@@ -1,5 +1,149 @@
|
||||
# Changelog
|
||||
|
||||
## v0.21.2
|
||||
|
||||
[compare changes](https://github.com/wxt-dev/wxt/compare/wxt-v0.21.1...wxt-v0.21.2)
|
||||
|
||||
### 🩹 Fixes
|
||||
|
||||
- Remove `web-ext-run`, it's unused now ([`859d654`](https://github.com/wxt-dev/wxt/commit/859d654611571941ee0a7aa4011f3ce011787a30))
|
||||
|
||||
### 📖 Documentation
|
||||
|
||||
- Fix typos and wording of upgrade guide ([`d1ab2d9`](https://github.com/wxt-dev/wxt/commit/d1ab2d923dada60ac4a3ece7d85001ee611f9731))
|
||||
- Fix heading level ([`466ae8a`](https://github.com/wxt-dev/wxt/commit/466ae8a33c73436ac2dc06e0046ea949e1982a7f))
|
||||
- Update package size links ([`925e97d`](https://github.com/wxt-dev/wxt/commit/925e97d4fc83ecfcc93bbbb357247373b594804f))
|
||||
|
||||
### ❤️ Contributors
|
||||
|
||||
- [@aklinker1](https://github.com/aklinker1)
|
||||
|
||||
|
||||
## v0.21.1
|
||||
|
||||
[compare changes](https://github.com/wxt-dev/wxt/compare/wxt-v0.20.27...wxt-v0.21.1)
|
||||
|
||||
### 🚀 Features
|
||||
|
||||
- Add `prepare:tsconfig` hook for updating `.wxt/tsconfig.json` file ([#2450](https://github.com/wxt-dev/wxt/pull/2450))
|
||||
- Add watch options config ([#2439](https://github.com/wxt-dev/wxt/pull/2439))
|
||||
- Export `getEntrypointBundlePath` from `wxt` ([#2463](https://github.com/wxt-dev/wxt/pull/2463))
|
||||
- Add `{{modeSuffix}}` to zip templates and update defaults ([#1623](https://github.com/wxt-dev/wxt/pull/1623))
|
||||
- Change default behavior of `getUnimportEslintOptions` true flag ([#2296](https://github.com/wxt-dev/wxt/pull/2296))
|
||||
- New template variable `{{versionName}}` and change of the behaviour of `{{version}}` ([#1612](https://github.com/wxt-dev/wxt/pull/1612))
|
||||
- **Firefox**: List files in sources zip ([#2513](https://github.com/wxt-dev/wxt/pull/2513))
|
||||
|
||||
### 🩹 Fixes
|
||||
|
||||
- `wxt clean` removes `.wxt/` directory at project root ([#2415](https://github.com/wxt-dev/wxt/pull/2415))
|
||||
- Handle spread content script configs ([#2448](https://github.com/wxt-dev/wxt/pull/2448))
|
||||
- Avoid deprecated Rollup asset name access ([#2453](https://github.com/wxt-dev/wxt/pull/2453))
|
||||
- **init**: Allow entering an empty directory for project path ([#2458](https://github.com/wxt-dev/wxt/pull/2458))
|
||||
- Opening the browser issue in windows. ([#2436](https://github.com/wxt-dev/wxt/pull/2436))
|
||||
- File reloading mechanism and add profile watch ignores ([#2112](https://github.com/wxt-dev/wxt/pull/2112))
|
||||
- Docs sidebar header, background color issue ([#2504](https://github.com/wxt-dev/wxt/pull/2504))
|
||||
- Deprecated `useAppConfig` in favour of `getAppConfig` ([#2487](https://github.com/wxt-dev/wxt/pull/2487))
|
||||
- Make `web-ext` a peer dependency ([#2079](https://github.com/wxt-dev/wxt/pull/2079))
|
||||
- Handle edge case where eslint version cannot be found ([`ab679ba`](https://github.com/wxt-dev/wxt/commit/ab679ba413772849e0c263315587334b42c25ed0))
|
||||
- Remove `url:` import feature ([#2456](https://github.com/wxt-dev/wxt/pull/2456))
|
||||
- **zip**: Make `includeSources`/`excludeSources` follow standard allowlist behavior ([#2114](https://github.com/wxt-dev/wxt/pull/2114))
|
||||
- Remove `console.log` ([`0b352f6`](https://github.com/wxt-dev/wxt/commit/0b352f6eff1fbb45034b788a134742d03db81816))
|
||||
- Loosen version of `@webext-core/isolated-element` ([`7d6caad`](https://github.com/wxt-dev/wxt/commit/7d6caad9b52bc263d0acb4263153fe0e05e24b76))
|
||||
- Update content and unlisted script `globalName` default to `false` ([#2511](https://github.com/wxt-dev/wxt/pull/2511))
|
||||
- **TS**: Update `.wxt/tsconfig.json` compiler options, require TS >=5.4 ([#2512](https://github.com/wxt-dev/wxt/pull/2512))
|
||||
|
||||
### 💅 Refactors
|
||||
|
||||
- Make vite a default peer ([#1945](https://github.com/wxt-dev/wxt/pull/1945))
|
||||
- Move to module-runner ([#1946](https://github.com/wxt-dev/wxt/pull/1946))
|
||||
|
||||
### 📖 Documentation
|
||||
|
||||
- Move Bun tabs to first position in installation ([#2428](https://github.com/wxt-dev/wxt/pull/2428))
|
||||
- Added package manager tab group synchronization across the entire installation page ([#2421](https://github.com/wxt-dev/wxt/pull/2421))
|
||||
- Make vitepress components css files more readable and simply ([#2272](https://github.com/wxt-dev/wxt/pull/2272))
|
||||
- Use bright green for example hover and link colors ([`d7f8ebe`](https://github.com/wxt-dev/wxt/commit/d7f8ebec3904ea6efa803c9d7b5dcd9b3ea59a01))
|
||||
- Document PerBrowser options for entrypoints (#2304) ([#2403](https://github.com/wxt-dev/wxt/pull/2403))
|
||||
- Show Edge Add-ons in showcase ([#2452](https://github.com/wxt-dev/wxt/pull/2452))
|
||||
- Don't underline the comma when hovering over showcase item store links ([#2454](https://github.com/wxt-dev/wxt/pull/2454))
|
||||
- Fix `undefined` issue for `ExampleSearch.vue` ([#2370](https://github.com/wxt-dev/wxt/pull/2370))
|
||||
- Update extension-showcase.yml ([#2457](https://github.com/wxt-dev/wxt/pull/2457))
|
||||
- Added "NiceTab" Edge Addons (edgeId) to extension showcase ([#2455](https://github.com/wxt-dev/wxt/pull/2455))
|
||||
- Prioritize Bun in package manager options ([#2425](https://github.com/wxt-dev/wxt/pull/2425))
|
||||
- Update BlogLayout.vue `useData` to correctly type ([#2369](https://github.com/wxt-dev/wxt/pull/2369))
|
||||
- Revert #2380 - locationWatcher ([#2416](https://github.com/wxt-dev/wxt/pull/2416))
|
||||
- Added "Teams Chat Exporter" Edge Addons (edgeId) to extension showcase ([#2472](https://github.com/wxt-dev/wxt/pull/2472))
|
||||
- Cleanup the "extension APIs" page ([#2473](https://github.com/wxt-dev/wxt/pull/2473))
|
||||
- Add MindSnap to showcase ([#2499](https://github.com/wxt-dev/wxt/pull/2499))
|
||||
- Use consola's fancy reporter in init demo GIF ([#2485](https://github.com/wxt-dev/wxt/pull/2485))
|
||||
- Update `wxt init` GIF ([`13be7c5`](https://github.com/wxt-dev/wxt/commit/13be7c5bfdedc6660fc799ded6d868736dffcb86))
|
||||
- Update `wxt init` GIF ([`299b0ad`](https://github.com/wxt-dev/wxt/commit/299b0add803caab65f707ab73a677fc92f8e3379))
|
||||
- Cleanup v0.21 migration guide ([`885f8f0`](https://github.com/wxt-dev/wxt/commit/885f8f0b76d8daa635957edcd0783cb3b2a41ade))
|
||||
- Finalize migration guide for wxt v0.21 ([#2516](https://github.com/wxt-dev/wxt/pull/2516))
|
||||
- Add section about install footprint ([`d8a86e7`](https://github.com/wxt-dev/wxt/commit/d8a86e76336be263271673028ee7677efeecf905))
|
||||
|
||||
### 🏡 Chore
|
||||
|
||||
- Skip package manager tests when binaries are missing ([#2441](https://github.com/wxt-dev/wxt/pull/2441))
|
||||
- **deps**: Bump actions/setup-go from 6.4.0 to 6.5.0 ([#2432](https://github.com/wxt-dev/wxt/pull/2432))
|
||||
- Bump minimum supported Node version to >=22 ([`008f5a6`](https://github.com/wxt-dev/wxt/commit/008f5a66c9eb9e01a3dd1db0545e362254641089))
|
||||
- **deps**: Remove `esbuild` dependency ([#2506](https://github.com/wxt-dev/wxt/pull/2506))
|
||||
- Upgrade `@webext-core/isolated-element` v1 → v3 ([#2098](https://github.com/wxt-dev/wxt/pull/2098))
|
||||
- Remove deprecated APIs ([#2488](https://github.com/wxt-dev/wxt/pull/2488))
|
||||
- **deps**: Upgrade major dependencies ([#2508](https://github.com/wxt-dev/wxt/pull/2508))
|
||||
|
||||
### 🤖 CI
|
||||
|
||||
- Fix VHS action ([#2459](https://github.com/wxt-dev/wxt/pull/2459))
|
||||
- Use `@aklinker1/zero-changelog` for release notes ([#2515](https://github.com/wxt-dev/wxt/pull/2515))
|
||||
|
||||
### ⚠️ Breaking Changes
|
||||
|
||||
- Add `{{modeSuffix}}` to zip templates and update defaults
|
||||
- Change default behavior of `getUnimportEslintOptions` true flag
|
||||
- New template variable `{{versionName}}` and change of the behaviour of `{{version}}`
|
||||
- Make `web-ext` a peer dependency
|
||||
- Remove `url:` import feature
|
||||
- **zip**: Make `includeSources`/`excludeSources` follow standard allowlist behavior
|
||||
- [#2511](https://github.com/wxt-dev/wxt/pull/2511): If your script needs to return a value, like for `browser.scripting.executeScript`, set `globalName: true` to maintain the old behavior.
|
||||
- [#2512](https://github.com/wxt-dev/wxt/pull/2512): Updates `.wxt/tsconfig.json` defaults to latest recommended settings for vite projects and requires Typescript 5.4 or later. See #2512 for details on what compiler options were changed.
|
||||
- Move to module-runner
|
||||
- Bump minimum supported Node version to >=22
|
||||
- Upgrade `@webext-core/isolated-element` v1 → v3
|
||||
- Remove deprecated APIs
|
||||
- **deps**: Upgrade major dependencies
|
||||
|
||||
### ❤️ Contributors
|
||||
|
||||
- [@z1lV3r](https://github.com/z1lV3r)
|
||||
- Peter Wong <www121ppp@gmail.com>
|
||||
- wangpeng618 <wangpeng618@jd.com>
|
||||
- Thribhuvan <thribhuvan003@gmail.com>
|
||||
- ТΞNSΛI <tensai@gmx.net>
|
||||
- silverfish2525 <silverfish25@proton.me>
|
||||
- [@PatrykKuniczak](https://github.com/PatrykKuniczak)
|
||||
- [@nishu-murmu](https://github.com/nishu-murmu)
|
||||
- Nazım Gediz Aydındoğmuş <nga@hotmail.com.tr>
|
||||
- Kai Gritun <kaigritun@gmail.com>
|
||||
- Kai Gritun <kai@kaigritun.com>
|
||||
- [@github-actions[bot]](https://github.com/github-actions[bot])
|
||||
- [@ded-furby](https://github.com/ded-furby)
|
||||
- [@dashitongzhi](https://github.com/dashitongzhi)
|
||||
- [@cookesan](https://github.com/cookesan)
|
||||
- Shubhrajit Sadhukhan <champa.281982@gmail.com>
|
||||
- BlazerYoo <blazeryoo1921@gmail.com>
|
||||
- [@aklinker1](https://github.com/aklinker1)
|
||||
- [@lishaduck](https://github.com/lishaduck)
|
||||
- [@nnthanh01061999](https://github.com/nnthanh01061999)
|
||||
- [@cookesan](https://github.com/cookesan)
|
||||
- [@smashedr](https://github.com/smashedr)
|
||||
- [@dependabot[bot]](https://github.com/dependabot[bot])
|
||||
- [@ded-furby](https://github.com/ded-furby)
|
||||
- [@ZerGo0](https://github.com/ZerGo0)
|
||||
- [@LUIDevo](https://github.com/LUIDevo)
|
||||
- [@dashitongzhi](https://github.com/dashitongzhi)
|
||||
- [@fkatsuhiro](https://github.com/fkatsuhiro)
|
||||
|
||||
## v0.20.27
|
||||
|
||||
[compare changes](https://github.com/wxt-dev/wxt/compare/wxt-v0.20.26...wxt-v0.20.27)
|
||||
@@ -3697,4 +3841,4 @@ Initial release of WXT. Full support for production builds and initial toolkit f
|
||||
### 🤖 CI
|
||||
|
||||
- Create validation workflow ([#12](https://github.com/wxt-dev/wxt/pull/12))
|
||||
- Create release workflow ([#13](https://github.com/wxt-dev/wxt/pull/13))
|
||||
- Create release workflow ([#13](https://github.com/wxt-dev/wxt/pull/13))
|
||||
|
||||
@@ -54,7 +54,6 @@ Or see the [installation guide](https://wxt.dev/guide/installation.html) to get
|
||||
- 📦 [Module system](https://wxt.dev/guide/essentials/wxt-modules.html#overview) for reusing code between extensions
|
||||
- 🖍️ Quickly bootstrap a new project
|
||||
- 📏 Bundle analysis
|
||||
- ⬇️ Download and bundle remote URL imports
|
||||
|
||||
## Sponsors
|
||||
|
||||
|
||||
@@ -119,8 +119,8 @@ export default {
|
||||
"
|
||||
`;
|
||||
|
||||
exports[`Auto Imports > eslintrc > "enabled: true" should output a JSON config file compatible with ESlint 8 1`] = `
|
||||
".wxt/eslintrc-auto-import.json
|
||||
exports[`Auto Imports > eslintrc > "enabled: true" should output a JSON config file compatible with ESlint of package.json 1`] = `
|
||||
".wxt/eslint-auto-imports.mjs
|
||||
----------------------------------------
|
||||
{
|
||||
"globals": {
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
import { describe, it, expect, beforeEach, vi } from 'vitest';
|
||||
import { TestProject } from '../utils';
|
||||
import { resetBundleIncrement } from '../../src/core/builders/vite/plugins';
|
||||
import open from 'open';
|
||||
import open from 'tiny-open';
|
||||
|
||||
vi.mock('open');
|
||||
vi.mock('tiny-open');
|
||||
const openMock = vi.mocked(open);
|
||||
|
||||
vi.mock('ci-info', () => ({
|
||||
|
||||
@@ -28,7 +28,7 @@ describe('Auto Imports', () => {
|
||||
const defineContentScript: typeof import('wxt/utils/define-content-script').defineContentScript
|
||||
const defineUnlistedScript: typeof import('wxt/utils/define-unlisted-script').defineUnlistedScript
|
||||
const defineWxtPlugin: typeof import('wxt/utils/define-wxt-plugin').defineWxtPlugin
|
||||
const fakeBrowser: typeof import('wxt/testing').fakeBrowser
|
||||
const fakeBrowser: typeof import('wxt/testing/fake-browser').fakeBrowser
|
||||
const getAppConfig: typeof import('wxt/utils/app-config').getAppConfig
|
||||
const injectScript: typeof import('wxt/utils/inject-script').injectScript
|
||||
const storage: typeof import('wxt/utils/storage').storage
|
||||
@@ -124,7 +124,7 @@ describe('Auto Imports', () => {
|
||||
export { defineWxtPlugin } from 'wxt/utils/define-wxt-plugin';
|
||||
export { injectScript, ScriptPublicPath, InjectScriptOptions } from 'wxt/utils/inject-script';
|
||||
export { InvalidMatchPattern, MatchPattern } from 'wxt/utils/match-patterns';
|
||||
export { fakeBrowser } from 'wxt/testing';
|
||||
export { fakeBrowser } from 'wxt/testing/fake-browser';
|
||||
export { startOfDay } from '../utils/time';
|
||||
}
|
||||
"
|
||||
@@ -209,7 +209,7 @@ describe('Auto Imports', () => {
|
||||
export { defineWxtPlugin } from 'wxt/utils/define-wxt-plugin';
|
||||
export { injectScript, ScriptPublicPath, InjectScriptOptions } from 'wxt/utils/inject-script';
|
||||
export { InvalidMatchPattern, MatchPattern } from 'wxt/utils/match-patterns';
|
||||
export { fakeBrowser } from 'wxt/testing';
|
||||
export { fakeBrowser } from 'wxt/testing/fake-browser';
|
||||
}
|
||||
"
|
||||
`);
|
||||
@@ -217,7 +217,7 @@ describe('Auto Imports', () => {
|
||||
});
|
||||
|
||||
describe('eslintrc', () => {
|
||||
it('"enabled: true" should output a JSON config file compatible with ESlint 8', async () => {
|
||||
it('"enabled: true" should output a JSON config file compatible with ESlint of package.json', async () => {
|
||||
const project = new TestProject();
|
||||
project.addFile('entrypoints/popup.html', `<html></html>`);
|
||||
|
||||
@@ -230,7 +230,7 @@ describe('Auto Imports', () => {
|
||||
});
|
||||
|
||||
expect(
|
||||
await project.serializeFile('.wxt/eslintrc-auto-import.json'),
|
||||
await project.serializeFile('.wxt/eslint-auto-imports.mjs'),
|
||||
).toMatchSnapshot();
|
||||
});
|
||||
|
||||
|
||||
@@ -10,7 +10,7 @@ describe('Dev Mode', () => {
|
||||
);
|
||||
|
||||
const server = await project.startServer({
|
||||
runner: {
|
||||
webExt: {
|
||||
disabled: true,
|
||||
},
|
||||
});
|
||||
@@ -30,7 +30,7 @@ describe('Dev Mode', () => {
|
||||
);
|
||||
|
||||
const server = await project.startServer({
|
||||
runner: { disabled: true },
|
||||
webExt: { disabled: true },
|
||||
dev: { server: { port: 4400 } },
|
||||
});
|
||||
try {
|
||||
@@ -51,7 +51,7 @@ describe('Dev Mode', () => {
|
||||
);
|
||||
|
||||
const server = await project.startServer({
|
||||
runner: { disabled: true },
|
||||
webExt: { disabled: true },
|
||||
dev: { server: { port } },
|
||||
});
|
||||
try {
|
||||
@@ -76,7 +76,7 @@ describe('Dev Mode', () => {
|
||||
try {
|
||||
await expect(
|
||||
project.startServer({
|
||||
runner: { disabled: true },
|
||||
webExt: { disabled: true },
|
||||
dev: { server: { port, strictPort: true } },
|
||||
}),
|
||||
).rejects.toThrow();
|
||||
|
||||
@@ -1,15 +0,0 @@
|
||||
import { test, expect } from 'vitest';
|
||||
import spawn from 'nano-spawn';
|
||||
|
||||
// Tests to ensure the total size of the WXT module is as small as possible
|
||||
// https://pkg-size.dev/wxt
|
||||
|
||||
test('Only one version of esbuild should be installed (each version is ~20mb of node_modules)', async () => {
|
||||
const { stdout } = await spawn('bun', ['why', 'esbuild']);
|
||||
|
||||
// This text represents the wxt package being responsible for a version of esbuild?
|
||||
// If this doesn't work, we'll need to find a better way to check this.
|
||||
const count = stdout.match(/\n [└├]─ wxt@workspace/g)?.length || 0;
|
||||
|
||||
expect(count).toBe(1);
|
||||
});
|
||||
@@ -506,7 +506,7 @@ describe('Output Directory Structure', () => {
|
||||
});
|
||||
|
||||
describe('globalName option', () => {
|
||||
it('generates an IIFE with a default name', async () => {
|
||||
it('does not generate a IIFE return variable by default', async () => {
|
||||
const project = new TestProject();
|
||||
project.addFile(
|
||||
'entrypoints/content.js',
|
||||
@@ -518,6 +518,25 @@ describe('Output Directory Structure', () => {
|
||||
|
||||
await project.build({ vite: () => ({ build: { minify: false } }) });
|
||||
|
||||
const output = await project.serializeFile(
|
||||
'.output/chrome-mv3/content-scripts/content.js',
|
||||
);
|
||||
expect(output.includes('var content')).toBe(false);
|
||||
});
|
||||
|
||||
it('does generates the IIFE name based on the entrypoint name when true', async () => {
|
||||
const project = new TestProject();
|
||||
project.addFile(
|
||||
'entrypoints/content.js',
|
||||
`export default defineContentScript({
|
||||
globalName: true,
|
||||
matches: ["*://*/*"],
|
||||
main() {},
|
||||
})`,
|
||||
);
|
||||
|
||||
await project.build({ vite: () => ({ build: { minify: false } }) });
|
||||
|
||||
const output = await project.serializeFile(
|
||||
'.output/chrome-mv3/content-scripts/content.js',
|
||||
);
|
||||
|
||||
@@ -1,26 +0,0 @@
|
||||
import { describe, it, expect } from 'vitest';
|
||||
import { TestProject } from '../utils';
|
||||
|
||||
describe('Remote Code', () => {
|
||||
it('should download "url:*" modules and include them in the final bundle', async () => {
|
||||
const url = 'https://cdn.jsdelivr.net/npm/lodash@4.17.21/lodash.min.js';
|
||||
const project = new TestProject();
|
||||
project.addFile(
|
||||
'entrypoints/popup.ts',
|
||||
`import "url:${url}"
|
||||
export default defineUnlistedScript(() => {})`,
|
||||
);
|
||||
|
||||
await project.build();
|
||||
|
||||
const output = await project.serializeFile('.output/chrome-mv3/popup.js');
|
||||
expect(output).toContain(
|
||||
// Some text that will hopefully be in future versions of this script
|
||||
'__lodash_placeholder__',
|
||||
);
|
||||
expect(output).not.toContain(url);
|
||||
expect(
|
||||
await project.pathExists(`.wxt/cache/${encodeURIComponent(url)}`),
|
||||
).toBe(true);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,157 @@
|
||||
import { expect, describe, vi, it, beforeEach } from 'vitest';
|
||||
import { ExtensionRunner } from '../../src';
|
||||
import { createSafariRunner } from '../../src/core/runners/safari';
|
||||
import { createManualRunner } from '../../src/core/runners/manual';
|
||||
import { createWebExtRunner } from '../../src/core/runners/web-ext';
|
||||
import { createWslRunner } from '../../src/core/runners/wsl';
|
||||
import { TestProject } from '../utils';
|
||||
import { wxt } from '../../src/core/wxt';
|
||||
|
||||
// Globals for modifying mock behaviors
|
||||
|
||||
let isWsl = false;
|
||||
let importWebExtRunnerError: Error | undefined = undefined;
|
||||
|
||||
// Mock runners to create constants for checking equality
|
||||
|
||||
type TestExtensionRunner = { name: string } & ExtensionRunner;
|
||||
|
||||
function createMockExtensionRunner(name: string): TestExtensionRunner {
|
||||
return {
|
||||
name,
|
||||
closeBrowser: () => Promise.resolve(),
|
||||
openBrowser: () => Promise.resolve(),
|
||||
};
|
||||
}
|
||||
|
||||
vi.mock('../../src/core/runners/safari', () => {
|
||||
const runner = createMockExtensionRunner('safari');
|
||||
return { createSafariRunner: () => runner };
|
||||
});
|
||||
const safariRunner = createSafariRunner();
|
||||
|
||||
vi.mock('../../src/core/runners/manual', () => {
|
||||
const runner = createMockExtensionRunner('manual');
|
||||
return { createManualRunner: () => runner };
|
||||
});
|
||||
const manualRunner = createManualRunner();
|
||||
|
||||
vi.mock('../../src/core/runners/web-ext', () => {
|
||||
const runner = createMockExtensionRunner('web-ext');
|
||||
return {
|
||||
createWebExtRunner: () => {
|
||||
if (!importWebExtRunnerError) return runner;
|
||||
else throw importWebExtRunnerError;
|
||||
},
|
||||
};
|
||||
});
|
||||
const webExtRunner = createWebExtRunner();
|
||||
|
||||
vi.mock('../../src/core/runners/wsl', () => {
|
||||
const runner = createMockExtensionRunner('wsl');
|
||||
return { createWslRunner: () => runner };
|
||||
});
|
||||
const wslRunner = createWslRunner();
|
||||
|
||||
// Other mocks
|
||||
|
||||
vi.mock('is-wsl', () => ({
|
||||
get default() {
|
||||
return isWsl;
|
||||
},
|
||||
}));
|
||||
|
||||
/** Imitate a real module not found error - needs the correct `code` property. */
|
||||
class ModuleNotFoundError extends Error {
|
||||
code = 'ERR_MODULE_NOT_FOUND';
|
||||
|
||||
constructor(mod: string) {
|
||||
super(`Cannot find package '${mod}' imported from ...`);
|
||||
this.name = 'ModuleNotFoundError';
|
||||
}
|
||||
}
|
||||
|
||||
describe('Runners', () => {
|
||||
beforeEach(() => {
|
||||
isWsl = false;
|
||||
importWebExtRunnerError = undefined;
|
||||
});
|
||||
|
||||
describe('build', () => {
|
||||
const command = 'build';
|
||||
|
||||
it('should use the manual runner as a placeholder since the runner is not used during builds', async () => {
|
||||
await TestProject.simple().registerWxt(command);
|
||||
|
||||
expect(wxt.config.runner).toBe(manualRunner);
|
||||
});
|
||||
});
|
||||
|
||||
describe('dev', () => {
|
||||
const command = 'serve';
|
||||
|
||||
describe('inside WSL', () => {
|
||||
beforeEach(() => {
|
||||
isWsl = true;
|
||||
});
|
||||
|
||||
it('should use the WSL runner', async () => {
|
||||
await TestProject.simple().registerWxt(command);
|
||||
|
||||
expect(wxt.config.runner).toBe(wslRunner);
|
||||
});
|
||||
});
|
||||
|
||||
describe('web-ext is installed', () => {
|
||||
it('should use the web-ext runner', async () => {
|
||||
await TestProject.simple().registerWxt(command);
|
||||
|
||||
expect(wxt.config.runner).toBe(webExtRunner);
|
||||
});
|
||||
|
||||
describe('disabled', () => {
|
||||
it('should use the manual runner', async () => {
|
||||
await TestProject.simple().registerWxt(command, {
|
||||
webExt: { disabled: true },
|
||||
});
|
||||
|
||||
expect(wxt.config.runner).toBe(manualRunner);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe('web-ext is not installed', () => {
|
||||
beforeEach(() => {
|
||||
importWebExtRunnerError = new ModuleNotFoundError('web-ext');
|
||||
});
|
||||
|
||||
it('should use the manual runner', async () => {
|
||||
await TestProject.simple().registerWxt(command);
|
||||
|
||||
expect(wxt.config.runner).toBe(manualRunner);
|
||||
});
|
||||
});
|
||||
|
||||
describe('some other error when importing the web-ext runner', () => {
|
||||
beforeEach(() => {
|
||||
importWebExtRunnerError = Error('test');
|
||||
});
|
||||
|
||||
it('should throw the error', async () => {
|
||||
await expect(TestProject.simple().registerWxt(command)).rejects.toThrow(
|
||||
importWebExtRunnerError,
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe('targeting safari', () => {
|
||||
it('should use the safari runner', async () => {
|
||||
await TestProject.simple().registerWxt(command, {
|
||||
browser: 'safari',
|
||||
});
|
||||
|
||||
expect(wxt.config.runner).toBe(safariRunner);
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -324,15 +324,23 @@ describe('TypeScript Project', () => {
|
||||
----------------------------------------
|
||||
{
|
||||
"compilerOptions": {
|
||||
"lib": [
|
||||
"ESNext",
|
||||
"DOM",
|
||||
"DOM.Iterable"
|
||||
],
|
||||
"target": "ESNext",
|
||||
"module": "ESNext",
|
||||
"module": "Preserve",
|
||||
"moduleDetection": "force",
|
||||
"moduleResolution": "Bundler",
|
||||
"allowImportingTsExtensions": true,
|
||||
"verbatimModuleSyntax": true,
|
||||
"noEmit": true,
|
||||
"esModuleInterop": true,
|
||||
"forceConsistentCasingInFileNames": true,
|
||||
"resolveJsonModule": true,
|
||||
"strict": true,
|
||||
"skipLibCheck": true,
|
||||
"noFallthroughCasesInSwitch": true,
|
||||
"noUncheckedIndexedAccess": true,
|
||||
"noImplicitOverride": true,
|
||||
"paths": {
|
||||
"@": [
|
||||
".."
|
||||
@@ -406,15 +414,23 @@ describe('TypeScript Project', () => {
|
||||
----------------------------------------
|
||||
{
|
||||
"compilerOptions": {
|
||||
"lib": [
|
||||
"ESNext",
|
||||
"DOM",
|
||||
"DOM.Iterable"
|
||||
],
|
||||
"target": "ESNext",
|
||||
"module": "ESNext",
|
||||
"module": "Preserve",
|
||||
"moduleDetection": "force",
|
||||
"moduleResolution": "Bundler",
|
||||
"allowImportingTsExtensions": true,
|
||||
"verbatimModuleSyntax": true,
|
||||
"noEmit": true,
|
||||
"esModuleInterop": true,
|
||||
"forceConsistentCasingInFileNames": true,
|
||||
"resolveJsonModule": true,
|
||||
"strict": true,
|
||||
"skipLibCheck": true,
|
||||
"noFallthroughCasesInSwitch": true,
|
||||
"noUncheckedIndexedAccess": true,
|
||||
"noImplicitOverride": true,
|
||||
"paths": {
|
||||
"@": [
|
||||
"../src"
|
||||
@@ -473,15 +489,23 @@ describe('TypeScript Project', () => {
|
||||
----------------------------------------
|
||||
{
|
||||
"compilerOptions": {
|
||||
"lib": [
|
||||
"ESNext",
|
||||
"DOM",
|
||||
"DOM.Iterable"
|
||||
],
|
||||
"target": "ESNext",
|
||||
"module": "ESNext",
|
||||
"module": "Preserve",
|
||||
"moduleDetection": "force",
|
||||
"moduleResolution": "Bundler",
|
||||
"allowImportingTsExtensions": true,
|
||||
"verbatimModuleSyntax": true,
|
||||
"noEmit": true,
|
||||
"esModuleInterop": true,
|
||||
"forceConsistentCasingInFileNames": true,
|
||||
"resolveJsonModule": true,
|
||||
"strict": true,
|
||||
"skipLibCheck": true,
|
||||
"noFallthroughCasesInSwitch": true,
|
||||
"noUncheckedIndexedAccess": true,
|
||||
"noImplicitOverride": true,
|
||||
"paths": {
|
||||
"example": [
|
||||
"../example"
|
||||
|
||||
@@ -64,21 +64,23 @@ describe('Zipping', () => {
|
||||
it('should correctly apply template variables for zip file names based on provided config', async () => {
|
||||
const project = new TestProject({
|
||||
name: 'test',
|
||||
version: '1.0.0',
|
||||
version: '1.0.0-beta.1',
|
||||
});
|
||||
project.addFile(
|
||||
'entrypoints/background.ts',
|
||||
'export default defineBackground(() => {});',
|
||||
);
|
||||
const artifactZip = '.output/test-1.0.0-firefox-development.zip';
|
||||
const sourcesZip = '.output/test-1.0.0-development-sources.zip';
|
||||
const artifactZip = '.output/test-1.0.0-beta.1-firefox-dev.zip';
|
||||
const sourcesZip = '.output/test-1.0.0-beta.1-sources-dev.zip';
|
||||
|
||||
await project.zip({
|
||||
browser: 'firefox',
|
||||
mode: 'development',
|
||||
zip: {
|
||||
artifactTemplate: '{{name}}-{{version}}-{{browser}}-{{mode}}.zip',
|
||||
sourcesTemplate: '{{name}}-{{version}}-{{mode}}-sources.zip',
|
||||
artifactTemplate:
|
||||
'{{name}}-{{packageVersion}}-{{browser}}{{modeSuffix}}.zip',
|
||||
sourcesTemplate:
|
||||
'{{name}}-{{packageVersion}}-sources{{modeSuffix}}.zip',
|
||||
},
|
||||
});
|
||||
|
||||
@@ -108,7 +110,7 @@ describe('Zipping', () => {
|
||||
expect(await project.pathExists(unzipDir, '.hidden-dir/file')).toBe(false);
|
||||
});
|
||||
|
||||
it('should not zip files inside hidden directories if only the directory is specified', async () => {
|
||||
it('should zip hidden files and directories when dotSources is enabled', async () => {
|
||||
const project = new TestProject({
|
||||
name: 'test',
|
||||
version: '1.0.0',
|
||||
@@ -125,17 +127,17 @@ describe('Zipping', () => {
|
||||
await project.zip({
|
||||
browser: 'firefox',
|
||||
zip: {
|
||||
includeSources: ['.hidden-dir'],
|
||||
dotSources: true,
|
||||
},
|
||||
});
|
||||
await extract(sourcesZip, { dir: unzipDir });
|
||||
expect(await project.pathExists(unzipDir, '.hidden-dir/file')).toBe(false);
|
||||
expect(await project.pathExists(unzipDir, '.hidden-dir/file')).toBe(true);
|
||||
expect(await project.pathExists(unzipDir, '.hidden-dir/nested/file')).toBe(
|
||||
false,
|
||||
true,
|
||||
);
|
||||
});
|
||||
|
||||
it('should allow zipping hidden files into sources when explicitly listed', async () => {
|
||||
it('should allow ignoring some hidden files', async () => {
|
||||
const project = new TestProject({
|
||||
name: 'test',
|
||||
version: '1.0.0',
|
||||
@@ -154,20 +156,57 @@ describe('Zipping', () => {
|
||||
await project.zip({
|
||||
browser: 'firefox',
|
||||
zip: {
|
||||
includeSources: ['.env', '.hidden-dir/file', '.hidden-dir/nested/**'],
|
||||
dotSources: true,
|
||||
excludeSources: ['.hidden-dir/nested'],
|
||||
},
|
||||
});
|
||||
await extract(sourcesZip, { dir: unzipDir });
|
||||
expect(await project.pathExists(unzipDir, '.env')).toBe(true);
|
||||
expect(await project.pathExists(unzipDir, '.hidden-dir/file')).toBe(true);
|
||||
expect(await project.pathExists(unzipDir, '.hidden-dir/nested/file1')).toBe(
|
||||
true,
|
||||
false,
|
||||
);
|
||||
expect(await project.pathExists(unzipDir, '.hidden-dir/nested/file2')).toBe(
|
||||
true,
|
||||
false,
|
||||
);
|
||||
});
|
||||
|
||||
it('should not include all files when includeSources is provided', async () => {
|
||||
const project = new TestProject({
|
||||
name: 'test',
|
||||
version: '1.0.0',
|
||||
});
|
||||
project.addFile(
|
||||
'entrypoints/background.ts',
|
||||
'export default defineBackground(() => {});',
|
||||
);
|
||||
project.addFile('utils/example.ts', 'export const x = 1;');
|
||||
project.addFile('secrets/api-key.txt', 'supersecret');
|
||||
project.addFile('cache/data.json', '{}');
|
||||
const unzipDir = project.resolvePath('.output/test-1.0.0-sources');
|
||||
const sourcesZip = project.resolvePath('.output/test-1.0.0-sources.zip');
|
||||
|
||||
await project.zip({
|
||||
browser: 'firefox',
|
||||
zip: {
|
||||
includeSources: ['entrypoints/**', 'utils/**'],
|
||||
},
|
||||
});
|
||||
await extract(sourcesZip, { dir: unzipDir });
|
||||
|
||||
// Included files should be present
|
||||
expect(
|
||||
await project.pathExists(unzipDir, 'entrypoints/background.ts'),
|
||||
).toBe(true);
|
||||
expect(await project.pathExists(unzipDir, 'utils/example.ts')).toBe(true);
|
||||
|
||||
// Non-included files should NOT be present (allowlist behavior)
|
||||
expect(await project.pathExists(unzipDir, 'secrets/api-key.txt')).toBe(
|
||||
false,
|
||||
);
|
||||
expect(await project.pathExists(unzipDir, 'cache/data.json')).toBe(false);
|
||||
});
|
||||
|
||||
it('should exclude skipped entrypoints from respective browser sources zip', async () => {
|
||||
const project = new TestProject({
|
||||
name: 'test',
|
||||
@@ -186,8 +225,7 @@ describe('Zipping', () => {
|
||||
`export default defineContentScript({
|
||||
matches: ['*://*/*'],
|
||||
main(ctx) {},
|
||||
});
|
||||
`,
|
||||
});`,
|
||||
);
|
||||
const unzipDir = project.resolvePath('.output/test-1.0.0-sources');
|
||||
const sourcesZip = project.resolvePath('.output/test-1.0.0-sources.zip');
|
||||
@@ -287,7 +325,8 @@ describe('Zipping', () => {
|
||||
|
||||
await project.zip({
|
||||
zip: {
|
||||
exclude: ['**/*.json', '!manifest.json'],
|
||||
// Exclude all JSON files except for ones named `manifest.json`
|
||||
exclude: ['**/!(manifest).json'],
|
||||
},
|
||||
});
|
||||
|
||||
|
||||
@@ -7,6 +7,7 @@ import { glob } from 'tinyglobby';
|
||||
import {
|
||||
InlineConfig,
|
||||
UserConfig,
|
||||
WxtCommand,
|
||||
build,
|
||||
createServer,
|
||||
prepare,
|
||||
@@ -14,6 +15,7 @@ import {
|
||||
} from '../src';
|
||||
import { normalizePath } from '../src/core/utils';
|
||||
import { pathExists, readJson } from '../src/core/utils/fs';
|
||||
import { registerWxt } from '../src/core/wxt';
|
||||
|
||||
// Run "bun wxt" to use the "wxt" dev script, not the "wxt" binary from the
|
||||
// wxt package. This uses the TS files instead of the compiled JS package
|
||||
@@ -23,6 +25,18 @@ export const WXT_PACKAGE_DIR = resolve(__dirname, '..');
|
||||
export const E2E_DIR = resolve(WXT_PACKAGE_DIR, 'e2e');
|
||||
|
||||
export class TestProject {
|
||||
/**
|
||||
* Create the simplest WXT project possible: one blank popup entrypoint, no
|
||||
* custom config.
|
||||
*/
|
||||
static simple(): TestProject {
|
||||
const project = new TestProject();
|
||||
|
||||
project.addFile('entrypoints/popup.html', '<html></html>');
|
||||
|
||||
return project;
|
||||
}
|
||||
|
||||
files: Array<[string, string]> = [];
|
||||
config: UserConfig | undefined;
|
||||
readonly root: string;
|
||||
@@ -84,6 +98,15 @@ export class TestProject {
|
||||
return this.resolvePath(filename);
|
||||
}
|
||||
|
||||
/**
|
||||
* Register the global `wxt` object for this project. After calling, you can
|
||||
* import `wxt` like normal and inspect it.
|
||||
*/
|
||||
async registerWxt(command: WxtCommand, config: InlineConfig = {}) {
|
||||
await this.writeProjectToDisk();
|
||||
await registerWxt(command, { ...config, root: this.root });
|
||||
}
|
||||
|
||||
async prepare(config: InlineConfig = {}) {
|
||||
await this.writeProjectToDisk();
|
||||
await prepare({ ...config, root: this.root });
|
||||
|
||||
+24
-23
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"name": "wxt",
|
||||
"type": "module",
|
||||
"version": "0.20.27",
|
||||
"version": "0.21.2",
|
||||
"description": "⚡ Next-gen Web Extension Framework",
|
||||
"license": "MIT",
|
||||
"scripts": {
|
||||
@@ -12,31 +12,28 @@
|
||||
"check:tsc-virtual": "tsc --noEmit -p src/virtual",
|
||||
"test": "buildc --deps-only -- vitest",
|
||||
"test:coverage": "bun run test run --coverage",
|
||||
"sync-releases": "pnpx changelogen@latest gh release",
|
||||
"prepack": "bun run build"
|
||||
},
|
||||
"dependencies": {
|
||||
"@1natsu/wait-element": "^4.1.2",
|
||||
"@aklinker1/rollup-plugin-visualizer": "5.12.0",
|
||||
"@webext-core/fake-browser": "^1.3.4",
|
||||
"@webext-core/isolated-element": "^1.1.3",
|
||||
"@webext-core/match-patterns": "^1.0.3",
|
||||
"@topcli/prompts": "^4.0.0",
|
||||
"@webext-core/fake-browser": "^2.0.1",
|
||||
"@webext-core/isolated-element": "^1.1.3 || ^2 || ^3",
|
||||
"@webext-core/match-patterns": "^2.0.0",
|
||||
"@wxt-dev/browser": "workspace:^",
|
||||
"@wxt-dev/storage": "workspace:^1.0.0",
|
||||
"async-mutex": "^0.5.0",
|
||||
"c12": "^3.3.4",
|
||||
"cac": "^6.7.14 || ^7.0.0",
|
||||
"chokidar": "^5.0.0",
|
||||
"ci-info": "^4.4.0",
|
||||
"consola": "^3.4.2",
|
||||
"defu": "^6.1.4",
|
||||
"dotenv-expand": "^12.0.3",
|
||||
"esbuild": "^0.27.1",
|
||||
"dotenv-expand": "^13.0.0",
|
||||
"filesize": "^11.0.17",
|
||||
"get-port-please": "^3.2.0",
|
||||
"giget": "^1.2.3 || ^2.0.0 || ^3.0.0",
|
||||
"hookable": "^6.1.0",
|
||||
"import-meta-resolve": "^4.2.0",
|
||||
"is-wsl": "^3.1.1",
|
||||
"json5": "^2.2.3",
|
||||
"jszip": "^3.10.1",
|
||||
@@ -47,23 +44,29 @@
|
||||
"normalize-path": "^3.0.0",
|
||||
"nypm": "^0.6.5",
|
||||
"ohash": "^2.0.11",
|
||||
"open": "^11.0.0",
|
||||
"picomatch": "^4.0.3",
|
||||
"prompts": "^2.4.2",
|
||||
"publish-browser-extension": "^2.3.0 || ^3.0.2 || ^4.0.5",
|
||||
"publish-browser-extension": "^5.1.0 || ^6.0.0",
|
||||
"scule": "^1.3.0",
|
||||
"superlock": "^1.3.2",
|
||||
"tiny-open": "^1.3.0",
|
||||
"tinyglobby": "^0.2.16",
|
||||
"unimport": "^3.13.1 || ^4.0.0 || ^5.0.0 || ^6.0.0",
|
||||
"vite": "^5.4.19 || ^6.3.4 || ^7.0.0 || ^8.0.0-0",
|
||||
"vite-node": "^3.2.4 || ^5.0.0 || ^6.0.0",
|
||||
"web-ext-run": "^0.2.4"
|
||||
"unimport": "^3.13.1 || ^4.0.0 || ^5.0.0 || ^6.0.0"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"eslint": "^8.57.0 || ^9.0.0 || ^10.0.0"
|
||||
"eslint": "^8.57.0 || ^9.0.0 || ^10.0.0",
|
||||
"vite": "^6.3.4 || ^7.0.0 || ^8.0.0-0",
|
||||
"web-ext": ">=9.2.0",
|
||||
"typescript": ">=5.4"
|
||||
},
|
||||
"peerDependenciesMeta": {
|
||||
"eslint": {
|
||||
"optional": true
|
||||
},
|
||||
"web-ext": {
|
||||
"optional": true
|
||||
},
|
||||
"typescript": {
|
||||
"optional": true
|
||||
}
|
||||
},
|
||||
"devDependencies": {
|
||||
@@ -83,8 +86,10 @@
|
||||
"publint": "catalog:",
|
||||
"tsdown": "catalog:",
|
||||
"typescript": "catalog:",
|
||||
"vite": "catalog:",
|
||||
"vitest": "catalog:",
|
||||
"vitest-plugin-random-seed": "catalog:"
|
||||
"vitest-plugin-random-seed": "catalog:",
|
||||
"web-ext": "^10.5.0"
|
||||
},
|
||||
"repository": {
|
||||
"type": "git",
|
||||
@@ -192,10 +197,6 @@
|
||||
"types": "./dist/testing/wxt-vitest-plugin.d.mts",
|
||||
"default": "./dist/testing/wxt-vitest-plugin.mjs"
|
||||
},
|
||||
"./testing": {
|
||||
"types": "./dist/testing/index.d.mts",
|
||||
"default": "./dist/testing/index.mjs"
|
||||
},
|
||||
"./vite-builder-env": {
|
||||
"types": "./dist/vite-builder-env.d.ts"
|
||||
},
|
||||
@@ -205,7 +206,7 @@
|
||||
}
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=20.12.0",
|
||||
"node": ">=22",
|
||||
"bun": ">=1.2.0"
|
||||
}
|
||||
}
|
||||
|
||||
Vendored
+2
-2
@@ -1,6 +1,6 @@
|
||||
// Custom TS definitions for non-TS packages
|
||||
|
||||
declare module 'web-ext-run' {
|
||||
declare module 'web-ext' {
|
||||
export interface WebExtRunInstance {
|
||||
reloadAllExtensions(): Promise<void>;
|
||||
exit(): Promise<void>;
|
||||
@@ -14,7 +14,7 @@ declare module 'web-ext-run' {
|
||||
export default webExt;
|
||||
}
|
||||
|
||||
declare module 'web-ext-run/util/logger' {
|
||||
declare module 'web-ext/util/logger' {
|
||||
// https://github.com/mozilla/web-ext/blob/e37e60a2738478f512f1255c537133321f301771/src/util/logger.js#L43
|
||||
export interface IConsoleStream {
|
||||
stopCapturing(): void;
|
||||
|
||||
@@ -0,0 +1,72 @@
|
||||
import { mkdir, mkdtemp, rm, stat, writeFile } from "node:fs/promises";
|
||||
import { tmpdir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
import { afterEach, beforeAll, describe, expect, it, vi } from "vitest";
|
||||
import { removeEmptyDirs } from "../index";
|
||||
|
||||
// `stat` is mocked (defaulting to the real implementation) so individual
|
||||
// tests can override it to simulate a file disappearing mid-walk - the race
|
||||
// this suite exists to cover (oleks/mcp-chrome#61).
|
||||
vi.mock("node:fs/promises", async (importOriginal) => {
|
||||
const actual = await importOriginal<typeof import("node:fs/promises")>();
|
||||
return { ...actual, stat: vi.fn(actual.stat) };
|
||||
});
|
||||
|
||||
const mockedStat = vi.mocked(stat);
|
||||
let realStat: typeof import("node:fs/promises").stat;
|
||||
|
||||
describe("removeEmptyDirs", () => {
|
||||
beforeAll(async () => {
|
||||
realStat = (
|
||||
await vi.importActual<typeof import("node:fs/promises")>(
|
||||
"node:fs/promises",
|
||||
)
|
||||
).stat;
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
mockedStat.mockImplementation(realStat);
|
||||
});
|
||||
|
||||
it("removes nested empty directories", async () => {
|
||||
const dir = await mkdtemp(join(tmpdir(), "wxt-remove-empty-dirs-"));
|
||||
try {
|
||||
await mkdir(join(dir, "a", "b"), { recursive: true });
|
||||
await writeFile(join(dir, "a", "keep.txt"), "x");
|
||||
|
||||
await removeEmptyDirs(dir);
|
||||
|
||||
await expect(realStat(join(dir, "a", "b"))).rejects.toThrow();
|
||||
await expect(realStat(join(dir, "a", "keep.txt"))).resolves.toBeDefined();
|
||||
} finally {
|
||||
await rm(dir, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
it("does not throw when a file disappears between readdir and stat (a concurrent plugin write, oleks/mcp-chrome#61)", async () => {
|
||||
const dir = await mkdtemp(join(tmpdir(), "wxt-remove-empty-dirs-"));
|
||||
try {
|
||||
await mkdir(join(dir, "inject-scripts"), { recursive: true });
|
||||
const raceyFile = join(dir, "inject-scripts", "recorder.js");
|
||||
await writeFile(raceyFile, "x");
|
||||
|
||||
mockedStat.mockImplementation((async (
|
||||
path: Parameters<typeof stat>[0],
|
||||
...args: unknown[]
|
||||
) => {
|
||||
if (path === raceyFile) {
|
||||
const err: NodeJS.ErrnoException = new Error(
|
||||
"ENOENT: no such file or directory",
|
||||
);
|
||||
err.code = "ENOENT";
|
||||
throw err;
|
||||
}
|
||||
return (realStat as (...a: unknown[]) => unknown)(path, ...args);
|
||||
}) as typeof stat);
|
||||
|
||||
await expect(removeEmptyDirs(dir)).resolves.not.toThrow();
|
||||
} finally {
|
||||
await rm(dir, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
});
|
||||
File diff suppressed because it is too large
Load Diff
@@ -1,36 +0,0 @@
|
||||
import type { Plugin } from 'vite';
|
||||
import type { ResolvedConfig } from '../../../../types';
|
||||
import { fetchCached } from '../../../utils/network';
|
||||
|
||||
/**
|
||||
* Downloads any URL imports, like Google Analytics, into virtual modules so
|
||||
* they are bundled with the extension instead of depending on remote code at
|
||||
* runtime.
|
||||
*
|
||||
* @example
|
||||
* import 'url:https://google-tagmanager.com/gtag?id=XYZ';
|
||||
*/
|
||||
export function download(config: ResolvedConfig): Plugin {
|
||||
return {
|
||||
name: 'wxt:download',
|
||||
enforce: 'pre',
|
||||
resolveId: {
|
||||
filter: {
|
||||
id: /^url:/,
|
||||
},
|
||||
handler(id) {
|
||||
return `\0${id}`;
|
||||
},
|
||||
},
|
||||
load: {
|
||||
filter: {
|
||||
//eslint-disable-next-line no-control-regex
|
||||
id: /^\x00url:/,
|
||||
},
|
||||
handler(id) {
|
||||
const url = id.replace('\0url:', '');
|
||||
return fetchCached(url, config);
|
||||
},
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -1,6 +1,5 @@
|
||||
export * from './devHtmlPrerender';
|
||||
export * from './devServerGlobals';
|
||||
export * from './download';
|
||||
export * from './resolveVirtualModules';
|
||||
export * from './tsconfigPaths';
|
||||
export * from './noopBackground';
|
||||
|
||||
@@ -22,7 +22,7 @@ export function removeEntrypointMainFunction(
|
||||
},
|
||||
handler(code) {
|
||||
const newCode = removeMainFunctionCode(code);
|
||||
config.logger.debug('vite-node transformed entrypoint', path);
|
||||
config.logger.debug('transformed entrypoint', path);
|
||||
config.logger.debug(`Original:\n---\n${code}\n---`);
|
||||
config.logger.debug(`Transformed:\n---\n${newCode.code}\n---`);
|
||||
return newCode;
|
||||
|
||||
@@ -13,24 +13,7 @@ import { styleText } from 'node:util';
|
||||
*
|
||||
* @param config Optional config that will override your `<root>/wxt.config.ts`.
|
||||
*/
|
||||
export async function clean(config?: InlineConfig): Promise<void>;
|
||||
/**
|
||||
* Remove generated/temp files from the directory.
|
||||
*
|
||||
* @deprecated
|
||||
* @example
|
||||
* await clean();
|
||||
*
|
||||
* @param root The directory to look for generated/temp files in. Defaults to
|
||||
* `process.cwd()`. Can be relative to `process.cwd()` or absolute.
|
||||
*/
|
||||
export async function clean(root?: string): Promise<void>;
|
||||
|
||||
export async function clean(config?: string | InlineConfig) {
|
||||
if (typeof config === 'string') {
|
||||
config = { root: config };
|
||||
}
|
||||
|
||||
export async function clean(config?: InlineConfig): Promise<void> {
|
||||
await registerWxt('build', config);
|
||||
wxt.logger.info('Cleaning Project');
|
||||
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
import chokidar from 'chokidar';
|
||||
import { InlineConfig, ServerInfo, WxtDevServer } from '../types';
|
||||
import { internalBuild } from './utils/building';
|
||||
import { createExtensionRunner } from './runners';
|
||||
import { deinitWxtModules, initWxtModules, registerWxt, wxt } from './wxt';
|
||||
import { unnormalizePath } from './utils/paths';
|
||||
import { createKeyboardShortcuts } from './keyboard-shortcuts';
|
||||
@@ -37,10 +36,7 @@ async function createServerInternal(): Promise<WxtDevServer> {
|
||||
return { host, port, origin };
|
||||
};
|
||||
|
||||
let [runner, builderServer] = await Promise.all([
|
||||
createExtensionRunner(),
|
||||
wxt.builder.createServer(getServerInfo()),
|
||||
]);
|
||||
let builderServer = await wxt.builder.createServer(getServerInfo());
|
||||
|
||||
// Used to track if modules need to be re-initialized
|
||||
let wasStopped = false;
|
||||
@@ -67,7 +63,6 @@ async function createServerInternal(): Promise<WxtDevServer> {
|
||||
async start() {
|
||||
if (wasStopped) {
|
||||
await wxt.reloadConfig();
|
||||
runner = await createExtensionRunner();
|
||||
builderServer = await wxt.builder.createServer(getServerInfo());
|
||||
await initWxtModules();
|
||||
}
|
||||
@@ -99,7 +94,7 @@ async function createServerInternal(): Promise<WxtDevServer> {
|
||||
async stop() {
|
||||
wasStopped = true;
|
||||
keyboardShortcuts.stop();
|
||||
await runner.closeBrowser?.();
|
||||
await wxt.config.runner.closeBrowser?.();
|
||||
await builderServer.close();
|
||||
await wxt.hooks.callHook('server:closed', wxt, server);
|
||||
|
||||
@@ -123,15 +118,14 @@ async function createServerInternal(): Promise<WxtDevServer> {
|
||||
server.ws.send('wxt:reload-extension');
|
||||
},
|
||||
async restartBrowser() {
|
||||
await runner.closeBrowser?.();
|
||||
await wxt.config.runner.closeBrowser?.();
|
||||
keyboardShortcuts.stop();
|
||||
await wxt.reloadConfig();
|
||||
runner = await createExtensionRunner();
|
||||
await runner.openBrowser();
|
||||
await wxt.config.runner.openBrowser();
|
||||
keyboardShortcuts.start();
|
||||
keyboardShortcuts.printHelp({
|
||||
canReopenBrowser:
|
||||
!wxt.config.runnerConfig.config.disabled && !!runner.canOpen?.(),
|
||||
!wxt.config.webExt.config.disabled && !!wxt.config.runner.canOpen?.(),
|
||||
});
|
||||
},
|
||||
};
|
||||
@@ -170,11 +164,11 @@ async function createServerInternal(): Promise<WxtDevServer> {
|
||||
}
|
||||
|
||||
// Open browser after everything is ready to go.
|
||||
await runner.openBrowser();
|
||||
await wxt.config.runner.openBrowser();
|
||||
keyboardShortcuts.start();
|
||||
keyboardShortcuts.printHelp({
|
||||
canReopenBrowser:
|
||||
!wxt.config.runnerConfig.config.disabled && !!runner.canOpen?.(),
|
||||
!wxt.config.webExt.config.disabled && !!wxt.config.runner.canOpen?.(),
|
||||
});
|
||||
};
|
||||
|
||||
|
||||
@@ -1,14 +1,5 @@
|
||||
import consola from 'consola';
|
||||
import { WebExtConfig } from '../types';
|
||||
|
||||
/** @deprecated Use `defineWebExtConfig` instead. Same function, different name. */
|
||||
export function defineRunnerConfig(config: WebExtConfig): WebExtConfig {
|
||||
consola.warn(
|
||||
'`defineRunnerConfig` is deprecated, use `defineWebExtConfig` instead. See https://wxt.dev/guide/resources/upgrading.html#v0-19-0-rarr-v0-20-0',
|
||||
);
|
||||
return defineWebExtConfig(config);
|
||||
}
|
||||
|
||||
/**
|
||||
* Configure how [`web-ext`](https://github.com/mozilla/web-ext) starts the
|
||||
* browser during development.
|
||||
|
||||
@@ -297,15 +297,23 @@ async function getTsConfigEntry(): Promise<WxtDirFileEntry> {
|
||||
|
||||
const tsconfig = {
|
||||
compilerOptions: {
|
||||
// Environment setup & latest features
|
||||
lib: ['ESNext', 'DOM', 'DOM.Iterable'],
|
||||
target: 'ESNext',
|
||||
module: 'ESNext',
|
||||
module: 'Preserve',
|
||||
moduleDetection: 'force',
|
||||
// Bundler mode
|
||||
moduleResolution: 'Bundler',
|
||||
allowImportingTsExtensions: true,
|
||||
verbatimModuleSyntax: true,
|
||||
noEmit: true,
|
||||
esModuleInterop: true,
|
||||
forceConsistentCasingInFileNames: true,
|
||||
resolveJsonModule: true,
|
||||
// Best practices
|
||||
strict: true,
|
||||
skipLibCheck: true,
|
||||
noFallthroughCasesInSwitch: true,
|
||||
noUncheckedIndexedAccess: true,
|
||||
noImplicitOverride: true,
|
||||
// Project settings
|
||||
paths,
|
||||
},
|
||||
include: [`${getTsconfigPath(wxt.config.root)}/**/*`, './wxt.d.ts'],
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import prompts from 'prompts';
|
||||
import { question, select } from '@topcli/prompts';
|
||||
import { consola } from 'consola';
|
||||
import { downloadTemplate } from 'giget';
|
||||
import { readdir, rename } from 'node:fs/promises';
|
||||
@@ -8,88 +8,78 @@ import { styleText } from 'node:util';
|
||||
import { TextStyle } from '../utils/text-style';
|
||||
|
||||
export async function initialize(options: {
|
||||
directory: string;
|
||||
template: string;
|
||||
packageManager: string;
|
||||
directory?: string;
|
||||
template?: string;
|
||||
packageManager?: string;
|
||||
}) {
|
||||
consola.info('Initializing new project');
|
||||
|
||||
const templates = await listTemplates();
|
||||
const defaultTemplate = templates.find(
|
||||
(template) => template.name === options.template?.toLowerCase().trim(),
|
||||
);
|
||||
const inputTemplateName = options.template
|
||||
? templates.find(
|
||||
(template) => template.name === options.template!.toLowerCase().trim(),
|
||||
)?.name
|
||||
: undefined;
|
||||
|
||||
const input = await prompts(
|
||||
[
|
||||
{
|
||||
name: 'directory',
|
||||
type: () => (options.directory == null ? 'text' : undefined),
|
||||
message: 'Project Directory',
|
||||
initial: options.directory,
|
||||
},
|
||||
{
|
||||
name: 'template',
|
||||
type: () => (defaultTemplate == null ? 'select' : undefined),
|
||||
message: 'Choose a template',
|
||||
choices: templates.map((template) => ({
|
||||
title: TEMPLATE_COLORS[template.name]
|
||||
? styleText(TEMPLATE_COLORS[template.name], template.name)
|
||||
: template.name,
|
||||
value: template,
|
||||
})),
|
||||
},
|
||||
{
|
||||
name: 'packageManager',
|
||||
type: () => (options.packageManager == null ? 'select' : undefined),
|
||||
message: 'Package Manager',
|
||||
choices: [
|
||||
{ title: styleText('magenta', 'bun'), value: 'bun' },
|
||||
{ title: styleText('red', 'npm'), value: 'npm' },
|
||||
{ title: styleText('yellow', 'pnpm'), value: 'pnpm' },
|
||||
{ title: styleText('cyan', 'yarn'), value: 'yarn' },
|
||||
],
|
||||
},
|
||||
],
|
||||
{
|
||||
onCancel: () => process.exit(1),
|
||||
},
|
||||
);
|
||||
input.directory ||= options.directory || '.';
|
||||
input.template ??= defaultTemplate;
|
||||
input.packageManager ??= options.packageManager;
|
||||
const directory =
|
||||
options.directory ??
|
||||
(await question('Project Directory', { defaultValue: '.' }));
|
||||
if (!directory) throw Error('Directory is required');
|
||||
|
||||
const isExists = await pathExists(input.directory);
|
||||
const templateName =
|
||||
inputTemplateName ??
|
||||
(await select('Choose a template', {
|
||||
choices: templates.map((template) => ({
|
||||
label: TEMPLATE_COLORS[template.name]
|
||||
? styleText(TEMPLATE_COLORS[template.name], template.name)
|
||||
: template.name,
|
||||
value: template.name,
|
||||
})),
|
||||
}));
|
||||
const template = templates.find((t) => t.name === templateName);
|
||||
if (!template) throw Error('Unknown template: ' + templateName);
|
||||
|
||||
const packageManager =
|
||||
options.packageManager ??
|
||||
(await select('Package Manager', {
|
||||
choices: [
|
||||
{ label: styleText('magenta', 'bun'), value: 'bun' },
|
||||
{ label: styleText('red', 'npm'), value: 'npm' },
|
||||
{ label: styleText('yellow', 'pnpm'), value: 'pnpm' },
|
||||
{ label: styleText('cyan', 'yarn'), value: 'yarn' },
|
||||
],
|
||||
}));
|
||||
|
||||
const isExists = await pathExists(directory);
|
||||
if (isExists) {
|
||||
const isEmpty =
|
||||
(await readdir(input.directory)).filter((dir) => dir !== '.git')
|
||||
.length === 0;
|
||||
(await readdir(directory)).filter((dir) => dir !== '.git').length === 0;
|
||||
if (!isEmpty) {
|
||||
consola.error(
|
||||
`The directory ${path.resolve(input.directory)} is not empty. Aborted.`,
|
||||
`The directory ${path.resolve(directory)} is not empty. Aborted.`,
|
||||
);
|
||||
process.exit(1);
|
||||
}
|
||||
}
|
||||
await cloneProject(input);
|
||||
await cloneProject({ directory, template });
|
||||
|
||||
const cdPath = path.relative(process.cwd(), path.resolve(input.directory));
|
||||
const cdPath = path.relative(process.cwd(), path.resolve(directory));
|
||||
console.log();
|
||||
consola.log(
|
||||
`✨ WXT project created with the ${
|
||||
TEMPLATE_COLORS[input.template.name]
|
||||
? styleText(TEMPLATE_COLORS[input.template.name], input.template.name)
|
||||
: input.template.name
|
||||
TEMPLATE_COLORS[template.name]
|
||||
? styleText(TEMPLATE_COLORS[template.name], template.name)
|
||||
: template.name
|
||||
} template.`,
|
||||
);
|
||||
console.log();
|
||||
consola.log('Next steps:');
|
||||
|
||||
let step = 0;
|
||||
if (cdPath !== '')
|
||||
consola.log(` ${++step}.`, styleText('cyan', `cd ${cdPath}`));
|
||||
consola.log(
|
||||
` ${++step}.`,
|
||||
styleText('cyan', `${input.packageManager} install`),
|
||||
);
|
||||
consola.log(` ${++step}.`, styleText('cyan', `${packageManager} install`));
|
||||
|
||||
console.log();
|
||||
}
|
||||
|
||||
|
||||
@@ -1,19 +1,19 @@
|
||||
import { loadConfig } from 'c12';
|
||||
import { resolve as esmResolve } from 'import-meta-resolve';
|
||||
import {
|
||||
InlineConfig,
|
||||
ResolvedConfig,
|
||||
UserConfig,
|
||||
ConfigEnv,
|
||||
UserManifestFn,
|
||||
UserManifest,
|
||||
WebExtConfig,
|
||||
WxtResolvedUnimportOptions,
|
||||
InlineConfig,
|
||||
Logger,
|
||||
ResolvedConfig,
|
||||
ResolvedEslintrc,
|
||||
UserConfig,
|
||||
UserManifest,
|
||||
UserManifestFn,
|
||||
WebExtConfig,
|
||||
WxtCommand,
|
||||
WxtModule,
|
||||
WxtModuleWithMetadata,
|
||||
ResolvedEslintrc,
|
||||
WxtResolvedUnimportOptions,
|
||||
ExtensionRunner,
|
||||
} from '../types';
|
||||
import path from 'node:path';
|
||||
import { createFsCache } from './utils/cache';
|
||||
@@ -29,6 +29,10 @@ import { safeStringToNumber } from './utils/number';
|
||||
import { loadEnv } from './utils/env';
|
||||
import { getPort } from 'get-port-please';
|
||||
import { fileURLToPath, pathToFileURL } from 'node:url';
|
||||
import { createSafariRunner } from './runners/safari';
|
||||
import isWsl from 'is-wsl';
|
||||
import { createWslRunner } from './runners/wsl';
|
||||
import { createManualRunner } from './runners/manual';
|
||||
|
||||
/**
|
||||
* Given an inline config, discover the config file if necessary, merge the
|
||||
@@ -119,19 +123,13 @@ export async function resolveConfig(
|
||||
|
||||
const outDir = path.resolve(outBaseDir, outDirTemplate);
|
||||
const reloadCommand = mergedConfig.dev?.reloadCommand ?? 'Alt+R';
|
||||
|
||||
if (inlineConfig.runner != null || userConfig.runner != null) {
|
||||
logger.warn(
|
||||
'`InlineConfig#runner` is deprecated, use `InlineConfig#webExt` instead. See https://wxt.dev/guide/resources/upgrading.html#v0-19-0-rarr-v0-20-0',
|
||||
);
|
||||
}
|
||||
const runnerConfig = await loadConfig<WebExtConfig>({
|
||||
const webExt = await loadConfig<WebExtConfig>({
|
||||
name: 'web-ext',
|
||||
cwd: root,
|
||||
globalRc: true,
|
||||
rcFile: '.webextrc',
|
||||
overrides: inlineConfig.webExt ?? inlineConfig.runner,
|
||||
defaults: userConfig.webExt ?? userConfig.runner,
|
||||
overrides: inlineConfig.webExt,
|
||||
defaults: userConfig.webExt,
|
||||
});
|
||||
// Make sure alias are absolute
|
||||
const alias = Object.fromEntries(
|
||||
@@ -146,20 +144,9 @@ export async function resolveConfig(
|
||||
|
||||
let devServerConfig: ResolvedConfig['dev']['server'];
|
||||
if (command === 'serve') {
|
||||
if (mergedConfig.dev?.server?.hostname)
|
||||
logger.warn(
|
||||
`The 'hostname' option is deprecated, please use 'host' or 'origin' depending on your circumstances.`,
|
||||
);
|
||||
|
||||
const host =
|
||||
mergedConfig.dev?.server?.host ??
|
||||
mergedConfig.dev?.server?.hostname ??
|
||||
'localhost';
|
||||
const host = mergedConfig.dev?.server?.host ?? 'localhost';
|
||||
let port = mergedConfig.dev?.server?.port;
|
||||
const origin =
|
||||
mergedConfig.dev?.server?.origin ??
|
||||
mergedConfig.dev?.server?.hostname ??
|
||||
'localhost';
|
||||
const origin = mergedConfig.dev?.server?.origin ?? 'localhost';
|
||||
const strictPort = mergedConfig.dev?.server?.strictPort ?? false;
|
||||
if (port == null || !isFinite(port)) {
|
||||
port = await getPort({
|
||||
@@ -225,7 +212,11 @@ export async function resolveConfig(
|
||||
publicDir,
|
||||
wxtModuleDir,
|
||||
root,
|
||||
runnerConfig,
|
||||
webExt,
|
||||
runner:
|
||||
command === 'serve'
|
||||
? await resolveRunner(browser, logger, mergedConfig)
|
||||
: createManualRunner(),
|
||||
srcDir,
|
||||
typesDir,
|
||||
wxtDir,
|
||||
@@ -308,10 +299,11 @@ function resolveZipConfig(
|
||||
const downloadedPackagesDir = path.resolve(root, '.wxt/local_modules');
|
||||
return {
|
||||
name: undefined,
|
||||
sourcesTemplate: '{{name}}-{{version}}-sources.zip',
|
||||
artifactTemplate: '{{name}}-{{version}}-{{browser}}.zip',
|
||||
sourcesTemplate: '{{name}}-{{packageVersion}}-sources{{modeSuffix}}.zip',
|
||||
artifactTemplate:
|
||||
'{{name}}-{{packageVersion}}-{{browser}}{{modeSuffix}}.zip',
|
||||
sourcesRoot: root,
|
||||
includeSources: [],
|
||||
includeSources: mergedConfig.zip?.includeSources ?? ['**/*'],
|
||||
compressionLevel: 9,
|
||||
...mergedConfig.zip,
|
||||
zipSources:
|
||||
@@ -321,8 +313,6 @@ function resolveZipConfig(
|
||||
'**/node_modules',
|
||||
// WXT files
|
||||
'**/web-ext.config.ts',
|
||||
// Hidden files
|
||||
'**/.*',
|
||||
// Tests
|
||||
'**/__tests__/**',
|
||||
'**/*.+(test|spec).?(c|m)+(j|t)s?(x)',
|
||||
@@ -331,6 +321,7 @@ function resolveZipConfig(
|
||||
// From user
|
||||
...(mergedConfig.zip?.excludeSources ?? []),
|
||||
],
|
||||
dotSources: mergedConfig.zip?.dotSources ?? false,
|
||||
downloadPackages: mergedConfig.zip?.downloadPackages ?? [],
|
||||
downloadedPackagesDir,
|
||||
};
|
||||
@@ -365,7 +356,11 @@ async function getUnimportOptions(
|
||||
config: InlineConfig,
|
||||
): Promise<WxtResolvedUnimportOptions> {
|
||||
const disabled = config.imports === false;
|
||||
const eslintrc = await getUnimportEslintOptions(wxtDir, config.imports);
|
||||
const eslintrc = await getUnimportEslintOptions(
|
||||
logger,
|
||||
wxtDir,
|
||||
config.imports,
|
||||
);
|
||||
// mlly sometimes picks up things as exports that aren't. That's what this array contains.
|
||||
const invalidExports = ['options'];
|
||||
|
||||
@@ -375,7 +370,7 @@ async function getUnimportOptions(
|
||||
];
|
||||
|
||||
const defaultOptions: WxtResolvedUnimportOptions = {
|
||||
imports: [{ name: 'fakeBrowser', from: 'wxt/testing' }],
|
||||
imports: [{ name: 'fakeBrowser', from: 'wxt/testing/fake-browser' }],
|
||||
presets: [
|
||||
{
|
||||
from: 'wxt/browser',
|
||||
@@ -505,25 +500,34 @@ async function getUnimportOptions(
|
||||
}
|
||||
|
||||
async function getUnimportEslintOptions(
|
||||
logger: Logger,
|
||||
wxtDir: string,
|
||||
options: InlineConfig['imports'],
|
||||
): Promise<ResolvedEslintrc> {
|
||||
const inlineEnabled =
|
||||
options === false ? false : (options?.eslintrc?.enabled ?? 'auto');
|
||||
|
||||
const version = await getEslintVersion();
|
||||
const major = parseInt(version[0]);
|
||||
|
||||
let enabled: ResolvedEslintrc['enabled'];
|
||||
switch (inlineEnabled) {
|
||||
case 'auto':
|
||||
const version = await getEslintVersion();
|
||||
let major = parseInt(version[0]);
|
||||
if (isNaN(major)) enabled = false;
|
||||
if (major <= 8) enabled = 8;
|
||||
else if (major >= 9) enabled = 9;
|
||||
// NaN
|
||||
else enabled = false;
|
||||
break;
|
||||
case true:
|
||||
enabled = 8;
|
||||
if (isNaN(major)) {
|
||||
if (inlineEnabled === true) {
|
||||
logger.warn(
|
||||
'Could not determine installed ESLint version, `eslint-auto-imports.mjs` not generated',
|
||||
);
|
||||
}
|
||||
enabled = false;
|
||||
} else if (major <= 8) {
|
||||
enabled = 8;
|
||||
} else if (major >= 9) {
|
||||
enabled = 9;
|
||||
} else {
|
||||
enabled = false;
|
||||
}
|
||||
break;
|
||||
default:
|
||||
enabled = inlineEnabled;
|
||||
@@ -533,7 +537,7 @@ async function getUnimportEslintOptions(
|
||||
enabled,
|
||||
filePath: path.resolve(
|
||||
wxtDir,
|
||||
enabled === 9 ? 'eslint-auto-imports.mjs' : 'eslintrc-auto-import.json',
|
||||
enabled === 8 ? 'eslintrc-auto-import.json' : 'eslint-auto-imports.mjs',
|
||||
),
|
||||
globalsPropValue: true,
|
||||
};
|
||||
@@ -541,10 +545,7 @@ async function getUnimportEslintOptions(
|
||||
|
||||
/** Returns the path to `node_modules/wxt`. */
|
||||
function resolveWxtModuleDir() {
|
||||
// TODO: Switch to import.meta.resolve() once the parent argument is unflagged
|
||||
// (e.g. --experimental-import-meta-resolve) and all Node.js versions we support
|
||||
// have it.
|
||||
const url = esmResolve('wxt', import.meta.url);
|
||||
const url = import.meta.resolve('wxt', import.meta.url);
|
||||
|
||||
// esmResolve() returns the "wxt/dist/index.mjs" file, not the package's root
|
||||
// directory, which we want to return from this function.
|
||||
@@ -600,9 +601,7 @@ export async function resolveWxtUserModules(
|
||||
// Resolve node_modules modules
|
||||
const npmModules = await Promise.all<WxtModuleWithMetadata<any>>(
|
||||
modules.map(async (moduleId) => {
|
||||
// Resolve before importing to allow for a local WXT clone to be
|
||||
// symlinked into a project.
|
||||
const resolvedModulePath = esmResolve(moduleId, importer);
|
||||
const resolvedModulePath = import.meta.resolve(moduleId, importer);
|
||||
const mod: { default: WxtModule<any> } = await import(
|
||||
/* @vite-ignore */ resolvedModulePath
|
||||
);
|
||||
@@ -651,3 +650,27 @@ export async function resolveWxtUserModules(
|
||||
);
|
||||
return [...npmModules, ...localModules];
|
||||
}
|
||||
|
||||
async function resolveRunner(
|
||||
browser: string,
|
||||
logger: Logger,
|
||||
mergedConfig: InlineConfig,
|
||||
): Promise<ExtensionRunner> {
|
||||
if (browser === 'safari') return createSafariRunner();
|
||||
|
||||
if (isWsl) return createWslRunner();
|
||||
|
||||
try {
|
||||
// This module imports `web-ext`, so if it fails, we know `web-ext` isn't installed
|
||||
const { createWebExtRunner } = await import('./runners/web-ext');
|
||||
return mergedConfig.webExt?.disabled
|
||||
? createManualRunner()
|
||||
: createWebExtRunner();
|
||||
} catch (err: any) {
|
||||
if (err?.code !== 'ERR_MODULE_NOT_FOUND') throw err;
|
||||
|
||||
logger.debug('Error loading the web-ext runner', err);
|
||||
}
|
||||
|
||||
return createManualRunner();
|
||||
}
|
||||
|
||||
@@ -1,87 +0,0 @@
|
||||
import { describe, expect, it, vi } from 'vitest';
|
||||
import { createExtensionRunner } from '..';
|
||||
import { setFakeWxt } from '../../utils/testing/fake-objects';
|
||||
import { mock } from 'vitest-mock-extended';
|
||||
import { createSafariRunner } from '../safari';
|
||||
import { createWslRunner } from '../wsl';
|
||||
import { createManualRunner } from '../manual';
|
||||
import { isWsl } from '../../utils/wsl';
|
||||
import { createWebExtRunner } from '../web-ext';
|
||||
import { ExtensionRunner } from '../../../types';
|
||||
|
||||
vi.mock('../../utils/wsl');
|
||||
const isWslMock = vi.mocked(isWsl);
|
||||
|
||||
vi.mock('../safari');
|
||||
const createSafariRunnerMock = vi.mocked(createSafariRunner);
|
||||
|
||||
vi.mock('../wsl');
|
||||
const createWslRunnerMock = vi.mocked(createWslRunner);
|
||||
|
||||
vi.mock('../manual');
|
||||
const createManualRunnerMock = vi.mocked(createManualRunner);
|
||||
|
||||
vi.mock('../web-ext');
|
||||
const createWebExtRunnerMock = vi.mocked(createWebExtRunner);
|
||||
|
||||
describe('createExtensionRunner', () => {
|
||||
it('should return a Safari runner when browser is "safari"', async () => {
|
||||
setFakeWxt({
|
||||
config: {
|
||||
browser: 'safari',
|
||||
},
|
||||
});
|
||||
const safariRunner = mock<ExtensionRunner>();
|
||||
createSafariRunnerMock.mockReturnValue(safariRunner);
|
||||
|
||||
await expect(createExtensionRunner()).resolves.toBe(safariRunner);
|
||||
});
|
||||
|
||||
it('should return a WSL runner when `is-wsl` is true', async () => {
|
||||
isWslMock.mockReturnValueOnce(true);
|
||||
setFakeWxt({
|
||||
config: {
|
||||
browser: 'chrome',
|
||||
},
|
||||
});
|
||||
const wslRunner = mock<ExtensionRunner>();
|
||||
createWslRunnerMock.mockReturnValue(wslRunner);
|
||||
|
||||
await expect(createExtensionRunner()).resolves.toBe(wslRunner);
|
||||
});
|
||||
|
||||
it('should return a manual runner when `runner.disabled` is true', async () => {
|
||||
isWslMock.mockReturnValueOnce(false);
|
||||
setFakeWxt({
|
||||
config: {
|
||||
browser: 'chrome',
|
||||
runnerConfig: {
|
||||
config: {
|
||||
disabled: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
const manualRunner = mock<ExtensionRunner>();
|
||||
createManualRunnerMock.mockReturnValue(manualRunner);
|
||||
|
||||
await expect(createExtensionRunner()).resolves.toBe(manualRunner);
|
||||
});
|
||||
|
||||
it('should return a web-ext runner otherwise', async () => {
|
||||
setFakeWxt({
|
||||
config: {
|
||||
browser: 'chrome',
|
||||
runnerConfig: {
|
||||
config: {
|
||||
disabled: undefined,
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
const manualRunner = mock<ExtensionRunner>();
|
||||
createWebExtRunnerMock.mockReturnValue(manualRunner);
|
||||
|
||||
await expect(createExtensionRunner()).resolves.toBe(manualRunner);
|
||||
});
|
||||
});
|
||||
@@ -1,16 +0,0 @@
|
||||
import type { ExtensionRunner } from '../../types';
|
||||
import { isWsl } from '../utils/wsl';
|
||||
import { wxt } from '../wxt';
|
||||
import { createManualRunner } from './manual';
|
||||
import { createSafariRunner } from './safari';
|
||||
import { createWebExtRunner } from './web-ext';
|
||||
import { createWslRunner } from './wsl';
|
||||
|
||||
export async function createExtensionRunner(): Promise<ExtensionRunner> {
|
||||
if (wxt.config.browser === 'safari') return createSafariRunner();
|
||||
|
||||
if (isWsl()) return createWslRunner();
|
||||
if (wxt.config.runnerConfig.config?.disabled) return createManualRunner();
|
||||
|
||||
return createWebExtRunner();
|
||||
}
|
||||
@@ -1,8 +1,10 @@
|
||||
import type { WebExtRunInstance } from 'web-ext-run';
|
||||
import type { WebExtRunInstance } from 'web-ext';
|
||||
import { ExtensionRunner } from '../../types';
|
||||
import { formatDuration } from '../utils/time';
|
||||
import defu from 'defu';
|
||||
import { wxt } from '../wxt';
|
||||
import webExt from 'web-ext';
|
||||
import { consoleStream } from 'web-ext/util/logger';
|
||||
|
||||
/** Create an `ExtensionRunner` backed by `web-ext`. */
|
||||
export function createWebExtRunner(): ExtensionRunner {
|
||||
@@ -16,13 +18,12 @@ export function createWebExtRunner(): ExtensionRunner {
|
||||
const startTime = Date.now();
|
||||
|
||||
// Use WXT's logger instead of web-ext's built-in one.
|
||||
const webExtLogger = await import('web-ext-run/util/logger');
|
||||
webExtLogger.consoleStream.write = ({ level, msg, name }) => {
|
||||
consoleStream.write = ({ level, msg, name }) => {
|
||||
if (level >= ERROR_LOG_LEVEL) wxt.logger.error(name, msg);
|
||||
if (level >= WARN_LOG_LEVEL) wxt.logger.warn(msg);
|
||||
};
|
||||
|
||||
const wxtUserConfig = wxt.config.runnerConfig.config;
|
||||
const wxtUserConfig = wxt.config.webExt.config;
|
||||
const userConfig = {
|
||||
browserConsole: wxtUserConfig?.openConsole,
|
||||
devtools: wxtUserConfig?.openDevtools,
|
||||
@@ -69,8 +70,7 @@ export function createWebExtRunner(): ExtensionRunner {
|
||||
wxt.logger.debug('web-ext config:', finalConfig);
|
||||
wxt.logger.debug('web-ext options:', options);
|
||||
|
||||
const webExt = await import('web-ext-run');
|
||||
runner = await webExt.default.cmd.run(finalConfig, options);
|
||||
runner = await webExt.cmd.run(finalConfig, options);
|
||||
|
||||
const duration = Date.now() - startTime;
|
||||
wxt.logger.success(`Opened browser in ${formatDuration(duration)}`);
|
||||
|
||||
@@ -1,71 +0,0 @@
|
||||
import { describe, it, expect } from 'vitest';
|
||||
import { picomatchMultiple } from '../picomatch-multiple';
|
||||
|
||||
describe('picomatchMultiple', () => {
|
||||
it('should return false if the pattern array is undefined', () => {
|
||||
const patterns = undefined;
|
||||
const search = 'test.json';
|
||||
|
||||
expect(picomatchMultiple(search, patterns)).toBe(false);
|
||||
});
|
||||
|
||||
it('should return false if the pattern array is empty', () => {
|
||||
const patterns: string[] = [];
|
||||
const search = 'test.json';
|
||||
|
||||
expect(picomatchMultiple(search, patterns)).toBe(false);
|
||||
});
|
||||
|
||||
it('should return true if the pattern array contains a match', () => {
|
||||
const patterns = ['test.yml', 'test.json'];
|
||||
const search = 'test.json';
|
||||
|
||||
expect(picomatchMultiple(search, patterns)).toBe(true);
|
||||
});
|
||||
|
||||
it('should return false if the pattern array does not contain a match', () => {
|
||||
const patterns = ['test.yml', 'test.json'];
|
||||
const search = 'test.txt';
|
||||
|
||||
expect(picomatchMultiple(search, patterns)).toBe(false);
|
||||
});
|
||||
|
||||
it('should return false if the pattern matches a negative pattern', () => {
|
||||
const patterns = ['test.*', '!test.json'];
|
||||
const search = 'test.json';
|
||||
|
||||
expect(picomatchMultiple(search, patterns)).toBe(false);
|
||||
});
|
||||
|
||||
it('should return false if the pattern matches a negative pattern, regardless of order', () => {
|
||||
const patterns = ['!test.json', 'test.*'];
|
||||
const search = 'test.json';
|
||||
|
||||
expect(picomatchMultiple(search, patterns)).toBe(false);
|
||||
});
|
||||
|
||||
it('should support extglob-like extension matching', () => {
|
||||
const patterns = ['content.[jt]s?(x)'];
|
||||
|
||||
expect(picomatchMultiple('content.ts', patterns)).toBe(true);
|
||||
expect(picomatchMultiple('content.jsx', patterns)).toBe(true);
|
||||
expect(picomatchMultiple('content.css', patterns)).toBe(false);
|
||||
});
|
||||
|
||||
it('should support nested paths', () => {
|
||||
const patterns = ['foo/**/*.ts'];
|
||||
|
||||
expect(picomatchMultiple('foo/bar/baz.ts', patterns)).toBe(true);
|
||||
expect(picomatchMultiple('foo/bar/baz.js', patterns)).toBe(false);
|
||||
});
|
||||
|
||||
it('should preserve include/exclude interaction used by zip filtering', () => {
|
||||
const include = ['special.txt'];
|
||||
const exclude = ['**/*.txt'];
|
||||
const search = 'special.txt';
|
||||
const shouldInclude =
|
||||
picomatchMultiple(search, include) || !picomatchMultiple(search, exclude);
|
||||
|
||||
expect(shouldInclude).toBe(true);
|
||||
});
|
||||
});
|
||||
@@ -103,7 +103,7 @@ describe('Detect Dev Changes', () => {
|
||||
const runnerFile = '/root/web-ext.config.ts';
|
||||
setFakeWxt({
|
||||
config: {
|
||||
runnerConfig: {
|
||||
webExt: {
|
||||
configFile: runnerFile,
|
||||
},
|
||||
},
|
||||
|
||||
@@ -63,7 +63,7 @@ export function detectDevChanges(
|
||||
|
||||
const isRunnerChange = some(
|
||||
relevantChangedFiles,
|
||||
(file) => file === wxt.config.runnerConfig.configFile,
|
||||
(file) => file === wxt.config.webExt.configFile,
|
||||
);
|
||||
if (isRunnerChange) return { type: 'browser-restart' };
|
||||
|
||||
@@ -146,7 +146,7 @@ export function getRelevantDevChangedFiles(
|
||||
return Array.from(new Set(changedFiles)).filter((changedFile) => {
|
||||
if (changedFile === wxt.config.userConfigMetadata.configFile) return true;
|
||||
if (changedFile.startsWith(wxt.config.modulesDir)) return true;
|
||||
if (changedFile === wxt.config.runnerConfig.configFile) return true;
|
||||
if (changedFile === wxt.config.webExt.configFile) return true;
|
||||
if (changedFile.startsWith(wxt.config.publicDir)) return true;
|
||||
return findEffectedSteps(changedFile, currentOutput).length > 0;
|
||||
});
|
||||
|
||||
@@ -18,6 +18,7 @@ import { wxt } from '../../wxt';
|
||||
import { mergeJsonOutputs } from '@aklinker1/rollup-plugin-visualizer';
|
||||
import { isCI } from 'ci-info';
|
||||
import { styleText } from 'node:util';
|
||||
import open from 'tiny-open';
|
||||
|
||||
/**
|
||||
* Builds the extension based on an internal config. No more config discovery is
|
||||
@@ -92,7 +93,6 @@ export async function internalBuild(): Promise<BuildOutput> {
|
||||
wxt.logger.info(
|
||||
`Opening ${styleText('yellow', statsPath)} in browser...`,
|
||||
);
|
||||
const { default: open } = await import('open');
|
||||
await open(wxt.config.analysis.outputFile);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { Mutex } from 'async-mutex';
|
||||
import { withLock } from 'superlock';
|
||||
import { relative } from 'node:path';
|
||||
import {
|
||||
BuildOutput,
|
||||
@@ -30,12 +30,12 @@ import { normalizePath } from './paths';
|
||||
* when a file changes.
|
||||
*/
|
||||
export function createFileReloader(server: WxtDevServer) {
|
||||
const fileChangedMutex = new Mutex();
|
||||
const fileChangedLock = withLock();
|
||||
const changeQueue: Array<[string, string]> = [];
|
||||
let processLoop: Promise<void> | undefined;
|
||||
|
||||
const processQueue = async () => {
|
||||
const reloading = fileChangedMutex.runExclusive(async () => {
|
||||
const reloading = fileChangedLock(async () => {
|
||||
const fileChanges = changeQueue
|
||||
.splice(0, changeQueue.length)
|
||||
.map(([_, file]) => file);
|
||||
|
||||
@@ -1,38 +0,0 @@
|
||||
import picomatch, { PicomatchOptions } from 'picomatch';
|
||||
|
||||
/**
|
||||
* Run [`picomatch`](https://npmjs.com/package/picomatch) against multiple
|
||||
* patterns.
|
||||
*
|
||||
* Supports negated patterns, the order does not matter. If your `search` string
|
||||
* matches any of the negative patterns, it will return `false`.
|
||||
*
|
||||
* @example
|
||||
* picomatchMultiple('a.json', ['*.json', '!b.json']); // => true
|
||||
* picomatchMultiple('b.json', ['*.json', '!b.json']); // => false
|
||||
*/
|
||||
export function picomatchMultiple(
|
||||
search: string,
|
||||
patterns: string[] | undefined,
|
||||
options?: PicomatchOptions,
|
||||
): boolean {
|
||||
if (patterns == null) return false;
|
||||
|
||||
const negatePatterns: string[] = [];
|
||||
const positivePatterns: string[] = [];
|
||||
for (const pattern of patterns) {
|
||||
if (pattern[0] === '!') negatePatterns.push(pattern.slice(1));
|
||||
else positivePatterns.push(pattern);
|
||||
}
|
||||
|
||||
if (
|
||||
negatePatterns.some((negatePattern) =>
|
||||
picomatch(negatePattern, options)(search),
|
||||
)
|
||||
)
|
||||
return false;
|
||||
|
||||
return positivePatterns.some((positivePattern) =>
|
||||
picomatch(positivePattern, options)(search),
|
||||
);
|
||||
}
|
||||
@@ -264,9 +264,10 @@ export const fakeResolvedConfig = fakeObjectCreator<ResolvedConfig>(() => {
|
||||
publicDir: fakeDir(),
|
||||
root: fakeDir(),
|
||||
wxtModuleDir: fakeDir(),
|
||||
runnerConfig: {
|
||||
webExt: {
|
||||
config: {},
|
||||
},
|
||||
runner: mock(),
|
||||
debug: faker.datatype.boolean(),
|
||||
srcDir: fakeDir(),
|
||||
typesDir: fakeDir(),
|
||||
@@ -284,6 +285,7 @@ export const fakeResolvedConfig = fakeObjectCreator<ResolvedConfig>(() => {
|
||||
artifactTemplate: '{{name}}-{{version}}.zip',
|
||||
includeSources: [],
|
||||
excludeSources: [],
|
||||
dotSources: false,
|
||||
exclude: [],
|
||||
sourcesRoot: fakeDir(),
|
||||
sourcesTemplate: '{{name}}-sources.zip',
|
||||
|
||||
@@ -22,7 +22,7 @@ export function withTimeout<T>(
|
||||
}
|
||||
|
||||
/**
|
||||
* @deprecated Don't use in production, just for testing and slowing things
|
||||
* @internal Don't use in production, just for testing and slowing things
|
||||
* down.
|
||||
*/
|
||||
export function sleep(ms: number): Promise<void> {
|
||||
|
||||
@@ -11,7 +11,6 @@ import { registerWxt, wxt } from './wxt';
|
||||
import JSZip from 'jszip';
|
||||
import { glob } from 'tinyglobby';
|
||||
import { normalizePath } from './utils';
|
||||
import { picomatchMultiple } from './utils/picomatch-multiple';
|
||||
|
||||
/**
|
||||
* Build and zip the extension for distribution.
|
||||
@@ -32,15 +31,22 @@ export async function zip(config?: InlineConfig): Promise<string[]> {
|
||||
const projectName =
|
||||
wxt.config.zip.name ??
|
||||
safeFilename(packageJson?.name || path.basename(process.cwd()));
|
||||
const modeSuffixes: Record<string, string | undefined> = {
|
||||
production: '',
|
||||
development: '-dev',
|
||||
};
|
||||
const modeSuffix = modeSuffixes[wxt.config.mode] ?? `-${wxt.config.mode}`;
|
||||
const applyTemplate = (template: string): string =>
|
||||
template
|
||||
.replaceAll('{{name}}', projectName)
|
||||
.replaceAll('{{browser}}', wxt.config.browser)
|
||||
.replaceAll('{{version}}', output.manifest.version)
|
||||
.replaceAll(
|
||||
'{{version}}',
|
||||
'{{versionName}}',
|
||||
output.manifest.version_name ?? output.manifest.version,
|
||||
)
|
||||
.replaceAll('{{packageVersion}}', packageJson?.version)
|
||||
.replaceAll('{{modeSuffix}}', modeSuffix)
|
||||
.replaceAll('{{mode}}', wxt.config.mode)
|
||||
.replaceAll('{{manifestVersion}}', `mv${wxt.config.manifestVersion}`);
|
||||
|
||||
@@ -64,7 +70,7 @@ export async function zip(config?: InlineConfig): Promise<string[]> {
|
||||
...skippedEntrypoints.map((entry) =>
|
||||
path.relative(wxt.config.zip.sourcesRoot, entry.inputPath),
|
||||
),
|
||||
].map((paths) => paths.replaceAll('\\', '/'));
|
||||
].map((paths) => paths.replaceAll('\\', '/')); // TODO: Use normalizePath?
|
||||
await wxt.hooks.callHook('zip:sources:start', wxt);
|
||||
const { overrides, files: downloadedPackages } =
|
||||
await downloadPrivatePackages();
|
||||
@@ -73,7 +79,7 @@ export async function zip(config?: InlineConfig): Promise<string[]> {
|
||||
wxt.config.outBaseDir,
|
||||
sourcesZipFilename,
|
||||
);
|
||||
await zipDir(wxt.config.zip.sourcesRoot, sourcesZipPath, {
|
||||
const files = await zipDir(wxt.config.zip.sourcesRoot, sourcesZipPath, {
|
||||
include: wxt.config.zip.includeSources,
|
||||
exclude: excludeSources,
|
||||
transform(absolutePath, zipPath, content) {
|
||||
@@ -82,9 +88,17 @@ export async function zip(config?: InlineConfig): Promise<string[]> {
|
||||
}
|
||||
},
|
||||
additionalFiles: downloadedPackages,
|
||||
dot: wxt.config.zip.dotSources,
|
||||
});
|
||||
zipFiles.push(sourcesZipPath);
|
||||
await wxt.hooks.callHook('zip:sources:done', wxt, sourcesZipPath);
|
||||
|
||||
await printFileList(
|
||||
wxt.logger.info,
|
||||
`Sources included in \`${sourcesZipFilename}\``,
|
||||
wxt.config.zip.sourcesRoot,
|
||||
files,
|
||||
);
|
||||
}
|
||||
|
||||
await printFileList(
|
||||
@@ -112,29 +126,24 @@ async function zipDir(
|
||||
) => Promise<string | undefined | void> | string | undefined | void;
|
||||
additionalWork?: (archive: JSZip) => Promise<void> | void;
|
||||
additionalFiles?: string[];
|
||||
dot?: boolean;
|
||||
},
|
||||
): Promise<void> {
|
||||
): Promise<string[]> {
|
||||
const archive = new JSZip();
|
||||
const files = (
|
||||
await glob(['**/*', ...(options?.include || [])], {
|
||||
cwd: directory,
|
||||
// Ignore node_modules, otherwise this glob step takes forever
|
||||
ignore: ['**/node_modules'],
|
||||
onlyFiles: true,
|
||||
expandDirectories: false,
|
||||
})
|
||||
).filter((relativePath) => {
|
||||
return (
|
||||
picomatchMultiple(relativePath, options?.include) ||
|
||||
!picomatchMultiple(relativePath, options?.exclude)
|
||||
);
|
||||
// includeSources patterns are used directly (defaults to ['**/*'] from config)
|
||||
// excludeSources patterns are passed to glob's ignore option for efficient filtering
|
||||
const files = await glob(options?.include ?? ['**/*'], {
|
||||
cwd: directory,
|
||||
ignore: options?.exclude ?? [],
|
||||
onlyFiles: true,
|
||||
dot: options?.dot,
|
||||
});
|
||||
const filesToZip = [
|
||||
...files,
|
||||
...(options?.additionalFiles ?? []).map((file) =>
|
||||
path.relative(directory, file),
|
||||
),
|
||||
];
|
||||
].sort();
|
||||
for (const file of filesToZip) {
|
||||
const absolutePath = path.resolve(directory, file);
|
||||
if (file.endsWith('.json')) {
|
||||
@@ -165,6 +174,8 @@ async function zipDir(
|
||||
.on('error', reject)
|
||||
.on('close', resolve),
|
||||
);
|
||||
|
||||
return filesToZip;
|
||||
}
|
||||
|
||||
async function downloadPrivatePackages() {
|
||||
|
||||
@@ -1,9 +0,0 @@
|
||||
/**
|
||||
* Utilities for unit testing WXT extensions.
|
||||
*
|
||||
* @module wxt/testing
|
||||
* @deprecated Use `wxt/testing/*` instead to prevent issues with JSDOM or
|
||||
* HappyDOM environments. Will be removed in the next major version of WXT.
|
||||
*/
|
||||
export * from './fake-browser';
|
||||
export * from './wxt-vitest-plugin';
|
||||
@@ -2,12 +2,11 @@
|
||||
* Contains a Vitest plugin that configures your test environment to work with
|
||||
* WXT projects.
|
||||
*
|
||||
* @module wxt/testing/vitest
|
||||
* @module wxt/testing/vitest-plugin
|
||||
*/
|
||||
|
||||
import type * as vite from 'vite';
|
||||
import {
|
||||
download,
|
||||
tsconfigPaths,
|
||||
globals,
|
||||
extensionApiMock,
|
||||
@@ -41,7 +40,6 @@ export async function WxtVitest(
|
||||
|
||||
const plugins: vite.PluginOption[] = [
|
||||
globals(wxt.config),
|
||||
download(wxt.config),
|
||||
tsconfigPaths(wxt.config),
|
||||
resolveAppConfig(wxt.config),
|
||||
extensionApiMock(wxt.config),
|
||||
|
||||
+71
-41
@@ -1,5 +1,5 @@
|
||||
import type * as vite from 'vite';
|
||||
import { UnimportOptions, Import } from 'unimport';
|
||||
import { Import, UnimportOptions } from 'unimport';
|
||||
import { LogLevel } from 'consola';
|
||||
import type { ContentScriptContext } from './utils/content-script-context';
|
||||
import type { PluginVisualizerOptions } from '@aklinker1/rollup-plugin-visualizer';
|
||||
@@ -184,8 +184,6 @@ export interface InlineConfig {
|
||||
* `web-ext.config.ts` file.
|
||||
*/
|
||||
webExt?: WebExtConfig;
|
||||
/** @deprecated Use `webExt` instead. Same option, just renamed. */
|
||||
runner?: WebExtConfig;
|
||||
zip?: {
|
||||
/**
|
||||
* Configure the filename output when zipping files.
|
||||
@@ -194,16 +192,20 @@ export interface InlineConfig {
|
||||
*
|
||||
* - <span v-pre>`{{name}}`</span> - The project's name converted to
|
||||
* kebab-case
|
||||
* - <span v-pre>`{{version}}`</span> - The version_name or version from the
|
||||
* manifest
|
||||
* - <span v-pre>`{{version}}`</span> - The version from the manifest
|
||||
* - <span v-pre>`{{versionName}}`</span> - The `version_name` from the
|
||||
* manifest or, if not set (i.e. if built for Firefox), the `version` from
|
||||
* the manifest
|
||||
* - <span v-pre>`{{packageVersion}}`</span> - The version from the
|
||||
* package.json
|
||||
* - <span v-pre>`{{browser}}`</span> - The target browser from the
|
||||
* `--browser` CLI flag
|
||||
* - <span v-pre>`{{mode}}`</span> - The current mode
|
||||
* - <span v-pre>`{{modeSuffix}}`</span>: A suffix based on the mode ('-dev'
|
||||
* for development, '' for production)
|
||||
* - <span v-pre>`{{manifestVersion}}`</span> - Either "2" or "3"
|
||||
*
|
||||
* @default '{{name}}-{{version}}-{{browser}}.zip'
|
||||
* @default '{{name}}-{{packageVersion}}-{{browser}}{{modeSuffix}}.zip'
|
||||
*/
|
||||
artifactTemplate?: string;
|
||||
/**
|
||||
@@ -223,16 +225,20 @@ export interface InlineConfig {
|
||||
*
|
||||
* - <span v-pre>`{{name}}`</span> - The project's name converted to
|
||||
* kebab-case
|
||||
* - <span v-pre>`{{version}}`</span> - The version_name or version from the
|
||||
* manifest
|
||||
* - <span v-pre>`{{version}}`</span> - The version from the manifest
|
||||
* - <span v-pre>`{{versionName}}`</span> - The `version_name` from the
|
||||
* manifest or, if not set (i.e. if built for Firefox), the `version` from
|
||||
* the manifest
|
||||
* - <span v-pre>`{{packageVersion}}`</span> - The version from the
|
||||
* package.json
|
||||
* - <span v-pre>`{{browser}}`</span> - The target browser from the
|
||||
* `--browser` CLI flag
|
||||
* - <span v-pre>`{{mode}}`</span> - The current mode
|
||||
* - <span v-pre>`{{modeSuffix}}`</span>: A suffix based on the mode ('-dev'
|
||||
* for development, '' for production)
|
||||
* - <span v-pre>`{{manifestVersion}}`</span> - Either "2" or "3"
|
||||
*
|
||||
* @default '{{name}}-{{version}}-sources.zip'
|
||||
* @default '{{name}}-{{packageVersion}}-sources{{modeSuffix}}.zip'
|
||||
*/
|
||||
sourcesTemplate?: string;
|
||||
/**
|
||||
@@ -248,25 +254,39 @@ export interface InlineConfig {
|
||||
*/
|
||||
sourcesRoot?: string;
|
||||
/**
|
||||
* [Picomatch](https://www.npmjs.com/package/picomatch) patterns of files to
|
||||
* include when creating a ZIP of all your source code for Firefox. Patterns
|
||||
* are relative to your `config.zip.sourcesRoot`.
|
||||
* [Tinyglobby](https://npmjs.org/tinyglobby) patterns of files to include
|
||||
* when creating a ZIP of all your source code for Firefox. Patterns are
|
||||
* relative to your `config.zip.sourcesRoot`.
|
||||
*
|
||||
* This setting overrides `excludeSources`. So if a file matches both lists,
|
||||
* it is included in the ZIP.
|
||||
* Sources ZIP files are created using standard allowlist/blocklist
|
||||
* behavior:
|
||||
*
|
||||
* - You specify a pattern to "include" (via `includeSources`), then a pattern
|
||||
* to "exclude" from the included files (via `excludeSources`).
|
||||
*
|
||||
* By default, this option includes all files except for hidden files and
|
||||
* directories (files/directories starting with a `.`).
|
||||
*
|
||||
* If you want to include hidden files/directories in your sources ZIP, see
|
||||
* `InlineConfig.zip.dotSources`.
|
||||
*
|
||||
* @example
|
||||
* [
|
||||
* 'coverage', // Include the coverage directory in the `sourcesRoot`
|
||||
* ];
|
||||
* ['entrypoints/**', 'wxt.config.ts', 'package.json', 'tsconfig.json'];
|
||||
*/
|
||||
includeSources?: string[];
|
||||
/**
|
||||
* [Picomatch](https://www.npmjs.com/package/picomatch) patterns of files to
|
||||
* exclude when creating a ZIP of all your source code for Firefox. Patterns
|
||||
* are relative to your `config.zip.sourcesRoot`.
|
||||
* [Tinyglobby](https://npmjs.org/tinyglobby) patterns of files to exclude
|
||||
* when creating a ZIP of all your source code for Firefox. Patterns are
|
||||
* relative to your `config.zip.sourcesRoot`.
|
||||
*
|
||||
* Hidden files, node_modules, and tests are ignored by default.
|
||||
* By default, WXT excludes some files:
|
||||
*
|
||||
* - `node_modules`
|
||||
* - Tests files and directories
|
||||
* - Output directory
|
||||
*
|
||||
* Any values specified in this option will be merged with the ones above -
|
||||
* you cannot replace the default values, only add to them.
|
||||
*
|
||||
* @example
|
||||
* [
|
||||
@@ -275,13 +295,31 @@ export interface InlineConfig {
|
||||
*/
|
||||
excludeSources?: string[];
|
||||
/**
|
||||
* [Picomatch](https://www.npmjs.com/package/picomatch) patterns of files to
|
||||
* exclude when zipping the extension.
|
||||
* Include hidden files/directories in your sources ZIP.
|
||||
*
|
||||
* [Tinyglobby](https://npmjs.org/tinyglobby) does not match against files
|
||||
* and directory that start with a `.` by default. For example, if you need
|
||||
* to include a `.env` file, you need to set this to `true`, then exclude
|
||||
* other hidden files/directories in `excludeSources`.
|
||||
*
|
||||
* **Be very careful when this is enabled - WXT may include files with
|
||||
* secrets in your ZIP you did not intend to share with Mozilla or upload to
|
||||
* other places**. Make sure all hidden files you don't want to include are
|
||||
* added to `excludeSources`.
|
||||
*
|
||||
* @default false
|
||||
*/
|
||||
dotSources?: boolean;
|
||||
/**
|
||||
* [Tinyglobby](https://npmjs.org/tinyglobby) patterns of files to exclude
|
||||
* when zipping the extension.
|
||||
*
|
||||
* @example
|
||||
* [
|
||||
* '**\/*.map', // Exclude all sourcemaps
|
||||
* ];
|
||||
*
|
||||
* @default [ ]
|
||||
*/
|
||||
exclude?: string[];
|
||||
/**
|
||||
@@ -412,13 +450,6 @@ export interface InlineConfig {
|
||||
* @default false
|
||||
*/
|
||||
strictPort?: boolean;
|
||||
/**
|
||||
* Hostname to run the dev server on.
|
||||
*
|
||||
* @deprecated Use `host` to specify the interface to bind to, or use
|
||||
* `origin` to specify the dev server hostname.
|
||||
*/
|
||||
hostname?: string;
|
||||
};
|
||||
/**
|
||||
* Controls whether a custom keyboard shortcut command, `Alt+R`, is added
|
||||
@@ -644,12 +675,12 @@ export interface BaseScriptEntrypointOptions extends BaseEntrypointOptions {
|
||||
* name
|
||||
* - `false`: Output the IIFE without a variable name, making it anonymous. This
|
||||
* is the safest option to avoid conflicts with existing variables on the
|
||||
* page. This will become the default in a future version of WXT.
|
||||
* page.
|
||||
* - `string`: Use the provided string as the global variable name.
|
||||
* - `function`: A function that receives the entrypoint and returns a string to
|
||||
* use as the variable name.
|
||||
*
|
||||
* @default true
|
||||
* @default false
|
||||
*/
|
||||
globalName?: string | boolean | ((entrypoint: Entrypoint) => string);
|
||||
}
|
||||
@@ -1138,9 +1169,6 @@ export interface ConfigEnv {
|
||||
|
||||
export type WxtCommand = 'build' | 'serve';
|
||||
|
||||
/** @deprecated Use `WebExtConfig` instead. */
|
||||
export type ExtensionRunnerConfig = WebExtConfig;
|
||||
|
||||
/**
|
||||
* Options for how [`web-ext`](https://github.com/mozilla/web-ext) starts the
|
||||
* browser.
|
||||
@@ -1223,7 +1251,7 @@ export interface WxtBuilder {
|
||||
* Import a JS entrypoint file, returning the default export containing the
|
||||
* options.
|
||||
*/
|
||||
importEntrypoint<T>(path: string): Promise<T>;
|
||||
importEntrypoint<T>(this: WxtBuilder, path: string): Promise<T>;
|
||||
/** Import a list of JS entrypoint files, returning their options. */
|
||||
importEntrypoints(paths: string[]): Promise<Record<string, unknown>[]>;
|
||||
/**
|
||||
@@ -1533,13 +1561,15 @@ export interface ResolvedConfig {
|
||||
imports: WxtResolvedUnimportOptions;
|
||||
manifest: UserManifest;
|
||||
fsCache: FsCache;
|
||||
runnerConfig: C12ResolvedConfig<WebExtConfig>;
|
||||
webExt: C12ResolvedConfig<WebExtConfig>;
|
||||
runner: ExtensionRunner;
|
||||
zip: {
|
||||
name?: string;
|
||||
artifactTemplate: string;
|
||||
sourcesTemplate: string;
|
||||
includeSources: string[];
|
||||
excludeSources: string[];
|
||||
dotSources: boolean;
|
||||
sourcesRoot: string;
|
||||
downloadedPackagesDir: string;
|
||||
downloadPackages: string[];
|
||||
@@ -1639,16 +1669,16 @@ export interface Eslintrc {
|
||||
* When true, generates a file that can be used by ESLint to know which
|
||||
* variables are valid globals.
|
||||
*
|
||||
* - `false`: Don't generate the file.
|
||||
* - `'auto'`: Check if eslint is installed, and if it is, generate a compatible
|
||||
* config file.
|
||||
* - `true`: Same as `8`.
|
||||
* - `true`: Same as `'auto'`.
|
||||
* - `false`: Don't generate the file.
|
||||
* - `8`: Generate a config file compatible with ESLint 8.
|
||||
* - `9`: Generate a config file compatible with ESLint 9.
|
||||
*
|
||||
* @default 'auto'
|
||||
*/
|
||||
enabled?: false | true | 'auto' | 8 | 9;
|
||||
enabled?: 'auto' | boolean | 8 | 9;
|
||||
/**
|
||||
* File path to save the generated eslint config.
|
||||
*
|
||||
@@ -1697,7 +1727,7 @@ export type WxtResolvedUnimportOptions = Partial<UnimportOptions> & {
|
||||
|
||||
/**
|
||||
* Package management utils built on top of
|
||||
* [`nypm`](https://www.npmjs.com/package/nypm)
|
||||
* [`nypm`](https://npmjs.org/package/nypm)
|
||||
*/
|
||||
export interface WxtPackageManager extends Nypm.PackageManager {
|
||||
addDependency: typeof Nypm.addDependency;
|
||||
|
||||
@@ -15,8 +15,16 @@ export function getAppConfig(): WxtAppConfig {
|
||||
/**
|
||||
* Alias for {@link getAppConfig}.
|
||||
*
|
||||
* @deprecated Use {@link getAppConfig} instead. Same function, different name.
|
||||
* @see https://wxt.dev/guide/essentials/config/runtime.html
|
||||
*/
|
||||
export function useAppConfig(): WxtAppConfig {
|
||||
// After v1.0 this function will be removed, and migrate to use only `getAppConfig` instead.
|
||||
if (import.meta.env.DEV) {
|
||||
console.warn(
|
||||
'[wxt] `useAppConfig` is deprecated. Please use `getAppConfig` instead.',
|
||||
);
|
||||
}
|
||||
|
||||
return getAppConfig();
|
||||
}
|
||||
|
||||
@@ -55,7 +55,7 @@ export async function createShadowRootUi<TMounted>(
|
||||
const mount = () => {
|
||||
// Add shadow root element to DOM
|
||||
mountUi(shadowHost, options);
|
||||
applyPosition(shadowHost, shadow.querySelector('html'), options);
|
||||
applyPosition(shadowHost, uiContainer, options);
|
||||
|
||||
// Add document CSS
|
||||
if (
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { fakeBrowser } from 'wxt/testing';
|
||||
import { fakeBrowser } from 'wxt/testing/fake-browser';
|
||||
|
||||
export const browser = fakeBrowser;
|
||||
export default fakeBrowser;
|
||||
|
||||
@@ -22,7 +22,10 @@ export default defineConfig({
|
||||
plugins: [RandomSeed({ define: 'import.meta.env.TEST_SEED' })],
|
||||
resolve: {
|
||||
alias: {
|
||||
'wxt/testing': path.resolve('src/testing'),
|
||||
'wxt/testing/fake-browser': path.resolve('src/testing/fake-browser.ts'),
|
||||
'wxt/testing/vitest-plugin': path.resolve(
|
||||
'src/testing/wxt-vitest-plugin.ts',
|
||||
),
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
@@ -1,119 +0,0 @@
|
||||
import {
|
||||
determineSemverChange,
|
||||
generateMarkDown,
|
||||
loadChangelogConfig,
|
||||
parseChangelogMarkdown,
|
||||
parseCommits,
|
||||
} from 'changelogen';
|
||||
import { consola } from 'consola';
|
||||
import { readdir } from 'node:fs/promises';
|
||||
import { join } from 'node:path';
|
||||
import { getPkgTag, grabPackageDetails, listCommitsInDir } from './git';
|
||||
|
||||
const pkg = process.argv[2];
|
||||
if (!pkg) {
|
||||
throw Error(
|
||||
'Package name missing. Usage: bun run scripts/bump-package-version.ts <package-name>',
|
||||
);
|
||||
}
|
||||
const { pkgDir, pkgName, currentVersion, prevTag, changelogPath, pkgJsonPath } =
|
||||
await grabPackageDetails(pkg);
|
||||
consola.info('Bumping:', { pkg, pkgDir, pkgName, currentVersion });
|
||||
|
||||
// Get commits
|
||||
const config = await loadChangelogConfig(process.cwd());
|
||||
consola.info('Config:', config);
|
||||
const additionalDirs = pkg === 'wxt' ? ['docs'] : [];
|
||||
const rawCommits = await listCommitsInDir(pkgDir, prevTag, additionalDirs);
|
||||
const commits = parseCommits(rawCommits, config);
|
||||
|
||||
// Bump version
|
||||
const originalBumpType = determineSemverChange(commits, config) ?? 'patch';
|
||||
let bumpType = originalBumpType;
|
||||
if (currentVersion.startsWith('0.')) {
|
||||
if (bumpType === 'major') {
|
||||
bumpType = 'minor';
|
||||
} else if (bumpType === 'minor') {
|
||||
bumpType = 'patch';
|
||||
}
|
||||
}
|
||||
await Bun.$`bun pm version ${bumpType}`.cwd(pkgDir);
|
||||
const updatedPkgJson = await Bun.file(pkgJsonPath).json();
|
||||
const newVersion: string = updatedPkgJson.version;
|
||||
const newTag = getPkgTag(pkg, newVersion);
|
||||
consola.info('Bump:', { currentVersion, bumpType, newVersion });
|
||||
|
||||
// Generate changelog
|
||||
const versionChangelog = await generateMarkDown(commits, {
|
||||
...config,
|
||||
from: prevTag,
|
||||
to: newTag,
|
||||
});
|
||||
let versionChangelogBody = versionChangelog
|
||||
.split('\n')
|
||||
.slice(1)
|
||||
.join('\n')
|
||||
.trim();
|
||||
if (originalBumpType === 'major') {
|
||||
versionChangelogBody = versionChangelogBody.replace(
|
||||
'[compare changes]',
|
||||
`[⚠️ breaking changes](https://wxt.dev/guide/resources/upgrading.html) • [compare changes]`,
|
||||
);
|
||||
}
|
||||
const { releases: prevReleases } = await Bun.file(changelogPath)
|
||||
.text()
|
||||
.then(parseChangelogMarkdown)
|
||||
.catch(() => ({ releases: [] }));
|
||||
const allReleases = [
|
||||
{
|
||||
version: newVersion,
|
||||
body: versionChangelogBody,
|
||||
},
|
||||
...prevReleases,
|
||||
];
|
||||
|
||||
const newChangelog =
|
||||
'# Changelog\n\n' +
|
||||
allReleases
|
||||
.map((release) => [`## v${release.version}`, release.body].join('\n\n'))
|
||||
.join('\n\n');
|
||||
await Bun.write(changelogPath, newChangelog);
|
||||
consola.success('Updated changelog');
|
||||
|
||||
// Update WXT version in templates when releasing wxt package
|
||||
const templatePkgJsonPaths: string[] = [];
|
||||
if (pkg === 'wxt') {
|
||||
const templatesDir = 'templates';
|
||||
const templateDirs = await readdir(templatesDir);
|
||||
for (const templateDir of templateDirs) {
|
||||
const templatePkgJsonPath = join(templatesDir, templateDir, 'package.json');
|
||||
const templatePkgJsonFile = Bun.file(templatePkgJsonPath);
|
||||
if (await templatePkgJsonFile.exists()) {
|
||||
const templatePkgJson = await templatePkgJsonFile.json();
|
||||
if (templatePkgJson.devDependencies?.wxt) {
|
||||
templatePkgJson.devDependencies.wxt = `^${newVersion}`;
|
||||
await templatePkgJsonFile.write(
|
||||
JSON.stringify(templatePkgJson, null, 2),
|
||||
);
|
||||
templatePkgJsonPaths.push(templatePkgJsonPath);
|
||||
consola.success(`Updated wxt version in ${templatePkgJsonPath}`);
|
||||
}
|
||||
} else {
|
||||
console.warn(`No package.json found in ${templatePkgJsonPath}`, {
|
||||
cwd: process.cwd(),
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Run a bun install to update the lockfile after the version change
|
||||
await Bun.$`bun install --ignore-scripts`;
|
||||
|
||||
// Commit changes
|
||||
await Bun.$`git add "${pkgJsonPath}" "${changelogPath}" bun.lock`;
|
||||
for (const packageJsonPath of templatePkgJsonPaths) {
|
||||
await Bun.$`git add "${packageJsonPath}"`;
|
||||
}
|
||||
await Bun.$`git commit -m "chore(release): ${pkgName} v${newVersion}"`;
|
||||
await Bun.$`git tag ${newTag}`;
|
||||
consola.success('Committed version and changelog');
|
||||
@@ -1,34 +0,0 @@
|
||||
import {
|
||||
createGithubRelease,
|
||||
GithubRelease,
|
||||
loadChangelogConfig,
|
||||
parseChangelogMarkdown,
|
||||
} from 'changelogen';
|
||||
import { grabPackageDetails } from './git';
|
||||
import consola from 'consola';
|
||||
|
||||
const pkg = process.argv[2];
|
||||
if (!pkg) {
|
||||
throw Error(
|
||||
'Package name missing. Usage: bun run scripts/create-github-release.ts <package-name>',
|
||||
);
|
||||
}
|
||||
|
||||
const { pkgName, prevTag, currentVersion, changelogPath } =
|
||||
await grabPackageDetails(pkg);
|
||||
consola.info('Creating release for:', { pkg, pkgName, prevTag });
|
||||
|
||||
const { releases } = await Bun.file(changelogPath)
|
||||
.text()
|
||||
.then(parseChangelogMarkdown)
|
||||
.catch(() => ({ releases: [] }));
|
||||
|
||||
const config = await loadChangelogConfig(process.cwd());
|
||||
config.tokens.github = process.env.GITHUB_TOKEN;
|
||||
await createGithubRelease(config, {
|
||||
tag_name: prevTag,
|
||||
name: `${pkgName} v${currentVersion}`,
|
||||
body: releases[0].body,
|
||||
make_latest: String(pkg === 'wxt'),
|
||||
} as GithubRelease & { make_latest: string });
|
||||
consola.success('Created release');
|
||||
@@ -1,42 +0,0 @@
|
||||
import { RawGitCommit, getGitDiff } from 'changelogen';
|
||||
import { consola } from 'consola';
|
||||
|
||||
export async function grabPackageDetails(pkg: string) {
|
||||
const pkgDir = `packages/${pkg}`;
|
||||
const pkgJsonPath = `${pkgDir}/package.json`;
|
||||
const pkgJson = await Bun.file(pkgJsonPath).json();
|
||||
const currentVersion: string = pkgJson.version;
|
||||
return {
|
||||
pkgDir,
|
||||
pkgJsonPath,
|
||||
changelogPath: `${pkgDir}/CHANGELOG.md`,
|
||||
pkgJson,
|
||||
pkgName: pkgJson.name,
|
||||
currentVersion,
|
||||
prevTag: getPkgTag(pkg, currentVersion),
|
||||
};
|
||||
}
|
||||
|
||||
export function getPkgTag(pkg: string, version: string | undefined) {
|
||||
return `${pkg}-v${version}`;
|
||||
}
|
||||
|
||||
export async function listCommitsInDir(
|
||||
dir: string,
|
||||
lastTag: string,
|
||||
additionalDirs: string[] = [],
|
||||
): Promise<RawGitCommit[]> {
|
||||
const allDirs = [dir, ...additionalDirs];
|
||||
consola.info('Listing commits:', { lastTag, dirs: allDirs });
|
||||
const commits = await getGitDiff(lastTag);
|
||||
consola.info('All commits:', commits.length);
|
||||
consola.debug(commits);
|
||||
// commit.body contains all the files that were modified/added. So just check to make sure "\t" + "packages/storage" + "/" is in the body to include
|
||||
// '"\n\nM\tpackages/wxt/vitest.config.ts\n"'
|
||||
const filtered = commits.filter((commit) =>
|
||||
allDirs.some((dir) => commit.body.includes(`\t${dir}/`)),
|
||||
);
|
||||
consola.info('Filtered:', filtered.length);
|
||||
consola.debug(filtered);
|
||||
return filtered;
|
||||
}
|
||||
@@ -1,43 +0,0 @@
|
||||
import {
|
||||
getGithubReleaseByTag,
|
||||
loadChangelogConfig,
|
||||
parseChangelogMarkdown,
|
||||
updateGithubRelease,
|
||||
} from 'changelogen';
|
||||
import { getPkgTag, grabPackageDetails } from './git';
|
||||
import consola from 'consola';
|
||||
|
||||
const pkg = process.argv[2];
|
||||
if (!pkg) {
|
||||
throw Error(
|
||||
'Package name missing. Usage: bun run scripts/sync-releases.ts <package-name>',
|
||||
);
|
||||
}
|
||||
|
||||
// Update
|
||||
const { changelogPath, pkgName } = await grabPackageDetails(pkg);
|
||||
const { releases } = await Bun.file(changelogPath)
|
||||
.text()
|
||||
.then(parseChangelogMarkdown)
|
||||
.catch(() => ({ releases: [] }));
|
||||
const config = await loadChangelogConfig(process.cwd());
|
||||
config.tokens.github = process.env.GITHUB_TOKEN;
|
||||
|
||||
// Update releases
|
||||
for (const release of releases) {
|
||||
const tag = getPkgTag(pkg, release.version);
|
||||
try {
|
||||
const existing = await getGithubReleaseByTag(config, tag);
|
||||
if (existing.body !== release.body) {
|
||||
await updateGithubRelease(config, existing.id!, {
|
||||
tag_name: tag,
|
||||
name: `${pkgName} v${release.version}`,
|
||||
body: release.body,
|
||||
});
|
||||
}
|
||||
consola.success(`Synced \`${tag}\``);
|
||||
} catch (err) {
|
||||
consola.fail(`\`${tag}\``, err);
|
||||
}
|
||||
}
|
||||
consola.success('Done');
|
||||
Vendored
+1
@@ -23,6 +23,7 @@
|
||||
"@types/react-dom": "^19.2.3",
|
||||
"@wxt-dev/module-react": "^1.1.5",
|
||||
"typescript": "^5.9.3",
|
||||
"web-ext": "^10.5.0",
|
||||
"wxt": "^0.20.27"
|
||||
}
|
||||
}
|
||||
|
||||
Vendored
+2
@@ -20,6 +20,8 @@
|
||||
"devDependencies": {
|
||||
"@wxt-dev/module-solid": "^1.1.4",
|
||||
"typescript": "^5.9.3",
|
||||
"vite": "^8.1.5",
|
||||
"web-ext": "^10.5.0",
|
||||
"wxt": "^0.20.27"
|
||||
}
|
||||
}
|
||||
|
||||
Vendored
+2
@@ -21,6 +21,8 @@
|
||||
"svelte-check": "^4.4.4",
|
||||
"tslib": "^2.8.1",
|
||||
"typescript": "^5.9.3",
|
||||
"vite": "^8.1.5",
|
||||
"web-ext": "^10.5.0",
|
||||
"wxt": "^0.20.27"
|
||||
}
|
||||
}
|
||||
|
||||
Vendored
+2
@@ -16,6 +16,8 @@
|
||||
},
|
||||
"devDependencies": {
|
||||
"typescript": "^5.9.3",
|
||||
"vite": "^8.1.5",
|
||||
"web-ext": "^10.5.0",
|
||||
"wxt": "^0.20.27"
|
||||
}
|
||||
}
|
||||
|
||||
Vendored
+2
@@ -20,7 +20,9 @@
|
||||
"devDependencies": {
|
||||
"@wxt-dev/module-vue": "^1.0.3",
|
||||
"typescript": "^5.9.3",
|
||||
"vite": "^8.1.5",
|
||||
"vue-tsc": "^3.2.5",
|
||||
"web-ext": "^10.5.0",
|
||||
"wxt": "^0.20.27"
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user