-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathwxt.config.ts
More file actions
524 lines (474 loc) · 17 KB
/
Copy pathwxt.config.ts
File metadata and controls
524 lines (474 loc) · 17 KB
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
import { execFileSync } from "node:child_process";
import { readdirSync, readFileSync, statSync } from "node:fs";
import { extname, join } from "node:path";
import { fileURLToPath } from "node:url";
import { defineConfig } from "wxt";
import type { ConfigEnv, Entrypoint, UserConfig } from "wxt";
import type { InlineConfig as ViteInlineConfig } from "vite";
// Build-identity stamp injected into the bundle as `__SAYPI_BUILD_STAMP__`
// (see src/build-stamp.ts). Lets a loaded build be matched against the current
// commit so a stale dev build is detectable rather than a guess. Computed once
// at config load; falls back gracefully outside a git checkout.
function computeBuildStamp(): { sha: string; branch: string; time: string } {
const cwd = fileURLToPath(new URL(".", import.meta.url));
const git = (args: string[]) =>
execFileSync("git", args, { cwd, encoding: "utf8", stdio: ["ignore", "pipe", "ignore"] }).trim();
try {
return {
sha: git(["rev-parse", "--short", "HEAD"]),
branch: git(["rev-parse", "--abbrev-ref", "HEAD"]),
time: new Date().toISOString(),
};
} catch {
return { sha: "unknown", branch: "unknown", time: new Date().toISOString() };
}
}
const BUILD_STAMP = computeBuildStamp();
const applyBuildStampDefine = (config: { define?: Record<string, any> }) => {
config.define ??= {};
config.define.__SAYPI_BUILD_STAMP__ = JSON.stringify(BUILD_STAMP);
};
// These constants are used for renaming CommonJS helper files generated during the build.
// Chrome requires safe filenames for extension chunks, and specifically does not allow underscores in chunk names.
// This is because Chrome's extension loader may fail to load chunks with underscores in their filenames.
const COMMONJS_CHUNK_PATTERN = "chunks/chunk-[hash].js";
const COMMONJS_HELPER_REGEX = /^_commonjsHelpers\.([^.]+)\.js(\.map)?$/;
const COMMONJS_HELPER_PREFIX = "chunks/commonjs-";
const TEXT_EXTENSIONS = new Set([".js", ".mjs", ".css", ".html", ".json", ".map"]);
const VAD_WORKLET_BUNDLE = fileURLToPath(
new URL("./node_modules/@ricky0123/vad-web/dist/vad.worklet.bundle.min.js", import.meta.url),
);
const ICON_SIZES = ["16", "32", "48", "128"] as const;
const ICON_FILE_NAMES = new Map(
ICON_SIZES.map((size) => [size, `bubble-${size}px.png`]),
);
const EXTRA_ICON_FILES = [
"bubble-green.svg",
"bubble-bw.svg",
"bubble-300px.png",
];
const FLAGS_DIR = fileURLToPath(new URL("./src/icons/flags", import.meta.url));
const replaceAllMappings = (input: string, mappings: Map<string, string>) => {
let result = input;
for (const [from, to] of mappings) {
result = result.split(from).join(to);
}
return result;
};
const renameHelperFile = (fileName: string) => {
const match = COMMONJS_HELPER_REGEX.exec(fileName);
if (!match) {
return null;
}
const [, hash, mapSuffix] = match;
const base = `${COMMONJS_HELPER_PREFIX}${hash}.js`;
return mapSuffix ? `${base}.map` : base;
};
const createCommonjsHelperRenamer = () => {
const rewriteSet = (values: Set<string>, mappings: Map<string, string>) => {
return new Set(Array.from(values, (value) => mappings.get(value) ?? value));
};
return {
name: "commonjs-helper-safe-names",
apply: "build",
generateBundle(_options: any, bundle: Record<string, any>) {
const renameMap = new Map<string, string>();
for (const fileName of Object.keys(bundle)) {
const renamed = renameHelperFile(fileName);
if (renamed) {
renameMap.set(fileName, renamed);
}
}
if (renameMap.size === 0) {
return;
}
for (const [from, to] of renameMap) {
const entry = bundle[from];
if (!entry) continue;
entry.fileName = to;
bundle[to] = entry;
delete bundle[from];
}
const rewriteArray = (values: string[] | undefined) => {
if (!Array.isArray(values)) return values;
return values.map((value) => renameMap.get(value) ?? value);
};
for (const output of Object.values(bundle)) {
if (output.type === "chunk") {
output.imports = rewriteArray(output.imports);
output.dynamicImports = rewriteArray(output.dynamicImports);
output.implicitlyLoadedBefore = rewriteArray(output.implicitlyLoadedBefore);
if (output.importedBindings) {
const next: Record<string, any> = {};
for (const [file, bindings] of Object.entries(output.importedBindings)) {
const target = renameMap.get(file) ?? file;
next[target] = bindings;
}
output.importedBindings = next;
}
if (output.viteMetadata) {
if (output.viteMetadata.importedChunks instanceof Set) {
output.viteMetadata.importedChunks = rewriteSet(output.viteMetadata.importedChunks, renameMap);
}
if (output.viteMetadata.importedAssets instanceof Set) {
output.viteMetadata.importedAssets = rewriteSet(output.viteMetadata.importedAssets, renameMap);
}
if (output.viteMetadata.importedCss instanceof Set) {
output.viteMetadata.importedCss = rewriteSet(output.viteMetadata.importedCss, renameMap);
}
}
if (typeof output.code === "string") {
output.code = replaceAllMappings(output.code, renameMap);
}
} else if (typeof output.source === "string") {
output.source = replaceAllMappings(output.source, renameMap);
}
}
},
};
};
const renamePublicCommonjsAssets = (files: Array<Record<string, any>>) => {
const renameMap = new Map<string, string>();
for (const file of files) {
const original = file.relativeDest;
const renamed = renameHelperFile(original);
if (renamed) {
renameMap.set(original, renamed);
file.relativeDest = renamed;
}
}
if (renameMap.size === 0) {
return;
}
for (const file of files) {
if (!("absoluteSrc" in file)) continue;
const targetPath = file.absoluteSrc;
const destination = file.relativeDest;
if (typeof targetPath !== "string" || typeof destination !== "string") continue;
const extension = extname(destination).toLowerCase();
if (!TEXT_EXTENSIONS.has(extension)) {
continue;
}
const source = readFileSync(targetPath, "utf8");
const updated = replaceAllMappings(source, renameMap);
if (updated !== source) {
file.contents = updated;
delete file.absoluteSrc;
}
}
};
const LOCALES_DIR = fileURLToPath(new URL("./_locales", import.meta.url));
const addLocalePublicAssets = (files: Array<Record<string, any>>) => {
try {
const stats = statSync(LOCALES_DIR);
if (!stats.isDirectory()) {
return;
}
} catch {
return;
}
const stack: Array<{ absolute: string; relative: string }> = [{ absolute: LOCALES_DIR, relative: "" }];
while (stack.length) {
const current = stack.pop();
if (!current) continue;
const entries = readdirSync(current.absolute, { withFileTypes: true });
for (const entry of entries) {
const absolutePath = join(current.absolute, entry.name);
const relativePath = current.relative ? `${current.relative}/${entry.name}` : entry.name;
if (entry.isDirectory()) {
stack.push({ absolute: absolutePath, relative: relativePath });
} else if (entry.isFile()) {
files.push({
relativeDest: `_locales/${relativePath}`,
absoluteSrc: absolutePath,
});
}
}
}
};
const addIconPublicAssets = (files: Array<Record<string, any>>) => {
for (const [, fileName] of ICON_FILE_NAMES) {
const relativeDest = `icons/${fileName}`;
if (files.some((file) => file.relativeDest === relativeDest)) {
continue;
}
const absolutePath = fileURLToPath(new URL(`./src/icons/${fileName}`, import.meta.url));
try {
const stats = statSync(absolutePath);
if (!stats.isFile()) {
continue;
}
} catch {
continue;
}
files.push({
relativeDest,
absoluteSrc: absolutePath,
});
}
for (const fileName of EXTRA_ICON_FILES) {
const relativeDest = `icons/${fileName}`;
if (files.some((file) => file.relativeDest === relativeDest)) {
continue;
}
const absolutePath = fileURLToPath(new URL(`./src/icons/${fileName}`, import.meta.url));
try {
const stats = statSync(absolutePath);
if (!stats.isFile()) continue;
} catch {
continue;
}
files.push({
relativeDest,
absoluteSrc: absolutePath,
});
}
};
const addFlagIconAssets = (files: Array<Record<string, any>>) => {
try {
const stats = statSync(FLAGS_DIR);
if (!stats.isDirectory()) {
return;
}
} catch {
return;
}
const entries = readdirSync(FLAGS_DIR, { withFileTypes: true });
for (const entry of entries) {
if (!entry.isFile()) continue;
const extension = extname(entry.name).toLowerCase();
if (extension !== ".svg" && extension !== ".png") {
continue;
}
const absolutePath = join(FLAGS_DIR, entry.name);
files.push({
relativeDest: `icons/flags/${entry.name}`,
absoluteSrc: absolutePath,
});
}
};
const addVadAssets = (files: Array<Record<string, any>>) => {
try {
const stats = statSync(VAD_WORKLET_BUNDLE);
if (!stats.isFile()) {
return;
}
} catch {
return;
}
if (!files.some((file) => file.relativeDest === "vad.worklet.bundle.min.js")) {
files.push({
relativeDest: "vad.worklet.bundle.min.js",
absoluteSrc: VAD_WORKLET_BUNDLE,
});
}
};
const applyChunkFilePattern = (config: { build?: Record<string, any>; plugins?: any[] }) => {
config.build ??= {};
const buildConfig = config.build as Record<string, any>;
buildConfig.rollupOptions ??= {};
const rollupOptions = buildConfig.rollupOptions as Record<string, any>;
const assignPattern = (output: any) => {
if (!output) {
return;
}
if (Array.isArray(output)) {
for (const entry of output) {
assignPattern(entry);
}
return;
}
if (typeof output === "object") {
output.chunkFileNames = COMMONJS_CHUNK_PATTERN;
}
};
if (rollupOptions.output == null) {
rollupOptions.output = { chunkFileNames: COMMONJS_CHUNK_PATTERN };
} else {
assignPattern(rollupOptions.output);
}
config.plugins ??= [];
config.plugins.push(createCommonjsHelperRenamer());
};
const formatHostPermission = (url?: string | null): string | null => {
if (!url) return null;
try {
const parsed = new URL(url);
const port = parsed.port ? `:${parsed.port}` : "";
return `${parsed.protocol}//${parsed.hostname}${port}/*`;
} catch (err) {
console.error(`Invalid URL in formatHostPermission: "${url}". Error:`, err);
return null;
}
};
const DEFAULT_HOST_PERMISSION_URLS = [
"https://api.saypi.ai",
"https://www.saypi.ai",
];
const hostPermissionCandidates = [
process.env.VITE_API_SERVER_URL ?? process.env.API_SERVER_URL,
process.env.VITE_AUTH_SERVER_URL ?? process.env.AUTH_SERVER_URL,
...DEFAULT_HOST_PERMISSION_URLS,
];
const HOST_PERMISSIONS = Array.from(
new Set(
hostPermissionCandidates
.map((candidate) => formatHostPermission(candidate))
.filter((value): value is string => Boolean(value)),
),
);
// WXT's loader (c12) supports a config factory `(env) => UserConfig`, but the
// published `defineConfig` overload only types the plain-object form. Type the
// factory's env/return explicitly and cast it through to satisfy the narrow
// overload — the cast is erased at runtime, so behavior is unchanged.
// `$schema` is a WXT-accepted IDE/JSON-schema hint and `optimizeDeps` is an
// extra key not present in this WXT version's typed `UserConfig`; widen the
// return type to permit both (values preserved verbatim) while still
// type-checking every real `UserConfig` member.
const configFactory = (
env: ConfigEnv,
): UserConfig & { $schema?: string; optimizeDeps?: Record<string, unknown> } => {
const browser =
(typeof process.env.WXT_BROWSER === "string" && process.env.WXT_BROWSER.length > 0
? process.env.WXT_BROWSER
: env?.browser) ?? "chrome";
const isFirefox = browser.startsWith("firefox");
const permissions: string[] = ["storage", "cookies", "tabs", "contextMenus", "alarms"];
if (!isFirefox) {
permissions.push("offscreen", "audio", "identity");
}
// WXT picks the first open port in 3000-3010 unless dev.server.port is set.
// Pin it (with a matching origin baked into the extension's reload client) so a
// manually-loaded unpacked extension reconnects to the same port across restarts.
// WXT enforces strictPort itself; the rig guarantees the port is free first.
const devServer = process.env.WXT_DEV_PORT
? {
port: Number(process.env.WXT_DEV_PORT),
origin: `http://localhost:${process.env.WXT_DEV_PORT}`,
}
: undefined;
return {
$schema: "https://unpkg.com/wxt/schemas/v6.json",
dev: { server: devServer },
webExt: {
disabled: process.env.WXT_DISABLE_RUNNER === "true",
},
hooks: {
"vite:build:extendConfig": (entrypoints: readonly Entrypoint[], config: ViteInlineConfig) => {
applyChunkFilePattern(config);
applyBuildStampDefine(config);
},
"vite:devServer:extendConfig": (config: ViteInlineConfig) => {
applyChunkFilePattern(config);
applyBuildStampDefine(config);
},
"build:publicAssets": (_wxt: any, files: any[]) => {
addLocalePublicAssets(files);
addIconPublicAssets(files);
addFlagIconAssets(files);
addVadAssets(files);
renamePublicCommonjsAssets(files);
},
"build:manifestGenerated": (wxtInstance: any, manifest: any) => {
const targetBrowser = String(wxtInstance.config.browser ?? browser);
const isDev = String(wxtInstance.config.mode) === "development";
const keepSegments = String(process.env.VITE_KEEP_SEGMENTS ?? process.env.KEEP_SEGMENTS ?? "").toLowerCase() === "true";
// Add downloads permission only in dev mode when keepSegments is enabled
if (isDev && keepSegments && Array.isArray(manifest.permissions) && !manifest.permissions.includes("downloads")) {
manifest.permissions.push("downloads");
}
if (targetBrowser.startsWith("firefox") && Array.isArray(manifest.permissions)) {
manifest.permissions = manifest.permissions.filter(
(permission: string) => permission !== "offscreen" && permission !== "audio",
);
}
},
},
root: ".",
srcDir: ".",
entrypointsDir: "entrypoints",
outDir: ".output",
optimizeDeps: {
disabled: true,
},
manifest: {
name: "__MSG_appName__",
description: "__MSG_appDescription__",
default_locale: "en",
// WXT/web-ext normalizes a string author at build time, but the MV3
// manifest type only permits `{ email: string }`. Cast to keep the string
// value (erased at runtime, so behavior is unchanged).
author: "Ross Cadogan" as unknown as { email: string },
homepage_url: "https://www.saypi.ai",
action: {
default_title: "Say, Pi",
},
permissions,
host_permissions: HOST_PERMISSIONS,
content_security_policy: {
extension_pages: "script-src 'self' 'wasm-unsafe-eval'; object-src 'self'",
},
icons: {
"16": "icons/bubble-16px.png",
"32": "icons/bubble-32px.png",
"48": "icons/bubble-48px.png",
"128": "icons/bubble-128px.png",
},
web_accessible_resources: [
{
resources: [
"silero_vad*.onnx",
"*.wasm",
"*.mjs",
"*.js",
"ort-wasm*",
"vad.worklet*.js",
"audio/*.mp3",
"icons/*.svg",
"icons/*.png",
"icons/logos/*.svg",
"icons/logos/*.png",
"icons/flags/*.svg",
],
matches: ["<all_urls>"],
},
],
browser_specific_settings: {
gecko: {
id: "gecko@saypi.ai",
},
},
},
vite: () => ({
define: {
__BUILD_DATE__: JSON.stringify(new Date().toISOString()),
},
resolve: {
alias: {
"~": fileURLToPath(new URL("./src", import.meta.url)),
"~/": fileURLToPath(new URL("./src", import.meta.url)),
events: fileURLToPath(new URL("./src/utils/EventEmitterShim.js", import.meta.url)),
},
},
build: {
// Disable modulePreload to avoid injecting window-dependent polyfill code
// into service worker bundles (service workers don't have window object)
modulePreload: false,
rollupOptions: {
output: {
chunkFileNames: COMMONJS_CHUNK_PATTERN,
entryFileNames: "[name].[hash].js",
assetFileNames: "assets/[name].[hash][extname]",
},
},
},
// Preact JSX via esbuild's automatic runtime. Affects only files that
// contain JSX (i.e. .tsx); the existing .ts/.js sources are untouched.
esbuild: {
jsx: "automatic",
jsxImportSource: "preact",
},
}),
};
};
export default defineConfig(configFactory as unknown as UserConfig);