Compare commits

...

5 Commits

Author SHA1 Message Date
GitHub Actions d3abb32cb4 chore(release): v0.16.9 2024-02-20 14:17:52 +00:00
Aaron 223ede9ff9 feat: Support setting side panel options in HTML file (#468) 2024-02-20 08:14:34 -06:00
Aaron 9d31a4eba1 chore: Simplify entrypoint types (#464) 2024-02-19 16:17:54 -06:00
okou ea0e40c269 fix: Fix order of ShadowRootUI hooks calling (#459) 2024-02-19 07:45:57 -06:00
Aaron Klinker bc24ea45a4 docs: Add wrapper div to react's createShadowRootUi example
Related to #456.
2024-02-17 09:20:35 -06:00
14 changed files with 642 additions and 418 deletions
+24
View File
@@ -1,5 +1,29 @@
# Changelog
## v0.16.9
[compare changes](https://github.com/wxt-dev/wxt/compare/v0.16.8...v0.16.9)
### 🚀 Enhancements
- Support setting side panel options in HTML file ([#468](https://github.com/wxt-dev/wxt/pull/468))
### 🩹 Fixes
- Fix order of ShadowRootUI hooks calling ([#459](https://github.com/wxt-dev/wxt/pull/459))
### 📖 Documentation
- Add wrapper div to react's `createShadowRootUi` example ([bc24ea4](https://github.com/wxt-dev/wxt/commit/bc24ea4))
### 🏡 Chore
- Simplify entrypoint types ([#464](https://github.com/wxt-dev/wxt/pull/464))
### ❤️ Contributors
- Okou
## v0.16.8
[compare changes](https://github.com/wxt-dev/wxt/compare/v0.16.7...v0.16.8)
+13 -1
View File
@@ -2,6 +2,8 @@
[Chrome Docs](https://developer.chrome.com/docs/extensions/reference/sidePanel/) • [Firefox Docs](https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/user_interface/Sidebars)
In Chrome, side panels use the "side_panel" API, while Firefox uses the "sidebar_action" API.
:::warning
Chrome added support for sidepanels in Manifest V3, they are not available in Manfiest V2.
:::
@@ -25,7 +27,17 @@ Chrome added support for sidepanels in Manifest V3, they are not available in Ma
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Title</title>
<title>Default Side Panel Title</title>
<meta
name="manifest.default_icon"
content="{
16: '/icon-16.png',
24: '/icon-24.png',
...
}"
/>
<meta name="manifest.open_at_install" content="true|false" />
<meta name="manifest.browser_style" content="true|false" />
<!-- Set include/exclude if the page should be removed from some builds -->
<meta name="manifest.include" content="['chrome', ...]" />
<meta name="manifest.exclude" content="['chrome', ...]" />
+7 -3
View File
@@ -157,7 +157,7 @@ export default defineContentScript({
See the [API Reference](/api/wxt/client/functions/createIntegratedUi) for the complete list of options.
You can control how CSS is injected for an integrated content script UI with the [`cssInjectionMode`](/api/wxt/interfaces/ContentScriptBaseDefinition#cssinjectionmode) property. Usually, you'll want to leave it as `"manifest"`, the default, so the UI inherits its style from the website's CSS.
You can control how CSS is injected for an integrated content script UI with the [`cssInjectionMode`](/api/wxt/interfaces/BaseContentScriptEntrypointOptions#cssinjectionmode) property. Usually, you'll want to leave it as `"manifest"`, the default, so the UI inherits its style from the website's CSS.
## Shadow Root
@@ -168,7 +168,7 @@ WXT's [`createShadowRootUi`](/api/wxt/client/functions/createShadowRootUi) abstr
To use `createShadowRootUi`, follow these steps:
1. Import your CSS file at the top of your content script
2. Set [`cssInjectionMode: "ui"`](/api/wxt/interfaces/ContentScriptBaseDefinition#cssinjectionmode) inside `defineContentScript`
2. Set [`cssInjectionMode: "ui"`](/api/wxt/interfaces/BaseContentScriptEntrypointOptions#cssinjectionmode) inside `defineContentScript`
3. Define your UI with `createShadowRootUi()`
4. Mount the UI so it is visible to users
@@ -253,8 +253,12 @@ export default defineContentScript({
name: 'example-ui',
position: 'inline',
onMount: (container) => {
// Container is a body, and React warns when creating a root on the body, so create a wrapper div
const app = document.createElement('div');
container.append(app);
// Create a root on the UI container and render a component
const root = ReactDOM.createRoot(container);
const root = ReactDOM.createRoot(app);
root.render(<App />);
return root;
},
+1 -1
View File
@@ -1,7 +1,7 @@
{
"name": "wxt",
"type": "module",
"version": "0.16.8",
"version": "0.16.9",
"description": "Next gen framework for developing web extensions",
"engines": {
"node": ">=18",
+4 -5
View File
@@ -119,19 +119,18 @@ export async function createShadowRootUi<TMounted>(
let mounted: TMounted;
const mount = () => {
// Mount UI inside shadow root
mounted = options.onMount(uiContainer, shadow, shadowHost);
// Add shadow root element to DOM
mountUi(shadowHost, options);
applyPosition(shadowHost, shadow.querySelector('html'), options);
// Mount UI inside shadow root
mounted = options.onMount(uiContainer, shadow, shadowHost);
};
const remove = () => {
// Detatch shadow root from DOM
shadowHost.remove();
// Cleanup mounted state
options.onRemove?.(mounted);
// Detatch shadow root from DOM
shadowHost.remove();
// Remove children from uiContainer
while (uiContainer.lastChild)
uiContainer.removeChild(uiContainer.lastChild);
+5 -23
View File
@@ -5,10 +5,7 @@ import {
ServerInfo,
WxtDevServer,
} from '~/types';
import {
getEntrypointBundlePath,
resolvePerBrowserOption,
} from '~/core/utils/entrypoints';
import { getEntrypointBundlePath } from '~/core/utils/entrypoints';
import {
getContentScriptCssFiles,
getContentScriptsCssMap,
@@ -26,6 +23,7 @@ import pc from 'picocolors';
import { relative } from 'node:path';
import { registerWxt, wxt } from './wxt';
import { unnormalizePath } from './utils/paths';
import { mapWxtOptionsToRegisteredContentScript } from './utils/content-scripts';
/**
* Creates a dev server and pre-builds all the files that need to exist before loading the extension.
@@ -236,25 +234,9 @@ function reloadContentScripts(steps: BuildStepOutput[], server: WxtDevServer) {
const cssMap = getContentScriptsCssMap(server.currentOutput, [entry]);
const css = getContentScriptCssFiles([entry], cssMap);
server.reloadContentScript({
allFrames: resolvePerBrowserOption(
entry.options.allFrames,
wxt.config.browser,
),
excludeMatches: resolvePerBrowserOption(
entry.options.excludeMatches,
wxt.config.browser,
),
matches: resolvePerBrowserOption(
entry.options.matches,
wxt.config.browser,
),
runAt: resolvePerBrowserOption(entry.options.runAt, wxt.config.browser),
// @ts-expect-error: Chrome accepts this, not typed in webextension-polyfill (https://developer.chrome.com/docs/extensions/reference/scripting/#type-RegisteredContentScript)
world: resolvePerBrowserOption(entry.options.world, wxt.config.browser),
js,
css,
});
server.reloadContentScript(
mapWxtOptionsToRegisteredContentScript(entry.options, js, css),
);
});
} else {
server.reloadExtension();
+67
View File
@@ -8,6 +8,7 @@ import {
fakeManifestCommand,
fakeOptionsEntrypoint,
fakePopupEntrypoint,
fakeSidepanelEntrypoint,
setFakeWxt,
} from '../testing/fake-objects';
import { Manifest } from 'webextension-polyfill';
@@ -758,6 +759,72 @@ describe('Manifest Utils', () => {
});
});
describe('sidepanel', () => {
it.each(['chrome', 'safari', 'edge'])(
'should include a side_panel ignoring all options for %s',
async (browser) => {
const sidepanel = fakeSidepanelEntrypoint({
outputDir: outDir,
});
const buildOutput = fakeBuildOutput();
setFakeWxt({
config: {
manifestVersion: 3,
browser,
outDir,
},
});
const expected = {
side_panel: {
default_path: 'sidepanel.html',
},
};
const { manifest: actual } = await generateManifest(
[sidepanel],
buildOutput,
);
expect(actual).toMatchObject(expected);
},
);
it.each(['firefox'])(
'should include a sidebar_action for %s',
async (browser) => {
const sidepanel = fakeSidepanelEntrypoint({
outputDir: outDir,
});
const buildOutput = fakeBuildOutput();
setFakeWxt({
config: {
manifestVersion: 3,
browser,
outDir,
},
});
const expected = {
sidebar_action: {
default_panel: 'sidepanel.html',
open_at_install: sidepanel.options.openAtInstall,
default_title: sidepanel.options.defaultTitle,
default_icon: sidepanel.options.defaultIcon,
browser_style: sidepanel.options.browserStyle,
},
};
const { manifest: actual } = await generateManifest(
[sidepanel],
buildOutput,
);
expect(actual).toMatchObject(expected);
},
);
});
describe('web_accessible_resources', () => {
it('should combine user defined resources and generated resources for MV3', async () => {
const cs: ContentScriptEntrypoint = {
@@ -1,10 +1,13 @@
import { describe, it, expect, vi, beforeEach } from 'vitest';
import {
BackgroundEntrypoint,
BackgroundEntrypointOptions,
BaseEntrypointOptions,
ContentScriptEntrypoint,
GenericEntrypoint,
OptionsEntrypoint,
PopupEntrypoint,
SidepanelEntrypoint,
} from '~/types';
import { resolve } from 'path';
import { findEntrypoints } from '../find-entrypoints';
@@ -242,7 +245,7 @@ describe('findEntrypoints', () => {
])(
'should find and load background entrypoint config from %s',
async (path, expected) => {
const options: BackgroundEntrypoint['options'] = {
const options: BackgroundEntrypointOptions = {
type: 'module',
};
globMock.mockResolvedValueOnce([path]);
@@ -256,13 +259,87 @@ describe('findEntrypoints', () => {
},
);
it.each<[string, string, SidepanelEntrypoint]>([
[
'sidepanel.html',
`
<html>
<head>
<title>Default Title</title>
<meta name="manifest.default_icon" content="{ '16': '/icon/16.png' }" />
<meta name="manifest.open_at_install" content="true" />
</head>
</html>
`,
{
type: 'sidepanel',
name: 'sidepanel',
inputPath: resolve(config.entrypointsDir, 'sidepanel.html'),
outputDir: config.outDir,
options: {
defaultTitle: 'Default Title',
defaultIcon: { '16': '/icon/16.png' },
openAtInstall: true,
},
skipped: false,
},
],
[
'sidepanel/index.html',
`<html></html>`,
{
type: 'sidepanel',
name: 'sidepanel',
inputPath: resolve(config.entrypointsDir, 'sidepanel/index.html'),
options: {},
outputDir: config.outDir,
skipped: false,
},
],
[
'named.sidepanel.html',
`<html></html>`,
{
type: 'sidepanel',
name: 'named',
inputPath: resolve(config.entrypointsDir, 'named.sidepanel.html'),
options: {},
outputDir: config.outDir,
skipped: false,
},
],
[
'named.sidepanel/index.html',
`<html></html>`,
{
type: 'sidepanel',
name: 'named',
inputPath: resolve(config.entrypointsDir, 'named.sidepanel/index.html'),
outputDir: config.outDir,
options: {},
skipped: false,
},
],
])(
'should find and load sidepanel entrypoint config from %s',
async (path, content, expected) => {
globMock.mockResolvedValueOnce([path]);
readFileMock.mockResolvedValueOnce(content);
const entrypoints = await findEntrypoints();
expect(entrypoints).toHaveLength(1);
expect(entrypoints[0]).toEqual(expected);
},
);
it('should remove type=module from MV2 background scripts', async () => {
setFakeWxt({
config: {
manifestVersion: 2,
},
});
const options: BackgroundEntrypoint['options'] = {
const options: BackgroundEntrypointOptions = {
type: 'module',
};
globMock.mockResolvedValueOnce(['background.ts']);
@@ -279,7 +356,7 @@ describe('findEntrypoints', () => {
manifestVersion: 3,
},
});
const options: BackgroundEntrypoint['options'] = {
const options: BackgroundEntrypointOptions = {
type: 'module',
};
globMock.mockResolvedValueOnce(['background.ts']);
@@ -331,7 +408,7 @@ describe('findEntrypoints', () => {
outputDir: config.outDir,
skipped: false,
};
const options: GenericEntrypoint['options'] = {};
const options: BaseEntrypointOptions = {};
globMock.mockResolvedValueOnce([path]);
importEntrypointFileMock.mockResolvedValue(options);
@@ -462,52 +539,6 @@ describe('findEntrypoints', () => {
},
],
// sidepanel
[
'sidepanel.html',
{
type: 'sidepanel',
name: 'sidepanel',
inputPath: resolve(config.entrypointsDir, 'sidepanel.html'),
outputDir: config.outDir,
options: {},
skipped: false,
},
],
[
'sidepanel/index.html',
{
type: 'sidepanel',
name: 'sidepanel',
inputPath: resolve(config.entrypointsDir, 'sidepanel/index.html'),
outputDir: config.outDir,
options: {},
skipped: false,
},
],
[
'named.sidepanel.html',
{
type: 'sidepanel',
name: 'named',
inputPath: resolve(config.entrypointsDir, 'named.sidepanel.html'),
outputDir: config.outDir,
options: {},
skipped: false,
},
],
[
'named.sidepanel/index.html',
{
type: 'sidepanel',
name: 'named',
inputPath: resolve(config.entrypointsDir, 'named.sidepanel/index.html'),
outputDir: config.outDir,
options: {},
skipped: false,
},
],
// devtools
[
'devtools.html',
+140 -144
View File
@@ -10,6 +10,10 @@ import {
OptionsEntrypoint,
PopupEntrypoint,
UnlistedScriptDefinition,
PopupEntrypointOptions,
OptionsEntrypointOptions,
SidepanelEntrypoint,
SidepanelEntrypointOptions,
} from '~/types';
import fs from 'fs-extra';
import { minimatch } from 'minimatch';
@@ -19,7 +23,7 @@ import { importEntrypointFile } from '~/core/utils/building';
import glob from 'fast-glob';
import {
getEntrypointName,
resolvePerBrowserOption,
resolvePerBrowserOptions,
} from '~/core/utils/entrypoints';
import { VIRTUAL_NOOP_BACKGROUND_MODULE_ID } from '~/core/utils/constants';
import { CSS_EXTENSIONS_PATTERN } from '~/core/utils/paths';
@@ -71,6 +75,8 @@ export async function findEntrypoints(): Promise<Entrypoint[]> {
switch (type) {
case 'popup':
return await getPopupEntrypoint(info);
case 'sidepanel':
return await getSidepanelEntrypoint(info);
case 'options':
return await getOptionsEntrypoint(info);
case 'background':
@@ -199,153 +205,81 @@ function preventNoEntrypoints(files: EntrypointInfo[]) {
}
}
function getHtmlBaseOptions(document: Document): BaseEntrypointOptions {
const options: BaseEntrypointOptions = {};
const includeContent = document
.querySelector("meta[name='manifest.include']")
?.getAttribute('content');
if (includeContent) {
options.include = JSON5.parse(includeContent);
}
const excludeContent = document
.querySelector("meta[name='manifest.exclude']")
?.getAttribute('content');
if (excludeContent) {
options.exclude = JSON5.parse(excludeContent);
}
return options;
}
/**
* @param path Absolute path to the popup HTML file.
* @param content String contents of the file at the path.
*/
async function getPopupEntrypoint({
inputPath,
name,
skipped,
}: EntrypointInfo): Promise<PopupEntrypoint> {
const content = await fs.readFile(inputPath, 'utf-8');
const { document } = parseHTML(content);
const options: PopupEntrypoint['options'] = getHtmlBaseOptions(document);
const title = document.querySelector('title');
if (title != null) options.defaultTitle = title.textContent ?? undefined;
const defaultIconContent = document
.querySelector("meta[name='manifest.default_icon']")
?.getAttribute('content');
if (defaultIconContent) {
try {
options.defaultIcon = JSON5.parse(defaultIconContent);
} catch (err) {
wxt.logger.fatal(
`Failed to parse default_icon meta tag content as JSON5. content=${defaultIconContent}`,
err,
);
}
}
const mv2TypeContent = document
.querySelector("meta[name='manifest.type']")
?.getAttribute('content');
if (mv2TypeContent) {
options.mv2Key =
mv2TypeContent === 'page_action' ? 'page_action' : 'browser_action';
}
const browserStyleContent = document
.querySelector("meta[name='manifest.browser_style']")
?.getAttribute('content');
if (browserStyleContent) {
options.browserStyle = browserStyleContent === 'true';
}
async function getPopupEntrypoint(
info: EntrypointInfo,
): Promise<PopupEntrypoint> {
const options = await getHtmlEntrypointOptions<PopupEntrypointOptions>(
info,
{
browserStyle: 'browse_style',
exclude: 'exclude',
include: 'include',
defaultIcon: 'default_icon',
defaultTitle: 'default_title',
mv2Key: 'type',
},
{
defaultTitle: (document) =>
document.querySelector('title')?.textContent || undefined,
},
{
defaultTitle: (content) => content,
mv2Key: (content) =>
content === 'page_action' ? 'page_action' : 'browser_action',
},
);
return {
type: 'popup',
name: 'popup',
options,
inputPath,
options: resolvePerBrowserOptions(options, wxt.config.browser),
inputPath: info.inputPath,
outputDir: wxt.config.outDir,
skipped,
skipped: info.skipped,
};
}
/**
* @param path Absolute path to the options HTML file.
* @param content String contents of the file at the path.
*/
async function getOptionsEntrypoint({
inputPath,
name,
skipped,
}: EntrypointInfo): Promise<OptionsEntrypoint> {
const content = await fs.readFile(inputPath, 'utf-8');
const { document } = parseHTML(content);
const options: OptionsEntrypoint['options'] = getHtmlBaseOptions(document);
const openInTabContent = document
.querySelector("meta[name='manifest.open_in_tab']")
?.getAttribute('content');
if (openInTabContent) {
options.openInTab = openInTabContent === 'true';
}
const chromeStyleContent = document
.querySelector("meta[name='manifest.chrome_style']")
?.getAttribute('content');
if (chromeStyleContent) {
options.chromeStyle = chromeStyleContent === 'true';
}
const browserStyleContent = document
.querySelector("meta[name='manifest.browser_style']")
?.getAttribute('content');
if (browserStyleContent) {
options.browserStyle = browserStyleContent === 'true';
}
async function getOptionsEntrypoint(
info: EntrypointInfo,
): Promise<OptionsEntrypoint> {
const options = await getHtmlEntrypointOptions<OptionsEntrypointOptions>(
info,
{
browserStyle: 'browse_style',
chromeStyle: 'chrome_style',
exclude: 'exclude',
include: 'include',
openInTab: 'open_in_tab',
},
);
return {
type: 'options',
name: 'options',
options,
inputPath,
options: resolvePerBrowserOptions(options, wxt.config.browser),
inputPath: info.inputPath,
outputDir: wxt.config.outDir,
skipped,
skipped: info.skipped,
};
}
/**
* @param path Absolute path to the HTML file.
* @param content String contents of the file at the path.
*/
async function getUnlistedPageEntrypoint({
inputPath,
name,
skipped,
}: EntrypointInfo): Promise<GenericEntrypoint> {
const content = await fs.readFile(inputPath, 'utf-8');
const { document } = parseHTML(content);
async function getUnlistedPageEntrypoint(
info: EntrypointInfo,
): Promise<GenericEntrypoint> {
const options = await getHtmlEntrypointOptions<BaseEntrypointOptions>(info, {
exclude: 'exclude',
include: 'include',
});
return {
type: 'unlisted-page',
name: getEntrypointName(wxt.config.entrypointsDir, inputPath),
inputPath,
name: info.name,
inputPath: info.inputPath,
outputDir: wxt.config.outDir,
options: getHtmlBaseOptions(document),
skipped,
options,
skipped: info.skipped,
};
}
/**
* @param path Absolute path to the script's file.
* @param content String contents of the file at the path.
*/
async function getUnlistedScriptEntrypoint({
inputPath,
name,
@@ -358,21 +292,17 @@ async function getUnlistedScriptEntrypoint({
`${name}: Default export not found, did you forget to call "export default defineUnlistedScript(...)"?`,
);
}
const { main: _, ...moduleOptions } = defaultExport;
const options: Omit<UnlistedScriptDefinition, 'main'> = moduleOptions;
const { main: _, ...options } = defaultExport;
return {
type: 'unlisted-script',
name,
inputPath,
outputDir: wxt.config.outDir,
options,
options: resolvePerBrowserOptions(options, wxt.config.browser),
skipped,
};
}
/**
* @param path Absolute path to the background's TS file.
*/
async function getBackgroundEntrypoint({
inputPath,
name,
@@ -400,21 +330,11 @@ async function getBackgroundEntrypoint({
name,
inputPath,
outputDir: wxt.config.outDir,
options: {
...options,
type: resolvePerBrowserOption(options.type, wxt.config.browser),
persistent: resolvePerBrowserOption(
options.persistent,
wxt.config.browser,
),
},
options: resolvePerBrowserOptions(options, wxt.config.browser),
skipped,
};
}
/**
* @param path Absolute path to the content script's TS file.
*/
async function getContentScriptEntrypoint({
inputPath,
name,
@@ -432,11 +352,87 @@ async function getContentScriptEntrypoint({
name,
inputPath,
outputDir: resolve(wxt.config.outDir, CONTENT_SCRIPT_OUT_DIR),
options,
options: resolvePerBrowserOptions(options, wxt.config.browser),
skipped,
};
}
async function getSidepanelEntrypoint(
info: EntrypointInfo,
): Promise<SidepanelEntrypoint> {
const options = await getHtmlEntrypointOptions<SidepanelEntrypointOptions>(
info,
{
browserStyle: 'browse_style',
exclude: 'exclude',
include: 'include',
defaultIcon: 'default_icon',
defaultTitle: 'default_title',
openAtInstall: 'open_at_install',
},
{
defaultTitle: (document) =>
document.querySelector('title')?.textContent || undefined,
},
{
defaultTitle: (content) => content,
},
);
return {
type: 'sidepanel',
name: info.name,
options: resolvePerBrowserOptions(options, wxt.config.browser),
inputPath: info.inputPath,
outputDir: wxt.config.outDir,
skipped: info.skipped,
};
}
/**
* Parse the HTML tags to extract options from them.
*/
async function getHtmlEntrypointOptions<T extends BaseEntrypointOptions>(
info: EntrypointInfo,
keyMap: Record<keyof T, string>,
queries?: Partial<{
[key in keyof T]: (
document: Document,
manifestKey: string,
) => string | undefined;
}>,
parsers?: Partial<{ [key in keyof T]: (content: string) => T[key] }>,
): Promise<T> {
const content = await fs.readFile(info.inputPath, 'utf-8');
const { document } = parseHTML(content);
const options = {} as T;
const defaultQuery = (manifestKey: string) =>
document
.querySelector(`meta[name='manifest.${manifestKey}']`)
?.getAttribute('content');
Object.entries(keyMap).forEach(([_key, manifestKey]) => {
const key = _key as keyof T;
const content = queries?.[key]
? queries[key]!(document, manifestKey)
: defaultQuery(manifestKey);
if (content) {
try {
options[key] = (parsers?.[key] ?? JSON5.parse)(content);
} catch (err) {
wxt.logger.fatal(
`Failed to parse meta tag content. Usually this means you have invalid JSON5 content (content=${content})`,
err,
);
}
}
});
return options;
}
const PATH_GLOB_TO_TYPE_MAP: Record<string, Entrypoint['type']> = {
'sandbox.html': 'sandbox',
'sandbox/index.html': 'sandbox',
+36 -28
View File
@@ -1,7 +1,5 @@
import type { Manifest } from '~/browser';
import type { Manifest, Scripting } from '~/browser';
import { ContentScriptEntrypoint } from '~/types';
import { resolvePerBrowserOption } from './entrypoints';
import { wxt } from '../wxt';
/**
* Returns a unique and consistent string hash based on a content scripts options.
@@ -11,7 +9,11 @@ import { wxt } from '../wxt';
export function hashContentScriptOptions(
options: ContentScriptEntrypoint['options'],
): string {
const simplifiedOptions = mapWxtOptionsToContentScript(options);
const simplifiedOptions = mapWxtOptionsToContentScript(
options,
undefined,
undefined,
);
// Remove undefined fields and use defaults to generate hash
Object.keys(simplifiedOptions).forEach((key) => {
@@ -45,33 +47,39 @@ export function hashContentScriptOptions(
export function mapWxtOptionsToContentScript(
options: ContentScriptEntrypoint['options'],
): Omit<Manifest.ContentScript, 'js' | 'css'> {
js: string[] | undefined,
css: string[] | undefined,
): Manifest.ContentScript {
return {
matches: resolvePerBrowserOption(options.matches, wxt.config.browser),
all_frames: resolvePerBrowserOption(options.allFrames, wxt.config.browser),
match_about_blank: resolvePerBrowserOption(
options.matchAboutBlank,
wxt.config.browser,
),
exclude_globs: resolvePerBrowserOption(
options.excludeGlobs,
wxt.config.browser,
),
exclude_matches: resolvePerBrowserOption(
options.excludeMatches,
wxt.config.browser,
),
include_globs: resolvePerBrowserOption(
options.includeGlobs,
wxt.config.browser,
),
run_at: resolvePerBrowserOption(options.runAt, wxt.config.browser),
matches: options.matches,
all_frames: options.allFrames,
match_about_blank: options.matchAboutBlank,
exclude_globs: options.excludeGlobs,
exclude_matches: options.excludeMatches,
include_globs: options.includeGlobs,
run_at: options.runAt,
css,
js,
// @ts-expect-error: untyped chrome options
match_origin_as_fallback: resolvePerBrowserOption(
options.matchOriginAsFallback,
wxt.config.browser,
),
match_origin_as_fallback: options.matchOriginAsFallback,
world: options.world,
};
}
export function mapWxtOptionsToRegisteredContentScript(
options: ContentScriptEntrypoint['options'],
js: string[] | undefined,
css: string[] | undefined,
): Omit<Scripting.RegisteredContentScript, 'id'> {
return {
allFrames: options.allFrames,
excludeMatches: options.excludeMatches,
matches: options.matches,
runAt: options.runAt,
js,
css,
// @ts-expect-error: Chrome accepts this, not typed in webextension-polyfill (https://developer.chrome.com/docs/extensions/reference/scripting/#type-RegisteredContentScript)
world: options.world,
};
}
+25 -1
View File
@@ -1,4 +1,9 @@
import { Entrypoint, PerBrowserOption, TargetBrowser } from '~/types';
import {
Entrypoint,
PerBrowserOption,
ResolvedPerBrowserOptions,
TargetBrowser,
} from '~/types';
import path, { relative, resolve } from 'node:path';
import { normalizePath } from './paths';
@@ -46,3 +51,22 @@ export function resolvePerBrowserOption<T>(
return (option as any)[browser];
return option;
}
/**
* Given an entrypoint option, resolve it's value based on a target browser.
*
* defaultIcon is special, it's the only key that's a record, which can confuse this function. So
* it's been manually excluded from resolution.
*/
export function resolvePerBrowserOptions<
T extends Record<string, any>,
TKeys extends keyof T,
>(options: T, browser: TargetBrowser): ResolvedPerBrowserOptions<T, TKeys> {
// @ts-expect-error: Object.entries is untyped.
return Object.fromEntries(
Object.entries(options).map(([key, value]) => [
key,
key === 'defaultIcon' ? value : resolvePerBrowserOption(value, browser),
]),
);
}
+20 -22
View File
@@ -6,13 +6,11 @@ import {
ContentScriptEntrypoint,
OptionsEntrypoint,
PopupEntrypoint,
SidepanelEntrypoint,
} from '~/types';
import fs from 'fs-extra';
import { resolve } from 'path';
import {
getEntrypointBundlePath,
resolvePerBrowserOption,
} from './entrypoints';
import { getEntrypointBundlePath } from './entrypoints';
import { ContentSecurityPolicy } from './content-security-policy';
import {
hashContentScriptOptions,
@@ -185,7 +183,9 @@ function addEntrypoints(
| undefined;
const popup = entriesByType['popup']?.[0] as PopupEntrypoint | undefined;
const sandboxes = entriesByType['sandbox'];
const sidepanels = entriesByType['sidepanel'];
const sidepanels = entriesByType['sidepanel'] as
| SidepanelEntrypoint[]
| undefined;
if (background) {
const script = getEntrypointBundlePath(
@@ -331,9 +331,11 @@ function addEntrypoints(
if (wxt.config.browser === 'firefox') {
manifest.sidebar_action = {
// TODO: Add options to side panel
// ...defaultSidepanel.options,
default_panel: page,
browser_style: defaultSidepanel.options.browserStyle,
default_icon: defaultSidepanel.options.defaultIcon,
default_title: defaultSidepanel.options.defaultTitle,
open_at_install: defaultSidepanel.options.openAtInstall,
};
} else if (wxt.config.manifestVersion === 3) {
// @ts-expect-error: Untyped
@@ -355,11 +357,7 @@ function addEntrypoints(
if (wxt.config.command === 'serve' && wxt.config.manifestVersion === 3) {
const hostPermissions = new Set<string>(manifest.host_permissions ?? []);
contentScripts.forEach((script) => {
const matches = resolvePerBrowserOption(
script.options.matches,
wxt.config.browser,
);
matches.forEach((matchPattern) => {
script.options.matches.forEach((matchPattern) => {
hostPermissions.add(matchPattern);
});
});
@@ -375,13 +373,14 @@ function addEntrypoints(
}, new Map<string, ContentScriptEntrypoint[]>());
const newContentScripts = Array.from(hashToEntrypointsMap.entries()).map(
([, scripts]) => ({
...mapWxtOptionsToContentScript(scripts[0].options),
css: getContentScriptCssFiles(scripts, cssMap),
js: scripts.map((entry) =>
getEntrypointBundlePath(entry, wxt.config.outDir, '.js'),
([, scripts]) =>
mapWxtOptionsToContentScript(
scripts[0].options,
scripts.map((entry) =>
getEntrypointBundlePath(entry, wxt.config.outDir, '.js'),
),
getContentScriptCssFiles(scripts, cssMap),
),
}),
);
if (newContentScripts.length >= 0) {
manifest.content_scripts ??= [];
@@ -519,10 +518,9 @@ export function getContentScriptCssWebAccessibleResources(
resources.push({
resources: [cssFile],
matches: resolvePerBrowserOption(
script.options.matches,
wxt.config.browser,
).map((matchPattern) => stripPathFromMatchPattern(matchPattern)),
matches: script.options.matches.map((matchPattern) =>
stripPathFromMatchPattern(matchPattern),
),
});
});
+25 -1
View File
@@ -21,6 +21,7 @@ import {
BuildStepOutput,
UserManifest,
Wxt,
SidepanelEntrypoint,
} from '~/types';
import { mock } from 'vitest-mock-extended';
import { vi } from 'vitest';
@@ -148,6 +149,30 @@ export const fakePopupEntrypoint = fakeObjectCreator<PopupEntrypoint>(() => ({
skipped: faker.datatype.boolean(),
}));
export const fakeSidepanelEntrypoint = fakeObjectCreator<SidepanelEntrypoint>(
() => ({
type: 'sidepanel',
inputPath: 'entrypoints/sidepanel.html',
name: 'sidepanel',
outputDir: fakeDir('.output'),
options: {
defaultTitle: faker.helpers.arrayElement([
faker.person.fullName(),
undefined,
]),
defaultIcon: faker.helpers.arrayElement([
{
'16': 'icon/16.png',
'24': 'icon/24.png',
'64': 'icon/64.png',
},
]),
openAtInstall: faker.helpers.arrayElement([true, false, undefined]),
},
skipped: faker.datatype.boolean(),
}),
);
export const fakeGenericEntrypoint = fakeObjectCreator<GenericEntrypoint>(
() => ({
type: faker.helpers.arrayElement([
@@ -155,7 +180,6 @@ export const fakeGenericEntrypoint = fakeObjectCreator<GenericEntrypoint>(
'bookmarks',
'history',
'newtab',
'sidepanel',
'devtools',
'unlisted-page',
'unlisted-script',
+194 -139
View File
@@ -424,131 +424,37 @@ export interface Logger {
}
export interface BaseEntrypointOptions {
/**
* List of target browsers to include this entrypoint in. Defaults to being included in all
* builds. Cannot be used with `exclude`. You must choose one of the two options.
*
* @default undefined
*/
include?: TargetBrowser[];
/**
* List of target browsers to exclude this entrypoint from. Cannot be used with `include`. You
* must choose one of the two options.
*
* @default undefined
*/
exclude?: TargetBrowser[];
}
export interface BaseEntrypoint {
export interface BackgroundEntrypointOptions extends BaseEntrypointOptions {
persistent?: PerBrowserOption<boolean>;
/**
* The entrypoint's name. This is the filename or dirname without the type suffix.
* Set to `"module"` to output the background entrypoint as ESM. ESM outputs can share chunks and
* reduce the overall size of the bundled extension.
*
* Examples:
* - `popup.html` &rarr; `popup`
* - `options/index.html` &rarr; `options`
* - `named.sandbox.html` &rarr; `named`
* - `named.sandbox/index.html` &rarr; `named`
* - `sandbox.html` &rarr; `sandbox`
* - `sandbox/index.html` &rarr; `sandbox`
* - `overlay.content.ts` &rarr; `overlay`
* - `overlay.content/index.ts` &rarr; `overlay`
* When `undefined`, the background is bundled individually into an IIFE format.
*
* The name is used when generating an output file:
* `<entrypoint.outputDir>/<entrypoint.name>.<ext>`
* @default undefined
*/
name: string;
/**
* Absolute path to the entrypoint's input file.
*/
inputPath: string;
/**
* Absolute path to the entrypoint's output directory. Can be the`InternalConfg.outDir` or a
* subdirectory of it.
*/
outputDir: string;
options: BaseEntrypointOptions;
skipped: boolean;
type?: PerBrowserOption<'module'>;
}
export interface GenericEntrypoint extends BaseEntrypoint {
type:
| 'sandbox'
| 'bookmarks'
| 'history'
| 'newtab'
| 'sidepanel'
| 'devtools'
| 'unlisted-page'
| 'unlisted-script'
| 'unlisted-style'
| 'content-script-style';
}
export interface BackgroundEntrypoint extends BaseEntrypoint {
type: 'background';
options: {
persistent?: boolean;
type?: 'module';
} & BaseEntrypointOptions;
}
export interface ContentScriptEntrypoint extends BaseEntrypoint {
type: 'content-script';
options: Omit<ContentScriptDefinition, 'main'> & BaseEntrypointOptions;
}
export interface PopupEntrypoint extends BaseEntrypoint {
type: 'popup';
options: {
/**
* Defaults to "browser_action" to be equivalent to MV3's "action" key
*/
mv2Key?: 'browser_action' | 'page_action';
defaultIcon?: Record<string, string>;
defaultTitle?: string;
browserStyle?: boolean;
} & BaseEntrypointOptions;
}
export interface OptionsEntrypoint extends BaseEntrypoint {
type: 'options';
options: {
openInTab?: boolean;
browserStyle?: boolean;
chromeStyle?: boolean;
} & BaseEntrypointOptions;
}
export type Entrypoint =
| GenericEntrypoint
| BackgroundEntrypoint
| ContentScriptEntrypoint
| PopupEntrypoint
| OptionsEntrypoint;
export type EntrypointGroup = Entrypoint | Entrypoint[];
export type OnContentScriptStopped = (cb: () => void) => void;
export type ContentScriptDefinition =
| ContentScriptIsolatedWorldDefinition
| ContentScriptMainWorldDefinition;
export interface ContentScriptIsolatedWorldDefinition
extends ContentScriptBaseDefinition {
/**
* See https://developer.chrome.com/docs/extensions/develop/concepts/content-scripts#isolated_world
* @default "ISOLATED"
*/
world?: 'ISOLATED';
/**
* Main function executed when the content script is loaded.
*/
main(ctx: ContentScriptContext): void | Promise<void>;
}
export interface ContentScriptMainWorldDefinition
extends ContentScriptBaseDefinition {
/**
* See https://developer.chrome.com/docs/extensions/develop/concepts/content-scripts#isolated_world
*/
world: 'MAIN';
/**
* Main function executed when the content script is loaded.
*/
main(): void | Promise<void>;
}
export interface ContentScriptBaseDefinition extends ExcludableEntrypoint {
export interface BaseContentScriptEntrypointOptions
extends BaseEntrypointOptions {
matches: PerBrowserOption<Manifest.ContentScript['matches']>;
/**
* See https://developer.chrome.com/docs/extensions/mv3/content_scripts/
@@ -596,44 +502,195 @@ export interface ContentScriptBaseDefinition extends ExcludableEntrypoint {
* onto the page. Use `browser.runtime.getURL("content-scripts/<name>.css")` to get the file's
* URL
* - `"ui"` - Exclude the CSS from the manifest. CSS will be automatically added to your UI when
* calling `createContentScriptUi`
* calling `createShadowRootUi`
*
* @default "manifest"
*/
cssInjectionMode?: PerBrowserOption<'manifest' | 'manual' | 'ui'>;
}
export interface BackgroundDefinition extends ExcludableEntrypoint {
type?: PerBrowserOption<'module'>;
persistent?: PerBrowserOption<boolean>;
export interface MainWorldContentScriptEntrypointOptions
extends BaseContentScriptEntrypointOptions {
/**
* See https://developer.chrome.com/docs/extensions/develop/concepts/content-scripts#isolated_world
*/
world: 'MAIN';
}
export interface IsolatedWorldContentScriptEntrypointOptions
extends BaseContentScriptEntrypointOptions {
/**
* See https://developer.chrome.com/docs/extensions/develop/concepts/content-scripts#isolated_world
* @default "ISOLATED"
*/
world?: 'ISOLATED';
}
export interface PopupEntrypointOptions extends BaseEntrypointOptions {
/**
* Defaults to "browser_action" to be equivalent to MV3's "action" key
*/
mv2Key?: PerBrowserOption<'browser_action' | 'page_action'>;
defaultIcon?: Record<string, string>;
defaultTitle?: PerBrowserOption<string>;
browserStyle?: PerBrowserOption<boolean>;
}
export interface OptionsEntrypointOptions extends BaseEntrypointOptions {
openInTab?: PerBrowserOption<boolean>;
browserStyle?: PerBrowserOption<boolean>;
chromeStyle?: PerBrowserOption<boolean>;
}
export interface SidepanelEntrypointOptions extends BaseEntrypointOptions {
/**
* Firefox only. See https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/sidebar_action#syntax
* @default false
*/
openAtInstall?: PerBrowserOption<boolean>;
/**
* @deprecated See https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/sidebar_action#syntax
*/
browserStyle?: PerBrowserOption<boolean>;
defaultIcon?: string | Record<string, string>;
defaultTitle?: PerBrowserOption<string>;
}
export interface BaseEntrypoint {
/**
* The entrypoint's name. This is the filename or dirname without the type suffix.
*
* Examples:
* - `popup.html` &rarr; `popup`
* - `options/index.html` &rarr; `options`
* - `named.sandbox.html` &rarr; `named`
* - `named.sandbox/index.html` &rarr; `named`
* - `sandbox.html` &rarr; `sandbox`
* - `sandbox/index.html` &rarr; `sandbox`
* - `overlay.content.ts` &rarr; `overlay`
* - `overlay.content/index.ts` &rarr; `overlay`
*
* The name is used when generating an output file:
* `<entrypoint.outputDir>/<entrypoint.name>.<ext>`
*/
name: string;
/**
* Absolute path to the entrypoint's input file.
*/
inputPath: string;
/**
* Absolute path to the entrypoint's output directory. Can be the`InternalConfg.outDir` or a
* subdirectory of it.
*/
outputDir: string;
skipped: boolean;
}
export interface GenericEntrypoint extends BaseEntrypoint {
type:
| 'sandbox'
| 'bookmarks'
| 'history'
| 'newtab'
| 'devtools'
| 'unlisted-page'
| 'unlisted-script'
| 'unlisted-style'
| 'content-script-style';
options: ResolvedPerBrowserOptions<BaseEntrypointOptions>;
}
export interface BackgroundEntrypoint extends BaseEntrypoint {
type: 'background';
options: ResolvedPerBrowserOptions<BackgroundEntrypointOptions>;
}
export interface ContentScriptEntrypoint extends BaseEntrypoint {
type: 'content-script';
options: ResolvedPerBrowserOptions<
| MainWorldContentScriptEntrypointOptions
| IsolatedWorldContentScriptEntrypointOptions
>;
}
export interface PopupEntrypoint extends BaseEntrypoint {
type: 'popup';
options: ResolvedPerBrowserOptions<PopupEntrypointOptions, 'defaultIcon'>;
}
export interface OptionsEntrypoint extends BaseEntrypoint {
type: 'options';
options: ResolvedPerBrowserOptions<OptionsEntrypointOptions>;
}
export interface SidepanelEntrypoint extends BaseEntrypoint {
type: 'sidepanel';
options: ResolvedPerBrowserOptions<SidepanelEntrypointOptions, 'defaultIcon'>;
}
export type Entrypoint =
| GenericEntrypoint
| BackgroundEntrypoint
| ContentScriptEntrypoint
| PopupEntrypoint
| OptionsEntrypoint
| SidepanelEntrypoint;
export type EntrypointGroup = Entrypoint | Entrypoint[];
export type OnContentScriptStopped = (cb: () => void) => void;
export interface IsolatedWorldContentScriptDefinition
extends IsolatedWorldContentScriptEntrypointOptions {
/**
* Main function executed when the content script is loaded.
*/
main(ctx: ContentScriptContext): void | Promise<void>;
}
export interface MainWorldContentScriptDefinition
extends MainWorldContentScriptEntrypointOptions {
/**
* Main function executed when the content script is loaded.
*/
main(): void | Promise<void>;
}
export type ContentScriptDefinition =
| IsolatedWorldContentScriptDefinition
| MainWorldContentScriptDefinition;
export interface BackgroundDefinition extends BackgroundEntrypointOptions {
/**
* Main function executed when the background script is started. Cannot be async.
*/
main(): void;
}
export interface UnlistedScriptDefinition extends ExcludableEntrypoint {
export interface UnlistedScriptDefinition extends BaseEntrypointOptions {
/**
* Main function executed when the unlisted script is ran.
*/
main(): void | Promise<void>;
}
export type PerBrowserOption<T> = T | { [browser: TargetBrowser]: T };
/**
* Either a single value or a map of different browsers to the value for that browser.
*/
export type PerBrowserOption<T> = T | PerBrowserMap<T>;
export type PerBrowserMap<T> = { [browser: TargetBrowser]: T };
export interface ExcludableEntrypoint {
/**
* List of target browsers to include this entrypoint in. Defaults to being included in all
* builds. Cannot be used with `exclude`. You must choose one of the two options.
*
* @default undefined
*/
include?: TargetBrowser[];
/**
* List of target browsers to exclude this entrypoint from. Cannot be used with `include`. You
* must choose one of the two options.
*
* @default undefined
*/
exclude?: TargetBrowser[];
}
/**
* Convert `{ key: PerBrowserOption<T> }` to just `{ key: T }`, stripping away the
* `PerBrowserOption` type for all fields inside the object.
*
* A optional second list of keys can be passed if a field isn't compatible with `PerBrowserOption`, like `defaultIcon`.
*/
export type ResolvedPerBrowserOptions<T, TOmitted extends keyof T = never> = {
[key in keyof Omit<T, TOmitted>]: T[key] extends PerBrowserOption<infer U>
? U
: T[key];
} & { [key in TOmitted]: T[key] };
/**
* Manifest customization available in the `wxt.config.ts` file. You cannot configure entrypoints
@@ -649,8 +706,6 @@ export type UserManifest = Partial<
| 'options_page'
| 'options_ui'
| 'sandbox'
| 'sidepanel'
| 'sidebar_action'
>
>;