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