/
index.ts
1251 lines (1189 loc) · 37.8 KB
/
index.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import type * as vite from 'vite';
import type { Manifest, Scripting } from '~/browser';
import { UnimportOptions } from 'unimport';
import { LogLevel } from 'consola';
import { ContentScriptContext } from '../client/content-scripts/content-script-context';
import type { PluginVisualizerOptions } from '@aklinker1/rollup-plugin-visualizer';
import type { FSWatcher } from 'chokidar';
import { ResolvedConfig as C12ResolvedConfig } from 'c12';
import { Hookable, NestedHooks } from 'hookable';
import type * as Nypm from 'nypm';
export interface InlineConfig {
/**
* Your project's root directory containing the `package.json` used to fill out the
* `manifest.json`.
*
* @default process.cwd()
*/
root?: string;
/**
* Directory containing all source code. Set to `"src"` to move all source code to a `src/`
* directory.
*
* After changing, don't forget to move the `public/` and `entrypoints/` directories into the new
* source dir.
*
* @default config.root
*/
srcDir?: string;
/**
* Directory containing files that will be copied to the output directory as-is.
*
* @default "${config.root}/public"
*/
publicDir?: string;
/**
* @default "${config.srcDir}/entrypoints"
*/
entrypointsDir?: string;
/**
* A list of entrypoint names (`"popup"`, `"options"`, etc.) to build. Will speed up the build if
* your extension has lots of entrypoints, and you don't need to build all of them to develop a
* feature.
*/
filterEntrypoints?: string[];
/**
* Output directory that stored build folders and ZIPs.
*
* @default ".output"
*/
outDir?: string;
/**
* > Only available when using the JS API. Not available in `wxt.config.ts` files
*
* Path to `wxt.config.ts` file or `false` to disable config file discovery.
*
* @default "wxt.config.ts"
*/
configFile?: string | false;
/**
* Set to `true` to show debug logs. Overriden by the command line `--debug` option.
*
* @default false
*/
debug?: boolean;
/**
* Explicitly set a mode to run in. This will override the default mode for each command, and can
* be overridden by the command line `--mode` option.
*/
mode?: string;
/**
* Customize auto-import options. Set to `false` to disable auto-imports.
*
* For example, to add a directory to auto-import from, you can use:
*
* ```ts
* export default defineConfig({
* imports: {
* dirs: ["some-directory"]
* }
* })
* ```
*/
imports?: WxtUnimportOptions | false;
/**
* Explicitly set a browser to build for. This will override the default browser for each command,
* and can be overridden by the command line `--browser` option.
*
* @default
* "chrome"
*/
browser?: TargetBrowser;
/**
* Explicitly set a manifest version to target. This will override the default manifest version
* for each command, and can be overridden by the command line `--mv2` or `--mv3` option.
*/
manifestVersion?: TargetManifestVersion;
/**
* Override the logger used.
*
* @default
* consola
*/
logger?: Logger;
/**
* Customize the `manifest.json` output. Can be an object, promise, or function that returns an
* object or promise.
*/
manifest?: UserManifest | Promise<UserManifest> | UserManifestFn;
/**
* Custom runner options. Options set here can be overridden in a `web-ext.config.ts` file.
*/
runner?: ExtensionRunnerConfig;
zip?: {
/**
* Configure the filename output when zipping files.
*
* Available template variables:
*
* - <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>`{{browser}}`</span> - The target browser from the `--browser` CLI flag
* - <span v-pre>`{{mode}}`</span> - The current mode
* - <span v-pre>`{{manifestVersion}}`</span> - Either "2" or "3"
*
* @default "{{name}}-{{version}}-{{browser}}.zip"
*/
artifactTemplate?: string;
/**
* Configure the filename output when zipping files.
*
* Available template variables:
*
* - <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>`{{browser}}`</span> - The target browser from the `--browser` CLI flag
* - <span v-pre>`{{mode}}`</span> - The current mode
* - <span v-pre>`{{manifestVersion}}`</span> - Either "2" or "3"
*
* @default "{{name}}-{{version}}-sources.zip"
*/
sourcesTemplate?: string;
/**
* Override the artifactTemplate's `{name}` template variable. Defaults to the `package.json`'s
* name, or if that doesn't exist, the current working directories name.
*/
name?: string;
/**
* Root directory to ZIP when generating the sources ZIP.
*
* @default config.root
*/
sourcesRoot?: string;
/**
* [Minimatch](https://www.npmjs.com/package/minimatch) 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.
*
* @example
* [
* "coverage", // Ignore the coverage directory in the `sourcesRoot`
* ]
*/
includeSources?: string[];
/**
* [Minimatch](https://www.npmjs.com/package/minimatch) 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.
*
* @example
* [
* "coverage", // Include the coverage directory in the `sourcesRoot`
* ]
*/
excludeSources?: string[];
/**
* The Firefox review process requires the extension be buildable from source to make reviewing
* easier. This field allows you to use private packages without exposing your auth tokens.
*
* Just list the name of all the packages you want to download and include in the sources zip.
* Usually, these will be private packages behind auth tokens, but they don't have to be.
*
* All packages listed here will be downloaded to in `.wxt/local_modules/` and an `overrides` or
* `resolutions` field (depending on your package manager) will be added to the `package.json`,
* pointing to the downloaded packages.
*
* > ***DO NOT include versions or version filters.*** Just the package name. If multiple
* > versions of a package are present in the project, all versions will be downloaded and
* > referenced in the package.json correctly.
*
* @default []
*
* @example
* // Correct:
* ["@scope/package-name", "package-name"]
*
* // Incorrect, don't include versions!!!
* ["@scope/package-name@1.1.3", "package-name@^2"]
*/
downloadPackages?: string[];
/**
* Compression level to use when zipping files.
*
* Levels: 0 (no compression) to 9 (maximum compression).
*
* @default 9
*/
compressionLevel?: 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9;
};
/**
* @deprecated Use `hooks.build.manifestGenerated` to modify your manifest instead. This option
* will be removed in v1.0
*
* Transform the final manifest before it's written to the file system. Edit the `manifest`
* parameter directly, do not return a new object. Return values are ignored.
*
* @example
* defineConfig({
* // Add a CSS-only content script.
* transformManifest(manifest) {
* manifest.content_scripts.push({
* matches: ["*://google.com/*"],
* css: ["content-scripts/some-example.css"],
* });
* }
* })
*/
transformManifest?: (manifest: Manifest.WebExtensionManifest) => void;
analysis?: {
/**
* Explicitly include bundle analysis when running `wxt build`. This can be overridden by the
* command line `--analysis` option.
*
* @default false
*/
enabled?: boolean;
/**
* Set to true to automatically open the `stats.html` file when the build is finished. When building in CI, the browser will never open.
*
* @default false
*/
open?: boolean;
/**
* When running `wxt build --analyze` or setting `analysis.enabled` to true, customize how the
* bundle will be visualized. See
* [`rollup-plugin-visualizer`](https://github.com/btd/rollup-plugin-visualizer#how-to-use-generated-files)
* for more details.
*
* @default "treemap"
*/
template?: PluginVisualizerOptions['template'];
/**
* Name of the output HTML file. Relative to the project's root directory.
*
* Changing the filename of the outputFile also effects the names of the artifacts generated
* when setting `keepArtifacts` to true:
* - "stats.html" => "stats-*.json"
* - "stats/bundle.html" => "bundle-*.json"
* - ".analysis/index.html" => "index-*.json"
*
* @default "stats.html"
*/
outputFile?: string;
/**
* By default, the `stats-*.json` artifacts generated during bundle analysis are deleted. Set to
* `true` to keep them.
*
* One stats file is output per build step.
*
* @default false
*/
keepArtifacts?: boolean;
};
/**
* Add additional paths to the `.wxt/tsconfig.json`. Use this instead of overwriting the `paths`
* in the root `tsconfig.json` if you want to add new paths.
*
* The key is the import alias and the value is either a relative path to the root directory or an absolute path.
*
* @example
* {
* "testing": "src/utils/testing.ts"
* }
*/
alias?: Record<string, string>;
/**
* Experimental settings - use with caution.
*/
experimental?: {
/**
* Whether to use [`webextension-polyfill`](https://www.npmjs.com/package/webextension-polyfill)
* when importing `browser` from `wxt/browser`.
*
* When set to `false`, WXT will export the chrome global instead of the polyfill from
* `wxt/browser`.
*
* You should use `browser` to access the web extension APIs.
*
* @experimental This option will remain experimental until Manifest V2 is dead.
*
* @default true
* @example
* export default defineConfig({
* experimental: {
* includeBrowserPolyfill: false
* }
* })
*/
includeBrowserPolyfill?: boolean;
/**
* When set to `true`, use the Vite Runtime API to load entrypoint options instead of the default, `jiti`.
*
* Lets you use imported variables and leverage your Vite config to add support for non-standard APIs/syntax.
*
* @experimental Early access to try out the feature before it becomes the default.
* @default false
*/
viteRuntime?: boolean;
};
/**
* Config effecting dev mode only.
*/
dev?: {
server?: {
/**
* Port to run the dev server on. Defaults to the first open port from 3000 to 3010.
*/
port?: number;
};
/**
* Controls whether a custom keyboard shortcut command, `Alt+R`, is added during dev mode to
* quickly reload the extension.
*
* If false, the shortcut is not added during development.
*
* If set to a custom string, you can override the key combo used. See
* [Chrome's command docs](https://developer.chrome.com/docs/extensions/reference/api/commands)
* for available options.
*
* @default "Alt+R"
*/
reloadCommand?: string | false;
};
/**
* Project hooks for running logic during the build process.
*/
hooks?: NestedHooks<WxtHooks>;
}
// TODO: Extract to @wxt/vite-builder and use module augmentation to include the vite field
export interface InlineConfig {
/**
* Return custom Vite options from a function. See
* <https://vitejs.dev/config/shared-options.html>.
*
* [`root`](#root), [`configFile`](#configfile), and [`mode`](#mode) should be set in WXT's config
* instead of Vite's.
*
* This is a function because any vite plugins added need to be recreated for each individual
* build step, incase they have internal state causing them to fail when reused.
*/
vite?: (env: ConfigEnv) => WxtViteConfig | Promise<WxtViteConfig>;
}
// TODO: Move into @wxt/vite-builder
export interface ResolvedConfig {
vite: (env: ConfigEnv) => WxtViteConfig | Promise<WxtViteConfig>;
}
// TODO: Move into @wxt/vite-builder
export type WxtViteConfig = Omit<
vite.UserConfig,
'root' | 'configFile' | 'mode'
>;
// TODO: Move into @wxt/vite-builder
export interface WxtHooks {
/**
* Called when WXT has created Vite's config for a build step. Useful if you
* want to add plugins or update the vite config per entrypoint group.
*
* @param entrypoints The list of entrypoints being built with the provided config.
* @param viteConfig The config that will be used for the dev server.
*/
'vite:build:extendConfig': (
entrypoints: readonly Entrypoint[],
viteConfig: vite.InlineConfig,
) => HookResult;
/**
* Called when WXT has created Vite's config for the dev server. Useful if
* you want to add plugins or update the vite config per entrypoint group.
*
* @param viteConfig The config that will be used to build the entrypoints. Can be updated by reference.
*/
'vite:devServer:extendConfig': (config: vite.InlineConfig) => HookResult;
}
export interface BuildOutput {
manifest: Manifest.WebExtensionManifest;
publicAssets: OutputAsset[];
steps: BuildStepOutput[];
}
export type OutputFile = OutputChunk | OutputAsset;
export interface OutputChunk {
type: 'chunk';
/**
* Relative, normalized path relative to the output directory.
*
* Ex: "content-scripts/overlay.js"
*/
fileName: string;
/**
* Absolute, normalized paths to all dependencies this chunk relies on.
*/
moduleIds: string[];
}
export interface OutputAsset {
type: 'asset';
/**
* Relative, normalized path relative to the output directory.
*
* Ex: "icons/16.png"
*/
fileName: string;
}
export interface BuildStepOutput {
entrypoints: EntrypointGroup;
chunks: OutputFile[];
}
export interface WxtDevServer
extends Omit<WxtBuilderServer, 'listen' | 'close'>,
ServerInfo {
/**
* Stores the current build output of the server.
*/
currentOutput: BuildOutput | undefined;
/**
* Start the server.
*/
start(): Promise<void>;
/**
* Stop the server.
*/
stop(): Promise<void>;
/**
* Close the browser, stop the server, rebuild the entire extension, and start the server again.
*/
restart(): Promise<void>;
/**
* Transform the HTML for dev mode.
*/
transformHtml(
url: string,
html: string,
originalUrl?: string | undefined,
): Promise<string>;
/**
* Tell the extension to reload by running `browser.runtime.reload`.
*/
reloadExtension: () => void;
/**
* Tell an extension page to reload.
*
* The path is the bundle path, not the input paths, so if the input paths is
* "src/options/index.html", you would pass "options.html" because that's where it is written to
* in the dist directory, and where it's available at in the actual extension.
*
* @example
* server.reloadPage("popup.html")
* server.reloadPage("sandbox.html")
*/
reloadPage: (path: string) => void;
/**
* Tell the extension to restart a content script.
*
* @param payload Information about the content script to reload.
*/
reloadContentScript: (payload: ReloadContentScriptPayload) => void;
/**
* Grab the latest runner config and restart the browser.
*/
restartBrowser: () => void;
}
export interface ReloadContentScriptPayload {
registration?: BaseContentScriptEntrypointOptions['registration'];
contentScript: Omit<Scripting.RegisteredContentScript, 'id'>;
}
export type TargetBrowser = string;
export type TargetManifestVersion = 2 | 3;
export type UserConfig = Omit<InlineConfig, 'configFile'>;
export interface Logger {
debug(...args: any[]): void;
log(...args: any[]): void;
info(...args: any[]): void;
warn(...args: any[]): void;
error(...args: any[]): void;
fatal(...args: any[]): void;
success(...args: any[]): void;
level: LogLevel;
}
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 BackgroundEntrypointOptions extends BaseEntrypointOptions {
persistent?: PerBrowserOption<boolean>;
/**
* Set to `"module"` to output the background entrypoint as ESM. ESM outputs can share chunks and
* reduce the overall size of the bundled extension.
*
* When `undefined`, the background is bundled individually into an IIFE format.
*
* @default undefined
*/
type?: PerBrowserOption<'module'>;
}
export interface BaseContentScriptEntrypointOptions
extends BaseEntrypointOptions {
matches: PerBrowserOption<Manifest.ContentScript['matches']>;
/**
* See https://developer.chrome.com/docs/extensions/mv3/content_scripts/
* @default "documentIdle"
*/
runAt?: PerBrowserOption<Manifest.ContentScript['run_at']>;
/**
* See https://developer.chrome.com/docs/extensions/mv3/content_scripts/
* @default false
*/
matchAboutBlank?: PerBrowserOption<
Manifest.ContentScript['match_about_blank']
>;
/**
* See https://developer.chrome.com/docs/extensions/mv3/content_scripts/
* @default []
*/
excludeMatches?: PerBrowserOption<Manifest.ContentScript['exclude_matches']>;
/**
* See https://developer.chrome.com/docs/extensions/mv3/content_scripts/
* @default []
*/
includeGlobs?: PerBrowserOption<Manifest.ContentScript['include_globs']>;
/**
* See https://developer.chrome.com/docs/extensions/mv3/content_scripts/
* @default []
*/
excludeGlobs?: PerBrowserOption<Manifest.ContentScript['exclude_globs']>;
/**
* See https://developer.chrome.com/docs/extensions/mv3/content_scripts/
* @default false
*/
allFrames?: PerBrowserOption<Manifest.ContentScript['all_frames']>;
/**
* See https://developer.chrome.com/docs/extensions/mv3/content_scripts/
* @default false
*/
matchOriginAsFallback?: PerBrowserOption<boolean>;
/**
* Customize how imported/generated styles are injected with the content script. Regardless of the
* mode selected, CSS will always be built and included in the output directory.
*
* - `"manifest"` - Include the CSS in the manifest, under the content script's `css` array.
* - `"manual"` - Exclude the CSS from the manifest. You are responsible for manually loading it
* onto the page. Use `browser.runtime.getURL("content-scripts/<name>.css")` to get the file's
* URL
* - `"ui"` - Exclude the CSS from the manifest. CSS will be automatically added to your UI when
* calling `createShadowRootUi`
*
* @default "manifest"
*/
cssInjectionMode?: PerBrowserOption<'manifest' | 'manual' | 'ui'>;
/**
* Specify how the content script is registered.
*
* - `"manifest"`: The content script will be added to the `content_scripts` entry in the
* manifest. This is the normal and most well known way of registering a content script.
* - `"runtime"`: The content script's `matches` is added to `host_permissions` and you are
* responsible for using the scripting API to register/execute the content script
* dynamically at runtime.
*
* @default "manifest"
*/
registration?: PerBrowserOption<'manifest' | 'runtime'>;
}
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` → `popup`
* - `options/index.html` → `options`
* - `named.sandbox.html` → `named`
* - `named.sandbox/index.html` → `named`
* - `sandbox.html` → `sandbox`
* - `sandbox/index.html` → `sandbox`
* - `overlay.content.ts` → `overlay`
* - `overlay.content/index.ts` → `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.
*
* When running a content script with `browser.scripting.executeScript`,
* values returned from this function will be returned in the `executeScript`
* result as well. Otherwise returning a value does nothing.
*/
main(ctx: ContentScriptContext): any | Promise<any>;
}
export interface MainWorldContentScriptDefinition
extends MainWorldContentScriptEntrypointOptions {
/**
* Main function executed when the content script is loaded.
*
* When running a content script with `browser.scripting.executeScript`,
* values returned from this function will be returned in the `executeScript`
* result as well. Otherwise returning a value does nothing.
*/
main(): any | Promise<any>;
}
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 BaseEntrypointOptions {
/**
* Main function executed when the unlisted script is ran.
*
* When running a content script with `browser.scripting.executeScript`,
* values returned from this function will be returned in the `executeScript`
* result as well. Otherwise returning a value does nothing.
*/
main(): any | Promise<any>;
}
/**
* 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 };
/**
* 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
* here, they are configured inline.
*/
export type UserManifest = Partial<
Omit<
Manifest.WebExtensionManifest,
| 'background'
| 'chrome_url_overrides'
| 'devtools_page'
| 'manifest_version'
| 'options_page'
| 'options_ui'
| 'sandbox'
>
>;
export type UserManifestFn = (
env: ConfigEnv,
) => UserManifest | Promise<UserManifest>;
export interface ConfigEnv {
/**
* The build mode passed into the CLI. By default, `wxt` uses `"development"` and `wxt build|zip`
* uses `"production"`.
*/
mode: string;
/**
* The command used to run WXT. `"serve"` during development and `"build"` for any other command.
*/
command: WxtCommand;
/**
* Browser passed in from the CLI via the `-b` or `--browser` flag. Defaults to `"chrome"` when not passed.
*/
browser: TargetBrowser;
/**
* Manifest version passed in from the CLI via the `--mv2` or `--mv3` flags. When not passed, it depends on the target browser. See
* [the guide](https://wxt.dev/guide/multiple-browsers.html#target-manifest-version) for more
* details.
*/
manifestVersion: 2 | 3;
}
export type WxtCommand = 'build' | 'serve';
/**
* Configure how the browser starts up.
*/
export interface ExtensionRunnerConfig {
/**
* Whether or not to open the browser with the extension installed in dev mode.
*
* @default false
*/
disabled?: boolean;
/**
* @see https://extensionworkshop.com/documentation/develop/web-ext-command-reference/#browser-console
*/
openConsole?: boolean;
/**
* @see https://extensionworkshop.com/documentation/develop/web-ext-command-reference/#devtools
*/
openDevtools?: boolean;
/**
* List of browser names and the binary that should be used to open the browser.
*
* @see https://extensionworkshop.com/documentation/develop/web-ext-command-reference/#chromium-binary
* @see https://extensionworkshop.com/documentation/develop/web-ext-command-reference/#firefox
*/
binaries?: Record<string, string>;
/**
* @see https://extensionworkshop.com/documentation/develop/web-ext-command-reference/#firefox-profile
*/
firefoxProfile?: string;
/**
* @see https://extensionworkshop.com/documentation/develop/web-ext-command-reference/#chromium-profile
*/
chromiumProfile?: string;
/**
* An map of chrome preferences from https://chromium.googlesource.com/chromium/src/+/main/chrome/common/pref_names.h
*
* @example
* // change your downloads directory
* {
* download: {
* default_directory: "/my/custom/dir",
* },
* }
*
* @default
* // Enable dev mode and allow content script sourcemaps
* {
* devtools: {
* synced_preferences_sync_disabled: {
* skipContentScripts: false,
* },
* }
* extensions: {
* ui: {
* developer_mode: true,
* },
* }
* }
*/
chromiumPref?: string;
/**
* @see https://extensionworkshop.com/documentation/develop/web-ext-command-reference/#pref
*/
firefoxPrefs?: Record<string, string>;
/**
* @see https://extensionworkshop.com/documentation/develop/web-ext-command-reference/#args
*/
firefoxArgs?: string[];
/**
* @see https://extensionworkshop.com/documentation/develop/web-ext-command-reference/#args
*/
chromiumArgs?: string[];
/**
* @see https://extensionworkshop.com/documentation/develop/web-ext-command-reference/#start-url
*/
startUrls?: string[];
/**
* @see https://extensionworkshop.com/documentation/develop/web-ext-command-reference/#keep-profile-changes
*/
keepProfileChanges?: boolean;
}
export interface WxtBuilder {
/**
* Name of tool used to build. Ex: "Vite" or "Webpack".
*/
name: string;
/**
* Version of tool used to build. Ex: "5.0.2"
*/
version: string;
/**
* Import the entrypoint file, returning the default export containing the options.
*/
importEntrypoint<T>(path: string): Promise<T>;
/**
* Build a single entrypoint group. This is effectively one of the multiple "steps" during the
* build process.
*/
build(group: EntrypointGroup): Promise<BuildStepOutput>;
/**
* Start a dev server at the provided port.
*/
createServer(info: ServerInfo): Promise<WxtBuilderServer>;
}
export interface WxtBuilderServer {
/**
* Start the server.
*/
listen(): Promise<void>;
/**
* Stop the server.
*/
close(): Promise<void>;
/**
* Transform the HTML for dev mode.
*/
transformHtml(
url: string,
html: string,
originalUrl?: string | undefined,
): Promise<string>;
/**
* The web socket server used to communicate with the extension.
*/
ws: {
/**
* Send a message via the server's websocket, with an optional payload.
*
* @example
* ws.send("wxt:reload-extension");
* ws.send("wxt:reload-content-script", { ... });
*/
send(message: string, payload?: any): void;
/**
* Listen for messages over the server's websocket.
*/
on(message: string, cb: (payload: any) => void): void;
};
/**
* Chokidar file watcher instance.
*/
watcher: FSWatcher;
}
export interface ServerInfo {