@crxjs/vite-plugin 1.0.13 → 2.0.0-beta.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (4) hide show
  1. package/dist/index.cjs +1336 -1309
  2. package/dist/index.d.ts +31 -19
  3. package/dist/index.mjs +1331 -1305
  4. package/package.json +25 -21
package/dist/index.mjs CHANGED
@@ -1,78 +1,70 @@
1
- import { watch } from 'rollup';
2
1
  import { simple } from 'acorn-walk';
3
- import { createHash as createHash$1 } from 'crypto';
4
- import debug$5 from 'debug';
5
- import fg from 'fast-glob';
2
+ import { createHash } from 'crypto';
3
+ import debug$2 from 'debug';
6
4
  import v8 from 'v8';
7
- import { promises, readFileSync, existsSync } from 'fs';
8
- import MagicString from 'magic-string';
9
5
  import { posix } from 'path';
10
- import fsExtra from 'fs-extra';
6
+ import fsx from 'fs-extra';
11
7
  import { performance } from 'perf_hooks';
12
- import colors from 'picocolors';
8
+ import { rollup } from 'rollup';
9
+ import * as lexer from 'es-module-lexer';
10
+ import { readFile as readFile$1 } from 'fs/promises';
11
+ import MagicString from 'magic-string';
13
12
  import { createLogger } from 'vite';
13
+ import { readFileSync, existsSync, promises } from 'fs';
14
14
  import { createRequire } from 'module';
15
+ import fg from 'fast-glob';
16
+ import getPort, { portNumbers } from 'get-port';
15
17
  import { load } from 'cheerio';
16
18
  import jsesc from 'jsesc';
17
- import injector from 'connect-injector';
19
+ import colors from 'picocolors';
20
+
21
+ const pluginName$1 = "crx:optionsProvider";
22
+ const pluginOptionsProvider = (options) => {
23
+ return {
24
+ name: pluginName$1,
25
+ api: {
26
+ crx: {
27
+ options
28
+ }
29
+ }
30
+ };
31
+ };
32
+ const getOptions = ({ plugins }) => {
33
+ if (typeof plugins === "undefined") {
34
+ throw new Error("config.plugins is undefined");
35
+ }
36
+ let options;
37
+ for (const p of plugins.flat()) {
38
+ if (isCrxPlugin(p)) {
39
+ if (p.name === pluginName$1) {
40
+ const plugin = p;
41
+ options = plugin.api.crx.options;
42
+ if (options)
43
+ break;
44
+ }
45
+ }
46
+ }
47
+ if (typeof options === "undefined") {
48
+ throw Error("Unable to get CRXJS options");
49
+ }
50
+ return options;
51
+ };
52
+ function isCrxPlugin(p) {
53
+ return !!p && typeof p === "object" && !(p instanceof Promise) && !Array.isArray(p) && p.name.startsWith("crx:");
54
+ }
55
+
56
+ var workerHmrClient = "const ownOrigin = new URL(chrome.runtime.getURL(\"/\")).origin;\nself.addEventListener(\"fetch\", (fetchEvent) => {\n const url = new URL(fetchEvent.request.url);\n if (url.origin === ownOrigin) {\n fetchEvent.respondWith(sendToServer(url));\n }\n});\nasync function sendToServer(url) {\n url.protocol = \"http:\";\n url.host = \"localhost\";\n url.port = __SERVER_PORT__;\n url.searchParams.set(\"t\", Date.now().toString());\n const response = await fetch(url.href.replace(/=$|=(?=&)/g, \"\"));\n return new Response(response.body, {\n headers: {\n \"Content-Type\": response.headers.get(\"Content-Type\") ?? \"text/javascript\"\n }\n });\n}\nconst ports = /* @__PURE__ */ new Set();\nchrome.runtime.onConnect.addListener((port) => {\n if (port.name === \"@crx/client\") {\n ports.add(port);\n port.onDisconnect.addListener((port2) => ports.delete(port2));\n port.onMessage.addListener((message) => {\n });\n port.postMessage({ data: JSON.stringify({ type: \"connected\" }) });\n }\n});\nfunction notifyContentScripts(payload) {\n const data = JSON.stringify(payload);\n for (const port of ports)\n port.postMessage({ data });\n}\nconsole.log(\"[vite] connecting...\");\nconst socketProtocol = __HMR_PROTOCOL__ || (location.protocol === \"https:\" ? \"wss\" : \"ws\");\nconst socketHost = `${__HMR_HOSTNAME__ || location.hostname}:${__HMR_PORT__}`;\nconst socket = new WebSocket(`${socketProtocol}://${socketHost}`, \"vite-hmr\");\nconst base = __BASE__ || \"/\";\nsocket.addEventListener(\"message\", async ({ data }) => {\n handleSocketMessage(JSON.parse(data));\n});\nfunction isCrxHmrPayload(x) {\n return x.type === \"custom\" && x.event.startsWith(\"crx:\");\n}\nfunction handleSocketMessage(payload) {\n if (isCrxHmrPayload(payload)) {\n handleCrxHmrPayload(payload);\n } else if (payload.type === \"connected\") {\n console.log(`[vite] connected.`);\n const interval = setInterval(() => socket.send(\"ping\"), __HMR_TIMEOUT__);\n socket.addEventListener(\"close\", () => clearInterval(interval));\n }\n}\nfunction handleCrxHmrPayload(payload) {\n notifyContentScripts(payload);\n switch (payload.event) {\n case \"crx:runtime-reload\":\n console.log(\"[crx] runtime reload\");\n chrome.runtime.reload();\n break;\n }\n}\nasync function waitForSuccessfulPing(ms = 1e3) {\n while (true) {\n try {\n await fetch(`${base}__vite_ping`);\n break;\n } catch (e) {\n await new Promise((resolve) => setTimeout(resolve, ms));\n }\n }\n}\nsocket.addEventListener(\"close\", async ({ wasClean }) => {\n if (wasClean)\n return;\n console.log(`[vite] server connection lost. polling for restart...`);\n await waitForSuccessfulPing();\n handleCrxHmrPayload({\n type: \"custom\",\n event: \"crx:runtime-reload\"\n });\n});\n";
18
57
 
19
- const _debug = (id) => debug$5("crx").extend(id);
58
+ const _debug = (id) => debug$2("crx").extend(id);
20
59
  const structuredClone = (obj) => {
21
60
  return v8.deserialize(v8.serialize(obj));
22
61
  };
23
- const createHash = (data, length = 5) => createHash$1("sha1").update(data).digest("base64").replace(/[^A-Za-z0-9]/g, "").slice(0, length);
62
+ const hash = (data, length = 5) => createHash("sha1").update(data).digest("base64").replace(/[^A-Za-z0-9]/g, "").slice(0, length);
24
63
  const isString = (x) => typeof x === "string";
25
- const isTruthy = (x) => !!x;
26
64
  function isObject(value) {
27
65
  return Object.prototype.toString.call(value) === "[object Object]";
28
66
  }
29
67
  const isResourceByMatch = (x) => "matches" in x;
30
- async function manifestFiles(manifest, options = {}) {
31
- let locales = [];
32
- if (manifest.default_locale)
33
- locales = await fg("_locales/**/messages.json", options);
34
- const rulesets = manifest.declarative_net_request?.rule_resources.flatMap(({ path }) => path) ?? [];
35
- const contentScripts = manifest.content_scripts?.flatMap(({ js }) => js) ?? [];
36
- const contentStyles = manifest.content_scripts?.flatMap(({ css }) => css);
37
- const serviceWorker = manifest.background?.service_worker;
38
- const htmlPages = htmlFiles(manifest);
39
- const icons = [
40
- Object.values(isString(manifest.icons) ? [manifest.icons] : manifest.icons ?? {}),
41
- Object.values(isString(manifest.action?.default_icon) ? [manifest.action?.default_icon] : manifest.action?.default_icon ?? {})
42
- ].flat();
43
- let webAccessibleResources = [];
44
- if (manifest.web_accessible_resources) {
45
- const resources = await Promise.all(manifest.web_accessible_resources.flatMap(({ resources: resources2 }) => resources2).map(async (r) => {
46
- if (["*", "**/*"].includes(r))
47
- return void 0;
48
- if (fg.isDynamicPattern(r))
49
- return fg(r, options);
50
- return r;
51
- }));
52
- webAccessibleResources = resources.flat().filter(isString);
53
- }
54
- return {
55
- contentScripts: [...new Set(contentScripts)].filter(isString),
56
- contentStyles: [...new Set(contentStyles)].filter(isString),
57
- html: htmlPages,
58
- icons: [...new Set(icons)].filter(isString),
59
- locales: [...new Set(locales)].filter(isString),
60
- rulesets: [...new Set(rulesets)].filter(isString),
61
- background: [serviceWorker].filter(isString),
62
- webAccessibleResources
63
- };
64
- }
65
- function htmlFiles(manifest) {
66
- const files = [
67
- manifest.action?.default_popup,
68
- Object.values(manifest.chrome_url_overrides ?? {}),
69
- manifest.devtools_page,
70
- manifest.options_page,
71
- manifest.options_ui?.page,
72
- manifest.sandbox?.pages
73
- ].flat().filter(isString).map((s) => s.split("#")[0]).sort();
74
- return [...new Set(files)];
75
- }
76
68
  function decodeManifest(code) {
77
69
  const tree = this.parse(code);
78
70
  let literal;
@@ -99,67 +91,25 @@ function encodeManifest(manifest) {
99
91
  const json = JSON.stringify(JSON.stringify(manifest));
100
92
  return `export default ${json}`;
101
93
  }
102
- const stubMatchPattern = (pattern) => {
94
+ function parseJsonAsset(bundle, key) {
95
+ const asset = bundle[key];
96
+ if (typeof asset === "undefined")
97
+ throw new TypeError(`OutputBundle["${key}"] is undefined.`);
98
+ if (asset.type !== "asset")
99
+ throw new Error(`OutputBundle["${key}"] is not an OutputAsset.`);
100
+ if (typeof asset.source !== "string")
101
+ throw new TypeError(`OutputBundle["${key}"].source is not a string.`);
102
+ return JSON.parse(asset.source);
103
+ }
104
+ const getMatchPatternOrigin = (pattern) => {
105
+ if (pattern.startsWith("<"))
106
+ return pattern;
103
107
  const [schema, rest] = pattern.split("://");
104
108
  const [origin, pathname] = rest.split("/");
105
109
  const root = `${schema}://${origin}`;
106
110
  return pathname ? `${root}/*` : root;
107
111
  };
108
112
 
109
- const idBySource = /* @__PURE__ */ new Map();
110
- const idByUrl = /* @__PURE__ */ new Map();
111
- const urlById = /* @__PURE__ */ new Map();
112
- function setUrlMeta({
113
- id,
114
- source,
115
- url
116
- }) {
117
- idBySource.set(source, id);
118
- idByUrl.set(url, id);
119
- urlById.set(id, url);
120
- }
121
- const fileById = /* @__PURE__ */ new Map();
122
- const fileByUrl = /* @__PURE__ */ new Map();
123
- const pathById = /* @__PURE__ */ new Map();
124
- const pathByUrl = /* @__PURE__ */ new Map();
125
- const setFileMeta = ({ file, id }) => {
126
- const url = urlById.get(id);
127
- if (!url)
128
- return;
129
- fileById.set(id, file);
130
- fileByUrl.set(url, file);
131
- const pathName = `/${file}`;
132
- pathById.set(id, pathName);
133
- pathByUrl.set(url, pathName);
134
- };
135
- const ownerById = /* @__PURE__ */ new Map();
136
- const pathByOwner = /* @__PURE__ */ new Map();
137
- const ownersByFile = /* @__PURE__ */ new Map();
138
- const setOwnerMeta = ({ owner, id }) => {
139
- const pathName = pathById.get(id);
140
- if (!pathName)
141
- return;
142
- pathByOwner.set(owner, pathName);
143
- ownerById.set(id, owner);
144
- const fileName = fileById.get(id);
145
- const owners = ownersByFile.get(fileName) ?? /* @__PURE__ */ new Set();
146
- owners.add(owner);
147
- ownersByFile.set(fileName, owners);
148
- };
149
- const outputById = /* @__PURE__ */ new Map();
150
- const outputByOwner = /* @__PURE__ */ new Map();
151
- const setOutputMeta = ({
152
- output,
153
- id
154
- }) => {
155
- const ownerName = ownerById.get(id);
156
- if (!ownerName)
157
- return;
158
- outputByOwner.set(ownerName, output);
159
- outputById.set(id, output);
160
- };
161
- const transformResultByOwner = /* @__PURE__ */ new Map();
162
-
163
113
  const {
164
114
  basename,
165
115
  dirname,
@@ -176,168 +126,39 @@ const {
176
126
  sep
177
127
  } = posix;
178
128
 
179
- const viteClientId = "/@vite/client";
180
- const customElementsId = "@webcomponents/custom-elements";
181
- const reactRefreshId = "/@react-refresh";
182
- const contentHmrPortId = "/crx-client-port";
183
- const manifestId = "/crx-manifest";
184
- const preambleId = "/crx-client-preamble";
185
- const stubId = "/crx-stub";
186
- const workerClientId = "/crx-client-worker";
187
-
188
- const { readFile: readFile$2 } = promises;
189
- const debug$4 = _debug("file-writer").extend("chunks");
190
- for (const source of [viteClientId, customElementsId]) {
191
- setUrlMeta(sourceToUrlMeta(source));
192
- }
193
- setUrlMeta({
194
- source: reactRefreshId,
195
- id: "/react-refresh",
196
- url: reactRefreshId
197
- });
198
- function sourceToUrlMeta(source) {
199
- const [p, query = ""] = source.split("?");
200
- const pathname = p.replace(/^\/@id\//, "").replace(/^\/@fs/, "");
201
- const url = [pathname, query].filter(isTruthy).join("?");
202
- const hash = createHash(url);
203
- const base = p.split("/").slice(-4).filter(isTruthy).join("-");
204
- const id = `/${base}-${hash}.js`.replace(/[@]/g, "");
205
- return { id, url, source };
206
- }
207
- const pluginFileWriterChunks = () => {
208
- let server;
209
- return {
210
- name: "crx:file-writer-chunks",
211
- apply: "build",
212
- fileWriterStart(_server) {
213
- server = _server;
214
- },
215
- async resolveId(source, importer) {
216
- if (this.meta.watchMode) {
217
- if (idBySource.has(source)) {
218
- const id = idBySource.get(source);
219
- debug$4(`resolved cached ${source} -> ${id}`);
220
- return id;
221
- } else if (importer) {
222
- const meta = sourceToUrlMeta(source);
223
- setUrlMeta(meta);
224
- const { id } = meta;
225
- debug$4(`resolved ${source} -> ${id}`);
226
- return id;
227
- } else {
228
- const [rawUrl] = await server.moduleGraph.resolveUrl(source);
229
- const name = rawUrl.split("/").join("-").replace(/^-/, "");
230
- const url = rawUrl.startsWith("/") ? rawUrl : `/${rawUrl}`;
231
- const id = `/${name}-${createHash(url)}.js`;
232
- setUrlMeta({ url, id, source });
233
- debug$4(`resolved entry ${source} -> ${id}`);
234
- return id;
235
- }
236
- }
237
- },
238
- async load(id) {
239
- if (this.meta.watchMode && urlById.has(id)) {
240
- const url = urlById.get(id);
241
- let serverModule = await server.moduleGraph.getModuleByUrl(url);
242
- let transformResult = null;
243
- if (!serverModule) {
244
- transformResult = await server.transformRequest(url);
245
- serverModule = await server.moduleGraph.getModuleByUrl(url);
246
- }
247
- if (!serverModule)
248
- throw new Error(`Unable to load "${url}" from server.`);
249
- const { file, url: owner } = serverModule;
250
- transformResult = transformResult ?? transformResultByOwner.get(owner) ?? serverModule.transformResult;
251
- if (!transformResult)
252
- transformResult = await server.transformRequest(url);
253
- if (!transformResult)
254
- throw new TypeError(`Unable to load "${url}" from server.`);
255
- transformResultByOwner.set(owner, transformResult);
256
- if (file) {
257
- setFileMeta({ id, file });
258
- this.addWatchFile(file);
259
- if (urlById.get(id).includes("?import"))
260
- this.emitFile({
261
- type: "asset",
262
- fileName: relative(server.config.root, file),
263
- source: await readFile$2(file)
264
- });
265
- }
266
- if (url)
267
- setOwnerMeta({ id, owner });
268
- return { code: transformResult.code, map: transformResult.map };
269
- }
270
- return null;
271
- },
272
- outputOptions(options) {
273
- const cacheDir = relative(server.config.root, server.config.cacheDir);
274
- const fileNameById = /* @__PURE__ */ new Map();
275
- fileNameById.set("/react-refresh", "vendor/react-refresh.js");
276
- function fileNames(info) {
277
- const id = info.type === "chunk" ? info.facadeModuleId : info.name;
278
- if (id && fileNameById.has(id))
279
- return fileNameById.get(id);
280
- let fileName = info.type === "chunk" ? "assets/[name].js" : "assets/[name].[ext]";
281
- if (id && fileById.has(id)) {
282
- fileName = fileById.get(id);
283
- const url = new URL(urlById.get(id), "stub://stub");
284
- if (url.searchParams.has("type"))
285
- fileName += `.${url.searchParams.get("type")}`;
286
- if (url.searchParams.has("index"))
287
- fileName += `.${url.searchParams.get("index")}`;
288
- }
289
- if (id?.startsWith("/@crx/"))
290
- fileName = `vendor/${id.slice("/@crx/".length).split("/").join("-")}`;
291
- if (fileName.startsWith(server.config.root))
292
- fileName = fileName.slice(server.config.root.length + 1);
293
- if (fileName.startsWith(cacheDir))
294
- fileName = `vendor/${fileName.slice(cacheDir.length + 1)}`;
295
- if (fileName.includes("/node_modules/"))
296
- fileName = `vendor/${fileName.split("/node_modules/").pop().split("/").join("-").replace("vite-dist-client", "vite")}`;
297
- if (fileName.startsWith("/"))
298
- fileName = fileName.slice(1);
299
- if (!fileName.endsWith(".js"))
300
- fileName += ".js";
301
- if (id)
302
- fileNameById.set(id, fileName);
303
- fileName = fileName.replace(/:/g, "-").replace(/@/, "");
304
- return fileName;
305
- }
306
- return {
307
- ...options,
308
- preserveModules: true,
309
- assetFileNames: fileNames,
310
- entryFileNames: fileNames
311
- };
312
- },
313
- generateBundle(options, bundle) {
314
- for (const chunk of Object.values(bundle))
315
- if (chunk.type === "chunk") {
316
- const { facadeModuleId: id, modules, code, fileName } = chunk;
317
- if (!id || Object.keys(modules).length !== 1)
318
- continue;
319
- const url = urlById.get(id);
320
- if (url === viteClientId)
321
- continue;
322
- const ownerPath = ownerById.get(id);
323
- if (!ownerPath)
324
- continue;
325
- const index = code.indexOf("createHotContext(");
326
- if (index === -1)
327
- continue;
328
- const start = code.indexOf(ownerPath, index);
329
- const end = start + ownerPath.length;
330
- if (start > 0) {
331
- const outputName = `/${fileName}`;
332
- setOutputMeta({ id, output: outputName });
333
- const magic = new MagicString(code);
334
- magic.overwrite(start, end, outputName);
335
- chunk.code = magic.toString();
336
- }
337
- }
129
+ function defineClientValues(code, config) {
130
+ let options = config.server.hmr;
131
+ options = options && typeof options !== "boolean" ? options : {};
132
+ const host = options.host || null;
133
+ const protocol = options.protocol || null;
134
+ const timeout = options.timeout || 3e4;
135
+ const overlay = options.overlay !== false;
136
+ let hmrPort;
137
+ if (isObject(config.server.hmr)) {
138
+ hmrPort = config.server.hmr.clientPort || config.server.hmr.port;
139
+ }
140
+ if (config.server.middlewareMode) {
141
+ hmrPort = String(hmrPort || 24678);
142
+ } else {
143
+ hmrPort = String(hmrPort || options.port || config.server.port);
144
+ }
145
+ let hmrBase = config.base;
146
+ if (options.path) {
147
+ hmrBase = join(hmrBase, options.path);
148
+ }
149
+ if (hmrBase !== "/") {
150
+ hmrPort = normalize(`${hmrPort}${hmrBase}`);
151
+ }
152
+ return code.replace(`__MODE__`, JSON.stringify(config.mode)).replace(`__BASE__`, JSON.stringify(config.base)).replace(`__DEFINES__`, serializeDefine(config.define || {})).replace(`__HMR_PROTOCOL__`, JSON.stringify(protocol)).replace(`__HMR_HOSTNAME__`, JSON.stringify(host)).replace(`__HMR_PORT__`, JSON.stringify(hmrPort)).replace(`__HMR_TIMEOUT__`, JSON.stringify(timeout)).replace(`__HMR_ENABLE_OVERLAY__`, JSON.stringify(overlay)).replace(`__SERVER_PORT__`, JSON.stringify(config.server.port?.toString()));
153
+ function serializeDefine(define) {
154
+ let res = `{`;
155
+ for (const key in define) {
156
+ const val = define[key];
157
+ res += `${JSON.stringify(key)}: ${typeof val === "string" ? `(${val})` : JSON.stringify(val)}, `;
338
158
  }
339
- };
340
- };
159
+ return res + `}`;
160
+ }
161
+ }
341
162
 
342
163
  /******************************************************************************
343
164
  Copyright (c) Microsoft Corporation.
@@ -1236,46 +1057,67 @@ var AnonymousSubject = (function (_super) {
1236
1057
  return AnonymousSubject;
1237
1058
  }(Subject));
1238
1059
 
1239
- var BehaviorSubject = (function (_super) {
1240
- __extends(BehaviorSubject, _super);
1241
- function BehaviorSubject(_value) {
1060
+ var dateTimestampProvider = {
1061
+ now: function () {
1062
+ return (dateTimestampProvider.delegate || Date).now();
1063
+ },
1064
+ delegate: undefined,
1065
+ };
1066
+
1067
+ var ReplaySubject = (function (_super) {
1068
+ __extends(ReplaySubject, _super);
1069
+ function ReplaySubject(_bufferSize, _windowTime, _timestampProvider) {
1070
+ if (_bufferSize === void 0) { _bufferSize = Infinity; }
1071
+ if (_windowTime === void 0) { _windowTime = Infinity; }
1072
+ if (_timestampProvider === void 0) { _timestampProvider = dateTimestampProvider; }
1242
1073
  var _this = _super.call(this) || this;
1243
- _this._value = _value;
1074
+ _this._bufferSize = _bufferSize;
1075
+ _this._windowTime = _windowTime;
1076
+ _this._timestampProvider = _timestampProvider;
1077
+ _this._buffer = [];
1078
+ _this._infiniteTimeWindow = true;
1079
+ _this._infiniteTimeWindow = _windowTime === Infinity;
1080
+ _this._bufferSize = Math.max(1, _bufferSize);
1081
+ _this._windowTime = Math.max(1, _windowTime);
1244
1082
  return _this;
1245
1083
  }
1246
- Object.defineProperty(BehaviorSubject.prototype, "value", {
1247
- get: function () {
1248
- return this.getValue();
1249
- },
1250
- enumerable: false,
1251
- configurable: true
1252
- });
1253
- BehaviorSubject.prototype._subscribe = function (subscriber) {
1254
- var subscription = _super.prototype._subscribe.call(this, subscriber);
1255
- !subscription.closed && subscriber.next(this._value);
1256
- return subscription;
1257
- };
1258
- BehaviorSubject.prototype.getValue = function () {
1259
- var _a = this, hasError = _a.hasError, thrownError = _a.thrownError, _value = _a._value;
1260
- if (hasError) {
1261
- throw thrownError;
1084
+ ReplaySubject.prototype.next = function (value) {
1085
+ var _a = this, isStopped = _a.isStopped, _buffer = _a._buffer, _infiniteTimeWindow = _a._infiniteTimeWindow, _timestampProvider = _a._timestampProvider, _windowTime = _a._windowTime;
1086
+ if (!isStopped) {
1087
+ _buffer.push(value);
1088
+ !_infiniteTimeWindow && _buffer.push(_timestampProvider.now() + _windowTime);
1262
1089
  }
1090
+ this._trimBuffer();
1091
+ _super.prototype.next.call(this, value);
1092
+ };
1093
+ ReplaySubject.prototype._subscribe = function (subscriber) {
1263
1094
  this._throwIfClosed();
1264
- return _value;
1095
+ this._trimBuffer();
1096
+ var subscription = this._innerSubscribe(subscriber);
1097
+ var _a = this, _infiniteTimeWindow = _a._infiniteTimeWindow, _buffer = _a._buffer;
1098
+ var copy = _buffer.slice();
1099
+ for (var i = 0; i < copy.length && !subscriber.closed; i += _infiniteTimeWindow ? 1 : 2) {
1100
+ subscriber.next(copy[i]);
1101
+ }
1102
+ this._checkFinalizedStatuses(subscriber);
1103
+ return subscription;
1265
1104
  };
1266
- BehaviorSubject.prototype.next = function (value) {
1267
- _super.prototype.next.call(this, (this._value = value));
1105
+ ReplaySubject.prototype._trimBuffer = function () {
1106
+ var _a = this, _bufferSize = _a._bufferSize, _timestampProvider = _a._timestampProvider, _buffer = _a._buffer, _infiniteTimeWindow = _a._infiniteTimeWindow;
1107
+ var adjustedBufferSize = (_infiniteTimeWindow ? 1 : 2) * _bufferSize;
1108
+ _bufferSize < Infinity && adjustedBufferSize < _buffer.length && _buffer.splice(0, _buffer.length - adjustedBufferSize);
1109
+ if (!_infiniteTimeWindow) {
1110
+ var now = _timestampProvider.now();
1111
+ var last = 0;
1112
+ for (var i = 1; i < _buffer.length && _buffer[i] <= now; i += 2) {
1113
+ last = i;
1114
+ }
1115
+ last && _buffer.splice(0, last + 1);
1116
+ }
1268
1117
  };
1269
- return BehaviorSubject;
1118
+ return ReplaySubject;
1270
1119
  }(Subject));
1271
1120
 
1272
- var dateTimestampProvider = {
1273
- now: function () {
1274
- return (dateTimestampProvider.delegate || Date).now();
1275
- },
1276
- delegate: undefined,
1277
- };
1278
-
1279
1121
  var Action = (function (_super) {
1280
1122
  __extends(Action, _super);
1281
1123
  function Action(scheduler, work) {
@@ -1448,15 +1290,9 @@ function isScheduler(value) {
1448
1290
  function last(arr) {
1449
1291
  return arr[arr.length - 1];
1450
1292
  }
1451
- function popResultSelector(args) {
1452
- return isFunction(last(args)) ? args.pop() : undefined;
1453
- }
1454
1293
  function popScheduler(args) {
1455
1294
  return isScheduler(last(args)) ? args.pop() : undefined;
1456
1295
  }
1457
- function popNumber(args, defaultValue) {
1458
- return typeof last(args) === 'number' ? args.pop() : defaultValue;
1459
- }
1460
1296
 
1461
1297
  var isArrayLike = (function (x) { return x && typeof x.length === 'number' && typeof x !== 'function'; });
1462
1298
 
@@ -1793,6 +1629,15 @@ function from(input, scheduler) {
1793
1629
  return scheduler ? scheduled(input, scheduler) : innerFrom(input);
1794
1630
  }
1795
1631
 
1632
+ function of() {
1633
+ var args = [];
1634
+ for (var _i = 0; _i < arguments.length; _i++) {
1635
+ args[_i] = arguments[_i];
1636
+ }
1637
+ var scheduler = popScheduler(args);
1638
+ return from(args, scheduler);
1639
+ }
1640
+
1796
1641
  var EmptyError = createErrorClass(function (_super) { return function EmptyErrorImpl() {
1797
1642
  _super(this);
1798
1643
  this.name = 'EmptyError';
@@ -1908,6 +1753,18 @@ function mergeAll(concurrent) {
1908
1753
  return mergeMap(identity, concurrent);
1909
1754
  }
1910
1755
 
1756
+ function concatAll() {
1757
+ return mergeAll(1);
1758
+ }
1759
+
1760
+ function concat$1() {
1761
+ var args = [];
1762
+ for (var _i = 0; _i < arguments.length; _i++) {
1763
+ args[_i] = arguments[_i];
1764
+ }
1765
+ return concatAll()(from(args, popScheduler(args)));
1766
+ }
1767
+
1911
1768
  function timer(dueTime, intervalOrScheduler, scheduler) {
1912
1769
  if (dueTime === void 0) { dueTime = 0; }
1913
1770
  if (scheduler === void 0) { scheduler = async; }
@@ -1940,24 +1797,6 @@ function timer(dueTime, intervalOrScheduler, scheduler) {
1940
1797
  });
1941
1798
  }
1942
1799
 
1943
- function merge() {
1944
- var args = [];
1945
- for (var _i = 0; _i < arguments.length; _i++) {
1946
- args[_i] = arguments[_i];
1947
- }
1948
- var scheduler = popScheduler(args);
1949
- var concurrent = popNumber(args, Infinity);
1950
- var sources = args;
1951
- return !sources.length
1952
- ?
1953
- EMPTY
1954
- : sources.length === 1
1955
- ?
1956
- innerFrom(sources[0])
1957
- :
1958
- mergeAll(concurrent)(from(sources, scheduler));
1959
- }
1960
-
1961
1800
  function filter(predicate, thisArg) {
1962
1801
  return operate(function (source, subscriber) {
1963
1802
  var index = 0;
@@ -1983,36 +1822,57 @@ function buffer(closingNotifier) {
1983
1822
  });
1984
1823
  }
1985
1824
 
1986
- function debounce(durationSelector) {
1987
- return operate(function (source, subscriber) {
1988
- var hasValue = false;
1989
- var lastValue = null;
1990
- var durationSubscriber = null;
1991
- var emit = function () {
1992
- durationSubscriber === null || durationSubscriber === void 0 ? void 0 : durationSubscriber.unsubscribe();
1993
- durationSubscriber = null;
1994
- if (hasValue) {
1995
- hasValue = false;
1996
- var value = lastValue;
1997
- lastValue = null;
1998
- subscriber.next(value);
1999
- }
2000
- };
1825
+ function scanInternals(accumulator, seed, hasSeed, emitOnNext, emitBeforeComplete) {
1826
+ return function (source, subscriber) {
1827
+ var hasState = hasSeed;
1828
+ var state = seed;
1829
+ var index = 0;
2001
1830
  source.subscribe(createOperatorSubscriber(subscriber, function (value) {
2002
- durationSubscriber === null || durationSubscriber === void 0 ? void 0 : durationSubscriber.unsubscribe();
2003
- hasValue = true;
2004
- lastValue = value;
2005
- durationSubscriber = createOperatorSubscriber(subscriber, emit, noop);
2006
- innerFrom(durationSelector(value)).subscribe(durationSubscriber);
2007
- }, function () {
2008
- emit();
2009
- subscriber.complete();
2010
- }, undefined, function () {
2011
- lastValue = durationSubscriber = null;
2012
- }));
1831
+ var i = index++;
1832
+ state = hasState
1833
+ ?
1834
+ accumulator(state, value, i)
1835
+ :
1836
+ ((hasState = true), value);
1837
+ emitOnNext && subscriber.next(state);
1838
+ }, emitBeforeComplete &&
1839
+ (function () {
1840
+ hasState && subscriber.next(state);
1841
+ subscriber.complete();
1842
+ })));
1843
+ };
1844
+ }
1845
+
1846
+ function reduce(accumulator, seed) {
1847
+ return operate(scanInternals(accumulator, seed, arguments.length >= 2, false, true));
1848
+ }
1849
+
1850
+ var arrReducer = function (arr, value) { return (arr.push(value), arr); };
1851
+ function toArray() {
1852
+ return operate(function (source, subscriber) {
1853
+ reduce(arrReducer, [])(source).subscribe(subscriber);
1854
+ });
1855
+ }
1856
+
1857
+ function concat() {
1858
+ var args = [];
1859
+ for (var _i = 0; _i < arguments.length; _i++) {
1860
+ args[_i] = arguments[_i];
1861
+ }
1862
+ var scheduler = popScheduler(args);
1863
+ return operate(function (source, subscriber) {
1864
+ concatAll()(from(__spreadArray([source], __read(args)), scheduler)).subscribe(subscriber);
2013
1865
  });
2014
1866
  }
2015
1867
 
1868
+ function concatWith() {
1869
+ var otherSources = [];
1870
+ for (var _i = 0; _i < arguments.length; _i++) {
1871
+ otherSources[_i] = arguments[_i];
1872
+ }
1873
+ return concat.apply(void 0, __spreadArray([], __read(otherSources)));
1874
+ }
1875
+
2016
1876
  function defaultIfEmpty(defaultValue) {
2017
1877
  return operate(function (source, subscriber) {
2018
1878
  var hasValue = false;
@@ -2066,6 +1926,81 @@ function first(predicate, defaultValue) {
2066
1926
  };
2067
1927
  }
2068
1928
 
1929
+ function retry(configOrCount) {
1930
+ if (configOrCount === void 0) { configOrCount = Infinity; }
1931
+ var config;
1932
+ if (configOrCount && typeof configOrCount === 'object') {
1933
+ config = configOrCount;
1934
+ }
1935
+ else {
1936
+ config = {
1937
+ count: configOrCount,
1938
+ };
1939
+ }
1940
+ var _a = config.count, count = _a === void 0 ? Infinity : _a, delay = config.delay, _b = config.resetOnSuccess, resetOnSuccess = _b === void 0 ? false : _b;
1941
+ return count <= 0
1942
+ ? identity
1943
+ : operate(function (source, subscriber) {
1944
+ var soFar = 0;
1945
+ var innerSub;
1946
+ var subscribeForRetry = function () {
1947
+ var syncUnsub = false;
1948
+ innerSub = source.subscribe(createOperatorSubscriber(subscriber, function (value) {
1949
+ if (resetOnSuccess) {
1950
+ soFar = 0;
1951
+ }
1952
+ subscriber.next(value);
1953
+ }, undefined, function (err) {
1954
+ if (soFar++ < count) {
1955
+ var resub_1 = function () {
1956
+ if (innerSub) {
1957
+ innerSub.unsubscribe();
1958
+ innerSub = null;
1959
+ subscribeForRetry();
1960
+ }
1961
+ else {
1962
+ syncUnsub = true;
1963
+ }
1964
+ };
1965
+ if (delay != null) {
1966
+ var notifier = typeof delay === 'number' ? timer(delay) : innerFrom(delay(err, soFar));
1967
+ var notifierSubscriber_1 = createOperatorSubscriber(subscriber, function () {
1968
+ notifierSubscriber_1.unsubscribe();
1969
+ resub_1();
1970
+ }, function () {
1971
+ subscriber.complete();
1972
+ });
1973
+ notifier.subscribe(notifierSubscriber_1);
1974
+ }
1975
+ else {
1976
+ resub_1();
1977
+ }
1978
+ }
1979
+ else {
1980
+ subscriber.error(err);
1981
+ }
1982
+ }));
1983
+ if (syncUnsub) {
1984
+ innerSub.unsubscribe();
1985
+ innerSub = null;
1986
+ subscribeForRetry();
1987
+ }
1988
+ };
1989
+ subscribeForRetry();
1990
+ });
1991
+ }
1992
+
1993
+ function startWith() {
1994
+ var values = [];
1995
+ for (var _i = 0; _i < arguments.length; _i++) {
1996
+ values[_i] = arguments[_i];
1997
+ }
1998
+ var scheduler = popScheduler(values);
1999
+ return operate(function (source, subscriber) {
2000
+ (scheduler ? concat$1(values, source, scheduler) : concat$1(values, source)).subscribe(subscriber);
2001
+ });
2002
+ }
2003
+
2069
2004
  function switchMap(project, resultSelector) {
2070
2005
  return operate(function (source, subscriber) {
2071
2006
  var innerSubscriber = null;
@@ -2087,184 +2022,478 @@ function switchMap(project, resultSelector) {
2087
2022
  });
2088
2023
  }
2089
2024
 
2090
- function withLatestFrom() {
2091
- var inputs = [];
2092
- for (var _i = 0; _i < arguments.length; _i++) {
2093
- inputs[_i] = arguments[_i];
2094
- }
2095
- var project = popResultSelector(inputs);
2025
+ function takeUntil(notifier) {
2096
2026
  return operate(function (source, subscriber) {
2097
- var len = inputs.length;
2098
- var otherValues = new Array(len);
2099
- var hasValue = inputs.map(function () { return false; });
2100
- var ready = false;
2101
- var _loop_1 = function (i) {
2102
- innerFrom(inputs[i]).subscribe(createOperatorSubscriber(subscriber, function (value) {
2103
- otherValues[i] = value;
2104
- if (!ready && !hasValue[i]) {
2105
- hasValue[i] = true;
2106
- (ready = hasValue.every(identity)) && (hasValue = null);
2107
- }
2108
- }, noop));
2109
- };
2110
- for (var i = 0; i < len; i++) {
2111
- _loop_1(i);
2112
- }
2113
- source.subscribe(createOperatorSubscriber(subscriber, function (value) {
2114
- if (ready) {
2115
- var values = __spreadArray([value], __read(otherValues));
2116
- subscriber.next(project ? project.apply(void 0, __spreadArray([], __read(values))) : values);
2117
- }
2118
- }));
2027
+ innerFrom(notifier).subscribe(createOperatorSubscriber(subscriber, function () { return subscriber.complete(); }, noop));
2028
+ !subscriber.closed && source.subscribe(subscriber);
2119
2029
  });
2120
2030
  }
2121
2031
 
2122
- const { pathExistsSync, outputFile, statSync } = fsExtra;
2123
- const debug$3 = _debug("file-writer").extend("events");
2124
- const writerEvent$ = new BehaviorSubject({
2125
- type: "init"
2126
- });
2127
- writerEvent$.subscribe((event) => {
2128
- debug$3("watcher event %O", event.type);
2129
- if (event.type === "error") {
2130
- debug$3("watcher error %O", event.error);
2032
+ class RxMap extends Map {
2033
+ static isChangeType = {
2034
+ clear: (x) => x.type === "clear",
2035
+ delete: (x) => x.type === "delete",
2036
+ set: (x) => x.type === "set"
2037
+ };
2038
+ change$;
2039
+ constructor(iterable) {
2040
+ super(iterable);
2041
+ const change$ = new Subject();
2042
+ this.change$ = change$.asObservable();
2043
+ const changeMethodKeys = ["clear", "set", "delete"];
2044
+ for (const type of changeMethodKeys) {
2045
+ const method = this[type];
2046
+ this[type] = function(...args) {
2047
+ const result = method.call(this, ...args);
2048
+ change$.next({ type, key: args[0], value: args[1], map: this });
2049
+ return result;
2050
+ }.bind(this);
2051
+ }
2131
2052
  }
2132
- });
2133
- const filesError$ = writerEvent$.pipe(filter((x) => {
2134
- return x.type === "error";
2135
- }));
2136
- const filesStart$ = writerEvent$.pipe(filter((x) => {
2137
- return x.type === "buildStart";
2138
- }));
2139
- const filesStart = () => firstValueFrom(filesStart$);
2140
- const filesReady$ = writerEvent$.pipe(filter((x) => {
2141
- return x.type === "writeBundle";
2142
- }), switchMap((event) => timer(0, 100).pipe(map(() => event), first(({ bundle, options, timestamp }) => {
2143
- const result = Object.keys(bundle).every((p) => {
2144
- const stats = statSync(join(options.dir, p));
2145
- return stats.mtimeMs > timestamp;
2146
- });
2147
- return result;
2148
- }))));
2149
- const filesReady = () => firstValueFrom(filesReady$);
2150
- const server$ = new Subject();
2151
- const triggerName = firstValueFrom(server$.pipe(map(({ config: { cacheDir } }) => cacheDir), filter(isString), map((dir) => join(dir, ".crx-watch-trigger"))));
2152
- const rebuildFiles = async () => {
2153
- debug$3("rebuildFiles start");
2154
- await filesReady();
2155
- await Promise.all([
2156
- outputFile(await triggerName, Date.now().toString()),
2157
- filesStart()
2158
- ]);
2159
- await filesReady();
2160
- debug$3("rebuildFiles end");
2161
- };
2162
- function startLogger(server) {
2163
- const logger = createLogger(server.config.logLevel, {
2164
- prefix: "[crx]"
2165
- });
2166
- const subs = [
2167
- filesStart$.subscribe(() => {
2168
- const message = colors.green("files start");
2169
- const outDir = colors.dim(relative(server.config.root, server.config.build.outDir));
2170
- logger.info(`${message} ${outDir}`, { timestamp: true });
2171
- }),
2172
- filesReady$.subscribe(({ duration: d }) => {
2173
- const message = colors.green("files ready");
2174
- const duration = colors.dim(`in ${colors.bold(`${d}ms`)}`);
2175
- logger.info(`${message} ${duration}`, { timestamp: true });
2176
- }),
2177
- filesError$.subscribe(({ error }) => {
2178
- logger.error(colors.dim("error from file writer:"), { timestamp: true });
2179
- if (error) {
2180
- const message = error?.stack ?? error.message;
2181
- logger.error(colors.red(message));
2182
- }
2183
- })
2184
- ];
2185
- return () => subs.forEach((sub) => sub.unsubscribe());
2186
2053
  }
2187
- const pluginFileWriterEvents = () => {
2188
- let start = performance.now();
2189
- let stopLogger;
2190
- return {
2191
- name: "crx:file-writer-events",
2192
- enforce: "post",
2193
- apply: "build",
2194
- fileWriterStart(server) {
2195
- debug$3("fileWriterStart");
2196
- stopLogger = startLogger(server);
2197
- },
2198
- closeWatcher() {
2199
- debug$3("closeWatcher");
2200
- stopLogger();
2201
- },
2202
- async buildStart(options) {
2203
- start = performance.now();
2204
- const filename = await triggerName;
2205
- if (!pathExistsSync(filename)) {
2206
- await outputFile(filename, Date.now().toString());
2054
+
2055
+ const outputFiles = new RxMap();
2056
+
2057
+ _debug("file-writer").extend("utilities");
2058
+ function prefix$1(prefix2, text) {
2059
+ return text.startsWith(prefix2) ? text : prefix2 + text;
2060
+ }
2061
+ function strip(prefix2, text) {
2062
+ return text?.startsWith(prefix2) ? text?.slice(prefix2.length) : text;
2063
+ }
2064
+ function formatFileData(script) {
2065
+ script.id = prefix$1("/", script.id);
2066
+ if (script.fileName)
2067
+ script.fileName = strip("/", script.fileName);
2068
+ if (script.loaderName)
2069
+ script.loaderName = strip("/", script.loaderName);
2070
+ return script;
2071
+ }
2072
+ function getFileName({ type, id }) {
2073
+ let fileName = id.replace(/t=\d+&/, "").replace(/^\//, "").replace(/\?/g, "__").replace(/&/g, "_").replace(/=/g, "--");
2074
+ if (fileName.includes("node_modules/")) {
2075
+ fileName = `vendor/${fileName.split("node_modules/").pop().replace(/\//g, "-")}`;
2076
+ } else if (fileName.startsWith("@")) {
2077
+ fileName = `vendor/${fileName.slice("@".length).replace(/\//g, "-")}`;
2078
+ } else if (fileName.startsWith(".vite/deps/")) {
2079
+ fileName = `vendor/${fileName.slice(".vite/deps/".length)}`;
2080
+ }
2081
+ switch (type) {
2082
+ case "iife":
2083
+ return `${fileName}.iife.js`;
2084
+ case "loader":
2085
+ return `${fileName}-loader.js`;
2086
+ case "module":
2087
+ return `${fileName}.js`;
2088
+ case "asset":
2089
+ return fileName;
2090
+ default:
2091
+ throw new Error(`Unexpected script type "${type}" for "${JSON.stringify({
2092
+ type,
2093
+ id
2094
+ })}"`);
2095
+ }
2096
+ }
2097
+ function getOutputPath(server, fileName) {
2098
+ const {
2099
+ root,
2100
+ build: { outDir }
2101
+ } = server.config;
2102
+ const target = isAbsolute(outDir) ? join(outDir, fileName) : join(root, outDir, fileName);
2103
+ return target;
2104
+ }
2105
+ function getViteUrl({ type, id }) {
2106
+ if (type === "asset") {
2107
+ throw new Error(`File type "${type}" not implemented.`);
2108
+ } else if (type === "iife") {
2109
+ throw new Error(`File type "${type}" not implemented.`);
2110
+ } else if (type === "loader") {
2111
+ throw new Error("Vite does not transform loader files.");
2112
+ } else if (type === "module") {
2113
+ if (id.startsWith("/@id/"))
2114
+ return id.slice("/@id/".length).replace("__x00__", "\0");
2115
+ return prefix$1("/", id);
2116
+ } else {
2117
+ throw new Error(`Invalid file type: "${type}"`);
2118
+ }
2119
+ }
2120
+ async function fileReady(script) {
2121
+ const fileName = getFileName(script);
2122
+ const file = outputFiles.get(fileName);
2123
+ if (!file)
2124
+ throw new Error("unknown script type and id");
2125
+ const { deps } = await file.file;
2126
+ await Promise.all(deps.map(fileReady));
2127
+ }
2128
+
2129
+ const viteClientId = "/@vite/client";
2130
+ const customElementsId = "/@webcomponents/custom-elements";
2131
+ const contentHmrPortId = "/@crx/client-port";
2132
+ const manifestId = "/@crx/manifest";
2133
+ const preambleId = "/@crx/client-preamble";
2134
+ const stubId = "/@crx/stub";
2135
+ const workerClientId = "/@crx/client-worker";
2136
+
2137
+ const pluginBackground = () => {
2138
+ let config;
2139
+ return [
2140
+ {
2141
+ name: "crx:background-client",
2142
+ apply: "serve",
2143
+ resolveId(source) {
2144
+ if (source === `/${workerClientId}`)
2145
+ return workerClientId;
2146
+ },
2147
+ load(id) {
2148
+ if (id === workerClientId) {
2149
+ const base = `http://localhost:${config.server.port}/`;
2150
+ return defineClientValues(workerHmrClient.replace("__BASE__", JSON.stringify(base)), config);
2151
+ }
2207
2152
  }
2208
- this.addWatchFile(filename);
2209
- writerEvent$.next({ type: "buildStart", options });
2210
- debug$3("buildStart");
2211
- },
2212
- writeBundle(options, bundle) {
2213
- const timestamp = performance.now();
2214
- const duration = Math.round(timestamp - start);
2215
- writerEvent$.next({
2216
- type: "writeBundle",
2217
- options,
2218
- bundle,
2219
- duration,
2220
- timestamp
2221
- });
2222
- debug$3("writeBundle");
2223
2153
  },
2224
- renderError(error) {
2225
- writerEvent$.next({ type: "error", error });
2226
- },
2227
- watchChange(id, { event }) {
2228
- writerEvent$.next({ type: "change", id, event });
2154
+ {
2155
+ name: "crx:background-loader-file",
2156
+ enforce: "post",
2157
+ configResolved(_config) {
2158
+ config = _config;
2159
+ },
2160
+ renderCrxManifest(manifest) {
2161
+ const worker = manifest.background?.service_worker;
2162
+ let loader;
2163
+ if (config.command === "serve") {
2164
+ const port = config.server.port?.toString();
2165
+ if (typeof port === "undefined")
2166
+ throw new Error("server port is undefined in watch mode");
2167
+ loader = `import 'http:/localhost:${port}/@vite/env';
2168
+ `;
2169
+ loader += `import 'http://localhost:${port}${workerClientId}';
2170
+ `;
2171
+ if (worker)
2172
+ loader += `import 'http://localhost:${port}/${worker}';
2173
+ `;
2174
+ } else if (worker) {
2175
+ loader = `import './${worker}';
2176
+ `;
2177
+ } else {
2178
+ return null;
2179
+ }
2180
+ const refId = this.emitFile({
2181
+ type: "asset",
2182
+ fileName: getFileName({ type: "loader", id: "service-worker" }),
2183
+ source: loader
2184
+ });
2185
+ manifest.background = {
2186
+ service_worker: this.getFileName(refId),
2187
+ type: "module"
2188
+ };
2189
+ return manifest;
2190
+ }
2229
2191
  }
2230
- };
2192
+ ];
2231
2193
  };
2232
2194
 
2233
- var precontrollerScript = "const id = setInterval(() => location.reload(), 100);\nsetTimeout(() => clearInterval(id), 5e3);\n";
2195
+ var contentHmrPort = "function isCrxHMRPayload(x) {\n return x.type === \"custom\" && x.event.startsWith(\"crx:\");\n}\nclass HMRPort {\n port;\n callbacks = /* @__PURE__ */ new Map();\n constructor() {\n setInterval(() => {\n try {\n this.port?.postMessage({ data: \"ping\" });\n } catch (error) {\n if (error instanceof Error && error.message.includes(\"Extension context invalidated.\")) {\n location.reload();\n } else\n throw error;\n }\n }, __CRX_HMR_TIMEOUT__);\n setInterval(this.initPort, 5 * 60 * 1e3);\n this.initPort();\n }\n initPort = () => {\n this.port?.disconnect();\n this.port = chrome.runtime.connect({ name: \"@crx/client\" });\n this.port.onDisconnect.addListener(this.handleDisconnect.bind(this));\n this.port.onMessage.addListener(this.handleMessage.bind(this));\n this.port.postMessage({ type: \"connected\" });\n };\n handleDisconnect = () => {\n if (this.callbacks.has(\"close\"))\n for (const cb of this.callbacks.get(\"close\")) {\n cb({ wasClean: true });\n }\n };\n handleMessage = (message) => {\n const forward = (data) => {\n if (this.callbacks.has(\"message\"))\n for (const cb of this.callbacks.get(\"message\")) {\n cb({ data });\n }\n };\n const payload = JSON.parse(message.data);\n if (isCrxHMRPayload(payload)) {\n if (payload.event === \"crx:runtime-reload\") {\n console.log(\"[crx] runtime reload\");\n setTimeout(() => location.reload(), 500);\n } else {\n forward(JSON.stringify(payload.data));\n }\n } else {\n forward(message.data);\n }\n };\n addEventListener = (event, callback) => {\n const cbs = this.callbacks.get(event) ?? /* @__PURE__ */ new Set();\n cbs.add(callback);\n this.callbacks.set(event, cbs);\n };\n send = (data) => {\n if (this.port)\n this.port.postMessage({ data });\n else\n throw new Error(\"HMRPort is not initialized\");\n };\n}\n\nexport { HMRPort };\n";
2196
+
2197
+ var contentDevLoader = "(function () {\n 'use strict';\n\n (async () => {\n if (__PREAMBLE__)\n await import(\n /* @vite-ignore */\n chrome.runtime.getURL(__PREAMBLE__)\n );\n await import(\n /* @vite-ignore */\n chrome.runtime.getURL(__CLIENT__)\n );\n await import(\n /* @vite-ignore */\n chrome.runtime.getURL(__SCRIPT__)\n );\n })().catch(console.error);\n\n})();\n";
2234
2198
 
2235
- var precontrollerHtml = "<!DOCTYPE html>\n<html lang=\"en\">\n <head>\n <title>Waiting for the extension service worker...</title>\n <script src=\"%PATH%\"></script>\n </head>\n <body>\n <h1>Waiting for service worker</h1>\n\n <p>\n If you see this message, it means the service worker has not loaded fully.\n </p>\n\n <p>This page is never added in production.</p>\n </body>\n</html>\n";
2199
+ var contentProLoader = "(function () {\n 'use strict';\n\n (async () => {\n await import(\n /* @vite-ignore */\n chrome.runtime.getURL(__SCRIPT__)\n );\n })().catch(console.error);\n\n})();\n";
2236
2200
 
2237
- const pluginFileWriterHtml = () => {
2238
- let precontrollerName;
2239
- return {
2240
- name: "crx:file-writer-html",
2241
- apply: "build",
2242
- fileWriterStart(server) {
2243
- const plugins = server.config.plugins;
2244
- const i = plugins.findIndex(({ name }) => name === "alias");
2245
- plugins.splice(i, 0, {
2246
- name: "crx:load-precontroller",
2247
- apply: "serve",
2248
- load(id) {
2249
- if (id === `/${precontrollerName}`)
2250
- return "location.reload();";
2201
+ const contentScripts = new RxMap();
2202
+ contentScripts.change$.pipe(filter(RxMap.isChangeType.set)).subscribe(({ map, value }) => {
2203
+ const keyNames = [
2204
+ "refId",
2205
+ "id",
2206
+ "fileName",
2207
+ "loaderName",
2208
+ "resolvedId",
2209
+ "scriptId"
2210
+ ];
2211
+ for (const keyName of keyNames) {
2212
+ const key = value[keyName];
2213
+ if (typeof key === "undefined" || map.has(key)) {
2214
+ continue;
2215
+ } else {
2216
+ map.set(key, value);
2217
+ }
2218
+ }
2219
+ });
2220
+ function hashScriptId(script) {
2221
+ return hash(`${script.type}&${script.id}`);
2222
+ }
2223
+ function createDevLoader({
2224
+ preamble,
2225
+ client,
2226
+ fileName
2227
+ }) {
2228
+ return contentDevLoader.replace(/__PREAMBLE__/g, JSON.stringify(preamble)).replace(/__CLIENT__/g, JSON.stringify(client)).replace(/__SCRIPT__/g, JSON.stringify(fileName)).replace(/__TIMESTAMP__/g, JSON.stringify(Date.now()));
2229
+ }
2230
+ function createProLoader({ fileName }) {
2231
+ return contentProLoader.replace(/__SCRIPT__/g, JSON.stringify(fileName));
2232
+ }
2233
+
2234
+ const serverEvent$ = new ReplaySubject(1);
2235
+ const close$ = serverEvent$.pipe(filter((e) => e.type === "close"), switchMap((e) => of(e)));
2236
+ const start$ = serverEvent$.pipe(filter((e) => e.type === "start"), switchMap((e) => of(e)));
2237
+ const fileWriterEvent$ = new ReplaySubject(1);
2238
+ const buildEnd$ = fileWriterEvent$.pipe(filter((e) => e.type === "build_end"), switchMap((e) => of(e)));
2239
+ fileWriterEvent$.pipe(filter((e) => e.type === "build_start"), switchMap((e) => of(e)));
2240
+ const allFilesReady$ = buildEnd$.pipe(switchMap(() => outputFiles.change$.pipe(startWith({ type: "start" }))), map(() => [...outputFiles.values()]), switchMap((files) => Promise.allSettled(files.map(({ file }) => file))));
2241
+ const isRejected = (x) => x?.status === "rejected";
2242
+ const fileWriterError$ = allFilesReady$.pipe(mergeMap((results) => results.filter(isRejected)), map((rejected) => ({ err: rejected.reason, type: "error" })));
2243
+ firstValueFrom(fileWriterError$.pipe(takeUntil(serverEvent$.pipe(first(({ type }) => type === "close"))), toArray()));
2244
+ function prepFileData(fileId) {
2245
+ const fileName = getFileName(fileId);
2246
+ if (fileId.type === "asset") {
2247
+ return prepAsset(fileName, fileId);
2248
+ } else {
2249
+ return prepScript(fileName, fileId);
2250
+ }
2251
+ }
2252
+ function prepAsset(fileName, { id, source }) {
2253
+ return ($) => $.pipe(mergeMap(async ({ server }) => {
2254
+ const target = getOutputPath(server, fileName);
2255
+ return {
2256
+ target,
2257
+ source: source ?? await readFile$1(join(server.config.root, id)),
2258
+ deps: []
2259
+ };
2260
+ }));
2261
+ }
2262
+ function prepScript(fileName, script) {
2263
+ return ($) => $.pipe(mergeMap(async ({ server }) => {
2264
+ const target = getOutputPath(server, fileName);
2265
+ const viteUrl = getViteUrl(script);
2266
+ const transformResult = await server.transformRequest(viteUrl);
2267
+ if (!transformResult)
2268
+ throw new TypeError(`Unable to load "${script.id}" from server.`);
2269
+ const { code, deps = [], dynamicDeps = [] } = transformResult;
2270
+ return { target, code, deps: [...deps, ...dynamicDeps].flat(), server };
2271
+ }), retry({ count: 10, delay: 100 }), mergeMap(async ({ target, server, ...rest }) => {
2272
+ const plugins = server.config.plugins;
2273
+ let { code, deps } = rest;
2274
+ for (const plugin of plugins) {
2275
+ const r = await plugin.renderCrxDevScript?.(code, script);
2276
+ if (typeof r === "string")
2277
+ code = r;
2278
+ }
2279
+ return { target, code, deps };
2280
+ }), mergeMap(async ({ target, code, deps }) => {
2281
+ await lexer.init;
2282
+ const [imports] = lexer.parse(code, fileName);
2283
+ const depSet = new Set(deps);
2284
+ const magic = new MagicString(code);
2285
+ for (const i of imports)
2286
+ if (i.n) {
2287
+ depSet.add(i.n);
2288
+ const fileName2 = getFileName({ type: "module", id: i.n });
2289
+ magic.overwrite(i.s, i.e, `/${fileName2}`);
2290
+ }
2291
+ return { target, source: magic.toString(), deps: [...depSet] };
2292
+ }));
2293
+ }
2294
+ async function allFilesReady() {
2295
+ await firstValueFrom(allFilesReady$);
2296
+ }
2297
+
2298
+ const { outputFile } = fsx;
2299
+ _debug("file-writer");
2300
+ async function start({
2301
+ server
2302
+ }) {
2303
+ serverEvent$.next({ type: "start", server });
2304
+ const plugins = server.config.plugins.filter((p) => p.name?.startsWith("crx:"));
2305
+ const { rollupOptions, outDir } = server.config.build;
2306
+ const inputOptions = {
2307
+ input: "index.html",
2308
+ ...rollupOptions,
2309
+ plugins
2310
+ };
2311
+ const rollupOutputOptions = [rollupOptions.output].flat()[0];
2312
+ const outputOptions = {
2313
+ ...rollupOutputOptions,
2314
+ dir: outDir,
2315
+ format: "es"
2316
+ };
2317
+ fileWriterEvent$.next({ type: "build_start" });
2318
+ const build = await rollup(inputOptions);
2319
+ await build.write(outputOptions);
2320
+ fileWriterEvent$.next({ type: "build_end" });
2321
+ await allFilesReady();
2322
+ }
2323
+ async function close() {
2324
+ serverEvent$.next({ type: "close" });
2325
+ }
2326
+ function add(script) {
2327
+ const fileName = getFileName(script);
2328
+ let file = outputFiles.get(fileName);
2329
+ if (typeof file === "undefined") {
2330
+ file = formatFileData({
2331
+ ...script,
2332
+ fileName,
2333
+ file: write(script)
2334
+ });
2335
+ outputFiles.set(file.fileName, file);
2336
+ }
2337
+ return file;
2338
+ }
2339
+ function update(_id) {
2340
+ const id = prefix$1("/", _id);
2341
+ const types = ["iife", "module"];
2342
+ const updatedFiles = [];
2343
+ for (const type of types) {
2344
+ const fileName = getFileName({ id, type });
2345
+ const scriptFile = outputFiles.get(fileName);
2346
+ if (scriptFile) {
2347
+ scriptFile.file = write({ id, type });
2348
+ updatedFiles.push(scriptFile);
2349
+ outputFiles.set(fileName, scriptFile);
2350
+ }
2351
+ }
2352
+ return updatedFiles;
2353
+ }
2354
+ async function write(fileId) {
2355
+ const start2 = performance.now();
2356
+ const deps = await firstValueFrom(start$.pipe(prepFileData(fileId), mergeMap(async ({ target, source, deps: deps2 }) => {
2357
+ const files = deps2.map((id) => {
2358
+ const r = [add({ id, type: "module" })];
2359
+ if (id.includes("?import")) {
2360
+ const [imported] = id.split("?import");
2361
+ r.push(add({ id: imported, type: "asset" }));
2362
+ }
2363
+ return r;
2364
+ }).flat();
2365
+ if (source instanceof Uint8Array)
2366
+ await outputFile(target, source);
2367
+ else
2368
+ await outputFile(target, source, { encoding: "utf8" });
2369
+ return files;
2370
+ }), takeUntil(close$), concatWith(of([]))));
2371
+ const close2 = performance.now();
2372
+ return { start: start2, close: close2, deps };
2373
+ }
2374
+
2375
+ const pluginContentScripts = () => {
2376
+ let server;
2377
+ let preambleCode;
2378
+ let hmrTimeout;
2379
+ let sub = new Subscription();
2380
+ return [
2381
+ {
2382
+ name: "crx:content-scripts",
2383
+ apply: "serve",
2384
+ config(config) {
2385
+ const { contentScripts: contentScripts2 = {} } = getOptions(config);
2386
+ hmrTimeout = contentScripts2.hmrTimeout ?? 5e3;
2387
+ preambleCode = preambleCode ?? contentScripts2.preambleCode;
2388
+ },
2389
+ async configureServer(_server) {
2390
+ server = _server;
2391
+ if (typeof preambleCode === "undefined" && server.config.plugins.some(({ name = "none" }) => name.toLowerCase().includes("react"))) {
2392
+ try {
2393
+ const react = await import('@vitejs/plugin-react');
2394
+ preambleCode = react.default.preambleCode;
2395
+ } catch (error) {
2396
+ preambleCode = false;
2397
+ }
2251
2398
  }
2252
- });
2399
+ sub.add(contentScripts.change$.pipe(filter(RxMap.isChangeType.set)).subscribe(({ value: script }) => {
2400
+ const { type, id } = script;
2401
+ if (type === "loader") {
2402
+ let preamble = { fileName: "" };
2403
+ if (preambleCode)
2404
+ preamble = add({ type: "module", id: preambleId });
2405
+ const client = add({ type: "module", id: viteClientId });
2406
+ const file = add({ type: "module", id });
2407
+ const loader = add({
2408
+ type: "asset",
2409
+ id: getFileName({ type: "loader", id }),
2410
+ source: createDevLoader({
2411
+ preamble: preamble.fileName,
2412
+ client: client.fileName,
2413
+ fileName: file.fileName
2414
+ })
2415
+ });
2416
+ script.fileName = loader.fileName;
2417
+ } else if (type === "iife") {
2418
+ throw new Error("IIFE content scripts are not implemented");
2419
+ } else {
2420
+ const file = add({ type: "module", id });
2421
+ script.fileName = file.fileName;
2422
+ }
2423
+ }));
2424
+ },
2425
+ resolveId(source) {
2426
+ if (source === preambleId)
2427
+ return preambleId;
2428
+ if (source === contentHmrPortId)
2429
+ return contentHmrPortId;
2430
+ },
2431
+ load(id) {
2432
+ if (id === preambleId && typeof preambleCode === "string") {
2433
+ const defined = preambleCode.replace(/__BASE__/g, server.config.base);
2434
+ return defined;
2435
+ }
2436
+ if (id === contentHmrPortId) {
2437
+ const defined = contentHmrPort.replace("__CRX_HMR_TIMEOUT__", JSON.stringify(hmrTimeout));
2438
+ return defined;
2439
+ }
2440
+ },
2441
+ closeBundle() {
2442
+ sub.unsubscribe();
2443
+ sub = new Subscription();
2444
+ }
2445
+ },
2446
+ {
2447
+ name: "crx:content-scripts",
2448
+ apply: "build",
2449
+ enforce: "pre",
2450
+ generateBundle() {
2451
+ for (const [key, script] of contentScripts)
2452
+ if (key === script.refId) {
2453
+ if (script.type === "module") {
2454
+ const fileName = this.getFileName(script.refId);
2455
+ script.fileName = fileName;
2456
+ } else if (script.type === "loader") {
2457
+ const fileName = this.getFileName(script.refId);
2458
+ script.fileName = fileName;
2459
+ const refId = this.emitFile({
2460
+ type: "asset",
2461
+ name: getFileName({ type: "loader", id: basename(script.id) }),
2462
+ source: createProLoader({ fileName })
2463
+ });
2464
+ script.loaderName = this.getFileName(refId);
2465
+ } else if (script.type === "iife") {
2466
+ throw new Error("IIFE content scripts are not implemented");
2467
+ }
2468
+ contentScripts.set(script.refId, formatFileData(script));
2469
+ }
2470
+ }
2471
+ }
2472
+ ];
2473
+ };
2474
+
2475
+ const pluginContentScriptsCss = () => {
2476
+ let injectCss;
2477
+ return {
2478
+ name: "crx:content-scripts-css",
2479
+ enforce: "post",
2480
+ config(config) {
2481
+ const { contentScripts: contentScripts2 = {} } = getOptions(config);
2482
+ injectCss = contentScripts2.injectCss ?? true;
2253
2483
  },
2254
2484
  renderCrxManifest(manifest) {
2255
- if (this.meta.watchMode) {
2256
- const refId = this.emitFile({
2257
- type: "asset",
2258
- name: "precontroller.js",
2259
- source: precontrollerScript
2260
- });
2261
- precontrollerName = this.getFileName(refId);
2262
- for (const fileName of htmlFiles(manifest)) {
2263
- this.emitFile({
2264
- type: "asset",
2265
- fileName,
2266
- source: precontrollerHtml.replace("%PATH%", `/${precontrollerName}`)
2267
- });
2485
+ if (injectCss) {
2486
+ if (manifest.content_scripts) {
2487
+ for (const script of manifest.content_scripts)
2488
+ if (script.js)
2489
+ for (const fileName of script.js)
2490
+ if (contentScripts.has(fileName)) {
2491
+ const { css } = contentScripts.get(fileName);
2492
+ if (css?.length)
2493
+ script.css = [script.css ?? [], css].flat();
2494
+ } else {
2495
+ throw new Error(`Content script is undefined by fileName: ${fileName}`);
2496
+ }
2268
2497
  }
2269
2498
  }
2270
2499
  return manifest;
@@ -2272,89 +2501,257 @@ const pluginFileWriterHtml = () => {
2272
2501
  };
2273
2502
  };
2274
2503
 
2275
- const { readFile: readFile$1 } = promises;
2276
- const pluginFileWriterPublic = () => {
2504
+ const pluginDeclaredContentScripts = () => {
2505
+ return [];
2506
+ };
2507
+
2508
+ const _dynamicScriptRegEx = /\b(import.meta).CRX_DYNAMIC_SCRIPT_(.+?);$/gm;
2509
+ const dynamicScriptRegEx = () => {
2510
+ _dynamicScriptRegEx.lastIndex = 0;
2511
+ return _dynamicScriptRegEx;
2512
+ };
2513
+ const pluginDynamicContentScripts = () => {
2277
2514
  let config;
2278
- return {
2279
- name: "crx:file-writer-public",
2280
- apply: "build",
2281
- configResolved(_config) {
2282
- config = _config;
2283
- },
2284
- async buildStart() {
2285
- if (this.meta.watchMode) {
2286
- this.addWatchFile(config.publicDir);
2287
- const publicFiles = await fg(`${config.publicDir}/**/*`);
2288
- for (const file of publicFiles) {
2289
- const source = await readFile$1(file);
2290
- const fileName = relative(config.publicDir, file);
2291
- this.emitFile({ type: "asset", fileName, source });
2515
+ return [
2516
+ {
2517
+ name: "crx:dynamic-content-scripts-loader",
2518
+ enforce: "pre",
2519
+ configResolved(_config) {
2520
+ config = _config;
2521
+ },
2522
+ async resolveId(_source, importer) {
2523
+ if (importer && _source.includes("?script")) {
2524
+ const url = new URL(_source, "stub://stub");
2525
+ if (url.searchParams.has("script")) {
2526
+ const [source] = _source.split("?");
2527
+ const resolved = await this.resolve(source, importer, {
2528
+ skipSelf: true
2529
+ });
2530
+ if (!resolved)
2531
+ throw new Error(`Could not resolve dynamic script: "${_source}" from "${importer}"`);
2532
+ const { id } = resolved;
2533
+ let type = "loader";
2534
+ if (url.searchParams.has("module")) {
2535
+ type = "module";
2536
+ } else if (url.searchParams.has("iife")) {
2537
+ type = "iife";
2538
+ }
2539
+ const scriptId = hashScriptId({ type, id });
2540
+ const resolvedId = `${id}?scriptId=${scriptId}`;
2541
+ let script = contentScripts.get(resolvedId);
2542
+ if (typeof script === "undefined") {
2543
+ let refId;
2544
+ let fileName;
2545
+ let loaderName;
2546
+ if (config.command === "build") {
2547
+ refId = this.emitFile({
2548
+ type: "chunk",
2549
+ id,
2550
+ name: basename(id)
2551
+ });
2552
+ } else {
2553
+ refId = scriptId;
2554
+ const relId = relative(config.root, id);
2555
+ fileName = getFileName({
2556
+ type: type === "iife" ? "iife" : "module",
2557
+ id: relId
2558
+ });
2559
+ if (type === "loader")
2560
+ loaderName = getFileName({ type, id: relId });
2561
+ }
2562
+ script = formatFileData({
2563
+ type,
2564
+ id: relative(config.root, id),
2565
+ isDynamicScript: true,
2566
+ fileName,
2567
+ loaderName,
2568
+ refId,
2569
+ scriptId,
2570
+ matches: []
2571
+ });
2572
+ contentScripts.set(script.id, script);
2573
+ }
2574
+ return resolvedId;
2575
+ } else if (url.searchParams.has("scriptId")) {
2576
+ return _source;
2577
+ }
2578
+ }
2579
+ },
2580
+ async load(id) {
2581
+ const index = id.indexOf("?scriptId=");
2582
+ if (index > -1) {
2583
+ const scriptId = id.slice(index + "?scriptId=".length);
2584
+ const script = contentScripts.get(scriptId);
2585
+ if (config.command === "build") {
2586
+ return `export default import.meta.CRX_DYNAMIC_SCRIPT_${script.refId};`;
2587
+ } else if (typeof script.fileName === "string") {
2588
+ await fileReady(script);
2589
+ return `export default ${JSON.stringify(script.fileName)};`;
2590
+ } else {
2591
+ throw new Error(`Content script fileName is undefined: "${script.id}"`);
2592
+ }
2292
2593
  }
2293
2594
  }
2595
+ },
2596
+ {
2597
+ name: "crx:dynamic-content-scripts-build",
2598
+ apply: "build",
2599
+ generateBundle(options, bundle) {
2600
+ for (const chunk of Object.values(bundle))
2601
+ if (chunk.type === "chunk") {
2602
+ if (dynamicScriptRegEx().test(chunk.code)) {
2603
+ const replaced = chunk.code.replace(dynamicScriptRegEx(), (match, p1, scriptKey) => {
2604
+ const script = contentScripts.get(scriptKey);
2605
+ if (typeof script === "undefined")
2606
+ throw new Error(`Content script refId is undefined: "${match}"`);
2607
+ if (typeof script.fileName === "undefined")
2608
+ throw new Error(`Content script fileName is undefined: "${script.id}"`);
2609
+ return `${JSON.stringify(`/${script.loaderName ?? script.fileName}`)};`;
2610
+ });
2611
+ chunk.code = replaced;
2612
+ }
2613
+ }
2614
+ }
2615
+ }
2616
+ ];
2617
+ };
2618
+
2619
+ const logger = createLogger("error", { prefix: "crxjs" });
2620
+ const pluginFileWriter = () => {
2621
+ fileWriterError$.subscribe((error) => {
2622
+ logger.error(error.err.message, { error: error.err });
2623
+ });
2624
+ return {
2625
+ name: "crx:file-writer",
2626
+ apply: "serve",
2627
+ configureServer(server) {
2628
+ server.httpServer?.on("listening", async () => {
2629
+ try {
2630
+ await start({ server });
2631
+ } catch (error) {
2632
+ console.error(error);
2633
+ server.close();
2634
+ }
2635
+ });
2636
+ server.httpServer?.on("close", () => close());
2637
+ },
2638
+ closeBundle() {
2639
+ outputFiles.clear();
2294
2640
  }
2295
2641
  };
2296
2642
  };
2297
2643
 
2298
2644
  const _require = typeof require === "undefined" ? createRequire(import.meta.url) : require;
2299
- const customElementsPath = _require.resolve(customElementsId);
2645
+ const customElementsPath = _require.resolve(customElementsId.slice(1));
2300
2646
  const customElementsCode = readFileSync(customElementsPath, "utf8");
2301
2647
  const customElementsMap = readFileSync(`${customElementsPath}.map`, "utf8");
2302
2648
  const pluginFileWriterPolyfill = () => {
2303
2649
  return {
2304
2650
  name: "crx:file-writer-polyfill",
2305
- apply: "build",
2651
+ apply: "serve",
2306
2652
  enforce: "pre",
2653
+ resolveId(source) {
2654
+ if (source === customElementsId) {
2655
+ return customElementsId;
2656
+ }
2657
+ },
2307
2658
  load(id) {
2308
- if (id === idByUrl.get(customElementsId)) {
2659
+ if (id === customElementsId) {
2309
2660
  return { code: customElementsCode, map: customElementsMap };
2310
2661
  }
2311
2662
  },
2312
- transform(code, id) {
2313
- if (id === idByUrl.get(viteClientId)) {
2663
+ renderCrxDevScript(code, { type, id }) {
2664
+ if (type === "module" && id === viteClientId) {
2314
2665
  const magic = new MagicString(code);
2315
2666
  magic.prepend(`import '${customElementsId}';`);
2316
2667
  magic.prepend(`import { HMRPort } from '${contentHmrPortId}';`);
2317
2668
  const ws = "new WebSocket";
2318
2669
  const index = code.indexOf(ws);
2319
2670
  magic.overwrite(index, index + ws.length, "new HMRPort");
2320
- return { code: magic.toString(), map: magic.generateMap() };
2671
+ return magic.toString();
2321
2672
  }
2322
2673
  }
2323
2674
  };
2324
2675
  };
2325
2676
 
2326
- function isUpdatePayload(p) {
2327
- return p.type === "update";
2328
- }
2329
- function isFullReloadPayload(p) {
2330
- return p.type === "full-reload";
2677
+ async function manifestFiles(manifest, options = {}) {
2678
+ let locales = [];
2679
+ if (manifest.default_locale)
2680
+ locales = await fg("_locales/**/messages.json", options);
2681
+ const rulesets = manifest.declarative_net_request?.rule_resources.flatMap(({ path }) => path) ?? [];
2682
+ const contentScripts = manifest.content_scripts?.flatMap(({ js }) => js) ?? [];
2683
+ const contentStyles = manifest.content_scripts?.flatMap(({ css }) => css);
2684
+ const serviceWorker = manifest.background?.service_worker;
2685
+ const htmlPages = htmlFiles(manifest);
2686
+ const icons = [
2687
+ Object.values(isString(manifest.icons) ? [manifest.icons] : manifest.icons ?? {}),
2688
+ Object.values(isString(manifest.action?.default_icon) ? [manifest.action?.default_icon] : manifest.action?.default_icon ?? {})
2689
+ ].flat();
2690
+ let webAccessibleResources = [];
2691
+ if (manifest.web_accessible_resources) {
2692
+ const resources = await Promise.all(manifest.web_accessible_resources.flatMap(({ resources: resources2 }) => resources2).map(async (r) => {
2693
+ if (["*", "**/*"].includes(r))
2694
+ return void 0;
2695
+ if (fg.isDynamicPattern(r))
2696
+ return fg(r, options);
2697
+ return r;
2698
+ }));
2699
+ webAccessibleResources = resources.flat().filter(isString);
2700
+ }
2701
+ return {
2702
+ contentScripts: [...new Set(contentScripts)].filter(isString),
2703
+ contentStyles: [...new Set(contentStyles)].filter(isString),
2704
+ html: htmlPages,
2705
+ icons: [...new Set(icons)].filter(isString),
2706
+ locales: [...new Set(locales)].filter(isString),
2707
+ rulesets: [...new Set(rulesets)].filter(isString),
2708
+ background: [serviceWorker].filter(isString),
2709
+ webAccessibleResources
2710
+ };
2331
2711
  }
2332
- function isPrunePayload(p) {
2333
- return p.type === "prune";
2712
+ async function dirFiles(dir) {
2713
+ const files = await fg(`${dir}/**/*`);
2714
+ return files;
2334
2715
  }
2335
- function isCrxHMRPayload(x) {
2336
- return x.type === "custom" && x.event.startsWith("crx:");
2716
+ function htmlFiles(manifest) {
2717
+ const files = [
2718
+ manifest.action?.default_popup,
2719
+ Object.values(manifest.chrome_url_overrides ?? {}),
2720
+ manifest.devtools_page,
2721
+ manifest.options_page,
2722
+ manifest.options_ui?.page,
2723
+ manifest.sandbox?.pages
2724
+ ].flat().filter(isString).map((s) => s.split("#")[0]).sort();
2725
+ return [...new Set(files)];
2337
2726
  }
2727
+
2728
+ const pluginFileWriterPublic = () => {
2729
+ let config;
2730
+ return {
2731
+ name: "crx:file-writer-public",
2732
+ apply: "serve",
2733
+ configResolved(_config) {
2734
+ config = _config;
2735
+ },
2736
+ async generateBundle() {
2737
+ const publicDir = isAbsolute(config.publicDir) ? config.publicDir : resolve(config.root, config.publicDir);
2738
+ const files = await dirFiles(publicDir);
2739
+ for (const filepath of files) {
2740
+ const source = await readFile$1(filepath);
2741
+ const fileName = relative(publicDir, filepath);
2742
+ this.emitFile({ type: "asset", source, fileName });
2743
+ }
2744
+ }
2745
+ };
2746
+ };
2747
+
2748
+ _debug("file-writer").extend("hmr");
2749
+ const isCrxHMRPayload = (p) => p.type === "custom" && p.event.startsWith("crx:");
2338
2750
  const hmrPayload$ = new Subject();
2339
- const hmrPrune$ = hmrPayload$.pipe(filter(isPrunePayload));
2340
- const hmrFullReload$ = hmrPayload$.pipe(filter(isFullReloadPayload));
2341
- const hmrUpdate$ = hmrPayload$.pipe(filter(isUpdatePayload));
2342
- const payload$ = merge(hmrFullReload$, hmrPrune$, hmrUpdate$);
2343
- const rebuildSignal$ = payload$.pipe(buffer(payload$.pipe(debounce(() => filesReady$))), map((payloads) => {
2344
- if (payloads.every(isUpdatePayload)) {
2345
- const owners = /* @__PURE__ */ new Set();
2346
- for (const { updates } of payloads)
2347
- for (const { path } of updates)
2348
- if (transformResultByOwner.has(path))
2349
- owners.add(path);
2350
- return { type: "partial", owners };
2351
- }
2352
- return { type: "full" };
2353
- }), filter((rebuild) => rebuild.type === "partial" ? rebuild.owners.size > 0 : true));
2354
- const crxHmrPayload$ = hmrPayload$.pipe(filter((p) => !isCrxHMRPayload(p)), buffer(filesReady$), mergeMap((pps) => {
2751
+ const crxHMRPayload$ = hmrPayload$.pipe(filter((p) => !isCrxHMRPayload(p)), buffer(allFilesReady$), mergeMap((pps) => {
2355
2752
  let fullReload;
2356
2753
  const payloads = [];
2357
- for (const p of pps.slice(-50))
2754
+ for (const p of pps)
2358
2755
  if (p.type === "full-reload") {
2359
2756
  fullReload = p;
2360
2757
  } else {
@@ -2366,38 +2763,37 @@ const crxHmrPayload$ = hmrPayload$.pipe(filter((p) => !isCrxHMRPayload(p)), buff
2366
2763
  }), map((p) => {
2367
2764
  switch (p.type) {
2368
2765
  case "full-reload": {
2369
- const path = p.path && outputByOwner.get(p.path);
2370
2766
  const fullReload = {
2371
2767
  type: "full-reload",
2372
- path
2768
+ path: p.path && getViteUrl({ id: p.path, type: "module" })
2373
2769
  };
2374
2770
  return fullReload;
2375
2771
  }
2376
2772
  case "prune": {
2377
- const paths = [];
2378
- for (const owner of p.paths)
2379
- if (outputByOwner.has(owner))
2380
- paths.push(outputByOwner.get(owner));
2381
- return { type: "prune", paths };
2773
+ const prune = {
2774
+ type: "prune",
2775
+ paths: p.paths.map((id) => getViteUrl({ id, type: "module" }))
2776
+ };
2777
+ return prune;
2382
2778
  }
2383
2779
  case "update": {
2384
- const updates = [];
2385
- for (const { acceptedPath, path, ...rest } of p.updates)
2386
- if (outputByOwner.has(acceptedPath) && outputByOwner.has(path))
2387
- updates.push({
2388
- ...rest,
2389
- acceptedPath: outputByOwner.get(acceptedPath),
2390
- path: outputByOwner.get(path)
2391
- });
2392
- return { type: "update", updates };
2780
+ const update = {
2781
+ type: "update",
2782
+ updates: p.updates.map(({ acceptedPath: ap, path: p2, ...rest }) => ({
2783
+ ...rest,
2784
+ acceptedPath: prefix$1("/", getFileName({ id: ap, type: "module" })),
2785
+ path: prefix$1("/", getFileName({ id: p2, type: "module" }))
2786
+ }))
2787
+ };
2788
+ return update;
2393
2789
  }
2394
2790
  default:
2395
2791
  return p;
2396
2792
  }
2397
- }), withLatestFrom(filesReady$), filter(([p, { bundle }]) => {
2793
+ }), filter((p) => {
2398
2794
  switch (p.type) {
2399
2795
  case "full-reload":
2400
- return typeof p.path === "undefined" || p.path in bundle;
2796
+ return typeof p.path === "undefined";
2401
2797
  case "prune":
2402
2798
  return p.paths.length > 0;
2403
2799
  case "update":
@@ -2405,127 +2801,13 @@ const crxHmrPayload$ = hmrPayload$.pipe(filter((p) => !isCrxHMRPayload(p)), buff
2405
2801
  default:
2406
2802
  return true;
2407
2803
  }
2408
- }), map(([p]) => ({
2409
- type: "custom",
2410
- event: "crx:content-script-payload",
2411
- data: p
2412
- })));
2413
-
2414
- function sortPlugins(plugins, command) {
2415
- const pre = [];
2416
- const mid = [];
2417
- const post = [];
2418
- for (const p of plugins) {
2419
- if (p.apply === command || !p.apply || !command) {
2420
- if (p.enforce === "pre")
2421
- pre.push(p);
2422
- else if (p.enforce === "post")
2423
- post.push(p);
2424
- else
2425
- mid.push(p);
2426
- }
2427
- }
2428
- return { pre, mid, post };
2429
- }
2430
- const pluginFileWriter = (crxPlugins) => (options) => {
2431
- const chunks = pluginFileWriterChunks();
2432
- const html = pluginFileWriterHtml();
2433
- const events = pluginFileWriterEvents();
2434
- const publicDir = pluginFileWriterPublic();
2435
- const polyfill = pluginFileWriterPolyfill();
2436
- const { pre, mid, post } = sortPlugins(crxPlugins, "build");
2437
- const plugins = [
2438
- ...pre,
2439
- ...mid,
2440
- polyfill,
2441
- chunks,
2442
- html,
2443
- publicDir,
2444
- ...post,
2445
- events
2446
- ].flat();
2447
- let watcher;
2804
+ }), map((data) => {
2448
2805
  return {
2449
- name: "crx:file-writer",
2450
- apply: "serve",
2451
- async config(_config, env) {
2452
- let config = _config;
2453
- for (const p of plugins) {
2454
- const r = await p.config?.(config, env);
2455
- config = r ?? config;
2456
- }
2457
- return config;
2458
- },
2459
- async configResolved(config) {
2460
- await Promise.all(plugins.map((p) => p.configResolved?.(config)));
2461
- },
2462
- configureServer(server) {
2463
- server.httpServer?.once("listening", async () => {
2464
- server$.next(server);
2465
- const optimizedDeps = server._optimizedDeps;
2466
- await optimizedDeps?.scanProcessing;
2467
- const { pre: pre2, mid: mid2, post: post2 } = sortPlugins([
2468
- ...server.config.plugins,
2469
- ...plugins
2470
- ]);
2471
- const allPlugins = [...pre2, ...mid2, ...post2];
2472
- await Promise.all(allPlugins.map(async (p) => {
2473
- try {
2474
- await p.fileWriterStart?.(server);
2475
- } catch (e) {
2476
- const hook = `[${p.name}].fileWriterStart`;
2477
- let error = new Error(`Error in plugin ${hook}`);
2478
- if (e instanceof Error) {
2479
- error = e;
2480
- error.message = `${hook} ${error.message}`;
2481
- } else if (typeof e === "string") {
2482
- error = new Error(`${hook} ${e}`);
2483
- }
2484
- writerEvent$.next({ type: "error", error });
2485
- }
2486
- }));
2487
- watcher = watch({
2488
- input: stubId,
2489
- context: "this",
2490
- output: {
2491
- dir: server.config.build.outDir,
2492
- format: "es"
2493
- },
2494
- plugins,
2495
- treeshake: false
2496
- });
2497
- watcher.on("event", (event) => {
2498
- if (event.code === "ERROR") {
2499
- const { message, parserError, stack, id, loc, code, frame } = event.error;
2500
- const error = parserError ?? new Error(message);
2501
- if (parserError && message.startsWith("Unexpected token")) {
2502
- const m = `Unexpected token in ${loc?.file ?? id}`;
2503
- error.message = [m, loc?.line, loc?.column].filter(isTruthy).join(":");
2504
- }
2505
- error.stack = (stack ?? error.stack)?.replace(/.+?\n/, `Error: ${error.message}
2506
- `);
2507
- writerEvent$.next({ type: "error", error, code, frame });
2508
- }
2509
- });
2510
- const rebuildSub = rebuildSignal$.subscribe((rebuild) => {
2511
- if (rebuild.type === "partial") {
2512
- for (const owner of rebuild.owners)
2513
- transformResultByOwner.delete(owner);
2514
- } else {
2515
- transformResultByOwner.clear();
2516
- }
2517
- rebuildFiles();
2518
- });
2519
- watcher.on("close", () => {
2520
- rebuildSub.unsubscribe();
2521
- });
2522
- });
2523
- },
2524
- closeBundle() {
2525
- watcher?.close();
2526
- }
2806
+ type: "custom",
2807
+ event: "crx:content-script-payload",
2808
+ data
2527
2809
  };
2528
- };
2810
+ }));
2529
2811
 
2530
2812
  function isImporter(file) {
2531
2813
  const seen = /* @__PURE__ */ new Set();
@@ -2543,68 +2825,108 @@ function isImporter(file) {
2543
2825
  return pred;
2544
2826
  }
2545
2827
 
2546
- const debug$2 = _debug("hmr");
2828
+ const debug$1 = _debug("hmr");
2547
2829
  const crxRuntimeReload = {
2548
2830
  type: "custom",
2549
2831
  event: "crx:runtime-reload"
2550
2832
  };
2551
2833
  const pluginHMR = () => {
2552
- let files;
2834
+ let inputManifestFiles;
2553
2835
  let decoratedSend;
2836
+ let config;
2837
+ let subs;
2554
2838
  return [
2555
- {
2556
- name: "crx:hmr",
2557
- apply: "build",
2558
- enforce: "post",
2559
- async renderCrxManifest(manifest) {
2560
- if (this.meta.watchMode) {
2561
- files = await manifestFiles(manifest);
2562
- }
2563
- return null;
2564
- }
2565
- },
2566
2839
  {
2567
2840
  name: "crx:hmr",
2568
2841
  apply: "serve",
2569
2842
  enforce: "pre",
2570
- config({ server = {}, ...config }) {
2843
+ async config({ server = {}, ...config2 }) {
2571
2844
  if (server.hmr === false)
2572
2845
  return;
2573
2846
  if (server.hmr === true)
2574
2847
  server.hmr = {};
2575
2848
  server.hmr = server.hmr ?? {};
2576
2849
  server.hmr.host = "localhost";
2577
- return { server, ...config };
2850
+ server.hmr.port = server.hmr.port ?? await getPort({ port: portNumbers(5200, 5300) });
2851
+ return { server, ...config2 };
2578
2852
  },
2579
- configResolved(config) {
2853
+ configResolved(_config) {
2854
+ config = _config;
2580
2855
  const { watch = {} } = config.server;
2581
2856
  config.server.watch = watch;
2582
2857
  watch.ignored = watch.ignored ? [...new Set([watch.ignored].flat())] : [];
2583
2858
  const outDir = isAbsolute(config.build.outDir) ? config.build.outDir : join(config.root, config.build.outDir, "**/*");
2584
- watch.ignored.push(outDir);
2859
+ if (!watch.ignored.includes(outDir))
2860
+ watch.ignored.push(outDir);
2585
2861
  },
2586
2862
  configureServer(server) {
2587
2863
  if (server.ws.send !== decoratedSend) {
2588
2864
  const { send } = server.ws;
2589
2865
  decoratedSend = (payload) => {
2590
- hmrPayload$.next(payload);
2866
+ if (payload.type === "error") {
2867
+ send({
2868
+ type: "custom",
2869
+ event: "crx:content-script-payload",
2870
+ data: payload
2871
+ });
2872
+ } else {
2873
+ hmrPayload$.next(payload);
2874
+ }
2591
2875
  send(payload);
2592
2876
  };
2593
2877
  server.ws.send = decoratedSend;
2594
- crxHmrPayload$.subscribe((payload) => {
2878
+ subs = new Subscription(() => subs = new Subscription());
2879
+ subs.add(fileWriterError$.subscribe(send));
2880
+ subs.add(crxHMRPayload$.subscribe((payload) => {
2595
2881
  send(payload);
2596
- });
2882
+ }));
2597
2883
  }
2598
2884
  },
2599
- handleHotUpdate({ file, modules, server }) {
2600
- const background = files.background[0] && join(server.config.root, files.background[0]);
2601
- if (background) {
2602
- if (file === background || modules.some(isImporter(background))) {
2603
- debug$2("sending runtime reload");
2885
+ closeBundle() {
2886
+ subs.unsubscribe();
2887
+ },
2888
+ handleHotUpdate({ modules, server }) {
2889
+ const { root } = server.config;
2890
+ const relFiles = /* @__PURE__ */ new Set();
2891
+ for (const m of modules)
2892
+ if (m.id?.startsWith(root)) {
2893
+ relFiles.add(m.id.slice(server.config.root.length));
2894
+ }
2895
+ if (inputManifestFiles.background.length) {
2896
+ const background = prefix$1("/", inputManifestFiles.background[0]);
2897
+ if (relFiles.has(background) || modules.some(isImporter(join(server.config.root, background)))) {
2898
+ debug$1("sending runtime reload");
2604
2899
  server.ws.send(crxRuntimeReload);
2605
2900
  return [];
2606
2901
  }
2607
2902
  }
2903
+ for (const [key, script] of contentScripts)
2904
+ if (key === script.id) {
2905
+ if (relFiles.has(script.id) || modules.some(isImporter(join(server.config.root, script.id)))) {
2906
+ relFiles.forEach((relFile) => update(relFile));
2907
+ }
2908
+ }
2909
+ }
2910
+ },
2911
+ {
2912
+ name: "crx:hmr",
2913
+ apply: "serve",
2914
+ enforce: "post",
2915
+ async transformCrxManifest(manifest) {
2916
+ inputManifestFiles = await manifestFiles(manifest, { cwd: config.root });
2917
+ return null;
2918
+ },
2919
+ renderCrxDevScript(code, { id: _id, type }) {
2920
+ if (type === "module" && _id !== "/@vite/client" && code.includes("createHotContext")) {
2921
+ const id = _id.replace(/t=\d+&/, "");
2922
+ const escaped = id.replace(/([?&.])/g, "\\$1");
2923
+ const regexp = new RegExp(`(?<=createHotContext\\(")${escaped}(?="\\))`);
2924
+ const fileUrl = prefix$1("/", getFileName({ id, type }));
2925
+ const replaced = code.replace(regexp, fileUrl);
2926
+ return replaced;
2927
+ } else {
2928
+ return code;
2929
+ }
2608
2930
  }
2609
2931
  }
2610
2932
  ];
@@ -2613,14 +2935,14 @@ const pluginHMR = () => {
2613
2935
  var loader = "try {\n for (const p of JSON.parse(SCRIPTS)) {\n const url = new URL(p, \"https://stub\");\n url.searchParams.set(\"t\", Date.now().toString());\n const req = url.pathname + url.search;\n await import(\n /* @vite-ignore */\n req\n );\n }\n} catch (error) {\n console.error(error);\n}\n";
2614
2936
 
2615
2937
  const pluginName = "crx:html-inline-scripts";
2616
- const debug$1 = _debug(pluginName);
2938
+ const debug = _debug(pluginName);
2617
2939
  const prefix = "@crx/inline-script";
2618
2940
  const isInlineTag = (t) => t.tag === "script" && !t.attrs?.src;
2619
2941
  const toKey = (ctx) => {
2620
2942
  const { dir, name } = parse(ctx.path);
2621
2943
  return join(prefix, dir, name);
2622
2944
  };
2623
- const pluginHtmlAuditor = () => {
2945
+ const pluginHtmlInlineScripts = () => {
2624
2946
  const pages = /* @__PURE__ */ new Map();
2625
2947
  const auditTransformIndexHtml = (p) => {
2626
2948
  let transform;
@@ -2734,15 +3056,19 @@ const pluginHtmlAuditor = () => {
2734
3056
  })}"`;
2735
3057
  return [inline, loader.replace("SCRIPTS", json)].join("\n");
2736
3058
  } else {
2737
- debug$1("page missing %s", id);
3059
+ debug("page missing %s", id);
2738
3060
  }
2739
3061
  }
2740
3062
  }
2741
3063
  };
2742
3064
  };
2743
3065
 
3066
+ var precontrollerJs = "const id = setInterval(() => location.reload(), 100);\nsetTimeout(() => clearInterval(id), 5e3);\n";
3067
+
3068
+ var precontrollerHtml = "<!DOCTYPE html>\n<html lang=\"en\">\n <head>\n <title>Waiting for the extension service worker...</title>\n <script src=\"%SCRIPT%\"></script>\n </head>\n <body>\n <h1>Waiting for service worker</h1>\n\n <p>\n If you see this message, it means the service worker has not loaded fully.\n </p>\n\n <p>This page is never added in production.</p>\n </body>\n</html>\n";
3069
+
2744
3070
  const { readFile } = promises;
2745
- const pluginManifest = (_manifest) => () => {
3071
+ const pluginManifest = () => {
2746
3072
  let manifest;
2747
3073
  let plugins;
2748
3074
  let refId;
@@ -2752,6 +3078,7 @@ const pluginManifest = (_manifest) => () => {
2752
3078
  name: "crx:manifest-init",
2753
3079
  enforce: "pre",
2754
3080
  async config(config2, env) {
3081
+ const { manifest: _manifest } = await getOptions(config2);
2755
3082
  manifest = await (typeof _manifest === "function" ? _manifest(env) : _manifest);
2756
3083
  if (manifest.manifest_version !== 3)
2757
3084
  throw new Error(`CRXJS does not support Manifest v${manifest.manifest_version}, please use Manifest v3`);
@@ -2760,7 +3087,7 @@ const pluginManifest = (_manifest) => () => {
2760
3087
  contentScripts: js,
2761
3088
  background: sw,
2762
3089
  html
2763
- } = await manifestFiles(manifest);
3090
+ } = await manifestFiles(manifest, { cwd: config2.root });
2764
3091
  const { entries = [] } = config2.optimizeDeps ?? {};
2765
3092
  let { input = [] } = config2.build?.rollupOptions ?? {};
2766
3093
  if (typeof input === "string")
@@ -2793,15 +3120,16 @@ const pluginManifest = (_manifest) => () => {
2793
3120
  },
2794
3121
  {
2795
3122
  name: "crx:manifest-loader",
2796
- apply: "build",
2797
3123
  enforce: "pre",
2798
- buildStart() {
2799
- refId = this.emitFile({
2800
- type: "chunk",
2801
- id: manifestId,
2802
- name: "crx-manifest.js",
2803
- preserveSignature: "strict"
2804
- });
3124
+ buildStart(options) {
3125
+ if (typeof options.input !== "undefined") {
3126
+ refId = this.emitFile({
3127
+ type: "chunk",
3128
+ id: manifestId,
3129
+ name: "crx-manifest.js",
3130
+ preserveSignature: "strict"
3131
+ });
3132
+ }
2805
3133
  },
2806
3134
  resolveId(source) {
2807
3135
  if (source === manifestId)
@@ -2816,13 +3144,22 @@ const pluginManifest = (_manifest) => () => {
2816
3144
  },
2817
3145
  {
2818
3146
  name: "crx:stub-input",
2819
- apply: "build",
2820
3147
  enforce: "pre",
2821
3148
  options({ input, ...options }) {
2822
- return {
2823
- input: isString(input) && input.endsWith("index.html") ? stubId : input,
2824
- ...options
2825
- };
3149
+ let finalInput = input;
3150
+ if (isString(input) && input.endsWith("index.html")) {
3151
+ finalInput = stubId;
3152
+ }
3153
+ if (config.command === "serve") {
3154
+ if (Array.isArray(input)) {
3155
+ finalInput = input.filter((x) => !x.endsWith(".html"));
3156
+ } else if (typeof input === "object") {
3157
+ for (const [key, value] of Object.entries(input))
3158
+ if (value.endsWith(".html"))
3159
+ delete input[key];
3160
+ }
3161
+ }
3162
+ return { input: finalInput, ...options };
2826
3163
  },
2827
3164
  resolveId(source) {
2828
3165
  if (source === stubId)
@@ -2845,7 +3182,6 @@ const pluginManifest = (_manifest) => () => {
2845
3182
  },
2846
3183
  {
2847
3184
  name: "crx:manifest-post",
2848
- apply: "build",
2849
3185
  enforce: "post",
2850
3186
  configResolved(_config) {
2851
3187
  config = _config;
@@ -2867,32 +3203,52 @@ const pluginManifest = (_manifest) => () => {
2867
3203
  if (error instanceof Error)
2868
3204
  error.message = `[${plugin.name}] ${error.message}`;
2869
3205
  throw error;
2870
- }
2871
- }
2872
- if (manifest2.content_scripts?.length) {
2873
- manifest2.content_scripts = manifest2.content_scripts.map(({ js = [], ...rest }) => {
2874
- const refJS = js.map((file) => this.emitFile({
2875
- type: "chunk",
2876
- id: file,
2877
- name: basename(file)
2878
- }));
2879
- return { js: refJS, ...rest };
2880
- });
3206
+ }
2881
3207
  }
2882
- if (!this.meta.watchMode) {
3208
+ if (config.command === "serve") {
3209
+ if (manifest2.content_scripts)
3210
+ for (const { js = [], matches = [] } of manifest2.content_scripts)
3211
+ for (const id2 of js) {
3212
+ contentScripts.set(prefix$1("/", id2), formatFileData({
3213
+ type: "loader",
3214
+ id: id2,
3215
+ matches,
3216
+ refId: hashScriptId({ type: "loader", id: id2 }),
3217
+ fileName: getFileName({ type: "loader", id: id2 })
3218
+ }));
3219
+ }
3220
+ } else {
3221
+ if (manifest2.content_scripts)
3222
+ for (const { js = [], matches = [] } of manifest2.content_scripts)
3223
+ for (const file of js) {
3224
+ const id2 = join(config.root, file);
3225
+ const refId2 = this.emitFile({
3226
+ type: "chunk",
3227
+ id: id2,
3228
+ name: basename(file)
3229
+ });
3230
+ contentScripts.set(file, formatFileData({
3231
+ type: "loader",
3232
+ id: file,
3233
+ refId: refId2,
3234
+ matches
3235
+ }));
3236
+ }
2883
3237
  if (manifest2.background?.service_worker) {
2884
3238
  const file = manifest2.background.service_worker;
3239
+ const id2 = join(config.root, file);
2885
3240
  const refId2 = this.emitFile({
2886
3241
  type: "chunk",
2887
- id: file,
3242
+ id: id2,
2888
3243
  name: basename(file)
2889
3244
  });
2890
3245
  manifest2.background.service_worker = refId2;
2891
3246
  }
2892
3247
  for (const file of htmlFiles(manifest2)) {
3248
+ const id2 = join(config.root, file);
2893
3249
  this.emitFile({
2894
3250
  type: "chunk",
2895
- id: file,
3251
+ id: id2,
2896
3252
  name: basename(file)
2897
3253
  });
2898
3254
  }
@@ -2904,15 +3260,30 @@ const pluginManifest = (_manifest) => () => {
2904
3260
  const manifestName = this.getFileName(refId);
2905
3261
  const manifestJs = bundle[manifestName];
2906
3262
  let manifest2 = decodeManifest.call(this, manifestJs.code);
2907
- if (manifest2.background?.service_worker && !this.meta.watchMode) {
2908
- const ref = manifest2.background.service_worker;
2909
- const name = this.getFileName(ref);
2910
- manifest2.background.service_worker = name;
2911
- }
2912
- manifest2.content_scripts = manifest2.content_scripts?.map(({ js = [], ...rest }) => {
2913
- const refJS = js.map((ref) => this.getFileName(ref));
2914
- return { js: refJS, ...rest };
2915
- });
3263
+ if (config.command === "serve") {
3264
+ if (manifest2.content_scripts)
3265
+ for (const script of manifest2.content_scripts) {
3266
+ script.js = script.js?.map((id) => getFileName({ id, type: "loader" }));
3267
+ }
3268
+ } else {
3269
+ if (manifest2.background?.service_worker) {
3270
+ const ref = manifest2.background.service_worker;
3271
+ const name = this.getFileName(ref);
3272
+ manifest2.background.service_worker = name;
3273
+ }
3274
+ manifest2.content_scripts = manifest2.content_scripts?.map(({ js = [], ...rest }) => {
3275
+ return {
3276
+ js: js.map((id) => {
3277
+ const script = contentScripts.get(id);
3278
+ const fileName = script?.loaderName ?? script?.fileName;
3279
+ if (typeof fileName === "undefined")
3280
+ throw new Error(`Content script fileName is undefined: "${id}"`);
3281
+ return fileName;
3282
+ }),
3283
+ ...rest
3284
+ };
3285
+ });
3286
+ }
2916
3287
  for (const plugin of plugins) {
2917
3288
  try {
2918
3289
  const m = structuredClone(manifest2);
@@ -2936,7 +3307,7 @@ const pluginManifest = (_manifest) => () => {
2936
3307
  "rulesets",
2937
3308
  "webAccessibleResources"
2938
3309
  ];
2939
- const files = await manifestFiles(manifest2);
3310
+ const files = await manifestFiles(manifest2, { cwd: config.root });
2940
3311
  await Promise.all(assetTypes.map((k) => files[k]).flat().map(async (f) => {
2941
3312
  if (typeof bundle[f] === "undefined") {
2942
3313
  let filename = join(config.root, f);
@@ -2954,6 +3325,19 @@ Public dir: "${config.publicDir}"`);
2954
3325
  });
2955
3326
  }
2956
3327
  }));
3328
+ if (config.command === "serve" && files.html.length) {
3329
+ const refId2 = this.emitFile({
3330
+ type: "asset",
3331
+ name: "precontroller.js",
3332
+ source: precontrollerJs
3333
+ });
3334
+ const precontrollerJsName = this.getFileName(refId2);
3335
+ files.html.map((f) => this.emitFile({
3336
+ type: "asset",
3337
+ fileName: f,
3338
+ source: precontrollerHtml.replace("%SCRIPT%", `/${precontrollerJsName}`)
3339
+ }));
3340
+ }
2957
3341
  const manifestJson = bundle["manifest.json"];
2958
3342
  if (typeof manifestJson === "undefined") {
2959
3343
  this.emitFile({
@@ -2970,570 +3354,212 @@ Public dir: "${config.publicDir}"`);
2970
3354
  ];
2971
3355
  };
2972
3356
 
2973
- var contentHmrPort = "function isCrxHMRPayload(x) {\n return x.type === \"custom\" && x.event.startsWith(\"crx:\");\n}\nclass HMRPort {\n port;\n callbacks = /* @__PURE__ */ new Map();\n constructor() {\n setInterval(() => {\n try {\n this.port?.postMessage({ data: \"ping\" });\n } catch (error) {\n if (error instanceof Error && error.message.includes(\"Extension context invalidated.\")) {\n location.reload();\n } else\n throw error;\n }\n }, __CRX_HMR_TIMEOUT__);\n setInterval(this.initPort, 5 * 60 * 1e3);\n this.initPort();\n }\n initPort = () => {\n this.port?.disconnect();\n this.port = chrome.runtime.connect({ name: \"@crx/client\" });\n this.port.onDisconnect.addListener(this.handleDisconnect.bind(this));\n this.port.onMessage.addListener(this.handleMessage.bind(this));\n this.port.postMessage({ type: \"connected\" });\n };\n handleDisconnect = () => {\n if (this.callbacks.has(\"close\"))\n for (const cb of this.callbacks.get(\"close\")) {\n cb({ wasClean: true });\n }\n };\n handleMessage = (message) => {\n const forward = (data) => {\n if (this.callbacks.has(\"message\"))\n for (const cb of this.callbacks.get(\"message\")) {\n cb({ data });\n }\n };\n const payload = JSON.parse(message.data);\n if (isCrxHMRPayload(payload)) {\n if (payload.event === \"crx:runtime-reload\") {\n console.log(\"[crx] runtime reload\");\n setTimeout(() => location.reload(), 500);\n } else {\n forward(JSON.stringify(payload.data));\n }\n } else {\n forward(message.data);\n }\n };\n addEventListener = (event, callback) => {\n const cbs = this.callbacks.get(event) ?? /* @__PURE__ */ new Set();\n cbs.add(callback);\n this.callbacks.set(event, cbs);\n };\n send = (data) => {\n if (this.port)\n this.port.postMessage({ data });\n else\n throw new Error(\"HMRPort is not initialized\");\n };\n}\n\nexport { HMRPort };\n";
2974
-
2975
- var contentDevLoader = "(function () {\n 'use strict';\n\n (async () => {\n if (__PREAMBLE__)\n await import(\n /* @vite-ignore */\n chrome.runtime.getURL(__PREAMBLE__)\n );\n await import(\n /* @vite-ignore */\n chrome.runtime.getURL(__CLIENT__)\n );\n await import(\n /* @vite-ignore */\n chrome.runtime.getURL(__SCRIPT__)\n );\n })().catch(console.error);\n\n})();\n";
2976
-
2977
- var contentProLoader = "(function () {\n 'use strict';\n\n (async () => {\n await import(\n /* @vite-ignore */\n chrome.runtime.getURL(__SCRIPT__)\n );\n })().catch(console.error);\n\n})();\n";
2978
-
2979
- function getScriptId({
2980
- format,
2981
- id
3357
+ function compileFileResources(fileName, {
3358
+ chunks,
3359
+ files,
3360
+ config
3361
+ }, resources = {
3362
+ assets: /* @__PURE__ */ new Set(),
3363
+ css: /* @__PURE__ */ new Set(),
3364
+ imports: /* @__PURE__ */ new Set()
2982
3365
  }) {
2983
- return createHash$1("sha1").update(format).update(id).digest("base64").replace(/[^A-Za-z0-9]/g, "").slice(0, 8);
2984
- }
2985
- const debug = _debug("content-scripts");
2986
- const dynamicResourcesName = "<dynamic_resource>";
2987
- const pluginResources = ({ contentScripts = {} }) => {
2988
- const { hmrTimeout = 5e3, injectCss = true } = contentScripts;
2989
- const dynamicScriptsById = /* @__PURE__ */ new Map();
2990
- const dynamicScriptsByLoaderRefId = /* @__PURE__ */ new Map();
2991
- const dynamicScriptsByRefId = /* @__PURE__ */ new Map();
2992
- const dynamicScriptsByScriptId = /* @__PURE__ */ new Map();
2993
- function emitDynamicScript(data) {
2994
- if (data.format === "iife") {
2995
- throw new Error(`Dynamic script format IIFE is unimplemented (imported in file: ${data.importer})`.trim());
2996
- } else {
2997
- data.refId = this.emitFile({ type: "chunk", id: data.id });
2998
- dynamicScriptsByRefId.set(data.refId, data);
2999
- }
3000
- if (data.format === "loader") {
3001
- data.loaderRefId = this.emitFile({
3002
- type: "asset",
3003
- name: `content-script-loader.${parse(data.id).name}.js`,
3004
- source: JSON.stringify(data)
3005
- });
3006
- dynamicScriptsByLoaderRefId.set(data.loaderRefId, data);
3007
- }
3008
- }
3009
- async function resolveDynamicScript(_source, importer) {
3010
- if (importer && _source.includes("?script")) {
3011
- const url = new URL(_source, "stub://stub");
3012
- if (url.searchParams.has("scriptId")) {
3013
- const scriptId = url.searchParams.get("scriptId");
3014
- const { finalId } = dynamicScriptsByScriptId.get(scriptId);
3015
- return finalId;
3016
- } else if (url.searchParams.has("script")) {
3017
- const [source] = _source.split("?");
3018
- const resolved = await this.resolve(source, importer, {
3019
- skipSelf: true
3020
- });
3021
- if (!resolved)
3022
- throw new Error(`Could not resolve dynamic script: "${_source}" from "${importer}"`);
3023
- const { id } = resolved;
3024
- let format = "loader";
3025
- if (url.searchParams.has("module")) {
3026
- format = "module";
3027
- } else if (url.searchParams.has("iife")) {
3028
- format = "iife";
3029
- }
3030
- const scriptId = getScriptId({ format, id });
3031
- const finalId = `${id}?scriptId=${scriptId}`;
3032
- const data = dynamicScriptsByScriptId.get(scriptId) ?? {
3033
- format,
3034
- id,
3035
- importer,
3036
- scriptId,
3037
- finalId
3038
- };
3039
- dynamicScriptsByScriptId.set(scriptId, data);
3040
- dynamicScriptsById.set(finalId, data);
3041
- return finalId;
3366
+ const chunk = chunks.get(fileName);
3367
+ if (chunk) {
3368
+ const { modules, facadeModuleId, imports, dynamicImports } = chunk;
3369
+ for (const x of imports)
3370
+ resources.imports.add(x);
3371
+ for (const x of dynamicImports)
3372
+ resources.imports.add(x);
3373
+ for (const x of [...imports, ...dynamicImports])
3374
+ compileFileResources(x, { chunks, files, config }, resources);
3375
+ for (const m of Object.keys(modules))
3376
+ if (m !== facadeModuleId) {
3377
+ const key = prefix$1("/", relative(config.root, m.split("?")[0]));
3378
+ const script = contentScripts.get(key);
3379
+ if (script)
3380
+ if (typeof script.fileName === "undefined") {
3381
+ throw new Error(`Content script fileName for ${m} is undefined`);
3382
+ } else {
3383
+ resources.imports.add(script.fileName);
3384
+ compileFileResources(script.fileName, { chunks, files, config }, resources);
3385
+ }
3042
3386
  }
3043
- }
3044
3387
  }
3045
- function loadDynamicScript(id) {
3046
- const data = dynamicScriptsById.get(id);
3047
- if (data)
3048
- return `export default import.meta.CRX_DYNAMIC_SCRIPT_${data.scriptId};`;
3388
+ const file = files.get(fileName);
3389
+ if (file) {
3390
+ const { assets = [], css = [] } = file;
3391
+ for (const x of assets)
3392
+ resources.assets.add(x);
3393
+ for (const x of css)
3394
+ resources.css.add(x);
3049
3395
  }
3050
- let port;
3051
- let server;
3052
- let { preambleCode } = contentScripts;
3053
- let preambleRefId;
3054
- let contentClientRefId;
3396
+ return resources;
3397
+ }
3398
+
3399
+ const defineManifest = (manifest) => manifest;
3400
+ const defineDynamicResource = ({
3401
+ matches = ["http://*/*", "https://*/*"],
3402
+ use_dynamic_url = true
3403
+ }) => ({
3404
+ matches,
3405
+ resources: [DYNAMIC_RESOURCE],
3406
+ use_dynamic_url
3407
+ });
3408
+ const DYNAMIC_RESOURCE = "<dynamic_resource>";
3409
+
3410
+ _debug("web-acc-res");
3411
+ const pluginWebAccessibleResources = () => {
3412
+ let config;
3413
+ let injectCss;
3055
3414
  return [
3056
3415
  {
3057
- name: "crx:content-scripts-pre",
3058
- apply: "build",
3059
- enforce: "pre",
3060
- async fileWriterStart(_server) {
3061
- server = _server;
3062
- port = server.config.server.port.toString();
3063
- if (process.env.NODE_ENV !== "test" && typeof preambleCode === "undefined" && server.config.plugins.some(({ name }) => name.toLowerCase().includes("react"))) {
3064
- try {
3065
- const react = await import('@vitejs/plugin-react');
3066
- preambleCode = react.default.preambleCode;
3067
- } catch (error) {
3068
- preambleCode = false;
3069
- }
3070
- }
3071
- },
3072
- buildStart() {
3073
- if (this.meta.watchMode) {
3074
- if (preambleCode) {
3075
- preambleRefId = this.emitFile({
3076
- type: "chunk",
3077
- id: preambleId,
3078
- name: "content-script-preamble.js"
3079
- });
3080
- }
3081
- contentClientRefId = this.emitFile({
3082
- type: "chunk",
3083
- id: "/@vite/client",
3084
- name: "content-script-client.js"
3085
- });
3086
- }
3087
- },
3088
- resolveId(source) {
3089
- if (source === preambleId)
3090
- return preambleId;
3091
- if (source === contentHmrPortId)
3092
- return contentHmrPortId;
3093
- },
3094
- load(id) {
3095
- if (server && id === preambleId && typeof preambleCode === "string") {
3096
- const defined = preambleCode.replace(/__BASE__/g, server.config.base);
3097
- return defined;
3098
- }
3099
- if (id === contentHmrPortId) {
3100
- const defined = contentHmrPort.replace("__CRX_HMR_TIMEOUT__", JSON.stringify(hmrTimeout));
3101
- return defined;
3102
- }
3103
- }
3104
- },
3105
- {
3106
- name: "crx:dynamic-scripts-load",
3416
+ name: "crx:web-accessible-resources",
3107
3417
  apply: "serve",
3108
- enforce: "pre",
3109
- resolveId: resolveDynamicScript,
3110
- load: loadDynamicScript
3111
- },
3112
- {
3113
- name: "crx:dynamic-scripts-load",
3114
- apply: "build",
3115
- enforce: "pre",
3116
- resolveId(id, importer) {
3117
- if (!this.meta.watchMode)
3118
- return resolveDynamicScript.call(this, id, importer);
3119
- },
3120
- load(id) {
3121
- if (!this.meta.watchMode)
3122
- return loadDynamicScript.call(this, id);
3418
+ enforce: "post",
3419
+ renderCrxManifest(manifest) {
3420
+ manifest.web_accessible_resources = manifest.web_accessible_resources ?? [];
3421
+ manifest.web_accessible_resources = manifest.web_accessible_resources.map(({ resources, ...rest }) => ({
3422
+ resources: resources.filter((r) => r !== DYNAMIC_RESOURCE),
3423
+ ...rest
3424
+ })).filter(({ resources }) => resources.length);
3425
+ manifest.web_accessible_resources.push({
3426
+ use_dynamic_url: true,
3427
+ matches: ["<all_urls>"],
3428
+ resources: ["**/*", "*"]
3429
+ });
3430
+ return manifest;
3123
3431
  }
3124
3432
  },
3125
3433
  {
3126
- name: "crx:dynamic-scripts-build",
3434
+ name: "crx:web-accessible-resources",
3127
3435
  apply: "build",
3128
- buildStart() {
3129
- dynamicScriptsByLoaderRefId.clear();
3130
- dynamicScriptsByRefId.clear();
3131
- for (const [, data] of dynamicScriptsByScriptId) {
3132
- emitDynamicScript.call(this, data);
3133
- }
3134
- },
3135
- async transform(code) {
3136
- if (code.includes("import.meta.CRX_DYNAMIC_SCRIPT_")) {
3137
- const match = code.match(/import.meta.CRX_DYNAMIC_SCRIPT_(.+?);/);
3138
- const index = match.index;
3139
- const [statement, scriptId] = match;
3140
- const data = dynamicScriptsByScriptId.get(scriptId);
3141
- if (!data.refId)
3142
- emitDynamicScript.call(this, data);
3143
- const magic = new MagicString(code);
3144
- magic.overwrite(index, index + statement.length, `import.meta.ROLLUP_FILE_URL_${data.loaderRefId ?? data.refId};`);
3145
- return { code: magic.toString(), map: magic.generateMap() };
3146
- }
3147
- },
3148
- resolveFileUrl({ referenceId, fileName, moduleId }) {
3149
- if (moduleId && referenceId) {
3150
- if (dynamicScriptsByRefId.has(referenceId) || dynamicScriptsByLoaderRefId.has(referenceId)) {
3151
- return `"/${fileName}"`;
3152
- }
3153
- }
3436
+ enforce: "post",
3437
+ async config({ build, ...config2 }, { command }) {
3438
+ const { contentScripts: contentScripts2 = {} } = await getOptions(config2);
3439
+ injectCss = contentScripts2.injectCss ?? true;
3440
+ return { ...config2, build: { ...build, manifest: command === "build" } };
3154
3441
  },
3155
- generateBundle(options, bundle) {
3156
- const preambleName = this.meta.watchMode && preambleRefId ? this.getFileName(preambleRefId) : "";
3157
- const contentClientName = this.meta.watchMode && contentClientRefId ? this.getFileName(contentClientRefId) : "";
3158
- for (const data of dynamicScriptsByScriptId.values()) {
3159
- if (data.refId && data.loaderRefId) {
3160
- const scriptName = this.getFileName(data.refId);
3161
- const loaderName = this.getFileName(data.loaderRefId);
3162
- const source = this.meta.watchMode ? contentDevLoader.replace(/__PREAMBLE__/g, JSON.stringify(preambleName)).replace(/__CLIENT__/g, JSON.stringify(contentClientName)).replace(/__SCRIPT__/g, JSON.stringify(scriptName)) : contentProLoader.replace(/__SCRIPT__/g, JSON.stringify(scriptName));
3163
- const asset = bundle[loaderName];
3164
- if (asset?.type === "asset")
3165
- asset.source = source;
3166
- }
3167
- }
3442
+ configResolved(_config) {
3443
+ config = _config;
3168
3444
  },
3169
- writeBundle() {
3170
- for (const [, data] of dynamicScriptsByScriptId) {
3171
- if (data.refId) {
3172
- data.fileName = this.getFileName(data.refId);
3173
- delete data.refId;
3174
- }
3175
- if (data.loaderRefId) {
3176
- data.loaderName = this.getFileName(data.loaderRefId);
3177
- delete data.loaderRefId;
3178
- }
3179
- }
3180
- }
3181
- },
3182
- {
3183
- name: "crx:dynamic-scripts-serve",
3184
- apply: "serve",
3185
- configureServer(server2) {
3186
- server2.middlewares.use(injector((req) => {
3187
- return !!req.url?.includes("?scriptId");
3188
- }, async (content, req, res, callback) => {
3189
- const code = isString(content) ? content : content.toString();
3190
- if (code.includes("import.meta.CRX_DYNAMIC_SCRIPT_")) {
3191
- const matches = Array.from(code.matchAll(/import.meta.CRX_DYNAMIC_SCRIPT_(.+?);/g)).map((m) => ({
3192
- statement: m[0],
3193
- index: m.index,
3194
- data: dynamicScriptsByScriptId.get(m[1])
3195
- }));
3196
- if (matches.some(({ data }) => data.refId))
3197
- await filesReady();
3198
- if (matches.some(({ data }) => !(data.loaderName ?? data.fileName))) {
3199
- await rebuildFiles();
3200
- server2.ws.send(crxRuntimeReload);
3201
- }
3202
- const magic = new MagicString(code);
3203
- for (const { index, statement, data } of matches)
3204
- if (typeof index === "number") {
3205
- magic.overwrite(index, index + statement.length, `"/${data.loaderName ?? data.fileName}"`);
3206
- }
3207
- callback(null, magic.toString());
3208
- } else {
3209
- callback(null, code);
3445
+ async renderCrxManifest(manifest, bundle) {
3446
+ const { web_accessible_resources: _war = [] } = manifest;
3447
+ const dynamicScriptMatches = /* @__PURE__ */ new Set();
3448
+ let dynamicScriptDynamicUrl = false;
3449
+ const web_accessible_resources = [];
3450
+ for (const r of _war) {
3451
+ const i = r.resources.indexOf(DYNAMIC_RESOURCE);
3452
+ if (i > -1 && isResourceByMatch(r)) {
3453
+ r.resources = [...r.resources];
3454
+ r.resources.splice(i, 1);
3455
+ for (const p of r.matches)
3456
+ dynamicScriptMatches.add(p);
3457
+ dynamicScriptDynamicUrl = r.use_dynamic_url ?? false;
3210
3458
  }
3211
- }));
3212
- }
3213
- },
3214
- {
3215
- name: "crx:content-script-resources",
3216
- apply: "build",
3217
- enforce: "post",
3218
- config({ build, ...config }, { command }) {
3219
- return { ...config, build: { ...build, manifest: command === "build" } };
3220
- },
3221
- renderCrxManifest(manifest, bundle) {
3222
- manifest.web_accessible_resources = manifest.web_accessible_resources ?? [];
3223
- if (manifest.content_scripts?.length || dynamicScriptsByRefId.size)
3224
- if (this.meta.watchMode) {
3225
- manifest.web_accessible_resources = manifest.web_accessible_resources.map(({ resources, ...rest }) => ({
3226
- resources: resources.filter((r) => r !== dynamicResourcesName),
3227
- ...rest
3228
- })).filter(({ resources }) => resources.length);
3229
- manifest.web_accessible_resources.push({
3230
- use_dynamic_url: true,
3231
- matches: ["<all_urls>"],
3232
- resources: ["**/*", "*"]
3233
- });
3234
- } else {
3235
- const vmAsset = bundle["manifest.json"];
3236
- if (!vmAsset)
3237
- throw new Error("vite manifest is missing");
3238
- const viteManifest = JSON.parse(vmAsset.source);
3239
- debug("vite manifest %O", viteManifest);
3240
- if (Object.keys(viteManifest).length === 0)
3241
- return;
3242
- const filesByName = /* @__PURE__ */ new Map();
3243
- for (const file of Object.values(viteManifest))
3244
- filesByName.set(file.file, file);
3245
- const chunksById = /* @__PURE__ */ new Map();
3246
- for (const [name, chunk] of Object.entries(bundle))
3247
- if (chunk.type === "chunk" && chunk.facadeModuleId)
3248
- chunksById.set(chunk.facadeModuleId, name);
3249
- const getChunkResources = (chunk) => {
3250
- const chunks = /* @__PURE__ */ new Set();
3251
- const assets = /* @__PURE__ */ new Set();
3252
- if (chunk.type === "asset")
3253
- return { chunks, assets };
3254
- const { dynamicImports, imports, modules } = chunk;
3255
- for (const i of dynamicImports)
3256
- chunks.add(i);
3257
- for (const i of imports)
3258
- chunks.add(i);
3259
- for (const id of Object.keys(modules))
3260
- if (dynamicScriptsById.has(id)) {
3261
- const data = dynamicScriptsById.get(id);
3262
- const fileName = this.getFileName(data.refId);
3263
- const chunk2 = bundle[fileName];
3264
- if (chunk2.type === "chunk")
3265
- chunks.add(fileName);
3266
- else
3267
- assets.add(fileName);
3268
- }
3269
- return { chunks, assets };
3270
- };
3271
- const getResources = (name, sets = {
3272
- assets: /* @__PURE__ */ new Set(),
3273
- css: /* @__PURE__ */ new Set(),
3274
- imports: /* @__PURE__ */ new Set()
3275
- }) => {
3276
- const {
3277
- assets = [],
3278
- css = [],
3279
- dynamicImports = [],
3280
- imports = [],
3281
- file
3282
- } = filesByName.get(name) ?? viteManifest[name] ?? {};
3283
- const chunk = bundle[file];
3284
- if (chunk?.type === "chunk") {
3285
- const r = getChunkResources(chunk);
3286
- assets.push(...r.assets);
3287
- for (const chunk2 of r.chunks) {
3288
- sets.imports.add(chunk2);
3289
- getResources(chunk2, sets);
3290
- }
3291
- }
3292
- for (const a of assets)
3293
- sets.assets.add(a);
3294
- for (const c of css)
3295
- sets.css.add(c);
3296
- for (const key of [...dynamicImports, ...imports]) {
3297
- const i = viteManifest[key].file;
3298
- sets.imports.add(i);
3299
- getResources(key, sets);
3300
- }
3301
- return sets;
3302
- };
3303
- for (const script of manifest.content_scripts ?? [])
3304
- if (script.js?.length) {
3305
- for (const name of script.js)
3306
- if (script.matches?.length) {
3307
- const { assets, css, imports } = getResources(name);
3308
- imports.add(name);
3309
- const resource = {
3310
- matches: script.matches,
3311
- resources: [...assets, ...imports],
3312
- use_dynamic_url: true
3313
- };
3314
- if (css.size)
3315
- if (injectCss) {
3316
- script.css = script.css ?? [];
3317
- script.css.push(...css);
3318
- } else {
3319
- resource.resources.push(...css);
3320
- }
3321
- if (resource.resources.length) {
3322
- resource.matches = resource.matches.map(stubMatchPattern);
3323
- manifest.web_accessible_resources.push(resource);
3324
- }
3459
+ if (r.resources.length > 0)
3460
+ web_accessible_resources.push(r);
3461
+ }
3462
+ if (dynamicScriptMatches.size === 0) {
3463
+ dynamicScriptMatches.add("http://*/*");
3464
+ dynamicScriptMatches.add("https://*/*");
3465
+ }
3466
+ if (contentScripts.size > 0) {
3467
+ const viteManifest = parseJsonAsset(bundle, "manifest.json");
3468
+ const viteFiles = /* @__PURE__ */ new Map();
3469
+ for (const [, file] of Object.entries(viteManifest))
3470
+ viteFiles.set(file.file, file);
3471
+ if (viteFiles.size === 0)
3472
+ return null;
3473
+ const bundleChunks = /* @__PURE__ */ new Map();
3474
+ for (const chunk of Object.values(bundle))
3475
+ if (chunk.type === "chunk")
3476
+ bundleChunks.set(chunk.fileName, chunk);
3477
+ const moduleScriptResources = /* @__PURE__ */ new Map();
3478
+ for (const [
3479
+ key,
3480
+ { id, fileName, matches, type, isDynamicScript = false }
3481
+ ] of contentScripts)
3482
+ if (key === id) {
3483
+ if (isDynamicScript || matches.length)
3484
+ if (typeof fileName === "undefined") {
3485
+ throw new Error(`Content script filename is undefined for "${id}"`);
3486
+ } else {
3487
+ const { assets, css, imports } = compileFileResources(fileName, { chunks: bundleChunks, files: viteFiles, config });
3488
+ contentScripts.get(key).css = [...css];
3489
+ if (type === "loader")
3490
+ imports.add(fileName);
3491
+ const resource = {
3492
+ matches: isDynamicScript ? [...dynamicScriptMatches] : matches,
3493
+ resources: [...assets, ...imports],
3494
+ use_dynamic_url: isDynamicScript ? dynamicScriptDynamicUrl : true
3495
+ };
3496
+ if (isDynamicScript || !injectCss) {
3497
+ resource.resources.push(...css);
3325
3498
  }
3326
- }
3327
- const dynamicResourceSet = /* @__PURE__ */ new Set();
3328
- for (const [refId, { format }] of dynamicScriptsByRefId)
3329
- if (format === "loader") {
3330
- const name = this.getFileName(refId);
3331
- const { assets, css, imports } = getResources(name);
3332
- dynamicResourceSet.add(name);
3333
- for (const a of assets)
3334
- dynamicResourceSet.add(a);
3335
- for (const c of css)
3336
- dynamicResourceSet.add(c);
3337
- for (const i of imports)
3338
- dynamicResourceSet.add(i);
3339
- }
3340
- if (dynamicResourceSet.size) {
3341
- let resource = manifest.web_accessible_resources.find(({ resources: [r] }) => r === dynamicResourcesName);
3342
- if (!resource) {
3343
- resource = {
3344
- resources: [dynamicResourcesName],
3345
- matches: ["http://*/*", "https://*/*"]
3346
- };
3347
- manifest.web_accessible_resources.push(resource);
3348
- }
3349
- resource.resources = [...dynamicResourceSet];
3499
+ if (resource.resources.length)
3500
+ if (type === "module") {
3501
+ moduleScriptResources.set(fileName, resource);
3502
+ } else {
3503
+ resource.matches = resource.matches.map(getMatchPatternOrigin);
3504
+ web_accessible_resources.push(resource);
3505
+ }
3506
+ }
3350
3507
  }
3508
+ for (const r of web_accessible_resources)
3509
+ if (isResourceByMatch(r))
3510
+ for (const res of r.resources)
3511
+ moduleScriptResources.delete(res);
3512
+ web_accessible_resources.push(...moduleScriptResources.values());
3513
+ }
3514
+ const hashedResources = /* @__PURE__ */ new Map();
3515
+ const combinedResources = [];
3516
+ for (const r of web_accessible_resources)
3517
+ if (isResourceByMatch(r)) {
3518
+ const { matches, resources, use_dynamic_url = false } = r;
3519
+ const key = JSON.stringify([use_dynamic_url, matches.sort()]);
3520
+ const combined = hashedResources.get(key) ?? /* @__PURE__ */ new Set();
3521
+ for (const res of resources)
3522
+ combined.add(res);
3523
+ hashedResources.set(key, combined);
3524
+ } else {
3525
+ combinedResources.push(r);
3351
3526
  }
3352
- if (manifest.web_accessible_resources?.length) {
3353
- const war = manifest.web_accessible_resources;
3354
- manifest.web_accessible_resources = [];
3355
- const map = /* @__PURE__ */ new Map();
3356
- for (const r of war)
3357
- if (isResourceByMatch(r)) {
3358
- const { matches, resources, use_dynamic_url = false } = r;
3359
- const key = [use_dynamic_url, matches.sort()].map((x) => JSON.stringify(x)).join("::");
3360
- const set = map.get(key) ?? /* @__PURE__ */ new Set();
3361
- resources.forEach((r2) => set.add(r2));
3362
- map.set(key, set);
3363
- } else {
3364
- manifest.web_accessible_resources.push(r);
3365
- }
3366
- for (const [key, set] of map) {
3367
- const [use_dynamic_url, matches] = key.split("::").map((x) => JSON.parse(x));
3368
- manifest.web_accessible_resources.push({
3527
+ for (const [key, resources] of hashedResources)
3528
+ if (resources.size > 0) {
3529
+ const [use_dynamic_url, matches] = JSON.parse(key);
3530
+ combinedResources.push({
3369
3531
  matches,
3370
- resources: [...set],
3532
+ resources: [...resources],
3371
3533
  use_dynamic_url
3372
3534
  });
3373
3535
  }
3374
- } else {
3536
+ if (combinedResources.length === 0)
3375
3537
  delete manifest.web_accessible_resources;
3376
- }
3377
- return manifest;
3378
- }
3379
- },
3380
- {
3381
- name: "crx:content-scripts-post",
3382
- apply: "build",
3383
- enforce: "post",
3384
- renderCrxManifest(manifest, bundle) {
3385
- if (this.meta.watchMode && typeof port === "undefined")
3386
- throw new Error("server port is undefined");
3387
- const preambleName = this.meta.watchMode && preambleRefId ? this.getFileName(preambleRefId) : "";
3388
- const contentClientName = this.meta.watchMode && contentClientRefId ? this.getFileName(contentClientRefId) : "";
3389
- if (!manifest.content_scripts?.length && !dynamicScriptsByRefId.size) {
3390
- delete bundle[contentClientName];
3391
- return manifest;
3392
- }
3393
- manifest.content_scripts = manifest.content_scripts?.map(({ js, ...rest }) => ({
3394
- js: js?.map((f) => {
3395
- const name = `content-script-loader.${parse(f).name}.js`;
3396
- const source = this.meta.watchMode ? contentDevLoader.replace(/__PREAMBLE__/g, JSON.stringify(preambleName)).replace(/__CLIENT__/g, JSON.stringify(contentClientName)).replace(/__SCRIPT__/g, JSON.stringify(f)).replace(/__TIMESTAMP__/g, JSON.stringify(Date.now())) : contentProLoader.replace(/__SCRIPT__/g, JSON.stringify(f));
3397
- const refId = this.emitFile({
3398
- type: "asset",
3399
- name,
3400
- source
3401
- });
3402
- return this.getFileName(refId);
3403
- }),
3404
- ...rest
3405
- }));
3538
+ else
3539
+ manifest.web_accessible_resources = combinedResources;
3406
3540
  return manifest;
3407
3541
  }
3408
3542
  }
3409
3543
  ];
3410
3544
  };
3411
3545
 
3412
- var workerHmrClient = "const ownOrigin = new URL(chrome.runtime.getURL(\"/\")).origin;\nself.addEventListener(\"fetch\", (fetchEvent) => {\n const url = new URL(fetchEvent.request.url);\n if (url.origin === ownOrigin) {\n fetchEvent.respondWith(sendToServer(url));\n }\n});\nasync function sendToServer(url) {\n url.protocol = \"http:\";\n url.host = \"localhost\";\n url.port = __SERVER_PORT__;\n url.searchParams.set(\"t\", Date.now().toString());\n const response = await fetch(url.href.replace(/=$|=(?=&)/g, \"\"));\n return new Response(response.body, {\n headers: {\n \"Content-Type\": response.headers.get(\"Content-Type\") ?? \"text/javascript\"\n }\n });\n}\nconst ports = /* @__PURE__ */ new Set();\nchrome.runtime.onConnect.addListener((port) => {\n if (port.name === \"@crx/client\") {\n ports.add(port);\n port.onDisconnect.addListener((port2) => ports.delete(port2));\n port.onMessage.addListener((message) => {\n });\n port.postMessage({ data: JSON.stringify({ type: \"connected\" }) });\n }\n});\nfunction notifyContentScripts(payload) {\n const data = JSON.stringify(payload);\n for (const port of ports)\n port.postMessage({ data });\n}\nconsole.log(\"[vite] connecting...\");\nconst socketProtocol = __HMR_PROTOCOL__ || (location.protocol === \"https:\" ? \"wss\" : \"ws\");\nconst socketHost = `${__HMR_HOSTNAME__ || location.hostname}:${__HMR_PORT__}`;\nconst socket = new WebSocket(`${socketProtocol}://${socketHost}`, \"vite-hmr\");\nconst base = __BASE__ || \"/\";\nsocket.addEventListener(\"message\", async ({ data }) => {\n handleSocketMessage(JSON.parse(data));\n});\nfunction isCrxHmrPayload(x) {\n return x.type === \"custom\" && x.event.startsWith(\"crx:\");\n}\nfunction handleSocketMessage(payload) {\n if (isCrxHmrPayload(payload)) {\n handleCrxHmrPayload(payload);\n } else if (payload.type === \"connected\") {\n console.log(`[vite] connected.`);\n const interval = setInterval(() => socket.send(\"ping\"), __HMR_TIMEOUT__);\n socket.addEventListener(\"close\", () => clearInterval(interval));\n }\n}\nfunction handleCrxHmrPayload(payload) {\n notifyContentScripts(payload);\n switch (payload.event) {\n case \"crx:runtime-reload\":\n console.log(\"[crx] runtime reload\");\n chrome.runtime.reload();\n break;\n }\n}\nasync function waitForSuccessfulPing(ms = 1e3) {\n while (true) {\n try {\n await fetch(`${base}__vite_ping`);\n break;\n } catch (e) {\n await new Promise((resolve) => setTimeout(resolve, ms));\n }\n }\n}\nsocket.addEventListener(\"close\", async ({ wasClean }) => {\n if (wasClean)\n return;\n console.log(`[vite] server connection lost. polling for restart...`);\n await waitForSuccessfulPing();\n chrome.runtime.reload();\n});\n";
3413
-
3414
- function defineClientValues(code, config) {
3415
- let options = config.server.hmr;
3416
- options = options && typeof options !== "boolean" ? options : {};
3417
- const host = options.host || null;
3418
- const protocol = options.protocol || null;
3419
- const timeout = options.timeout || 3e4;
3420
- const overlay = options.overlay !== false;
3421
- let hmrPort;
3422
- if (isObject(config.server.hmr)) {
3423
- hmrPort = config.server.hmr.clientPort || config.server.hmr.port;
3424
- }
3425
- if (config.server.middlewareMode) {
3426
- hmrPort = String(hmrPort || 24678);
3427
- } else {
3428
- hmrPort = String(hmrPort || options.port || config.server.port);
3429
- }
3430
- let hmrBase = config.base;
3431
- if (options.path) {
3432
- hmrBase = join(hmrBase, options.path);
3433
- }
3434
- if (hmrBase !== "/") {
3435
- hmrPort = normalize(`${hmrPort}${hmrBase}`);
3436
- }
3437
- return code.replace(`__MODE__`, JSON.stringify(config.mode)).replace(`__BASE__`, JSON.stringify(config.base)).replace(`__DEFINES__`, serializeDefine(config.define || {})).replace(`__HMR_PROTOCOL__`, JSON.stringify(protocol)).replace(`__HMR_HOSTNAME__`, JSON.stringify(host)).replace(`__HMR_PORT__`, JSON.stringify(hmrPort)).replace(`__HMR_TIMEOUT__`, JSON.stringify(timeout)).replace(`__HMR_ENABLE_OVERLAY__`, JSON.stringify(overlay)).replace(`__SERVER_PORT__`, JSON.stringify(config.server.port?.toString()));
3438
- function serializeDefine(define) {
3439
- let res = `{`;
3440
- for (const key in define) {
3441
- const val = define[key];
3442
- res += `${JSON.stringify(key)}: ${typeof val === "string" ? `(${val})` : JSON.stringify(val)}, `;
3443
- }
3444
- return res + `}`;
3445
- }
3446
- }
3447
-
3448
- const pluginBackground = () => {
3449
- let port;
3450
- let server;
3546
+ const crx = (options) => {
3451
3547
  return [
3452
- {
3453
- name: "crx:background-client",
3454
- apply: "serve",
3455
- configureServer(_server) {
3456
- server = _server;
3457
- },
3458
- resolveId(source) {
3459
- if (source === `/${workerClientId}`)
3460
- return workerClientId;
3461
- },
3462
- load(id) {
3463
- if (id === workerClientId) {
3464
- const base = `http://localhost:${server.config.server.port}/`;
3465
- return defineClientValues(workerHmrClient.replace("__BASE__", JSON.stringify(base)), server.config);
3466
- }
3467
- }
3468
- },
3469
- {
3470
- name: "crx:background-loader-file",
3471
- apply: "build",
3472
- enforce: "post",
3473
- fileWriterStart(server2) {
3474
- port = server2.config.server.port.toString();
3475
- },
3476
- renderCrxManifest(manifest) {
3477
- const worker = manifest.background?.service_worker;
3478
- let loader;
3479
- if (this.meta.watchMode) {
3480
- if (typeof port === "undefined")
3481
- throw new Error("server port is undefined in watch mode");
3482
- loader = `import 'http:/localhost:${port}/@vite/env';
3483
- `;
3484
- loader += `import 'http://localhost:${port}${workerClientId}';
3485
- `;
3486
- if (worker)
3487
- loader += `import 'http://localhost:${port}/${worker}';
3488
- `;
3489
- } else if (worker) {
3490
- loader = `import './${worker}';
3491
- `;
3492
- } else {
3493
- return null;
3494
- }
3495
- const refId = this.emitFile({
3496
- type: "asset",
3497
- fileName: "service-worker-loader.js",
3498
- source: loader
3499
- });
3500
- manifest.background = {
3501
- service_worker: this.getFileName(refId),
3502
- type: "module"
3503
- };
3504
- return manifest;
3505
- }
3506
- }
3507
- ];
3508
- };
3509
-
3510
- const defineManifest = (manifest) => manifest;
3511
- const defineDynamicResource = ({
3512
- matches = ["http://*/*", "https://*/*"],
3513
- use_dynamic_url = true
3514
- }) => ({
3515
- matches,
3516
- resources: [dynamicResourcesName],
3517
- use_dynamic_url
3518
- });
3519
-
3520
- function init(options, plugins) {
3521
- return plugins.map((p) => p?.(options)).flat().filter((p) => !!p && typeof p.name === "string");
3522
- }
3523
- const crx = ({
3524
- manifest,
3525
- ...options
3526
- }) => {
3527
- const plugins = init(options, [
3528
- pluginHMR,
3529
- pluginHtmlAuditor,
3530
- pluginResources,
3531
- pluginBackground,
3532
- pluginManifest(manifest)
3533
- ]);
3534
- plugins.unshift(...init(options, [pluginFileWriter(plugins)]));
3535
- return plugins;
3548
+ pluginOptionsProvider(options),
3549
+ pluginBackground(),
3550
+ pluginContentScripts(),
3551
+ pluginDeclaredContentScripts(),
3552
+ pluginDynamicContentScripts(),
3553
+ pluginFileWriter(),
3554
+ pluginFileWriterPublic(),
3555
+ pluginFileWriterPolyfill(),
3556
+ pluginHtmlInlineScripts(),
3557
+ pluginWebAccessibleResources(),
3558
+ pluginContentScriptsCss(),
3559
+ pluginHMR(),
3560
+ pluginManifest()
3561
+ ].flat();
3536
3562
  };
3537
3563
  const chromeExtension = crx;
3538
3564
 
3539
- export { chromeExtension, crx, defineDynamicResource, defineManifest, filesReady, rebuildFiles };
3565
+ export { allFilesReady, chromeExtension, crx, defineDynamicResource, defineManifest, fileReady as filesReady };