@crxjs/vite-plugin 1.0.14 → 2.0.0-beta.10

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.
package/dist/index.mjs CHANGED
@@ -1,78 +1,73 @@
1
- import { watch } from 'rollup';
2
1
  import { simple } from 'acorn-walk';
3
- import { createHash as createHash$1 } from 'crypto';
4
- import debug$5 from 'debug';
5
- import fg from 'fast-glob';
2
+ import { createHash } from 'crypto';
3
+ import debug$2 from 'debug';
6
4
  import v8 from 'v8';
7
- import { promises, readFileSync, existsSync } from 'fs';
8
- import MagicString from 'magic-string';
9
5
  import { posix } from 'path';
10
- import fsExtra from 'fs-extra';
6
+ import { Subject, filter, ReplaySubject, switchMap, of, startWith, map, mergeMap, firstValueFrom, takeUntil, first, toArray, retry, concatWith, Subscription, buffer } from 'rxjs';
7
+ import fsx from 'fs-extra';
11
8
  import { performance } from 'perf_hooks';
12
- import colors from 'picocolors';
9
+ import { rollup } from 'rollup';
10
+ import * as lexer from 'es-module-lexer';
11
+ import { readFile as readFile$1 } from 'fs/promises';
12
+ import MagicString from 'magic-string';
13
13
  import { createLogger } from 'vite';
14
+ import { readFileSync, existsSync, promises } from 'fs';
14
15
  import { createRequire } from 'module';
16
+ import fg from 'fast-glob';
15
17
  import { load } from 'cheerio';
16
18
  import jsesc from 'jsesc';
17
- import injector from 'connect-injector';
19
+ import colors from 'picocolors';
20
+
21
+ const pluginName$1 = "crx:optionsProvider";
22
+ const pluginOptionsProvider = (options) => {
23
+ return {
24
+ name: pluginName$1,
25
+ api: {
26
+ crx: {
27
+ options
28
+ }
29
+ }
30
+ };
31
+ };
32
+ const getOptions = async ({
33
+ plugins
34
+ }) => {
35
+ if (typeof plugins === "undefined") {
36
+ throw new Error("config.plugins is undefined");
37
+ }
38
+ const awaitedPlugins = await Promise.all(plugins);
39
+ let options;
40
+ for (const p of awaitedPlugins.flat()) {
41
+ if (isCrxPlugin(p)) {
42
+ if (p.name === pluginName$1) {
43
+ const plugin = p;
44
+ options = plugin.api.crx.options;
45
+ if (options)
46
+ break;
47
+ }
48
+ }
49
+ }
50
+ if (typeof options === "undefined") {
51
+ throw Error("Unable to get CRXJS options");
52
+ }
53
+ return options;
54
+ };
55
+ function isCrxPlugin(p) {
56
+ return !!p && typeof p === "object" && !(p instanceof Promise) && !Array.isArray(p) && p.name.startsWith("crx:");
57
+ }
18
58
 
19
- const _debug = (id) => debug$5("crx").extend(id);
59
+ 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";
60
+
61
+ const _debug = (id) => debug$2("crx").extend(id);
20
62
  const structuredClone = (obj) => {
21
63
  return v8.deserialize(v8.serialize(obj));
22
64
  };
23
- const createHash = (data, length = 5) => createHash$1("sha1").update(data).digest("base64").replace(/[^A-Za-z0-9]/g, "").slice(0, length);
65
+ const hash = (data, length = 5) => createHash("sha1").update(data).digest("base64").replace(/[^A-Za-z0-9]/g, "").slice(0, length);
24
66
  const isString = (x) => typeof x === "string";
25
- const isTruthy = (x) => !!x;
26
67
  function isObject(value) {
27
68
  return Object.prototype.toString.call(value) === "[object Object]";
28
69
  }
29
70
  const isResourceByMatch = (x) => "matches" in x;
30
- async function manifestFiles(manifest, options = {}) {
31
- let locales = [];
32
- if (manifest.default_locale)
33
- locales = await fg("_locales/**/messages.json", options);
34
- const rulesets = manifest.declarative_net_request?.rule_resources.flatMap(({ path }) => path) ?? [];
35
- const contentScripts = manifest.content_scripts?.flatMap(({ js }) => js) ?? [];
36
- const contentStyles = manifest.content_scripts?.flatMap(({ css }) => css);
37
- const serviceWorker = manifest.background?.service_worker;
38
- const htmlPages = htmlFiles(manifest);
39
- const icons = [
40
- Object.values(isString(manifest.icons) ? [manifest.icons] : manifest.icons ?? {}),
41
- Object.values(isString(manifest.action?.default_icon) ? [manifest.action?.default_icon] : manifest.action?.default_icon ?? {})
42
- ].flat();
43
- let webAccessibleResources = [];
44
- if (manifest.web_accessible_resources) {
45
- const resources = await Promise.all(manifest.web_accessible_resources.flatMap(({ resources: resources2 }) => resources2).map(async (r) => {
46
- if (["*", "**/*"].includes(r))
47
- return void 0;
48
- if (fg.isDynamicPattern(r))
49
- return fg(r, options);
50
- return r;
51
- }));
52
- webAccessibleResources = resources.flat().filter(isString);
53
- }
54
- return {
55
- contentScripts: [...new Set(contentScripts)].filter(isString),
56
- contentStyles: [...new Set(contentStyles)].filter(isString),
57
- html: htmlPages,
58
- icons: [...new Set(icons)].filter(isString),
59
- locales: [...new Set(locales)].filter(isString),
60
- rulesets: [...new Set(rulesets)].filter(isString),
61
- background: [serviceWorker].filter(isString),
62
- webAccessibleResources
63
- };
64
- }
65
- function htmlFiles(manifest) {
66
- const files = [
67
- manifest.action?.default_popup,
68
- Object.values(manifest.chrome_url_overrides ?? {}),
69
- manifest.devtools_page,
70
- manifest.options_page,
71
- manifest.options_ui?.page,
72
- manifest.sandbox?.pages
73
- ].flat().filter(isString).map((s) => s.split("#")[0]).sort();
74
- return [...new Set(files)];
75
- }
76
71
  function decodeManifest(code) {
77
72
  const tree = this.parse(code);
78
73
  let literal;
@@ -99,70 +94,25 @@ function encodeManifest(manifest) {
99
94
  const json = JSON.stringify(JSON.stringify(manifest));
100
95
  return `export default ${json}`;
101
96
  }
102
- const stubMatchPattern = (pattern) => {
103
- if (pattern === "<all_urls>") {
97
+ function parseJsonAsset(bundle, key) {
98
+ const asset = bundle[key];
99
+ if (typeof asset === "undefined")
100
+ throw new TypeError(`OutputBundle["${key}"] is undefined.`);
101
+ if (asset.type !== "asset")
102
+ throw new Error(`OutputBundle["${key}"] is not an OutputAsset.`);
103
+ if (typeof asset.source !== "string")
104
+ throw new TypeError(`OutputBundle["${key}"].source is not a string.`);
105
+ return JSON.parse(asset.source);
106
+ }
107
+ const getMatchPatternOrigin = (pattern) => {
108
+ if (pattern.startsWith("<"))
104
109
  return pattern;
105
- }
106
110
  const [schema, rest] = pattern.split("://");
107
111
  const [origin, pathname] = rest.split("/");
108
112
  const root = `${schema}://${origin}`;
109
113
  return pathname ? `${root}/*` : root;
110
114
  };
111
115
 
112
- const idBySource = /* @__PURE__ */ new Map();
113
- const idByUrl = /* @__PURE__ */ new Map();
114
- const urlById = /* @__PURE__ */ new Map();
115
- function setUrlMeta({
116
- id,
117
- source,
118
- url
119
- }) {
120
- idBySource.set(source, id);
121
- idByUrl.set(url, id);
122
- urlById.set(id, url);
123
- }
124
- const fileById = /* @__PURE__ */ new Map();
125
- const fileByUrl = /* @__PURE__ */ new Map();
126
- const pathById = /* @__PURE__ */ new Map();
127
- const pathByUrl = /* @__PURE__ */ new Map();
128
- const setFileMeta = ({ file, id }) => {
129
- const url = urlById.get(id);
130
- if (!url)
131
- return;
132
- fileById.set(id, file);
133
- fileByUrl.set(url, file);
134
- const pathName = `/${file}`;
135
- pathById.set(id, pathName);
136
- pathByUrl.set(url, pathName);
137
- };
138
- const ownerById = /* @__PURE__ */ new Map();
139
- const pathByOwner = /* @__PURE__ */ new Map();
140
- const ownersByFile = /* @__PURE__ */ new Map();
141
- const setOwnerMeta = ({ owner, id }) => {
142
- const pathName = pathById.get(id);
143
- if (!pathName)
144
- return;
145
- pathByOwner.set(owner, pathName);
146
- ownerById.set(id, owner);
147
- const fileName = fileById.get(id);
148
- const owners = ownersByFile.get(fileName) ?? /* @__PURE__ */ new Set();
149
- owners.add(owner);
150
- ownersByFile.set(fileName, owners);
151
- };
152
- const outputById = /* @__PURE__ */ new Map();
153
- const outputByOwner = /* @__PURE__ */ new Map();
154
- const setOutputMeta = ({
155
- output,
156
- id
157
- }) => {
158
- const ownerName = ownerById.get(id);
159
- if (!ownerName)
160
- return;
161
- outputByOwner.set(ownerName, output);
162
- outputById.set(id, output);
163
- };
164
- const transformResultByOwner = /* @__PURE__ */ new Map();
165
-
166
116
  const {
167
117
  basename,
168
118
  dirname,
@@ -179,2095 +129,559 @@ const {
179
129
  sep
180
130
  } = posix;
181
131
 
182
- const viteClientId = "/@vite/client";
183
- const customElementsId = "@webcomponents/custom-elements";
184
- const reactRefreshId = "/@react-refresh";
185
- const contentHmrPortId = "/crx-client-port";
186
- const manifestId = "/crx-manifest";
187
- const preambleId = "/crx-client-preamble";
188
- const stubId = "/crx-stub";
189
- const workerClientId = "/crx-client-worker";
190
-
191
- const { readFile: readFile$2 } = promises;
192
- const debug$4 = _debug("file-writer").extend("chunks");
193
- for (const source of [viteClientId, customElementsId]) {
194
- setUrlMeta(sourceToUrlMeta(source));
195
- }
196
- setUrlMeta({
197
- source: reactRefreshId,
198
- id: "/react-refresh",
199
- url: reactRefreshId
200
- });
201
- function sourceToUrlMeta(source) {
202
- const [p, query = ""] = source.split("?");
203
- const pathname = p.replace(/^\/@id\//, "").replace(/^\/@fs/, "");
204
- const url = [pathname, query].filter(isTruthy).join("?");
205
- const hash = createHash(url);
206
- const base = p.split("/").slice(-4).filter(isTruthy).join("-");
207
- const id = `/${base}-${hash}.js`.replace(/[@]/g, "");
208
- return { id, url, source };
209
- }
210
- const pluginFileWriterChunks = () => {
211
- let server;
212
- return {
213
- name: "crx:file-writer-chunks",
214
- apply: "build",
215
- fileWriterStart(_server) {
216
- server = _server;
217
- },
218
- async resolveId(source, importer) {
219
- if (this.meta.watchMode) {
220
- if (idBySource.has(source)) {
221
- const id = idBySource.get(source);
222
- debug$4(`resolved cached ${source} -> ${id}`);
223
- return id;
224
- } else if (importer) {
225
- const meta = sourceToUrlMeta(source);
226
- setUrlMeta(meta);
227
- const { id } = meta;
228
- debug$4(`resolved ${source} -> ${id}`);
229
- return id;
230
- } else {
231
- const [rawUrl] = await server.moduleGraph.resolveUrl(source);
232
- const name = rawUrl.split("/").join("-").replace(/^-/, "");
233
- const url = rawUrl.startsWith("/") ? rawUrl : `/${rawUrl}`;
234
- const id = `/${name}-${createHash(url)}.js`;
235
- setUrlMeta({ url, id, source });
236
- debug$4(`resolved entry ${source} -> ${id}`);
237
- return id;
238
- }
239
- }
240
- },
241
- async load(id) {
242
- if (this.meta.watchMode && urlById.has(id)) {
243
- const url = urlById.get(id);
244
- let serverModule = await server.moduleGraph.getModuleByUrl(url);
245
- let transformResult = null;
246
- if (!serverModule) {
247
- transformResult = await server.transformRequest(url);
248
- serverModule = await server.moduleGraph.getModuleByUrl(url);
249
- }
250
- if (!serverModule)
251
- throw new Error(`Unable to load "${url}" from server.`);
252
- const { file, url: owner } = serverModule;
253
- transformResult = transformResult ?? transformResultByOwner.get(owner) ?? serverModule.transformResult;
254
- if (!transformResult)
255
- transformResult = await server.transformRequest(url);
256
- if (!transformResult)
257
- throw new TypeError(`Unable to load "${url}" from server.`);
258
- transformResultByOwner.set(owner, transformResult);
259
- if (file) {
260
- setFileMeta({ id, file });
261
- this.addWatchFile(file);
262
- if (urlById.get(id).includes("?import"))
263
- this.emitFile({
264
- type: "asset",
265
- fileName: relative(server.config.root, file),
266
- source: await readFile$2(file)
267
- });
268
- }
269
- if (url)
270
- setOwnerMeta({ id, owner });
271
- return { code: transformResult.code, map: transformResult.map };
272
- }
273
- return null;
274
- },
275
- outputOptions(options) {
276
- const cacheDir = relative(server.config.root, server.config.cacheDir);
277
- const fileNameById = /* @__PURE__ */ new Map();
278
- fileNameById.set("/react-refresh", "vendor/react-refresh.js");
279
- function fileNames(info) {
280
- const id = info.type === "chunk" ? info.facadeModuleId : info.name;
281
- if (id && fileNameById.has(id))
282
- return fileNameById.get(id);
283
- let fileName = info.type === "chunk" ? "assets/[name].js" : "assets/[name].[ext]";
284
- if (id && fileById.has(id)) {
285
- fileName = fileById.get(id);
286
- const url = new URL(urlById.get(id), "stub://stub");
287
- if (url.searchParams.has("type"))
288
- fileName += `.${url.searchParams.get("type")}`;
289
- if (url.searchParams.has("index"))
290
- fileName += `.${url.searchParams.get("index")}`;
291
- }
292
- if (id?.startsWith("/@crx/"))
293
- fileName = `vendor/${id.slice("/@crx/".length).split("/").join("-")}`;
294
- if (fileName.startsWith(server.config.root))
295
- fileName = fileName.slice(server.config.root.length + 1);
296
- if (fileName.startsWith(cacheDir))
297
- fileName = `vendor/${fileName.slice(cacheDir.length + 1)}`;
298
- if (fileName.includes("/node_modules/"))
299
- fileName = `vendor/${fileName.split("/node_modules/").pop().split("/").join("-").replace("vite-dist-client", "vite")}`;
300
- if (fileName.startsWith("/"))
301
- fileName = fileName.slice(1);
302
- if (!fileName.endsWith(".js"))
303
- fileName += ".js";
304
- if (id)
305
- fileNameById.set(id, fileName);
306
- fileName = fileName.replace(/:/g, "-").replace(/@/, "");
307
- return fileName;
308
- }
309
- return {
310
- ...options,
311
- preserveModules: true,
312
- assetFileNames: fileNames,
313
- entryFileNames: fileNames
314
- };
315
- },
316
- generateBundle(options, bundle) {
317
- for (const chunk of Object.values(bundle))
318
- if (chunk.type === "chunk") {
319
- const { facadeModuleId: id, modules, code, fileName } = chunk;
320
- if (!id || Object.keys(modules).length !== 1)
321
- continue;
322
- const url = urlById.get(id);
323
- if (url === viteClientId)
324
- continue;
325
- const ownerPath = ownerById.get(id);
326
- if (!ownerPath)
327
- continue;
328
- const index = code.indexOf("createHotContext(");
329
- if (index === -1)
330
- continue;
331
- const start = code.indexOf(ownerPath, index);
332
- const end = start + ownerPath.length;
333
- if (start > 0) {
334
- const outputName = `/${fileName}`;
335
- setOutputMeta({ id, output: outputName });
336
- const magic = new MagicString(code);
337
- magic.overwrite(start, end, outputName);
338
- chunk.code = magic.toString();
339
- }
340
- }
132
+ function defineClientValues(code, config) {
133
+ let options = config.server.hmr;
134
+ options = options && typeof options !== "boolean" ? options : {};
135
+ const host = options.host || null;
136
+ const protocol = options.protocol || null;
137
+ const timeout = options.timeout || 3e4;
138
+ const overlay = options.overlay !== false;
139
+ let hmrPort;
140
+ if (isObject(config.server.hmr)) {
141
+ hmrPort = config.server.hmr.clientPort || config.server.hmr.port;
142
+ }
143
+ if (config.server.middlewareMode) {
144
+ hmrPort = String(hmrPort || 24678);
145
+ } else {
146
+ hmrPort = String(hmrPort || options.port || config.server.port);
147
+ }
148
+ let hmrBase = config.base;
149
+ if (options.path) {
150
+ hmrBase = join(hmrBase, options.path);
151
+ }
152
+ if (hmrBase !== "/") {
153
+ hmrPort = normalize(`${hmrPort}${hmrBase}`);
154
+ }
155
+ 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()));
156
+ function serializeDefine(define) {
157
+ let res = `{`;
158
+ for (const key in define) {
159
+ const val = define[key];
160
+ res += `${JSON.stringify(key)}: ${typeof val === "string" ? `(${val})` : JSON.stringify(val)}, `;
341
161
  }
342
- };
343
- };
344
-
345
- /******************************************************************************
346
- Copyright (c) Microsoft Corporation.
347
-
348
- Permission to use, copy, modify, and/or distribute this software for any
349
- purpose with or without fee is hereby granted.
350
-
351
- THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
352
- REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
353
- AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
354
- INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
355
- LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
356
- OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
357
- PERFORMANCE OF THIS SOFTWARE.
358
- ***************************************************************************** */
359
- /* global Reflect, Promise */
360
-
361
- var extendStatics = function(d, b) {
362
- extendStatics = Object.setPrototypeOf ||
363
- ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
364
- function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
365
- return extendStatics(d, b);
366
- };
367
-
368
- function __extends(d, b) {
369
- if (typeof b !== "function" && b !== null)
370
- throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
371
- extendStatics(d, b);
372
- function __() { this.constructor = d; }
373
- d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
374
- }
375
-
376
- function __awaiter(thisArg, _arguments, P, generator) {
377
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
378
- return new (P || (P = Promise))(function (resolve, reject) {
379
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
380
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
381
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
382
- step((generator = generator.apply(thisArg, _arguments || [])).next());
383
- });
384
- }
385
-
386
- function __generator(thisArg, body) {
387
- var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
388
- return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
389
- function verb(n) { return function (v) { return step([n, v]); }; }
390
- function step(op) {
391
- if (f) throw new TypeError("Generator is already executing.");
392
- while (_) try {
393
- if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
394
- if (y = 0, t) op = [op[0] & 2, t.value];
395
- switch (op[0]) {
396
- case 0: case 1: t = op; break;
397
- case 4: _.label++; return { value: op[1], done: false };
398
- case 5: _.label++; y = op[1]; op = [0]; continue;
399
- case 7: op = _.ops.pop(); _.trys.pop(); continue;
400
- default:
401
- if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
402
- if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
403
- if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
404
- if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
405
- if (t[2]) _.ops.pop();
406
- _.trys.pop(); continue;
407
- }
408
- op = body.call(thisArg, _);
409
- } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
410
- if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
411
- }
412
- }
413
-
414
- function __values(o) {
415
- var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0;
416
- if (m) return m.call(o);
417
- if (o && typeof o.length === "number") return {
418
- next: function () {
419
- if (o && i >= o.length) o = void 0;
420
- return { value: o && o[i++], done: !o };
421
- }
422
- };
423
- throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined.");
424
- }
425
-
426
- function __read(o, n) {
427
- var m = typeof Symbol === "function" && o[Symbol.iterator];
428
- if (!m) return o;
429
- var i = m.call(o), r, ar = [], e;
430
- try {
431
- while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
432
- }
433
- catch (error) { e = { error: error }; }
434
- finally {
435
- try {
436
- if (r && !r.done && (m = i["return"])) m.call(i);
437
- }
438
- finally { if (e) throw e.error; }
439
- }
440
- return ar;
441
- }
442
-
443
- function __spreadArray(to, from, pack) {
444
- if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
445
- if (ar || !(i in from)) {
446
- if (!ar) ar = Array.prototype.slice.call(from, 0, i);
447
- ar[i] = from[i];
448
- }
449
- }
450
- return to.concat(ar || Array.prototype.slice.call(from));
451
- }
452
-
453
- function __await(v) {
454
- return this instanceof __await ? (this.v = v, this) : new __await(v);
455
- }
456
-
457
- function __asyncGenerator(thisArg, _arguments, generator) {
458
- if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
459
- var g = generator.apply(thisArg, _arguments || []), i, q = [];
460
- return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i;
461
- function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; }
462
- function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } }
463
- function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); }
464
- function fulfill(value) { resume("next", value); }
465
- function reject(value) { resume("throw", value); }
466
- function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); }
467
- }
468
-
469
- function __asyncValues(o) {
470
- if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
471
- var m = o[Symbol.asyncIterator], i;
472
- return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i);
473
- function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; }
474
- function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); }
475
- }
476
-
477
- function isFunction(value) {
478
- return typeof value === 'function';
162
+ return res + `}`;
163
+ }
479
164
  }
480
165
 
481
- function createErrorClass(createImpl) {
482
- var _super = function (instance) {
483
- Error.call(instance);
484
- instance.stack = new Error().stack;
485
- };
486
- var ctorFunc = createImpl(_super);
487
- ctorFunc.prototype = Object.create(Error.prototype);
488
- ctorFunc.prototype.constructor = ctorFunc;
489
- return ctorFunc;
166
+ class RxMap extends Map {
167
+ static isChangeType = {
168
+ clear: (x) => x.type === "clear",
169
+ delete: (x) => x.type === "delete",
170
+ set: (x) => x.type === "set"
171
+ };
172
+ change$;
173
+ constructor(iterable) {
174
+ super(iterable);
175
+ const change$ = new Subject();
176
+ this.change$ = change$.asObservable();
177
+ const changeMethodKeys = ["clear", "set", "delete"];
178
+ for (const type of changeMethodKeys) {
179
+ const method = this[type];
180
+ this[type] = function(...args) {
181
+ const result = method.call(this, ...args);
182
+ change$.next({ type, key: args[0], value: args[1], map: this });
183
+ return result;
184
+ }.bind(this);
185
+ }
186
+ }
490
187
  }
491
188
 
492
- var UnsubscriptionError = createErrorClass(function (_super) {
493
- return function UnsubscriptionErrorImpl(errors) {
494
- _super(this);
495
- this.message = errors
496
- ? errors.length + " errors occurred during unsubscription:\n" + errors.map(function (err, i) { return i + 1 + ") " + err.toString(); }).join('\n ')
497
- : '';
498
- this.name = 'UnsubscriptionError';
499
- this.errors = errors;
500
- };
501
- });
189
+ const outputFiles = new RxMap();
502
190
 
503
- function arrRemove(arr, item) {
504
- if (arr) {
505
- var index = arr.indexOf(item);
506
- 0 <= index && arr.splice(index, 1);
507
- }
191
+ _debug("file-writer").extend("utilities");
192
+ function prefix$1(prefix2, text) {
193
+ return text.startsWith(prefix2) ? text : prefix2 + text;
508
194
  }
509
-
510
- var Subscription = (function () {
511
- function Subscription(initialTeardown) {
512
- this.initialTeardown = initialTeardown;
513
- this.closed = false;
514
- this._parentage = null;
515
- this._finalizers = null;
516
- }
517
- Subscription.prototype.unsubscribe = function () {
518
- var e_1, _a, e_2, _b;
519
- var errors;
520
- if (!this.closed) {
521
- this.closed = true;
522
- var _parentage = this._parentage;
523
- if (_parentage) {
524
- this._parentage = null;
525
- if (Array.isArray(_parentage)) {
526
- try {
527
- for (var _parentage_1 = __values(_parentage), _parentage_1_1 = _parentage_1.next(); !_parentage_1_1.done; _parentage_1_1 = _parentage_1.next()) {
528
- var parent_1 = _parentage_1_1.value;
529
- parent_1.remove(this);
530
- }
531
- }
532
- catch (e_1_1) { e_1 = { error: e_1_1 }; }
533
- finally {
534
- try {
535
- if (_parentage_1_1 && !_parentage_1_1.done && (_a = _parentage_1.return)) _a.call(_parentage_1);
536
- }
537
- finally { if (e_1) throw e_1.error; }
538
- }
539
- }
540
- else {
541
- _parentage.remove(this);
542
- }
543
- }
544
- var initialFinalizer = this.initialTeardown;
545
- if (isFunction(initialFinalizer)) {
546
- try {
547
- initialFinalizer();
548
- }
549
- catch (e) {
550
- errors = e instanceof UnsubscriptionError ? e.errors : [e];
551
- }
552
- }
553
- var _finalizers = this._finalizers;
554
- if (_finalizers) {
555
- this._finalizers = null;
556
- try {
557
- for (var _finalizers_1 = __values(_finalizers), _finalizers_1_1 = _finalizers_1.next(); !_finalizers_1_1.done; _finalizers_1_1 = _finalizers_1.next()) {
558
- var finalizer = _finalizers_1_1.value;
559
- try {
560
- execFinalizer(finalizer);
561
- }
562
- catch (err) {
563
- errors = errors !== null && errors !== void 0 ? errors : [];
564
- if (err instanceof UnsubscriptionError) {
565
- errors = __spreadArray(__spreadArray([], __read(errors)), __read(err.errors));
566
- }
567
- else {
568
- errors.push(err);
569
- }
570
- }
571
- }
572
- }
573
- catch (e_2_1) { e_2 = { error: e_2_1 }; }
574
- finally {
575
- try {
576
- if (_finalizers_1_1 && !_finalizers_1_1.done && (_b = _finalizers_1.return)) _b.call(_finalizers_1);
577
- }
578
- finally { if (e_2) throw e_2.error; }
579
- }
580
- }
581
- if (errors) {
582
- throw new UnsubscriptionError(errors);
583
- }
584
- }
585
- };
586
- Subscription.prototype.add = function (teardown) {
587
- var _a;
588
- if (teardown && teardown !== this) {
589
- if (this.closed) {
590
- execFinalizer(teardown);
591
- }
592
- else {
593
- if (teardown instanceof Subscription) {
594
- if (teardown.closed || teardown._hasParent(this)) {
595
- return;
596
- }
597
- teardown._addParent(this);
598
- }
599
- (this._finalizers = (_a = this._finalizers) !== null && _a !== void 0 ? _a : []).push(teardown);
600
- }
601
- }
602
- };
603
- Subscription.prototype._hasParent = function (parent) {
604
- var _parentage = this._parentage;
605
- return _parentage === parent || (Array.isArray(_parentage) && _parentage.includes(parent));
606
- };
607
- Subscription.prototype._addParent = function (parent) {
608
- var _parentage = this._parentage;
609
- this._parentage = Array.isArray(_parentage) ? (_parentage.push(parent), _parentage) : _parentage ? [_parentage, parent] : parent;
610
- };
611
- Subscription.prototype._removeParent = function (parent) {
612
- var _parentage = this._parentage;
613
- if (_parentage === parent) {
614
- this._parentage = null;
615
- }
616
- else if (Array.isArray(_parentage)) {
617
- arrRemove(_parentage, parent);
618
- }
619
- };
620
- Subscription.prototype.remove = function (teardown) {
621
- var _finalizers = this._finalizers;
622
- _finalizers && arrRemove(_finalizers, teardown);
623
- if (teardown instanceof Subscription) {
624
- teardown._removeParent(this);
625
- }
626
- };
627
- Subscription.EMPTY = (function () {
628
- var empty = new Subscription();
629
- empty.closed = true;
630
- return empty;
631
- })();
632
- return Subscription;
633
- }());
634
- var EMPTY_SUBSCRIPTION = Subscription.EMPTY;
635
- function isSubscription(value) {
636
- return (value instanceof Subscription ||
637
- (value && 'closed' in value && isFunction(value.remove) && isFunction(value.add) && isFunction(value.unsubscribe)));
195
+ function strip(prefix2, text) {
196
+ return text?.startsWith(prefix2) ? text?.slice(prefix2.length) : text;
638
197
  }
639
- function execFinalizer(finalizer) {
640
- if (isFunction(finalizer)) {
641
- finalizer();
642
- }
643
- else {
644
- finalizer.unsubscribe();
645
- }
198
+ function formatFileData(script) {
199
+ script.id = prefix$1("/", script.id);
200
+ if (script.fileName)
201
+ script.fileName = strip("/", script.fileName);
202
+ if (script.loaderName)
203
+ script.loaderName = strip("/", script.loaderName);
204
+ return script;
205
+ }
206
+ function getFileName({ type, id }) {
207
+ let fileName = id.replace(/t=\d+&/, "").replace(/^\//, "").replace(/\?/g, "__").replace(/&/g, "_").replace(/=/g, "--");
208
+ if (fileName.includes("node_modules/")) {
209
+ fileName = `vendor/${fileName.split("node_modules/").pop().replace(/\//g, "-")}`;
210
+ } else if (fileName.startsWith("@")) {
211
+ fileName = `vendor/${fileName.slice("@".length).replace(/\//g, "-")}`;
212
+ } else if (fileName.startsWith(".vite/deps/")) {
213
+ fileName = `vendor/${fileName.slice(".vite/deps/".length)}`;
214
+ }
215
+ switch (type) {
216
+ case "iife":
217
+ return `${fileName}.iife.js`;
218
+ case "loader":
219
+ return `${fileName}-loader.js`;
220
+ case "module":
221
+ return `${fileName}.js`;
222
+ case "asset":
223
+ return fileName;
224
+ default:
225
+ throw new Error(
226
+ `Unexpected script type "${type}" for "${JSON.stringify({
227
+ type,
228
+ id
229
+ })}"`
230
+ );
231
+ }
232
+ }
233
+ function getOutputPath(server, fileName) {
234
+ const {
235
+ root,
236
+ build: { outDir }
237
+ } = server.config;
238
+ const target = isAbsolute(outDir) ? join(outDir, fileName) : join(root, outDir, fileName);
239
+ return target;
240
+ }
241
+ function getViteUrl({ type, id }) {
242
+ if (type === "asset") {
243
+ throw new Error(`File type "${type}" not implemented.`);
244
+ } else if (type === "iife") {
245
+ throw new Error(`File type "${type}" not implemented.`);
246
+ } else if (type === "loader") {
247
+ throw new Error("Vite does not transform loader files.");
248
+ } else if (type === "module") {
249
+ if (id.startsWith("/@id/"))
250
+ return id.slice("/@id/".length).replace("__x00__", "\0");
251
+ return prefix$1("/", id);
252
+ } else {
253
+ throw new Error(`Invalid file type: "${type}"`);
254
+ }
255
+ }
256
+ async function fileReady(script) {
257
+ const fileName = getFileName(script);
258
+ const file = outputFiles.get(fileName);
259
+ if (!file)
260
+ throw new Error("unknown script type and id");
261
+ const { deps } = await file.file;
262
+ await Promise.all(deps.map(fileReady));
646
263
  }
647
264
 
648
- var config = {
649
- onUnhandledError: null,
650
- onStoppedNotification: null,
651
- Promise: undefined,
652
- useDeprecatedSynchronousErrorHandling: false,
653
- useDeprecatedNextContext: false,
654
- };
265
+ const viteClientId = "/@vite/client";
266
+ const customElementsId = "/@webcomponents/custom-elements";
267
+ const contentHmrPortId = "/@crx/client-port";
268
+ const manifestId = "/@crx/manifest";
269
+ const preambleId = "/@crx/client-preamble";
270
+ const stubId = "/@crx/stub";
271
+ const workerClientId = "/@crx/client-worker";
655
272
 
656
- var timeoutProvider = {
657
- setTimeout: function (handler, timeout) {
658
- var args = [];
659
- for (var _i = 2; _i < arguments.length; _i++) {
660
- args[_i - 2] = arguments[_i];
661
- }
662
- var delegate = timeoutProvider.delegate;
663
- if (delegate === null || delegate === void 0 ? void 0 : delegate.setTimeout) {
664
- return delegate.setTimeout.apply(delegate, __spreadArray([handler, timeout], __read(args)));
273
+ const pluginBackground = () => {
274
+ let config;
275
+ return [
276
+ {
277
+ name: "crx:background-client",
278
+ apply: "serve",
279
+ resolveId(source) {
280
+ if (source === `/${workerClientId}`)
281
+ return workerClientId;
282
+ },
283
+ load(id) {
284
+ if (id === workerClientId) {
285
+ const base = `http://localhost:${config.server.port}/`;
286
+ return defineClientValues(
287
+ workerHmrClient.replace("__BASE__", JSON.stringify(base)),
288
+ config
289
+ );
665
290
  }
666
- return setTimeout.apply(void 0, __spreadArray([handler, timeout], __read(args)));
667
- },
668
- clearTimeout: function (handle) {
669
- var delegate = timeoutProvider.delegate;
670
- return ((delegate === null || delegate === void 0 ? void 0 : delegate.clearTimeout) || clearTimeout)(handle);
291
+ }
671
292
  },
672
- delegate: undefined,
293
+ {
294
+ name: "crx:background-loader-file",
295
+ enforce: "post",
296
+ configResolved(_config) {
297
+ config = _config;
298
+ },
299
+ renderCrxManifest(manifest) {
300
+ const worker = manifest.background?.service_worker;
301
+ let loader;
302
+ if (config.command === "serve") {
303
+ const port = config.server.port?.toString();
304
+ if (typeof port === "undefined")
305
+ throw new Error("server port is undefined in watch mode");
306
+ loader = `import 'http://localhost:${port}/@vite/env';
307
+ `;
308
+ loader += `import 'http://localhost:${port}${workerClientId}';
309
+ `;
310
+ if (worker)
311
+ loader += `import 'http://localhost:${port}/${worker}';
312
+ `;
313
+ } else if (worker) {
314
+ loader = `import './${worker}';
315
+ `;
316
+ } else {
317
+ return null;
318
+ }
319
+ const refId = this.emitFile({
320
+ type: "asset",
321
+ fileName: getFileName({ type: "loader", id: "service-worker" }),
322
+ source: loader
323
+ });
324
+ manifest.background = {
325
+ service_worker: this.getFileName(refId),
326
+ type: "module"
327
+ };
328
+ return manifest;
329
+ }
330
+ }
331
+ ];
673
332
  };
674
333
 
675
- function reportUnhandledError(err) {
676
- timeoutProvider.setTimeout(function () {
677
- {
678
- throw err;
679
- }
680
- });
681
- }
334
+ 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";
335
+
336
+ 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";
682
337
 
683
- function noop() { }
338
+ 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";
684
339
 
685
- var COMPLETE_NOTIFICATION = (function () { return createNotification('C', undefined, undefined); })();
686
- function errorNotification(error) {
687
- return createNotification('E', undefined, error);
340
+ const contentScripts = new RxMap();
341
+ contentScripts.change$.pipe(filter(RxMap.isChangeType.set)).subscribe(({ map, value }) => {
342
+ const keyNames = [
343
+ "refId",
344
+ "id",
345
+ "fileName",
346
+ "loaderName",
347
+ "resolvedId",
348
+ "scriptId"
349
+ ];
350
+ for (const keyName of keyNames) {
351
+ const key = value[keyName];
352
+ if (typeof key === "undefined" || map.has(key)) {
353
+ continue;
354
+ } else {
355
+ map.set(key, value);
356
+ }
357
+ }
358
+ });
359
+ function hashScriptId(script) {
360
+ return hash(`${script.type}&${script.id}`);
361
+ }
362
+ function createDevLoader({
363
+ preamble,
364
+ client,
365
+ fileName
366
+ }) {
367
+ 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()));
368
+ }
369
+ function createProLoader({ fileName }) {
370
+ return contentProLoader.replace(/__SCRIPT__/g, JSON.stringify(fileName));
371
+ }
372
+
373
+ const serverEvent$ = new ReplaySubject(1);
374
+ const close$ = serverEvent$.pipe(
375
+ filter((e) => e.type === "close"),
376
+ switchMap((e) => of(e))
377
+ );
378
+ const start$ = serverEvent$.pipe(
379
+ filter((e) => e.type === "start"),
380
+ switchMap((e) => of(e))
381
+ );
382
+ const fileWriterEvent$ = new ReplaySubject(1);
383
+ const buildEnd$ = fileWriterEvent$.pipe(
384
+ filter((e) => e.type === "build_end"),
385
+ switchMap((e) => of(e))
386
+ );
387
+ fileWriterEvent$.pipe(
388
+ filter((e) => e.type === "build_start"),
389
+ switchMap((e) => of(e))
390
+ );
391
+ const allFilesReady$ = buildEnd$.pipe(
392
+ switchMap(() => outputFiles.change$.pipe(startWith({ type: "start" }))),
393
+ map(() => [...outputFiles.values()]),
394
+ switchMap((files) => Promise.allSettled(files.map(({ file }) => file)))
395
+ );
396
+ const isRejected = (x) => x?.status === "rejected";
397
+ const fileWriterError$ = allFilesReady$.pipe(
398
+ mergeMap((results) => results.filter(isRejected)),
399
+ map((rejected) => ({ err: rejected.reason, type: "error" }))
400
+ );
401
+ firstValueFrom(
402
+ fileWriterError$.pipe(
403
+ takeUntil(serverEvent$.pipe(first(({ type }) => type === "close"))),
404
+ toArray()
405
+ )
406
+ );
407
+ function prepFileData(fileId) {
408
+ const fileName = getFileName(fileId);
409
+ if (fileId.type === "asset") {
410
+ return prepAsset(fileName, fileId);
411
+ } else {
412
+ return prepScript(fileName, fileId);
413
+ }
688
414
  }
689
- function nextNotification(value) {
690
- return createNotification('N', value, undefined);
415
+ function prepAsset(fileName, { id, source }) {
416
+ return ($) => $.pipe(
417
+ mergeMap(async ({ server }) => {
418
+ const target = getOutputPath(server, fileName);
419
+ return {
420
+ target,
421
+ source: source ?? await readFile$1(join(server.config.root, id)),
422
+ deps: []
423
+ };
424
+ })
425
+ );
426
+ }
427
+ function prepScript(fileName, script) {
428
+ return ($) => $.pipe(
429
+ mergeMap(async ({ server }) => {
430
+ const target = getOutputPath(server, fileName);
431
+ const viteUrl = getViteUrl(script);
432
+ const transformResult = await server.transformRequest(viteUrl);
433
+ if (!transformResult)
434
+ throw new TypeError(`Unable to load "${script.id}" from server.`);
435
+ const { code, deps = [], dynamicDeps = [] } = transformResult;
436
+ return { target, code, deps: [...deps, ...dynamicDeps].flat(), server };
437
+ }),
438
+ retry({ count: 10, delay: 100 }),
439
+ mergeMap(async ({ target, server, ...rest }) => {
440
+ const plugins = server.config.plugins;
441
+ let { code, deps } = rest;
442
+ for (const plugin of plugins) {
443
+ const r = await plugin.renderCrxDevScript?.(code, script);
444
+ if (typeof r === "string")
445
+ code = r;
446
+ }
447
+ return { target, code, deps };
448
+ }),
449
+ mergeMap(async ({ target, code, deps }) => {
450
+ await lexer.init;
451
+ const [imports] = lexer.parse(code, fileName);
452
+ const depSet = new Set(deps);
453
+ const magic = new MagicString(code);
454
+ for (const i of imports)
455
+ if (i.n) {
456
+ depSet.add(i.n);
457
+ const fileName2 = getFileName({ type: "module", id: i.n });
458
+ magic.overwrite(i.s, i.e, `/${fileName2}`);
459
+ }
460
+ return { target, source: magic.toString(), deps: [...depSet] };
461
+ })
462
+ );
691
463
  }
692
- function createNotification(kind, value, error) {
693
- return {
694
- kind: kind,
695
- value: value,
696
- error: error,
697
- };
464
+ async function allFilesReady() {
465
+ await firstValueFrom(allFilesReady$);
698
466
  }
699
467
 
700
- var context = null;
701
- function errorContext(cb) {
702
- if (config.useDeprecatedSynchronousErrorHandling) {
703
- var isRoot = !context;
704
- if (isRoot) {
705
- context = { errorThrown: false, error: null };
706
- }
707
- cb();
708
- if (isRoot) {
709
- var _a = context, errorThrown = _a.errorThrown, error = _a.error;
710
- context = null;
711
- if (errorThrown) {
712
- throw error;
713
- }
714
- }
715
- }
716
- else {
717
- cb();
718
- }
719
- }
720
-
721
- var Subscriber = (function (_super) {
722
- __extends(Subscriber, _super);
723
- function Subscriber(destination) {
724
- var _this = _super.call(this) || this;
725
- _this.isStopped = false;
726
- if (destination) {
727
- _this.destination = destination;
728
- if (isSubscription(destination)) {
729
- destination.add(_this);
730
- }
731
- }
732
- else {
733
- _this.destination = EMPTY_OBSERVER;
734
- }
735
- return _this;
736
- }
737
- Subscriber.create = function (next, error, complete) {
738
- return new SafeSubscriber(next, error, complete);
739
- };
740
- Subscriber.prototype.next = function (value) {
741
- if (this.isStopped) {
742
- handleStoppedNotification(nextNotification(value), this);
743
- }
744
- else {
745
- this._next(value);
746
- }
747
- };
748
- Subscriber.prototype.error = function (err) {
749
- if (this.isStopped) {
750
- handleStoppedNotification(errorNotification(err), this);
751
- }
752
- else {
753
- this.isStopped = true;
754
- this._error(err);
755
- }
756
- };
757
- Subscriber.prototype.complete = function () {
758
- if (this.isStopped) {
759
- handleStoppedNotification(COMPLETE_NOTIFICATION, this);
760
- }
761
- else {
762
- this.isStopped = true;
763
- this._complete();
764
- }
765
- };
766
- Subscriber.prototype.unsubscribe = function () {
767
- if (!this.closed) {
768
- this.isStopped = true;
769
- _super.prototype.unsubscribe.call(this);
770
- this.destination = null;
771
- }
772
- };
773
- Subscriber.prototype._next = function (value) {
774
- this.destination.next(value);
775
- };
776
- Subscriber.prototype._error = function (err) {
777
- try {
778
- this.destination.error(err);
779
- }
780
- finally {
781
- this.unsubscribe();
782
- }
783
- };
784
- Subscriber.prototype._complete = function () {
785
- try {
786
- this.destination.complete();
787
- }
788
- finally {
789
- this.unsubscribe();
790
- }
791
- };
792
- return Subscriber;
793
- }(Subscription));
794
- var _bind = Function.prototype.bind;
795
- function bind(fn, thisArg) {
796
- return _bind.call(fn, thisArg);
797
- }
798
- var ConsumerObserver = (function () {
799
- function ConsumerObserver(partialObserver) {
800
- this.partialObserver = partialObserver;
801
- }
802
- ConsumerObserver.prototype.next = function (value) {
803
- var partialObserver = this.partialObserver;
804
- if (partialObserver.next) {
805
- try {
806
- partialObserver.next(value);
807
- }
808
- catch (error) {
809
- handleUnhandledError(error);
810
- }
811
- }
812
- };
813
- ConsumerObserver.prototype.error = function (err) {
814
- var partialObserver = this.partialObserver;
815
- if (partialObserver.error) {
816
- try {
817
- partialObserver.error(err);
818
- }
819
- catch (error) {
820
- handleUnhandledError(error);
821
- }
822
- }
823
- else {
824
- handleUnhandledError(err);
825
- }
826
- };
827
- ConsumerObserver.prototype.complete = function () {
828
- var partialObserver = this.partialObserver;
829
- if (partialObserver.complete) {
830
- try {
831
- partialObserver.complete();
832
- }
833
- catch (error) {
834
- handleUnhandledError(error);
835
- }
836
- }
837
- };
838
- return ConsumerObserver;
839
- }());
840
- var SafeSubscriber = (function (_super) {
841
- __extends(SafeSubscriber, _super);
842
- function SafeSubscriber(observerOrNext, error, complete) {
843
- var _this = _super.call(this) || this;
844
- var partialObserver;
845
- if (isFunction(observerOrNext) || !observerOrNext) {
846
- partialObserver = {
847
- next: observerOrNext !== null && observerOrNext !== void 0 ? observerOrNext : undefined,
848
- error: error !== null && error !== void 0 ? error : undefined,
849
- complete: complete !== null && complete !== void 0 ? complete : undefined,
850
- };
851
- }
852
- else {
853
- var context_1;
854
- if (_this && config.useDeprecatedNextContext) {
855
- context_1 = Object.create(observerOrNext);
856
- context_1.unsubscribe = function () { return _this.unsubscribe(); };
857
- partialObserver = {
858
- next: observerOrNext.next && bind(observerOrNext.next, context_1),
859
- error: observerOrNext.error && bind(observerOrNext.error, context_1),
860
- complete: observerOrNext.complete && bind(observerOrNext.complete, context_1),
861
- };
862
- }
863
- else {
864
- partialObserver = observerOrNext;
865
- }
866
- }
867
- _this.destination = new ConsumerObserver(partialObserver);
868
- return _this;
869
- }
870
- return SafeSubscriber;
871
- }(Subscriber));
872
- function handleUnhandledError(error) {
873
- {
874
- reportUnhandledError(error);
875
- }
876
- }
877
- function defaultErrorHandler(err) {
878
- throw err;
879
- }
880
- function handleStoppedNotification(notification, subscriber) {
881
- var onStoppedNotification = config.onStoppedNotification;
882
- onStoppedNotification && timeoutProvider.setTimeout(function () { return onStoppedNotification(notification, subscriber); });
883
- }
884
- var EMPTY_OBSERVER = {
885
- closed: true,
886
- next: noop,
887
- error: defaultErrorHandler,
888
- complete: noop,
889
- };
890
-
891
- var observable = (function () { return (typeof Symbol === 'function' && Symbol.observable) || '@@observable'; })();
892
-
893
- function identity(x) {
894
- return x;
895
- }
896
-
897
- function pipeFromArray(fns) {
898
- if (fns.length === 0) {
899
- return identity;
900
- }
901
- if (fns.length === 1) {
902
- return fns[0];
903
- }
904
- return function piped(input) {
905
- return fns.reduce(function (prev, fn) { return fn(prev); }, input);
906
- };
907
- }
908
-
909
- var Observable = (function () {
910
- function Observable(subscribe) {
911
- if (subscribe) {
912
- this._subscribe = subscribe;
913
- }
914
- }
915
- Observable.prototype.lift = function (operator) {
916
- var observable = new Observable();
917
- observable.source = this;
918
- observable.operator = operator;
919
- return observable;
920
- };
921
- Observable.prototype.subscribe = function (observerOrNext, error, complete) {
922
- var _this = this;
923
- var subscriber = isSubscriber(observerOrNext) ? observerOrNext : new SafeSubscriber(observerOrNext, error, complete);
924
- errorContext(function () {
925
- var _a = _this, operator = _a.operator, source = _a.source;
926
- subscriber.add(operator
927
- ?
928
- operator.call(subscriber, source)
929
- : source
930
- ?
931
- _this._subscribe(subscriber)
932
- :
933
- _this._trySubscribe(subscriber));
934
- });
935
- return subscriber;
936
- };
937
- Observable.prototype._trySubscribe = function (sink) {
938
- try {
939
- return this._subscribe(sink);
940
- }
941
- catch (err) {
942
- sink.error(err);
943
- }
944
- };
945
- Observable.prototype.forEach = function (next, promiseCtor) {
946
- var _this = this;
947
- promiseCtor = getPromiseCtor(promiseCtor);
948
- return new promiseCtor(function (resolve, reject) {
949
- var subscriber = new SafeSubscriber({
950
- next: function (value) {
951
- try {
952
- next(value);
953
- }
954
- catch (err) {
955
- reject(err);
956
- subscriber.unsubscribe();
957
- }
958
- },
959
- error: reject,
960
- complete: resolve,
961
- });
962
- _this.subscribe(subscriber);
963
- });
964
- };
965
- Observable.prototype._subscribe = function (subscriber) {
966
- var _a;
967
- return (_a = this.source) === null || _a === void 0 ? void 0 : _a.subscribe(subscriber);
968
- };
969
- Observable.prototype[observable] = function () {
970
- return this;
971
- };
972
- Observable.prototype.pipe = function () {
973
- var operations = [];
974
- for (var _i = 0; _i < arguments.length; _i++) {
975
- operations[_i] = arguments[_i];
976
- }
977
- return pipeFromArray(operations)(this);
978
- };
979
- Observable.prototype.toPromise = function (promiseCtor) {
980
- var _this = this;
981
- promiseCtor = getPromiseCtor(promiseCtor);
982
- return new promiseCtor(function (resolve, reject) {
983
- var value;
984
- _this.subscribe(function (x) { return (value = x); }, function (err) { return reject(err); }, function () { return resolve(value); });
985
- });
986
- };
987
- Observable.create = function (subscribe) {
988
- return new Observable(subscribe);
989
- };
990
- return Observable;
991
- }());
992
- function getPromiseCtor(promiseCtor) {
993
- var _a;
994
- return (_a = promiseCtor !== null && promiseCtor !== void 0 ? promiseCtor : config.Promise) !== null && _a !== void 0 ? _a : Promise;
995
- }
996
- function isObserver(value) {
997
- return value && isFunction(value.next) && isFunction(value.error) && isFunction(value.complete);
998
- }
999
- function isSubscriber(value) {
1000
- return (value && value instanceof Subscriber) || (isObserver(value) && isSubscription(value));
1001
- }
1002
-
1003
- function hasLift(source) {
1004
- return isFunction(source === null || source === void 0 ? void 0 : source.lift);
1005
- }
1006
- function operate(init) {
1007
- return function (source) {
1008
- if (hasLift(source)) {
1009
- return source.lift(function (liftedSource) {
1010
- try {
1011
- return init(liftedSource, this);
1012
- }
1013
- catch (err) {
1014
- this.error(err);
1015
- }
1016
- });
1017
- }
1018
- throw new TypeError('Unable to lift unknown Observable type');
1019
- };
1020
- }
1021
-
1022
- function createOperatorSubscriber(destination, onNext, onComplete, onError, onFinalize) {
1023
- return new OperatorSubscriber(destination, onNext, onComplete, onError, onFinalize);
1024
- }
1025
- var OperatorSubscriber = (function (_super) {
1026
- __extends(OperatorSubscriber, _super);
1027
- function OperatorSubscriber(destination, onNext, onComplete, onError, onFinalize, shouldUnsubscribe) {
1028
- var _this = _super.call(this, destination) || this;
1029
- _this.onFinalize = onFinalize;
1030
- _this.shouldUnsubscribe = shouldUnsubscribe;
1031
- _this._next = onNext
1032
- ? function (value) {
1033
- try {
1034
- onNext(value);
1035
- }
1036
- catch (err) {
1037
- destination.error(err);
1038
- }
1039
- }
1040
- : _super.prototype._next;
1041
- _this._error = onError
1042
- ? function (err) {
1043
- try {
1044
- onError(err);
1045
- }
1046
- catch (err) {
1047
- destination.error(err);
1048
- }
1049
- finally {
1050
- this.unsubscribe();
1051
- }
1052
- }
1053
- : _super.prototype._error;
1054
- _this._complete = onComplete
1055
- ? function () {
1056
- try {
1057
- onComplete();
1058
- }
1059
- catch (err) {
1060
- destination.error(err);
1061
- }
1062
- finally {
1063
- this.unsubscribe();
1064
- }
1065
- }
1066
- : _super.prototype._complete;
1067
- return _this;
1068
- }
1069
- OperatorSubscriber.prototype.unsubscribe = function () {
1070
- var _a;
1071
- if (!this.shouldUnsubscribe || this.shouldUnsubscribe()) {
1072
- var closed_1 = this.closed;
1073
- _super.prototype.unsubscribe.call(this);
1074
- !closed_1 && ((_a = this.onFinalize) === null || _a === void 0 ? void 0 : _a.call(this));
1075
- }
1076
- };
1077
- return OperatorSubscriber;
1078
- }(Subscriber));
1079
-
1080
- var ObjectUnsubscribedError = createErrorClass(function (_super) {
1081
- return function ObjectUnsubscribedErrorImpl() {
1082
- _super(this);
1083
- this.name = 'ObjectUnsubscribedError';
1084
- this.message = 'object unsubscribed';
1085
- };
1086
- });
1087
-
1088
- var Subject = (function (_super) {
1089
- __extends(Subject, _super);
1090
- function Subject() {
1091
- var _this = _super.call(this) || this;
1092
- _this.closed = false;
1093
- _this.currentObservers = null;
1094
- _this.observers = [];
1095
- _this.isStopped = false;
1096
- _this.hasError = false;
1097
- _this.thrownError = null;
1098
- return _this;
1099
- }
1100
- Subject.prototype.lift = function (operator) {
1101
- var subject = new AnonymousSubject(this, this);
1102
- subject.operator = operator;
1103
- return subject;
1104
- };
1105
- Subject.prototype._throwIfClosed = function () {
1106
- if (this.closed) {
1107
- throw new ObjectUnsubscribedError();
1108
- }
1109
- };
1110
- Subject.prototype.next = function (value) {
1111
- var _this = this;
1112
- errorContext(function () {
1113
- var e_1, _a;
1114
- _this._throwIfClosed();
1115
- if (!_this.isStopped) {
1116
- if (!_this.currentObservers) {
1117
- _this.currentObservers = Array.from(_this.observers);
1118
- }
1119
- try {
1120
- for (var _b = __values(_this.currentObservers), _c = _b.next(); !_c.done; _c = _b.next()) {
1121
- var observer = _c.value;
1122
- observer.next(value);
1123
- }
1124
- }
1125
- catch (e_1_1) { e_1 = { error: e_1_1 }; }
1126
- finally {
1127
- try {
1128
- if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
1129
- }
1130
- finally { if (e_1) throw e_1.error; }
1131
- }
1132
- }
1133
- });
1134
- };
1135
- Subject.prototype.error = function (err) {
1136
- var _this = this;
1137
- errorContext(function () {
1138
- _this._throwIfClosed();
1139
- if (!_this.isStopped) {
1140
- _this.hasError = _this.isStopped = true;
1141
- _this.thrownError = err;
1142
- var observers = _this.observers;
1143
- while (observers.length) {
1144
- observers.shift().error(err);
1145
- }
1146
- }
1147
- });
1148
- };
1149
- Subject.prototype.complete = function () {
1150
- var _this = this;
1151
- errorContext(function () {
1152
- _this._throwIfClosed();
1153
- if (!_this.isStopped) {
1154
- _this.isStopped = true;
1155
- var observers = _this.observers;
1156
- while (observers.length) {
1157
- observers.shift().complete();
1158
- }
1159
- }
1160
- });
1161
- };
1162
- Subject.prototype.unsubscribe = function () {
1163
- this.isStopped = this.closed = true;
1164
- this.observers = this.currentObservers = null;
1165
- };
1166
- Object.defineProperty(Subject.prototype, "observed", {
1167
- get: function () {
1168
- var _a;
1169
- return ((_a = this.observers) === null || _a === void 0 ? void 0 : _a.length) > 0;
1170
- },
1171
- enumerable: false,
1172
- configurable: true
1173
- });
1174
- Subject.prototype._trySubscribe = function (subscriber) {
1175
- this._throwIfClosed();
1176
- return _super.prototype._trySubscribe.call(this, subscriber);
1177
- };
1178
- Subject.prototype._subscribe = function (subscriber) {
1179
- this._throwIfClosed();
1180
- this._checkFinalizedStatuses(subscriber);
1181
- return this._innerSubscribe(subscriber);
1182
- };
1183
- Subject.prototype._innerSubscribe = function (subscriber) {
1184
- var _this = this;
1185
- var _a = this, hasError = _a.hasError, isStopped = _a.isStopped, observers = _a.observers;
1186
- if (hasError || isStopped) {
1187
- return EMPTY_SUBSCRIPTION;
1188
- }
1189
- this.currentObservers = null;
1190
- observers.push(subscriber);
1191
- return new Subscription(function () {
1192
- _this.currentObservers = null;
1193
- arrRemove(observers, subscriber);
1194
- });
1195
- };
1196
- Subject.prototype._checkFinalizedStatuses = function (subscriber) {
1197
- var _a = this, hasError = _a.hasError, thrownError = _a.thrownError, isStopped = _a.isStopped;
1198
- if (hasError) {
1199
- subscriber.error(thrownError);
1200
- }
1201
- else if (isStopped) {
1202
- subscriber.complete();
1203
- }
1204
- };
1205
- Subject.prototype.asObservable = function () {
1206
- var observable = new Observable();
1207
- observable.source = this;
1208
- return observable;
1209
- };
1210
- Subject.create = function (destination, source) {
1211
- return new AnonymousSubject(destination, source);
1212
- };
1213
- return Subject;
1214
- }(Observable));
1215
- var AnonymousSubject = (function (_super) {
1216
- __extends(AnonymousSubject, _super);
1217
- function AnonymousSubject(destination, source) {
1218
- var _this = _super.call(this) || this;
1219
- _this.destination = destination;
1220
- _this.source = source;
1221
- return _this;
1222
- }
1223
- AnonymousSubject.prototype.next = function (value) {
1224
- var _a, _b;
1225
- (_b = (_a = this.destination) === null || _a === void 0 ? void 0 : _a.next) === null || _b === void 0 ? void 0 : _b.call(_a, value);
1226
- };
1227
- AnonymousSubject.prototype.error = function (err) {
1228
- var _a, _b;
1229
- (_b = (_a = this.destination) === null || _a === void 0 ? void 0 : _a.error) === null || _b === void 0 ? void 0 : _b.call(_a, err);
1230
- };
1231
- AnonymousSubject.prototype.complete = function () {
1232
- var _a, _b;
1233
- (_b = (_a = this.destination) === null || _a === void 0 ? void 0 : _a.complete) === null || _b === void 0 ? void 0 : _b.call(_a);
1234
- };
1235
- AnonymousSubject.prototype._subscribe = function (subscriber) {
1236
- var _a, _b;
1237
- return (_b = (_a = this.source) === null || _a === void 0 ? void 0 : _a.subscribe(subscriber)) !== null && _b !== void 0 ? _b : EMPTY_SUBSCRIPTION;
1238
- };
1239
- return AnonymousSubject;
1240
- }(Subject));
1241
-
1242
- var BehaviorSubject = (function (_super) {
1243
- __extends(BehaviorSubject, _super);
1244
- function BehaviorSubject(_value) {
1245
- var _this = _super.call(this) || this;
1246
- _this._value = _value;
1247
- return _this;
1248
- }
1249
- Object.defineProperty(BehaviorSubject.prototype, "value", {
1250
- get: function () {
1251
- return this.getValue();
1252
- },
1253
- enumerable: false,
1254
- configurable: true
1255
- });
1256
- BehaviorSubject.prototype._subscribe = function (subscriber) {
1257
- var subscription = _super.prototype._subscribe.call(this, subscriber);
1258
- !subscription.closed && subscriber.next(this._value);
1259
- return subscription;
1260
- };
1261
- BehaviorSubject.prototype.getValue = function () {
1262
- var _a = this, hasError = _a.hasError, thrownError = _a.thrownError, _value = _a._value;
1263
- if (hasError) {
1264
- throw thrownError;
1265
- }
1266
- this._throwIfClosed();
1267
- return _value;
1268
- };
1269
- BehaviorSubject.prototype.next = function (value) {
1270
- _super.prototype.next.call(this, (this._value = value));
1271
- };
1272
- return BehaviorSubject;
1273
- }(Subject));
1274
-
1275
- var dateTimestampProvider = {
1276
- now: function () {
1277
- return (dateTimestampProvider.delegate || Date).now();
1278
- },
1279
- delegate: undefined,
1280
- };
1281
-
1282
- var Action = (function (_super) {
1283
- __extends(Action, _super);
1284
- function Action(scheduler, work) {
1285
- return _super.call(this) || this;
1286
- }
1287
- Action.prototype.schedule = function (state, delay) {
1288
- return this;
1289
- };
1290
- return Action;
1291
- }(Subscription));
1292
-
1293
- var intervalProvider = {
1294
- setInterval: function (handler, timeout) {
1295
- var args = [];
1296
- for (var _i = 2; _i < arguments.length; _i++) {
1297
- args[_i - 2] = arguments[_i];
1298
- }
1299
- var delegate = intervalProvider.delegate;
1300
- if (delegate === null || delegate === void 0 ? void 0 : delegate.setInterval) {
1301
- return delegate.setInterval.apply(delegate, __spreadArray([handler, timeout], __read(args)));
1302
- }
1303
- return setInterval.apply(void 0, __spreadArray([handler, timeout], __read(args)));
1304
- },
1305
- clearInterval: function (handle) {
1306
- var delegate = intervalProvider.delegate;
1307
- return ((delegate === null || delegate === void 0 ? void 0 : delegate.clearInterval) || clearInterval)(handle);
1308
- },
1309
- delegate: undefined,
1310
- };
1311
-
1312
- var AsyncAction = (function (_super) {
1313
- __extends(AsyncAction, _super);
1314
- function AsyncAction(scheduler, work) {
1315
- var _this = _super.call(this, scheduler, work) || this;
1316
- _this.scheduler = scheduler;
1317
- _this.work = work;
1318
- _this.pending = false;
1319
- return _this;
1320
- }
1321
- AsyncAction.prototype.schedule = function (state, delay) {
1322
- if (delay === void 0) { delay = 0; }
1323
- if (this.closed) {
1324
- return this;
1325
- }
1326
- this.state = state;
1327
- var id = this.id;
1328
- var scheduler = this.scheduler;
1329
- if (id != null) {
1330
- this.id = this.recycleAsyncId(scheduler, id, delay);
1331
- }
1332
- this.pending = true;
1333
- this.delay = delay;
1334
- this.id = this.id || this.requestAsyncId(scheduler, this.id, delay);
1335
- return this;
1336
- };
1337
- AsyncAction.prototype.requestAsyncId = function (scheduler, _id, delay) {
1338
- if (delay === void 0) { delay = 0; }
1339
- return intervalProvider.setInterval(scheduler.flush.bind(scheduler, this), delay);
1340
- };
1341
- AsyncAction.prototype.recycleAsyncId = function (_scheduler, id, delay) {
1342
- if (delay === void 0) { delay = 0; }
1343
- if (delay != null && this.delay === delay && this.pending === false) {
1344
- return id;
1345
- }
1346
- intervalProvider.clearInterval(id);
1347
- return undefined;
1348
- };
1349
- AsyncAction.prototype.execute = function (state, delay) {
1350
- if (this.closed) {
1351
- return new Error('executing a cancelled action');
1352
- }
1353
- this.pending = false;
1354
- var error = this._execute(state, delay);
1355
- if (error) {
1356
- return error;
1357
- }
1358
- else if (this.pending === false && this.id != null) {
1359
- this.id = this.recycleAsyncId(this.scheduler, this.id, null);
1360
- }
1361
- };
1362
- AsyncAction.prototype._execute = function (state, _delay) {
1363
- var errored = false;
1364
- var errorValue;
1365
- try {
1366
- this.work(state);
1367
- }
1368
- catch (e) {
1369
- errored = true;
1370
- errorValue = e ? e : new Error('Scheduled action threw falsy error');
1371
- }
1372
- if (errored) {
1373
- this.unsubscribe();
1374
- return errorValue;
1375
- }
1376
- };
1377
- AsyncAction.prototype.unsubscribe = function () {
1378
- if (!this.closed) {
1379
- var _a = this, id = _a.id, scheduler = _a.scheduler;
1380
- var actions = scheduler.actions;
1381
- this.work = this.state = this.scheduler = null;
1382
- this.pending = false;
1383
- arrRemove(actions, this);
1384
- if (id != null) {
1385
- this.id = this.recycleAsyncId(scheduler, id, null);
1386
- }
1387
- this.delay = null;
1388
- _super.prototype.unsubscribe.call(this);
1389
- }
1390
- };
1391
- return AsyncAction;
1392
- }(Action));
1393
-
1394
- var Scheduler = (function () {
1395
- function Scheduler(schedulerActionCtor, now) {
1396
- if (now === void 0) { now = Scheduler.now; }
1397
- this.schedulerActionCtor = schedulerActionCtor;
1398
- this.now = now;
1399
- }
1400
- Scheduler.prototype.schedule = function (work, delay, state) {
1401
- if (delay === void 0) { delay = 0; }
1402
- return new this.schedulerActionCtor(this, work).schedule(state, delay);
1403
- };
1404
- Scheduler.now = dateTimestampProvider.now;
1405
- return Scheduler;
1406
- }());
1407
-
1408
- var AsyncScheduler = (function (_super) {
1409
- __extends(AsyncScheduler, _super);
1410
- function AsyncScheduler(SchedulerAction, now) {
1411
- if (now === void 0) { now = Scheduler.now; }
1412
- var _this = _super.call(this, SchedulerAction, now) || this;
1413
- _this.actions = [];
1414
- _this._active = false;
1415
- _this._scheduled = undefined;
1416
- return _this;
1417
- }
1418
- AsyncScheduler.prototype.flush = function (action) {
1419
- var actions = this.actions;
1420
- if (this._active) {
1421
- actions.push(action);
1422
- return;
1423
- }
1424
- var error;
1425
- this._active = true;
1426
- do {
1427
- if ((error = action.execute(action.state, action.delay))) {
1428
- break;
1429
- }
1430
- } while ((action = actions.shift()));
1431
- this._active = false;
1432
- if (error) {
1433
- while ((action = actions.shift())) {
1434
- action.unsubscribe();
1435
- }
1436
- throw error;
1437
- }
1438
- };
1439
- return AsyncScheduler;
1440
- }(Scheduler));
1441
-
1442
- var asyncScheduler = new AsyncScheduler(AsyncAction);
1443
- var async = asyncScheduler;
1444
-
1445
- var EMPTY = new Observable(function (subscriber) { return subscriber.complete(); });
1446
-
1447
- function isScheduler(value) {
1448
- return value && isFunction(value.schedule);
1449
- }
1450
-
1451
- function last(arr) {
1452
- return arr[arr.length - 1];
1453
- }
1454
- function popResultSelector(args) {
1455
- return isFunction(last(args)) ? args.pop() : undefined;
1456
- }
1457
- function popScheduler(args) {
1458
- return isScheduler(last(args)) ? args.pop() : undefined;
1459
- }
1460
- function popNumber(args, defaultValue) {
1461
- return typeof last(args) === 'number' ? args.pop() : defaultValue;
1462
- }
1463
-
1464
- var isArrayLike = (function (x) { return x && typeof x.length === 'number' && typeof x !== 'function'; });
1465
-
1466
- function isPromise(value) {
1467
- return isFunction(value === null || value === void 0 ? void 0 : value.then);
1468
- }
1469
-
1470
- function isInteropObservable(input) {
1471
- return isFunction(input[observable]);
1472
- }
1473
-
1474
- function isAsyncIterable(obj) {
1475
- return Symbol.asyncIterator && isFunction(obj === null || obj === void 0 ? void 0 : obj[Symbol.asyncIterator]);
1476
- }
1477
-
1478
- function createInvalidObservableTypeError(input) {
1479
- return new TypeError("You provided " + (input !== null && typeof input === 'object' ? 'an invalid object' : "'" + input + "'") + " where a stream was expected. You can provide an Observable, Promise, ReadableStream, Array, AsyncIterable, or Iterable.");
1480
- }
1481
-
1482
- function getSymbolIterator() {
1483
- if (typeof Symbol !== 'function' || !Symbol.iterator) {
1484
- return '@@iterator';
1485
- }
1486
- return Symbol.iterator;
1487
- }
1488
- var iterator = getSymbolIterator();
1489
-
1490
- function isIterable(input) {
1491
- return isFunction(input === null || input === void 0 ? void 0 : input[iterator]);
1492
- }
1493
-
1494
- function readableStreamLikeToAsyncGenerator(readableStream) {
1495
- return __asyncGenerator(this, arguments, function readableStreamLikeToAsyncGenerator_1() {
1496
- var reader, _a, value, done;
1497
- return __generator(this, function (_b) {
1498
- switch (_b.label) {
1499
- case 0:
1500
- reader = readableStream.getReader();
1501
- _b.label = 1;
1502
- case 1:
1503
- _b.trys.push([1, , 9, 10]);
1504
- _b.label = 2;
1505
- case 2:
1506
- return [4, __await(reader.read())];
1507
- case 3:
1508
- _a = _b.sent(), value = _a.value, done = _a.done;
1509
- if (!done) return [3, 5];
1510
- return [4, __await(void 0)];
1511
- case 4: return [2, _b.sent()];
1512
- case 5: return [4, __await(value)];
1513
- case 6: return [4, _b.sent()];
1514
- case 7:
1515
- _b.sent();
1516
- return [3, 2];
1517
- case 8: return [3, 10];
1518
- case 9:
1519
- reader.releaseLock();
1520
- return [7];
1521
- case 10: return [2];
1522
- }
1523
- });
1524
- });
1525
- }
1526
- function isReadableStreamLike(obj) {
1527
- return isFunction(obj === null || obj === void 0 ? void 0 : obj.getReader);
1528
- }
1529
-
1530
- function innerFrom(input) {
1531
- if (input instanceof Observable) {
1532
- return input;
1533
- }
1534
- if (input != null) {
1535
- if (isInteropObservable(input)) {
1536
- return fromInteropObservable(input);
1537
- }
1538
- if (isArrayLike(input)) {
1539
- return fromArrayLike(input);
1540
- }
1541
- if (isPromise(input)) {
1542
- return fromPromise(input);
1543
- }
1544
- if (isAsyncIterable(input)) {
1545
- return fromAsyncIterable(input);
1546
- }
1547
- if (isIterable(input)) {
1548
- return fromIterable(input);
1549
- }
1550
- if (isReadableStreamLike(input)) {
1551
- return fromReadableStreamLike(input);
1552
- }
1553
- }
1554
- throw createInvalidObservableTypeError(input);
1555
- }
1556
- function fromInteropObservable(obj) {
1557
- return new Observable(function (subscriber) {
1558
- var obs = obj[observable]();
1559
- if (isFunction(obs.subscribe)) {
1560
- return obs.subscribe(subscriber);
1561
- }
1562
- throw new TypeError('Provided object does not correctly implement Symbol.observable');
1563
- });
1564
- }
1565
- function fromArrayLike(array) {
1566
- return new Observable(function (subscriber) {
1567
- for (var i = 0; i < array.length && !subscriber.closed; i++) {
1568
- subscriber.next(array[i]);
1569
- }
1570
- subscriber.complete();
1571
- });
1572
- }
1573
- function fromPromise(promise) {
1574
- return new Observable(function (subscriber) {
1575
- promise
1576
- .then(function (value) {
1577
- if (!subscriber.closed) {
1578
- subscriber.next(value);
1579
- subscriber.complete();
1580
- }
1581
- }, function (err) { return subscriber.error(err); })
1582
- .then(null, reportUnhandledError);
1583
- });
1584
- }
1585
- function fromIterable(iterable) {
1586
- return new Observable(function (subscriber) {
1587
- var e_1, _a;
1588
- try {
1589
- for (var iterable_1 = __values(iterable), iterable_1_1 = iterable_1.next(); !iterable_1_1.done; iterable_1_1 = iterable_1.next()) {
1590
- var value = iterable_1_1.value;
1591
- subscriber.next(value);
1592
- if (subscriber.closed) {
1593
- return;
1594
- }
1595
- }
1596
- }
1597
- catch (e_1_1) { e_1 = { error: e_1_1 }; }
1598
- finally {
1599
- try {
1600
- if (iterable_1_1 && !iterable_1_1.done && (_a = iterable_1.return)) _a.call(iterable_1);
1601
- }
1602
- finally { if (e_1) throw e_1.error; }
1603
- }
1604
- subscriber.complete();
1605
- });
1606
- }
1607
- function fromAsyncIterable(asyncIterable) {
1608
- return new Observable(function (subscriber) {
1609
- process$1(asyncIterable, subscriber).catch(function (err) { return subscriber.error(err); });
1610
- });
1611
- }
1612
- function fromReadableStreamLike(readableStream) {
1613
- return fromAsyncIterable(readableStreamLikeToAsyncGenerator(readableStream));
1614
- }
1615
- function process$1(asyncIterable, subscriber) {
1616
- var asyncIterable_1, asyncIterable_1_1;
1617
- var e_2, _a;
1618
- return __awaiter(this, void 0, void 0, function () {
1619
- var value, e_2_1;
1620
- return __generator(this, function (_b) {
1621
- switch (_b.label) {
1622
- case 0:
1623
- _b.trys.push([0, 5, 6, 11]);
1624
- asyncIterable_1 = __asyncValues(asyncIterable);
1625
- _b.label = 1;
1626
- case 1: return [4, asyncIterable_1.next()];
1627
- case 2:
1628
- if (!(asyncIterable_1_1 = _b.sent(), !asyncIterable_1_1.done)) return [3, 4];
1629
- value = asyncIterable_1_1.value;
1630
- subscriber.next(value);
1631
- if (subscriber.closed) {
1632
- return [2];
1633
- }
1634
- _b.label = 3;
1635
- case 3: return [3, 1];
1636
- case 4: return [3, 11];
1637
- case 5:
1638
- e_2_1 = _b.sent();
1639
- e_2 = { error: e_2_1 };
1640
- return [3, 11];
1641
- case 6:
1642
- _b.trys.push([6, , 9, 10]);
1643
- if (!(asyncIterable_1_1 && !asyncIterable_1_1.done && (_a = asyncIterable_1.return))) return [3, 8];
1644
- return [4, _a.call(asyncIterable_1)];
1645
- case 7:
1646
- _b.sent();
1647
- _b.label = 8;
1648
- case 8: return [3, 10];
1649
- case 9:
1650
- if (e_2) throw e_2.error;
1651
- return [7];
1652
- case 10: return [7];
1653
- case 11:
1654
- subscriber.complete();
1655
- return [2];
1656
- }
1657
- });
1658
- });
1659
- }
1660
-
1661
- function executeSchedule(parentSubscription, scheduler, work, delay, repeat) {
1662
- if (delay === void 0) { delay = 0; }
1663
- if (repeat === void 0) { repeat = false; }
1664
- var scheduleSubscription = scheduler.schedule(function () {
1665
- work();
1666
- if (repeat) {
1667
- parentSubscription.add(this.schedule(null, delay));
1668
- }
1669
- else {
1670
- this.unsubscribe();
1671
- }
1672
- }, delay);
1673
- parentSubscription.add(scheduleSubscription);
1674
- if (!repeat) {
1675
- return scheduleSubscription;
1676
- }
1677
- }
1678
-
1679
- function observeOn(scheduler, delay) {
1680
- if (delay === void 0) { delay = 0; }
1681
- return operate(function (source, subscriber) {
1682
- source.subscribe(createOperatorSubscriber(subscriber, function (value) { return executeSchedule(subscriber, scheduler, function () { return subscriber.next(value); }, delay); }, function () { return executeSchedule(subscriber, scheduler, function () { return subscriber.complete(); }, delay); }, function (err) { return executeSchedule(subscriber, scheduler, function () { return subscriber.error(err); }, delay); }));
1683
- });
1684
- }
1685
-
1686
- function subscribeOn(scheduler, delay) {
1687
- if (delay === void 0) { delay = 0; }
1688
- return operate(function (source, subscriber) {
1689
- subscriber.add(scheduler.schedule(function () { return source.subscribe(subscriber); }, delay));
1690
- });
1691
- }
1692
-
1693
- function scheduleObservable(input, scheduler) {
1694
- return innerFrom(input).pipe(subscribeOn(scheduler), observeOn(scheduler));
1695
- }
1696
-
1697
- function schedulePromise(input, scheduler) {
1698
- return innerFrom(input).pipe(subscribeOn(scheduler), observeOn(scheduler));
1699
- }
1700
-
1701
- function scheduleArray(input, scheduler) {
1702
- return new Observable(function (subscriber) {
1703
- var i = 0;
1704
- return scheduler.schedule(function () {
1705
- if (i === input.length) {
1706
- subscriber.complete();
1707
- }
1708
- else {
1709
- subscriber.next(input[i++]);
1710
- if (!subscriber.closed) {
1711
- this.schedule();
1712
- }
1713
- }
1714
- });
1715
- });
1716
- }
1717
-
1718
- function scheduleIterable(input, scheduler) {
1719
- return new Observable(function (subscriber) {
1720
- var iterator$1;
1721
- executeSchedule(subscriber, scheduler, function () {
1722
- iterator$1 = input[iterator]();
1723
- executeSchedule(subscriber, scheduler, function () {
1724
- var _a;
1725
- var value;
1726
- var done;
1727
- try {
1728
- (_a = iterator$1.next(), value = _a.value, done = _a.done);
1729
- }
1730
- catch (err) {
1731
- subscriber.error(err);
1732
- return;
1733
- }
1734
- if (done) {
1735
- subscriber.complete();
1736
- }
1737
- else {
1738
- subscriber.next(value);
1739
- }
1740
- }, 0, true);
1741
- });
1742
- return function () { return isFunction(iterator$1 === null || iterator$1 === void 0 ? void 0 : iterator$1.return) && iterator$1.return(); };
1743
- });
1744
- }
1745
-
1746
- function scheduleAsyncIterable(input, scheduler) {
1747
- if (!input) {
1748
- throw new Error('Iterable cannot be null');
1749
- }
1750
- return new Observable(function (subscriber) {
1751
- executeSchedule(subscriber, scheduler, function () {
1752
- var iterator = input[Symbol.asyncIterator]();
1753
- executeSchedule(subscriber, scheduler, function () {
1754
- iterator.next().then(function (result) {
1755
- if (result.done) {
1756
- subscriber.complete();
1757
- }
1758
- else {
1759
- subscriber.next(result.value);
1760
- }
1761
- });
1762
- }, 0, true);
1763
- });
1764
- });
1765
- }
1766
-
1767
- function scheduleReadableStreamLike(input, scheduler) {
1768
- return scheduleAsyncIterable(readableStreamLikeToAsyncGenerator(input), scheduler);
1769
- }
1770
-
1771
- function scheduled(input, scheduler) {
1772
- if (input != null) {
1773
- if (isInteropObservable(input)) {
1774
- return scheduleObservable(input, scheduler);
1775
- }
1776
- if (isArrayLike(input)) {
1777
- return scheduleArray(input, scheduler);
1778
- }
1779
- if (isPromise(input)) {
1780
- return schedulePromise(input, scheduler);
1781
- }
1782
- if (isAsyncIterable(input)) {
1783
- return scheduleAsyncIterable(input, scheduler);
1784
- }
1785
- if (isIterable(input)) {
1786
- return scheduleIterable(input, scheduler);
1787
- }
1788
- if (isReadableStreamLike(input)) {
1789
- return scheduleReadableStreamLike(input, scheduler);
1790
- }
1791
- }
1792
- throw createInvalidObservableTypeError(input);
1793
- }
1794
-
1795
- function from(input, scheduler) {
1796
- return scheduler ? scheduled(input, scheduler) : innerFrom(input);
1797
- }
1798
-
1799
- var EmptyError = createErrorClass(function (_super) { return function EmptyErrorImpl() {
1800
- _super(this);
1801
- this.name = 'EmptyError';
1802
- this.message = 'no elements in sequence';
1803
- }; });
1804
-
1805
- function firstValueFrom(source, config) {
1806
- var hasConfig = typeof config === 'object';
1807
- return new Promise(function (resolve, reject) {
1808
- var subscriber = new SafeSubscriber({
1809
- next: function (value) {
1810
- resolve(value);
1811
- subscriber.unsubscribe();
1812
- },
1813
- error: reject,
1814
- complete: function () {
1815
- if (hasConfig) {
1816
- resolve(config.defaultValue);
1817
- }
1818
- else {
1819
- reject(new EmptyError());
1820
- }
1821
- },
1822
- });
1823
- source.subscribe(subscriber);
1824
- });
1825
- }
1826
-
1827
- function isValidDate(value) {
1828
- return value instanceof Date && !isNaN(value);
1829
- }
1830
-
1831
- function map(project, thisArg) {
1832
- return operate(function (source, subscriber) {
1833
- var index = 0;
1834
- source.subscribe(createOperatorSubscriber(subscriber, function (value) {
1835
- subscriber.next(project.call(thisArg, value, index++));
1836
- }));
1837
- });
1838
- }
1839
-
1840
- function mergeInternals(source, subscriber, project, concurrent, onBeforeNext, expand, innerSubScheduler, additionalFinalizer) {
1841
- var buffer = [];
1842
- var active = 0;
1843
- var index = 0;
1844
- var isComplete = false;
1845
- var checkComplete = function () {
1846
- if (isComplete && !buffer.length && !active) {
1847
- subscriber.complete();
1848
- }
1849
- };
1850
- var outerNext = function (value) { return (active < concurrent ? doInnerSub(value) : buffer.push(value)); };
1851
- var doInnerSub = function (value) {
1852
- expand && subscriber.next(value);
1853
- active++;
1854
- var innerComplete = false;
1855
- innerFrom(project(value, index++)).subscribe(createOperatorSubscriber(subscriber, function (innerValue) {
1856
- onBeforeNext === null || onBeforeNext === void 0 ? void 0 : onBeforeNext(innerValue);
1857
- if (expand) {
1858
- outerNext(innerValue);
1859
- }
1860
- else {
1861
- subscriber.next(innerValue);
1862
- }
1863
- }, function () {
1864
- innerComplete = true;
1865
- }, undefined, function () {
1866
- if (innerComplete) {
1867
- try {
1868
- active--;
1869
- var _loop_1 = function () {
1870
- var bufferedValue = buffer.shift();
1871
- if (innerSubScheduler) {
1872
- executeSchedule(subscriber, innerSubScheduler, function () { return doInnerSub(bufferedValue); });
1873
- }
1874
- else {
1875
- doInnerSub(bufferedValue);
1876
- }
1877
- };
1878
- while (buffer.length && active < concurrent) {
1879
- _loop_1();
1880
- }
1881
- checkComplete();
1882
- }
1883
- catch (err) {
1884
- subscriber.error(err);
1885
- }
1886
- }
1887
- }));
1888
- };
1889
- source.subscribe(createOperatorSubscriber(subscriber, outerNext, function () {
1890
- isComplete = true;
1891
- checkComplete();
1892
- }));
1893
- return function () {
1894
- additionalFinalizer === null || additionalFinalizer === void 0 ? void 0 : additionalFinalizer();
1895
- };
1896
- }
1897
-
1898
- function mergeMap(project, resultSelector, concurrent) {
1899
- if (concurrent === void 0) { concurrent = Infinity; }
1900
- if (isFunction(resultSelector)) {
1901
- return mergeMap(function (a, i) { return map(function (b, ii) { return resultSelector(a, b, i, ii); })(innerFrom(project(a, i))); }, concurrent);
1902
- }
1903
- else if (typeof resultSelector === 'number') {
1904
- concurrent = resultSelector;
1905
- }
1906
- return operate(function (source, subscriber) { return mergeInternals(source, subscriber, project, concurrent); });
1907
- }
1908
-
1909
- function mergeAll(concurrent) {
1910
- if (concurrent === void 0) { concurrent = Infinity; }
1911
- return mergeMap(identity, concurrent);
1912
- }
1913
-
1914
- function timer(dueTime, intervalOrScheduler, scheduler) {
1915
- if (dueTime === void 0) { dueTime = 0; }
1916
- if (scheduler === void 0) { scheduler = async; }
1917
- var intervalDuration = -1;
1918
- if (intervalOrScheduler != null) {
1919
- if (isScheduler(intervalOrScheduler)) {
1920
- scheduler = intervalOrScheduler;
1921
- }
1922
- else {
1923
- intervalDuration = intervalOrScheduler;
1924
- }
1925
- }
1926
- return new Observable(function (subscriber) {
1927
- var due = isValidDate(dueTime) ? +dueTime - scheduler.now() : dueTime;
1928
- if (due < 0) {
1929
- due = 0;
1930
- }
1931
- var n = 0;
1932
- return scheduler.schedule(function () {
1933
- if (!subscriber.closed) {
1934
- subscriber.next(n++);
1935
- if (0 <= intervalDuration) {
1936
- this.schedule(undefined, intervalDuration);
1937
- }
1938
- else {
1939
- subscriber.complete();
1940
- }
1941
- }
1942
- }, due);
1943
- });
1944
- }
1945
-
1946
- function merge() {
1947
- var args = [];
1948
- for (var _i = 0; _i < arguments.length; _i++) {
1949
- args[_i] = arguments[_i];
1950
- }
1951
- var scheduler = popScheduler(args);
1952
- var concurrent = popNumber(args, Infinity);
1953
- var sources = args;
1954
- return !sources.length
1955
- ?
1956
- EMPTY
1957
- : sources.length === 1
1958
- ?
1959
- innerFrom(sources[0])
1960
- :
1961
- mergeAll(concurrent)(from(sources, scheduler));
1962
- }
1963
-
1964
- function filter(predicate, thisArg) {
1965
- return operate(function (source, subscriber) {
1966
- var index = 0;
1967
- source.subscribe(createOperatorSubscriber(subscriber, function (value) { return predicate.call(thisArg, value, index++) && subscriber.next(value); }));
1968
- });
1969
- }
1970
-
1971
- function buffer(closingNotifier) {
1972
- return operate(function (source, subscriber) {
1973
- var currentBuffer = [];
1974
- source.subscribe(createOperatorSubscriber(subscriber, function (value) { return currentBuffer.push(value); }, function () {
1975
- subscriber.next(currentBuffer);
1976
- subscriber.complete();
1977
- }));
1978
- closingNotifier.subscribe(createOperatorSubscriber(subscriber, function () {
1979
- var b = currentBuffer;
1980
- currentBuffer = [];
1981
- subscriber.next(b);
1982
- }, noop));
1983
- return function () {
1984
- currentBuffer = null;
1985
- };
1986
- });
1987
- }
1988
-
1989
- function debounce(durationSelector) {
1990
- return operate(function (source, subscriber) {
1991
- var hasValue = false;
1992
- var lastValue = null;
1993
- var durationSubscriber = null;
1994
- var emit = function () {
1995
- durationSubscriber === null || durationSubscriber === void 0 ? void 0 : durationSubscriber.unsubscribe();
1996
- durationSubscriber = null;
1997
- if (hasValue) {
1998
- hasValue = false;
1999
- var value = lastValue;
2000
- lastValue = null;
2001
- subscriber.next(value);
2002
- }
2003
- };
2004
- source.subscribe(createOperatorSubscriber(subscriber, function (value) {
2005
- durationSubscriber === null || durationSubscriber === void 0 ? void 0 : durationSubscriber.unsubscribe();
2006
- hasValue = true;
2007
- lastValue = value;
2008
- durationSubscriber = createOperatorSubscriber(subscriber, emit, noop);
2009
- innerFrom(durationSelector(value)).subscribe(durationSubscriber);
2010
- }, function () {
2011
- emit();
2012
- subscriber.complete();
2013
- }, undefined, function () {
2014
- lastValue = durationSubscriber = null;
2015
- }));
2016
- });
2017
- }
2018
-
2019
- function defaultIfEmpty(defaultValue) {
2020
- return operate(function (source, subscriber) {
2021
- var hasValue = false;
2022
- source.subscribe(createOperatorSubscriber(subscriber, function (value) {
2023
- hasValue = true;
2024
- subscriber.next(value);
2025
- }, function () {
2026
- if (!hasValue) {
2027
- subscriber.next(defaultValue);
2028
- }
2029
- subscriber.complete();
2030
- }));
2031
- });
2032
- }
2033
-
2034
- function take(count) {
2035
- return count <= 0
2036
- ?
2037
- function () { return EMPTY; }
2038
- : operate(function (source, subscriber) {
2039
- var seen = 0;
2040
- source.subscribe(createOperatorSubscriber(subscriber, function (value) {
2041
- if (++seen <= count) {
2042
- subscriber.next(value);
2043
- if (count <= seen) {
2044
- subscriber.complete();
2045
- }
2046
- }
2047
- }));
2048
- });
2049
- }
2050
-
2051
- function throwIfEmpty(errorFactory) {
2052
- if (errorFactory === void 0) { errorFactory = defaultErrorFactory; }
2053
- return operate(function (source, subscriber) {
2054
- var hasValue = false;
2055
- source.subscribe(createOperatorSubscriber(subscriber, function (value) {
2056
- hasValue = true;
2057
- subscriber.next(value);
2058
- }, function () { return (hasValue ? subscriber.complete() : subscriber.error(errorFactory())); }));
2059
- });
2060
- }
2061
- function defaultErrorFactory() {
2062
- return new EmptyError();
2063
- }
2064
-
2065
- function first(predicate, defaultValue) {
2066
- var hasDefaultValue = arguments.length >= 2;
2067
- return function (source) {
2068
- return source.pipe(predicate ? filter(function (v, i) { return predicate(v, i, source); }) : identity, take(1), hasDefaultValue ? defaultIfEmpty(defaultValue) : throwIfEmpty(function () { return new EmptyError(); }));
2069
- };
2070
- }
2071
-
2072
- function switchMap(project, resultSelector) {
2073
- return operate(function (source, subscriber) {
2074
- var innerSubscriber = null;
2075
- var index = 0;
2076
- var isComplete = false;
2077
- var checkComplete = function () { return isComplete && !innerSubscriber && subscriber.complete(); };
2078
- source.subscribe(createOperatorSubscriber(subscriber, function (value) {
2079
- innerSubscriber === null || innerSubscriber === void 0 ? void 0 : innerSubscriber.unsubscribe();
2080
- var innerIndex = 0;
2081
- var outerIndex = index++;
2082
- innerFrom(project(value, outerIndex)).subscribe((innerSubscriber = createOperatorSubscriber(subscriber, function (innerValue) { return subscriber.next(resultSelector ? resultSelector(value, innerValue, outerIndex, innerIndex++) : innerValue); }, function () {
2083
- innerSubscriber = null;
2084
- checkComplete();
2085
- })));
2086
- }, function () {
2087
- isComplete = true;
2088
- checkComplete();
2089
- }));
468
+ const { outputFile } = fsx;
469
+ _debug("file-writer");
470
+ async function start({
471
+ server
472
+ }) {
473
+ serverEvent$.next({ type: "start", server });
474
+ const plugins = server.config.plugins.filter(
475
+ (p) => p.name?.startsWith("crx:")
476
+ );
477
+ const { rollupOptions, outDir } = server.config.build;
478
+ const inputOptions = {
479
+ input: "index.html",
480
+ ...rollupOptions,
481
+ plugins
482
+ };
483
+ const rollupOutputOptions = [rollupOptions.output].flat()[0];
484
+ const outputOptions = {
485
+ ...rollupOutputOptions,
486
+ dir: outDir,
487
+ format: "es"
488
+ };
489
+ fileWriterEvent$.next({ type: "build_start" });
490
+ const build = await rollup(inputOptions);
491
+ await build.write(outputOptions);
492
+ fileWriterEvent$.next({ type: "build_end" });
493
+ await allFilesReady();
494
+ }
495
+ async function close() {
496
+ serverEvent$.next({ type: "close" });
497
+ }
498
+ function add(script) {
499
+ const fileName = getFileName(script);
500
+ let file = outputFiles.get(fileName);
501
+ if (typeof file === "undefined") {
502
+ file = formatFileData({
503
+ ...script,
504
+ fileName,
505
+ file: write(script)
2090
506
  });
2091
- }
2092
-
2093
- function withLatestFrom() {
2094
- var inputs = [];
2095
- for (var _i = 0; _i < arguments.length; _i++) {
2096
- inputs[_i] = arguments[_i];
507
+ outputFiles.set(file.fileName, file);
508
+ }
509
+ return file;
510
+ }
511
+ function update(_id) {
512
+ const id = prefix$1("/", _id);
513
+ const types = ["iife", "module"];
514
+ const updatedFiles = [];
515
+ for (const type of types) {
516
+ const fileName = getFileName({ id, type });
517
+ const scriptFile = outputFiles.get(fileName);
518
+ if (scriptFile) {
519
+ scriptFile.file = write({ id, type });
520
+ updatedFiles.push(scriptFile);
521
+ outputFiles.set(fileName, scriptFile);
2097
522
  }
2098
- var project = popResultSelector(inputs);
2099
- return operate(function (source, subscriber) {
2100
- var len = inputs.length;
2101
- var otherValues = new Array(len);
2102
- var hasValue = inputs.map(function () { return false; });
2103
- var ready = false;
2104
- var _loop_1 = function (i) {
2105
- innerFrom(inputs[i]).subscribe(createOperatorSubscriber(subscriber, function (value) {
2106
- otherValues[i] = value;
2107
- if (!ready && !hasValue[i]) {
2108
- hasValue[i] = true;
2109
- (ready = hasValue.every(identity)) && (hasValue = null);
2110
- }
2111
- }, noop));
2112
- };
2113
- for (var i = 0; i < len; i++) {
2114
- _loop_1(i);
523
+ }
524
+ return updatedFiles;
525
+ }
526
+ async function write(fileId) {
527
+ const start2 = performance.now();
528
+ const deps = await firstValueFrom(
529
+ start$.pipe(
530
+ prepFileData(fileId),
531
+ mergeMap(async ({ target, source, deps: deps2 }) => {
532
+ const files = deps2.map((id) => {
533
+ const r = [add({ id, type: "module" })];
534
+ if (id.includes("?import")) {
535
+ const [imported] = id.split("?import");
536
+ r.push(add({ id: imported, type: "asset" }));
537
+ }
538
+ return r;
539
+ }).flat();
540
+ if (source instanceof Uint8Array)
541
+ await outputFile(target, source);
542
+ else
543
+ await outputFile(target, source, { encoding: "utf8" });
544
+ return files;
545
+ }),
546
+ takeUntil(close$),
547
+ concatWith(of([]))
548
+ )
549
+ );
550
+ const close2 = performance.now();
551
+ return { start: start2, close: close2, deps };
552
+ }
553
+
554
+ const pluginContentScripts = () => {
555
+ let server;
556
+ let preambleCode;
557
+ let hmrTimeout;
558
+ let sub = new Subscription();
559
+ return [
560
+ {
561
+ name: "crx:content-scripts",
562
+ apply: "serve",
563
+ async config(config) {
564
+ const { contentScripts: contentScripts2 = {} } = await getOptions(config);
565
+ hmrTimeout = contentScripts2.hmrTimeout ?? 5e3;
566
+ preambleCode = preambleCode ?? contentScripts2.preambleCode;
567
+ },
568
+ async configureServer(_server) {
569
+ server = _server;
570
+ if (typeof preambleCode === "undefined" && server.config.plugins.some(
571
+ ({ name = "none" }) => name.toLowerCase().includes("react") && !name.toLowerCase().includes("preact")
572
+ )) {
573
+ try {
574
+ const react = await import('@vitejs/plugin-react');
575
+ preambleCode = react.default.preambleCode;
576
+ } catch (error) {
577
+ preambleCode = false;
578
+ }
2115
579
  }
2116
- source.subscribe(createOperatorSubscriber(subscriber, function (value) {
2117
- if (ready) {
2118
- var values = __spreadArray([value], __read(otherValues));
2119
- subscriber.next(project ? project.apply(void 0, __spreadArray([], __read(values))) : values);
580
+ sub.add(
581
+ contentScripts.change$.pipe(filter(RxMap.isChangeType.set)).subscribe(({ value: script }) => {
582
+ const { type, id } = script;
583
+ if (type === "loader") {
584
+ let preamble = { fileName: "" };
585
+ if (preambleCode)
586
+ preamble = add({ type: "module", id: preambleId });
587
+ const client = add({ type: "module", id: viteClientId });
588
+ const file = add({ type: "module", id });
589
+ const loader = add({
590
+ type: "asset",
591
+ id: getFileName({ type: "loader", id }),
592
+ source: createDevLoader({
593
+ preamble: preamble.fileName,
594
+ client: client.fileName,
595
+ fileName: file.fileName
596
+ })
597
+ });
598
+ script.fileName = loader.fileName;
599
+ } else if (type === "iife") {
600
+ throw new Error("IIFE content scripts are not implemented");
601
+ } else {
602
+ const file = add({ type: "module", id });
603
+ script.fileName = file.fileName;
2120
604
  }
2121
- }));
2122
- });
2123
- }
2124
-
2125
- const { pathExistsSync, outputFile, statSync } = fsExtra;
2126
- const debug$3 = _debug("file-writer").extend("events");
2127
- const writerEvent$ = new BehaviorSubject({
2128
- type: "init"
2129
- });
2130
- writerEvent$.subscribe((event) => {
2131
- debug$3("watcher event %O", event.type);
2132
- if (event.type === "error") {
2133
- debug$3("watcher error %O", event.error);
2134
- }
2135
- });
2136
- const filesError$ = writerEvent$.pipe(filter((x) => {
2137
- return x.type === "error";
2138
- }));
2139
- const filesStart$ = writerEvent$.pipe(filter((x) => {
2140
- return x.type === "buildStart";
2141
- }));
2142
- const filesStart = () => firstValueFrom(filesStart$);
2143
- const filesReady$ = writerEvent$.pipe(filter((x) => {
2144
- return x.type === "writeBundle";
2145
- }), switchMap((event) => timer(0, 100).pipe(map(() => event), first(({ bundle, options, timestamp }) => {
2146
- const result = Object.keys(bundle).every((p) => {
2147
- const stats = statSync(join(options.dir, p));
2148
- return stats.mtimeMs > timestamp;
2149
- });
2150
- return result;
2151
- }))));
2152
- const filesReady = () => firstValueFrom(filesReady$);
2153
- const server$ = new Subject();
2154
- const triggerName = firstValueFrom(server$.pipe(map(({ config: { cacheDir } }) => cacheDir), filter(isString), map((dir) => join(dir, ".crx-watch-trigger"))));
2155
- const rebuildFiles = async () => {
2156
- debug$3("rebuildFiles start");
2157
- await filesReady();
2158
- await Promise.all([
2159
- outputFile(await triggerName, Date.now().toString()),
2160
- filesStart()
2161
- ]);
2162
- await filesReady();
2163
- debug$3("rebuildFiles end");
2164
- };
2165
- function startLogger(server) {
2166
- const logger = createLogger(server.config.logLevel, {
2167
- prefix: "[crx]"
2168
- });
2169
- const subs = [
2170
- filesStart$.subscribe(() => {
2171
- const message = colors.green("files start");
2172
- const outDir = colors.dim(relative(server.config.root, server.config.build.outDir));
2173
- logger.info(`${message} ${outDir}`, { timestamp: true });
2174
- }),
2175
- filesReady$.subscribe(({ duration: d }) => {
2176
- const message = colors.green("files ready");
2177
- const duration = colors.dim(`in ${colors.bold(`${d}ms`)}`);
2178
- logger.info(`${message} ${duration}`, { timestamp: true });
2179
- }),
2180
- filesError$.subscribe(({ error }) => {
2181
- logger.error(colors.dim("error from file writer:"), { timestamp: true });
2182
- if (error) {
2183
- const message = error?.stack ?? error.message;
2184
- logger.error(colors.red(message));
605
+ })
606
+ );
607
+ },
608
+ resolveId(source) {
609
+ if (source === preambleId)
610
+ return preambleId;
611
+ if (source === contentHmrPortId)
612
+ return contentHmrPortId;
613
+ },
614
+ load(id) {
615
+ if (id === preambleId && typeof preambleCode === "string") {
616
+ const defined = preambleCode.replace(/__BASE__/g, server.config.base);
617
+ return defined;
618
+ }
619
+ if (id === contentHmrPortId) {
620
+ const defined = contentHmrPort.replace(
621
+ "__CRX_HMR_TIMEOUT__",
622
+ JSON.stringify(hmrTimeout)
623
+ );
624
+ return defined;
625
+ }
626
+ },
627
+ closeBundle() {
628
+ sub.unsubscribe();
629
+ sub = new Subscription();
2185
630
  }
2186
- })
2187
- ];
2188
- return () => subs.forEach((sub) => sub.unsubscribe());
2189
- }
2190
- const pluginFileWriterEvents = () => {
2191
- let start = performance.now();
2192
- let stopLogger;
2193
- return {
2194
- name: "crx:file-writer-events",
2195
- enforce: "post",
2196
- apply: "build",
2197
- fileWriterStart(server) {
2198
- debug$3("fileWriterStart");
2199
- stopLogger = startLogger(server);
2200
631
  },
2201
- closeWatcher() {
2202
- debug$3("closeWatcher");
2203
- stopLogger();
2204
- },
2205
- async buildStart(options) {
2206
- start = performance.now();
2207
- const filename = await triggerName;
2208
- if (!pathExistsSync(filename)) {
2209
- await outputFile(filename, Date.now().toString());
632
+ {
633
+ name: "crx:content-scripts",
634
+ apply: "build",
635
+ enforce: "pre",
636
+ generateBundle() {
637
+ for (const [key, script] of contentScripts)
638
+ if (key === script.refId) {
639
+ if (script.type === "module") {
640
+ const fileName = this.getFileName(script.refId);
641
+ script.fileName = fileName;
642
+ } else if (script.type === "loader") {
643
+ const fileName = this.getFileName(script.refId);
644
+ script.fileName = fileName;
645
+ const refId = this.emitFile({
646
+ type: "asset",
647
+ name: getFileName({ type: "loader", id: basename(script.id) }),
648
+ source: createProLoader({ fileName })
649
+ });
650
+ script.loaderName = this.getFileName(refId);
651
+ } else if (script.type === "iife") {
652
+ throw new Error("IIFE content scripts are not implemented");
653
+ }
654
+ contentScripts.set(script.refId, formatFileData(script));
655
+ }
2210
656
  }
2211
- this.addWatchFile(filename);
2212
- writerEvent$.next({ type: "buildStart", options });
2213
- debug$3("buildStart");
2214
- },
2215
- writeBundle(options, bundle) {
2216
- const timestamp = performance.now();
2217
- const duration = Math.round(timestamp - start);
2218
- writerEvent$.next({
2219
- type: "writeBundle",
2220
- options,
2221
- bundle,
2222
- duration,
2223
- timestamp
2224
- });
2225
- debug$3("writeBundle");
2226
- },
2227
- renderError(error) {
2228
- writerEvent$.next({ type: "error", error });
2229
- },
2230
- watchChange(id, { event }) {
2231
- writerEvent$.next({ type: "change", id, event });
2232
657
  }
2233
- };
658
+ ];
2234
659
  };
2235
660
 
2236
- var precontrollerScript = "const id = setInterval(() => location.reload(), 100);\nsetTimeout(() => clearInterval(id), 5e3);\n";
2237
-
2238
- 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";
2239
-
2240
- const pluginFileWriterHtml = () => {
2241
- let precontrollerName;
661
+ const pluginContentScriptsCss = () => {
662
+ let injectCss;
2242
663
  return {
2243
- name: "crx:file-writer-html",
2244
- apply: "build",
2245
- fileWriterStart(server) {
2246
- const plugins = server.config.plugins;
2247
- const i = plugins.findIndex(({ name }) => name === "alias");
2248
- plugins.splice(i, 0, {
2249
- name: "crx:load-precontroller",
2250
- apply: "serve",
2251
- load(id) {
2252
- if (id === `/${precontrollerName}`)
2253
- return "location.reload();";
2254
- }
2255
- });
664
+ name: "crx:content-scripts-css",
665
+ enforce: "post",
666
+ async config(config) {
667
+ const { contentScripts: contentScripts2 = {} } = await getOptions(config);
668
+ injectCss = contentScripts2.injectCss ?? true;
2256
669
  },
2257
670
  renderCrxManifest(manifest) {
2258
- if (this.meta.watchMode) {
2259
- const refId = this.emitFile({
2260
- type: "asset",
2261
- name: "precontroller.js",
2262
- source: precontrollerScript
2263
- });
2264
- precontrollerName = this.getFileName(refId);
2265
- for (const fileName of htmlFiles(manifest)) {
2266
- this.emitFile({
2267
- type: "asset",
2268
- fileName,
2269
- source: precontrollerHtml.replace("%PATH%", `/${precontrollerName}`)
2270
- });
671
+ if (injectCss) {
672
+ if (manifest.content_scripts) {
673
+ for (const script of manifest.content_scripts)
674
+ if (script.js)
675
+ for (const fileName of script.js)
676
+ if (contentScripts.has(fileName)) {
677
+ const { css } = contentScripts.get(fileName);
678
+ if (css?.length)
679
+ script.css = [script.css ?? [], css].flat();
680
+ } else {
681
+ throw new Error(
682
+ `Content script is undefined by fileName: ${fileName}`
683
+ );
684
+ }
2271
685
  }
2272
686
  }
2273
687
  return manifest;
@@ -2275,261 +689,342 @@ const pluginFileWriterHtml = () => {
2275
689
  };
2276
690
  };
2277
691
 
2278
- const { readFile: readFile$1 } = promises;
2279
- const pluginFileWriterPublic = () => {
692
+ const pluginDeclaredContentScripts = () => {
693
+ return [];
694
+ };
695
+
696
+ const _dynamicScriptRegEx = /\b(import.meta).CRX_DYNAMIC_SCRIPT_(.+?)[,;]/gm;
697
+ const dynamicScriptRegEx = () => {
698
+ _dynamicScriptRegEx.lastIndex = 0;
699
+ return _dynamicScriptRegEx;
700
+ };
701
+ const pluginDynamicContentScripts = () => {
2280
702
  let config;
2281
- return {
2282
- name: "crx:file-writer-public",
2283
- apply: "build",
2284
- configResolved(_config) {
2285
- config = _config;
2286
- },
2287
- async buildStart() {
2288
- if (this.meta.watchMode) {
2289
- this.addWatchFile(config.publicDir);
2290
- const publicFiles = await fg(`${config.publicDir}/**/*`);
2291
- for (const file of publicFiles) {
2292
- const source = await readFile$1(file);
2293
- const fileName = relative(config.publicDir, file);
2294
- this.emitFile({ type: "asset", fileName, source });
703
+ return [
704
+ {
705
+ name: "crx:dynamic-content-scripts-loader",
706
+ enforce: "pre",
707
+ configResolved(_config) {
708
+ config = _config;
709
+ },
710
+ async resolveId(_source, importer) {
711
+ if (importer && _source.includes("?script")) {
712
+ const url = new URL(_source, "stub://stub");
713
+ if (url.searchParams.has("script")) {
714
+ const [source] = _source.split("?");
715
+ const resolved = await this.resolve(source, importer, {
716
+ skipSelf: true
717
+ });
718
+ if (!resolved)
719
+ throw new Error(
720
+ `Could not resolve dynamic script: "${_source}" from "${importer}"`
721
+ );
722
+ const { id } = resolved;
723
+ let type = "loader";
724
+ if (url.searchParams.has("module")) {
725
+ type = "module";
726
+ } else if (url.searchParams.has("iife")) {
727
+ type = "iife";
728
+ }
729
+ const scriptId = hashScriptId({ type, id });
730
+ const resolvedId = `${id}?scriptId=${scriptId}`;
731
+ let script = contentScripts.get(resolvedId);
732
+ if (typeof script === "undefined") {
733
+ let refId;
734
+ let fileName;
735
+ let loaderName;
736
+ if (config.command === "build") {
737
+ refId = this.emitFile({
738
+ type: "chunk",
739
+ id,
740
+ name: basename(id)
741
+ });
742
+ } else {
743
+ refId = scriptId;
744
+ const relId = relative(config.root, id);
745
+ fileName = getFileName({
746
+ type: type === "iife" ? "iife" : "module",
747
+ id: relId
748
+ });
749
+ if (type === "loader")
750
+ loaderName = getFileName({ type, id: relId });
751
+ }
752
+ script = formatFileData({
753
+ type,
754
+ id: relative(config.root, id),
755
+ isDynamicScript: true,
756
+ fileName,
757
+ loaderName,
758
+ refId,
759
+ scriptId,
760
+ matches: []
761
+ });
762
+ contentScripts.set(script.id, script);
763
+ }
764
+ return resolvedId;
765
+ } else if (url.searchParams.has("scriptId")) {
766
+ return _source;
767
+ }
768
+ }
769
+ },
770
+ async load(id) {
771
+ const index = id.indexOf("?scriptId=");
772
+ if (index > -1) {
773
+ const scriptId = id.slice(index + "?scriptId=".length);
774
+ const script = contentScripts.get(scriptId);
775
+ if (config.command === "build") {
776
+ return `export default import.meta.CRX_DYNAMIC_SCRIPT_${script.refId};`;
777
+ } else if (typeof script.fileName === "string") {
778
+ await fileReady(script);
779
+ return `export default ${JSON.stringify(script.fileName)};`;
780
+ } else {
781
+ throw new Error(
782
+ `Content script fileName is undefined: "${script.id}"`
783
+ );
784
+ }
2295
785
  }
2296
786
  }
787
+ },
788
+ {
789
+ name: "crx:dynamic-content-scripts-build",
790
+ apply: "build",
791
+ generateBundle(options, bundle) {
792
+ for (const chunk of Object.values(bundle))
793
+ if (chunk.type === "chunk") {
794
+ if (dynamicScriptRegEx().test(chunk.code)) {
795
+ const replaced = chunk.code.replace(
796
+ dynamicScriptRegEx(),
797
+ (match, p1, scriptKey) => {
798
+ const script = contentScripts.get(scriptKey);
799
+ if (typeof script === "undefined")
800
+ throw new Error(
801
+ `Content script refId is undefined: "${match}"`
802
+ );
803
+ if (typeof script.fileName === "undefined")
804
+ throw new Error(
805
+ `Content script fileName is undefined: "${script.id}"`
806
+ );
807
+ return `${JSON.stringify(
808
+ `/${script.loaderName ?? script.fileName}`
809
+ )}${match.split(scriptKey)[1]}`;
810
+ }
811
+ );
812
+ chunk.code = replaced;
813
+ }
814
+ }
815
+ }
816
+ }
817
+ ];
818
+ };
819
+
820
+ const logger = createLogger("error", { prefix: "crxjs" });
821
+ const pluginFileWriter = () => {
822
+ fileWriterError$.subscribe((error) => {
823
+ logger.error(error.err.message, { error: error.err });
824
+ });
825
+ return {
826
+ name: "crx:file-writer",
827
+ apply: "serve",
828
+ configureServer(server) {
829
+ server.httpServer?.on("listening", async () => {
830
+ try {
831
+ await start({ server });
832
+ } catch (error) {
833
+ console.error(error);
834
+ server.close();
835
+ }
836
+ });
837
+ server.httpServer?.on("close", () => close());
838
+ },
839
+ closeBundle() {
840
+ outputFiles.clear();
2297
841
  }
2298
842
  };
2299
843
  };
2300
844
 
2301
845
  const _require = typeof require === "undefined" ? createRequire(import.meta.url) : require;
2302
- const customElementsPath = _require.resolve(customElementsId);
846
+ const customElementsPath = _require.resolve(customElementsId.slice(1));
2303
847
  const customElementsCode = readFileSync(customElementsPath, "utf8");
2304
848
  const customElementsMap = readFileSync(`${customElementsPath}.map`, "utf8");
2305
849
  const pluginFileWriterPolyfill = () => {
2306
850
  return {
2307
851
  name: "crx:file-writer-polyfill",
2308
- apply: "build",
852
+ apply: "serve",
2309
853
  enforce: "pre",
854
+ resolveId(source) {
855
+ if (source === customElementsId) {
856
+ return customElementsId;
857
+ }
858
+ },
2310
859
  load(id) {
2311
- if (id === idByUrl.get(customElementsId)) {
860
+ if (id === customElementsId) {
2312
861
  return { code: customElementsCode, map: customElementsMap };
2313
862
  }
2314
863
  },
2315
- transform(code, id) {
2316
- if (id === idByUrl.get(viteClientId)) {
864
+ renderCrxDevScript(code, { type, id }) {
865
+ if (type === "module" && id === viteClientId) {
2317
866
  const magic = new MagicString(code);
2318
867
  magic.prepend(`import '${customElementsId}';`);
2319
868
  magic.prepend(`import { HMRPort } from '${contentHmrPortId}';`);
2320
869
  const ws = "new WebSocket";
2321
870
  const index = code.indexOf(ws);
2322
871
  magic.overwrite(index, index + ws.length, "new HMRPort");
2323
- return { code: magic.toString(), map: magic.generateMap() };
872
+ return magic.toString();
2324
873
  }
2325
874
  }
2326
875
  };
2327
876
  };
2328
877
 
2329
- function isUpdatePayload(p) {
2330
- return p.type === "update";
2331
- }
2332
- function isFullReloadPayload(p) {
2333
- return p.type === "full-reload";
878
+ async function manifestFiles(manifest, options = {}) {
879
+ let locales = [];
880
+ if (manifest.default_locale)
881
+ locales = await fg("_locales/**/messages.json", options);
882
+ const rulesets = manifest.declarative_net_request?.rule_resources.flatMap(
883
+ ({ path }) => path
884
+ ) ?? [];
885
+ const contentScripts = manifest.content_scripts?.flatMap(({ js }) => js) ?? [];
886
+ const contentStyles = manifest.content_scripts?.flatMap(({ css }) => css);
887
+ const serviceWorker = manifest.background?.service_worker;
888
+ const htmlPages = htmlFiles(manifest);
889
+ const icons = [
890
+ Object.values(
891
+ isString(manifest.icons) ? [manifest.icons] : manifest.icons ?? {}
892
+ ),
893
+ Object.values(
894
+ isString(manifest.action?.default_icon) ? [manifest.action?.default_icon] : manifest.action?.default_icon ?? {}
895
+ )
896
+ ].flat();
897
+ let webAccessibleResources = [];
898
+ if (manifest.web_accessible_resources) {
899
+ const resources = await Promise.all(
900
+ manifest.web_accessible_resources.flatMap(({ resources: resources2 }) => resources2).map(async (r) => {
901
+ if (["*", "**/*"].includes(r))
902
+ return void 0;
903
+ if (fg.isDynamicPattern(r))
904
+ return fg(r, options);
905
+ return r;
906
+ })
907
+ );
908
+ webAccessibleResources = [...new Set(resources.flat())].filter(isString);
909
+ }
910
+ return {
911
+ contentScripts: [...new Set(contentScripts)].filter(isString),
912
+ contentStyles: [...new Set(contentStyles)].filter(isString),
913
+ html: htmlPages,
914
+ icons: [...new Set(icons)].filter(isString),
915
+ locales: [...new Set(locales)].filter(isString),
916
+ rulesets: [...new Set(rulesets)].filter(isString),
917
+ background: [serviceWorker].filter(isString),
918
+ webAccessibleResources
919
+ };
2334
920
  }
2335
- function isPrunePayload(p) {
2336
- return p.type === "prune";
921
+ async function dirFiles(dir) {
922
+ const files = await fg(`${dir}/**/*`);
923
+ return files;
2337
924
  }
2338
- function isCrxHMRPayload(x) {
2339
- return x.type === "custom" && x.event.startsWith("crx:");
925
+ function htmlFiles(manifest) {
926
+ const files = [
927
+ manifest.action?.default_popup,
928
+ Object.values(manifest.chrome_url_overrides ?? {}),
929
+ manifest.devtools_page,
930
+ manifest.options_page,
931
+ manifest.options_ui?.page,
932
+ manifest.sandbox?.pages
933
+ ].flat().filter(isString).map((s) => s.split("#")[0]).sort();
934
+ return [...new Set(files)];
2340
935
  }
2341
- const hmrPayload$ = new Subject();
2342
- const hmrPrune$ = hmrPayload$.pipe(filter(isPrunePayload));
2343
- const hmrFullReload$ = hmrPayload$.pipe(filter(isFullReloadPayload));
2344
- const hmrUpdate$ = hmrPayload$.pipe(filter(isUpdatePayload));
2345
- const payload$ = merge(hmrFullReload$, hmrPrune$, hmrUpdate$);
2346
- const rebuildSignal$ = payload$.pipe(buffer(payload$.pipe(debounce(() => filesReady$))), map((payloads) => {
2347
- if (payloads.every(isUpdatePayload)) {
2348
- const owners = /* @__PURE__ */ new Set();
2349
- for (const { updates } of payloads)
2350
- for (const { path } of updates)
2351
- if (transformResultByOwner.has(path))
2352
- owners.add(path);
2353
- return { type: "partial", owners };
2354
- }
2355
- return { type: "full" };
2356
- }), filter((rebuild) => rebuild.type === "partial" ? rebuild.owners.size > 0 : true));
2357
- const crxHmrPayload$ = hmrPayload$.pipe(filter((p) => !isCrxHMRPayload(p)), buffer(filesReady$), mergeMap((pps) => {
2358
- let fullReload;
2359
- const payloads = [];
2360
- for (const p of pps.slice(-50))
2361
- if (p.type === "full-reload") {
2362
- fullReload = p;
2363
- } else {
2364
- payloads.push(p);
2365
- }
2366
- if (fullReload)
2367
- payloads.push(fullReload);
2368
- return payloads;
2369
- }), map((p) => {
2370
- switch (p.type) {
2371
- case "full-reload": {
2372
- const path = p.path && outputByOwner.get(p.path);
2373
- const fullReload = {
2374
- type: "full-reload",
2375
- path
2376
- };
2377
- return fullReload;
2378
- }
2379
- case "prune": {
2380
- const paths = [];
2381
- for (const owner of p.paths)
2382
- if (outputByOwner.has(owner))
2383
- paths.push(outputByOwner.get(owner));
2384
- return { type: "prune", paths };
2385
- }
2386
- case "update": {
2387
- const updates = [];
2388
- for (const { acceptedPath, path, ...rest } of p.updates)
2389
- if (outputByOwner.has(acceptedPath) && outputByOwner.has(path))
2390
- updates.push({
2391
- ...rest,
2392
- acceptedPath: outputByOwner.get(acceptedPath),
2393
- path: outputByOwner.get(path)
2394
- });
2395
- return { type: "update", updates };
2396
- }
2397
- default:
2398
- return p;
2399
- }
2400
- }), withLatestFrom(filesReady$), filter(([p, { bundle }]) => {
2401
- switch (p.type) {
2402
- case "full-reload":
2403
- return typeof p.path === "undefined" || p.path in bundle;
2404
- case "prune":
2405
- return p.paths.length > 0;
2406
- case "update":
2407
- return p.updates.length > 0;
2408
- default:
2409
- return true;
2410
- }
2411
- }), map(([p]) => ({
2412
- type: "custom",
2413
- event: "crx:content-script-payload",
2414
- data: p
2415
- })));
2416
936
 
2417
- function sortPlugins(plugins, command) {
2418
- const pre = [];
2419
- const mid = [];
2420
- const post = [];
2421
- for (const p of plugins) {
2422
- if (p.apply === command || !p.apply || !command) {
2423
- if (p.enforce === "pre")
2424
- pre.push(p);
2425
- else if (p.enforce === "post")
2426
- post.push(p);
2427
- else
2428
- mid.push(p);
2429
- }
2430
- }
2431
- return { pre, mid, post };
2432
- }
2433
- const pluginFileWriter = (crxPlugins) => (options) => {
2434
- const chunks = pluginFileWriterChunks();
2435
- const html = pluginFileWriterHtml();
2436
- const events = pluginFileWriterEvents();
2437
- const publicDir = pluginFileWriterPublic();
2438
- const polyfill = pluginFileWriterPolyfill();
2439
- const { pre, mid, post } = sortPlugins(crxPlugins, "build");
2440
- const plugins = [
2441
- ...pre,
2442
- ...mid,
2443
- polyfill,
2444
- chunks,
2445
- html,
2446
- publicDir,
2447
- ...post,
2448
- events
2449
- ].flat();
2450
- let watcher;
937
+ const pluginFileWriterPublic = () => {
938
+ let config;
2451
939
  return {
2452
- name: "crx:file-writer",
940
+ name: "crx:file-writer-public",
2453
941
  apply: "serve",
2454
- async config(_config, env) {
2455
- let config = _config;
2456
- for (const p of plugins) {
2457
- const r = await p.config?.(config, env);
2458
- config = r ?? config;
2459
- }
2460
- return config;
2461
- },
2462
- async configResolved(config) {
2463
- await Promise.all(plugins.map((p) => p.configResolved?.(config)));
2464
- },
2465
- configureServer(server) {
2466
- server.httpServer?.once("listening", async () => {
2467
- server$.next(server);
2468
- const optimizedDeps = server._optimizedDeps;
2469
- await optimizedDeps?.scanProcessing;
2470
- const { pre: pre2, mid: mid2, post: post2 } = sortPlugins([
2471
- ...server.config.plugins,
2472
- ...plugins
2473
- ]);
2474
- const allPlugins = [...pre2, ...mid2, ...post2];
2475
- await Promise.all(allPlugins.map(async (p) => {
2476
- try {
2477
- await p.fileWriterStart?.(server);
2478
- } catch (e) {
2479
- const hook = `[${p.name}].fileWriterStart`;
2480
- let error = new Error(`Error in plugin ${hook}`);
2481
- if (e instanceof Error) {
2482
- error = e;
2483
- error.message = `${hook} ${error.message}`;
2484
- } else if (typeof e === "string") {
2485
- error = new Error(`${hook} ${e}`);
2486
- }
2487
- writerEvent$.next({ type: "error", error });
2488
- }
2489
- }));
2490
- watcher = watch({
2491
- input: stubId,
2492
- context: "this",
2493
- output: {
2494
- dir: server.config.build.outDir,
2495
- format: "es"
2496
- },
2497
- plugins,
2498
- treeshake: false
2499
- });
2500
- watcher.on("event", (event) => {
2501
- if (event.code === "ERROR") {
2502
- const { message, parserError, stack, id, loc, code, frame } = event.error;
2503
- const error = parserError ?? new Error(message);
2504
- if (parserError && message.startsWith("Unexpected token")) {
2505
- const m = `Unexpected token in ${loc?.file ?? id}`;
2506
- error.message = [m, loc?.line, loc?.column].filter(isTruthy).join(":");
2507
- }
2508
- error.stack = (stack ?? error.stack)?.replace(/.+?\n/, `Error: ${error.message}
2509
- `);
2510
- writerEvent$.next({ type: "error", error, code, frame });
2511
- }
2512
- });
2513
- const rebuildSub = rebuildSignal$.subscribe((rebuild) => {
2514
- if (rebuild.type === "partial") {
2515
- for (const owner of rebuild.owners)
2516
- transformResultByOwner.delete(owner);
2517
- } else {
2518
- transformResultByOwner.clear();
2519
- }
2520
- rebuildFiles();
2521
- });
2522
- watcher.on("close", () => {
2523
- rebuildSub.unsubscribe();
2524
- });
2525
- });
942
+ configResolved(_config) {
943
+ config = _config;
2526
944
  },
2527
- closeBundle() {
2528
- watcher?.close();
945
+ async generateBundle() {
946
+ const publicDir = isAbsolute(config.publicDir) ? config.publicDir : resolve(config.root, config.publicDir);
947
+ const files = await dirFiles(publicDir);
948
+ for (const filepath of files) {
949
+ const source = await readFile$1(filepath);
950
+ const fileName = relative(publicDir, filepath);
951
+ this.emitFile({ type: "asset", source, fileName });
952
+ }
2529
953
  }
2530
954
  };
2531
955
  };
2532
956
 
957
+ _debug("file-writer").extend("hmr");
958
+ const isCrxHMRPayload = (p) => p.type === "custom" && p.event.startsWith("crx:");
959
+ const hmrPayload$ = new Subject();
960
+ const crxHMRPayload$ = hmrPayload$.pipe(
961
+ filter((p) => !isCrxHMRPayload(p)),
962
+ buffer(allFilesReady$),
963
+ mergeMap((pps) => {
964
+ let fullReload;
965
+ const payloads = [];
966
+ for (const p of pps)
967
+ if (p.type === "full-reload") {
968
+ fullReload = p;
969
+ } else {
970
+ payloads.push(p);
971
+ }
972
+ if (fullReload)
973
+ payloads.push(fullReload);
974
+ return payloads;
975
+ }),
976
+ map((p) => {
977
+ switch (p.type) {
978
+ case "full-reload": {
979
+ const fullReload = {
980
+ type: "full-reload",
981
+ path: p.path && getViteUrl({ id: p.path, type: "module" })
982
+ };
983
+ return fullReload;
984
+ }
985
+ case "prune": {
986
+ const prune = {
987
+ type: "prune",
988
+ paths: p.paths.map((id) => getViteUrl({ id, type: "module" }))
989
+ };
990
+ return prune;
991
+ }
992
+ case "update": {
993
+ const update = {
994
+ type: "update",
995
+ updates: p.updates.map(({ acceptedPath: ap, path: p2, ...rest }) => ({
996
+ ...rest,
997
+ acceptedPath: prefix$1("/", getFileName({ id: ap, type: "module" })),
998
+ path: prefix$1("/", getFileName({ id: p2, type: "module" }))
999
+ }))
1000
+ };
1001
+ return update;
1002
+ }
1003
+ default:
1004
+ return p;
1005
+ }
1006
+ }),
1007
+ filter((p) => {
1008
+ switch (p.type) {
1009
+ case "full-reload":
1010
+ return typeof p.path === "undefined";
1011
+ case "prune":
1012
+ return p.paths.length > 0;
1013
+ case "update":
1014
+ return p.updates.length > 0;
1015
+ default:
1016
+ return true;
1017
+ }
1018
+ }),
1019
+ map((data) => {
1020
+ return {
1021
+ type: "custom",
1022
+ event: "crx:content-script-payload",
1023
+ data
1024
+ };
1025
+ })
1026
+ );
1027
+
2533
1028
  function isImporter(file) {
2534
1029
  const seen = /* @__PURE__ */ new Set();
2535
1030
  const pred = (changedNode) => {
@@ -2546,68 +1041,111 @@ function isImporter(file) {
2546
1041
  return pred;
2547
1042
  }
2548
1043
 
2549
- const debug$2 = _debug("hmr");
1044
+ const debug$1 = _debug("hmr");
2550
1045
  const crxRuntimeReload = {
2551
1046
  type: "custom",
2552
1047
  event: "crx:runtime-reload"
2553
1048
  };
2554
1049
  const pluginHMR = () => {
2555
- let files;
1050
+ let inputManifestFiles;
2556
1051
  let decoratedSend;
1052
+ let config;
1053
+ let subs;
2557
1054
  return [
2558
- {
2559
- name: "crx:hmr",
2560
- apply: "build",
2561
- enforce: "post",
2562
- async renderCrxManifest(manifest) {
2563
- if (this.meta.watchMode) {
2564
- files = await manifestFiles(manifest);
2565
- }
2566
- return null;
2567
- }
2568
- },
2569
1055
  {
2570
1056
  name: "crx:hmr",
2571
1057
  apply: "serve",
2572
1058
  enforce: "pre",
2573
- config({ server = {}, ...config }) {
1059
+ async config({ server = {}, ...config2 }) {
2574
1060
  if (server.hmr === false)
2575
1061
  return;
2576
1062
  if (server.hmr === true)
2577
1063
  server.hmr = {};
2578
1064
  server.hmr = server.hmr ?? {};
2579
1065
  server.hmr.host = "localhost";
2580
- return { server, ...config };
1066
+ return { server, ...config2 };
2581
1067
  },
2582
- configResolved(config) {
1068
+ configResolved(_config) {
1069
+ config = _config;
2583
1070
  const { watch = {} } = config.server;
2584
1071
  config.server.watch = watch;
2585
1072
  watch.ignored = watch.ignored ? [...new Set([watch.ignored].flat())] : [];
2586
1073
  const outDir = isAbsolute(config.build.outDir) ? config.build.outDir : join(config.root, config.build.outDir, "**/*");
2587
- watch.ignored.push(outDir);
1074
+ if (!watch.ignored.includes(outDir))
1075
+ watch.ignored.push(outDir);
2588
1076
  },
2589
1077
  configureServer(server) {
2590
1078
  if (server.ws.send !== decoratedSend) {
2591
1079
  const { send } = server.ws;
2592
1080
  decoratedSend = (payload) => {
2593
- hmrPayload$.next(payload);
1081
+ if (payload.type === "error") {
1082
+ send({
1083
+ type: "custom",
1084
+ event: "crx:content-script-payload",
1085
+ data: payload
1086
+ });
1087
+ } else {
1088
+ hmrPayload$.next(payload);
1089
+ }
2594
1090
  send(payload);
2595
1091
  };
2596
1092
  server.ws.send = decoratedSend;
2597
- crxHmrPayload$.subscribe((payload) => {
2598
- send(payload);
2599
- });
1093
+ subs = new Subscription(() => subs = new Subscription());
1094
+ subs.add(fileWriterError$.subscribe(send));
1095
+ subs.add(
1096
+ crxHMRPayload$.subscribe((payload) => {
1097
+ send(payload);
1098
+ })
1099
+ );
2600
1100
  }
2601
1101
  },
2602
- handleHotUpdate({ file, modules, server }) {
2603
- const background = files.background[0] && join(server.config.root, files.background[0]);
2604
- if (background) {
2605
- if (file === background || modules.some(isImporter(background))) {
2606
- debug$2("sending runtime reload");
1102
+ closeBundle() {
1103
+ subs.unsubscribe();
1104
+ },
1105
+ handleHotUpdate({ modules, server }) {
1106
+ const { root } = server.config;
1107
+ const relFiles = /* @__PURE__ */ new Set();
1108
+ for (const m of modules)
1109
+ if (m.id?.startsWith(root)) {
1110
+ relFiles.add(m.id.slice(server.config.root.length));
1111
+ }
1112
+ if (inputManifestFiles.background.length) {
1113
+ const background = prefix$1("/", inputManifestFiles.background[0]);
1114
+ if (relFiles.has(background) || modules.some(isImporter(join(server.config.root, background)))) {
1115
+ debug$1("sending runtime reload");
2607
1116
  server.ws.send(crxRuntimeReload);
2608
1117
  return [];
2609
1118
  }
2610
1119
  }
1120
+ for (const [key, script] of contentScripts)
1121
+ if (key === script.id) {
1122
+ if (relFiles.has(script.id) || modules.some(isImporter(join(server.config.root, script.id)))) {
1123
+ relFiles.forEach((relFile) => update(relFile));
1124
+ }
1125
+ }
1126
+ }
1127
+ },
1128
+ {
1129
+ name: "crx:hmr",
1130
+ apply: "serve",
1131
+ enforce: "post",
1132
+ async transformCrxManifest(manifest) {
1133
+ inputManifestFiles = await manifestFiles(manifest, { cwd: config.root });
1134
+ return null;
1135
+ },
1136
+ renderCrxDevScript(code, { id: _id, type }) {
1137
+ if (type === "module" && _id !== "/@vite/client" && code.includes("createHotContext")) {
1138
+ const id = _id.replace(/t=\d+&/, "");
1139
+ const escaped = id.replace(/([?&.])/g, "\\$1");
1140
+ const regexp = new RegExp(
1141
+ `(?<=createHotContext\\(")${escaped}(?="\\))`
1142
+ );
1143
+ const fileUrl = prefix$1("/", getFileName({ id, type }));
1144
+ const replaced = code.replace(regexp, fileUrl);
1145
+ return replaced;
1146
+ } else {
1147
+ return code;
1148
+ }
2611
1149
  }
2612
1150
  }
2613
1151
  ];
@@ -2616,14 +1154,14 @@ const pluginHMR = () => {
2616
1154
  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";
2617
1155
 
2618
1156
  const pluginName = "crx:html-inline-scripts";
2619
- const debug$1 = _debug(pluginName);
1157
+ const debug = _debug(pluginName);
2620
1158
  const prefix = "@crx/inline-script";
2621
1159
  const isInlineTag = (t) => t.tag === "script" && !t.attrs?.src;
2622
1160
  const toKey = (ctx) => {
2623
1161
  const { dir, name } = parse(ctx.path);
2624
1162
  return join(prefix, dir, name);
2625
1163
  };
2626
- const pluginHtmlAuditor = () => {
1164
+ const pluginHtmlInlineScripts = () => {
2627
1165
  const pages = /* @__PURE__ */ new Map();
2628
1166
  const auditTransformIndexHtml = (p) => {
2629
1167
  let transform;
@@ -2686,10 +1224,12 @@ const pluginHtmlAuditor = () => {
2686
1224
  const p = pages.get(key);
2687
1225
  if (p?.scripts.some(isInlineTag)) {
2688
1226
  const $ = load(html);
2689
- p.scripts.push(...$("script").toArray().map((el) => ({
2690
- tag: "script",
2691
- attrs: { src: $(el).attr("src"), type: "module" }
2692
- })));
1227
+ p.scripts.push(
1228
+ ...$("script").toArray().map((el) => ({
1229
+ tag: "script",
1230
+ attrs: { src: $(el).attr("src"), type: "module" }
1231
+ }))
1232
+ );
2693
1233
  $("script").remove();
2694
1234
  const loader2 = {
2695
1235
  tag: "script",
@@ -2737,15 +1277,19 @@ const pluginHtmlAuditor = () => {
2737
1277
  })}"`;
2738
1278
  return [inline, loader.replace("SCRIPTS", json)].join("\n");
2739
1279
  } else {
2740
- debug$1("page missing %s", id);
1280
+ debug("page missing %s", id);
2741
1281
  }
2742
1282
  }
2743
1283
  }
2744
1284
  };
2745
1285
  };
2746
1286
 
1287
+ var precontrollerJs = "const id = setInterval(() => location.reload(), 100);\nsetTimeout(() => clearInterval(id), 5e3);\n";
1288
+
1289
+ 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";
1290
+
2747
1291
  const { readFile } = promises;
2748
- const pluginManifest = (_manifest) => () => {
1292
+ const pluginManifest = () => {
2749
1293
  let manifest;
2750
1294
  let plugins;
2751
1295
  let refId;
@@ -2755,15 +1299,18 @@ const pluginManifest = (_manifest) => () => {
2755
1299
  name: "crx:manifest-init",
2756
1300
  enforce: "pre",
2757
1301
  async config(config2, env) {
1302
+ const { manifest: _manifest } = await getOptions(config2);
2758
1303
  manifest = await (typeof _manifest === "function" ? _manifest(env) : _manifest);
2759
1304
  if (manifest.manifest_version !== 3)
2760
- throw new Error(`CRXJS does not support Manifest v${manifest.manifest_version}, please use Manifest v3`);
1305
+ throw new Error(
1306
+ `CRXJS does not support Manifest v${manifest.manifest_version}, please use Manifest v3`
1307
+ );
2761
1308
  if (env.command === "serve") {
2762
1309
  const {
2763
1310
  contentScripts: js,
2764
1311
  background: sw,
2765
1312
  html
2766
- } = await manifestFiles(manifest);
1313
+ } = await manifestFiles(manifest, { cwd: config2.root });
2767
1314
  const { entries = [] } = config2.optimizeDeps ?? {};
2768
1315
  let { input = [] } = config2.build?.rollupOptions ?? {};
2769
1316
  if (typeof input === "string")
@@ -2796,15 +1343,16 @@ const pluginManifest = (_manifest) => () => {
2796
1343
  },
2797
1344
  {
2798
1345
  name: "crx:manifest-loader",
2799
- apply: "build",
2800
1346
  enforce: "pre",
2801
- buildStart() {
2802
- refId = this.emitFile({
2803
- type: "chunk",
2804
- id: manifestId,
2805
- name: "crx-manifest.js",
2806
- preserveSignature: "strict"
2807
- });
1347
+ buildStart(options) {
1348
+ if (typeof options.input !== "undefined" && !("ssr" in this)) {
1349
+ refId = this.emitFile({
1350
+ type: "chunk",
1351
+ id: manifestId,
1352
+ name: "crx-manifest.js",
1353
+ preserveSignature: "strict"
1354
+ });
1355
+ }
2808
1356
  },
2809
1357
  resolveId(source) {
2810
1358
  if (source === manifestId)
@@ -2819,13 +1367,22 @@ const pluginManifest = (_manifest) => () => {
2819
1367
  },
2820
1368
  {
2821
1369
  name: "crx:stub-input",
2822
- apply: "build",
2823
1370
  enforce: "pre",
2824
1371
  options({ input, ...options }) {
2825
- return {
2826
- input: isString(input) && input.endsWith("index.html") ? stubId : input,
2827
- ...options
2828
- };
1372
+ let finalInput = input;
1373
+ if (isString(input) && input.endsWith("index.html")) {
1374
+ finalInput = stubId;
1375
+ }
1376
+ if (config.command === "serve") {
1377
+ if (Array.isArray(input)) {
1378
+ finalInput = input.filter((x) => !x.endsWith(".html"));
1379
+ } else if (typeof input === "object") {
1380
+ for (const [key, value] of Object.entries(input))
1381
+ if (value.endsWith(".html"))
1382
+ delete input[key];
1383
+ }
1384
+ }
1385
+ return { input: finalInput, ...options };
2829
1386
  },
2830
1387
  resolveId(source) {
2831
1388
  if (source === stubId)
@@ -2848,12 +1405,13 @@ const pluginManifest = (_manifest) => () => {
2848
1405
  },
2849
1406
  {
2850
1407
  name: "crx:manifest-post",
2851
- apply: "build",
2852
1408
  enforce: "post",
2853
1409
  configResolved(_config) {
2854
1410
  config = _config;
2855
1411
  const plugins2 = config.plugins;
2856
- const crx = plugins2.findIndex(({ name }) => name === "crx:manifest-post");
1412
+ const crx = plugins2.findIndex(
1413
+ ({ name }) => name === "crx:manifest-post"
1414
+ );
2857
1415
  const [plugin] = plugins2.splice(crx, 1);
2858
1416
  plugins2.push(plugin);
2859
1417
  },
@@ -2872,30 +1430,56 @@ const pluginManifest = (_manifest) => () => {
2872
1430
  throw error;
2873
1431
  }
2874
1432
  }
2875
- if (manifest2.content_scripts?.length) {
2876
- manifest2.content_scripts = manifest2.content_scripts.map(({ js = [], ...rest }) => {
2877
- const refJS = js.map((file) => this.emitFile({
2878
- type: "chunk",
2879
- id: file,
2880
- name: basename(file)
2881
- }));
2882
- return { js: refJS, ...rest };
2883
- });
2884
- }
2885
- if (!this.meta.watchMode) {
1433
+ if (config.command === "serve") {
1434
+ if (manifest2.content_scripts)
1435
+ for (const { js = [], matches = [] } of manifest2.content_scripts)
1436
+ for (const id2 of js) {
1437
+ contentScripts.set(
1438
+ prefix$1("/", id2),
1439
+ formatFileData({
1440
+ type: "loader",
1441
+ id: id2,
1442
+ matches,
1443
+ refId: hashScriptId({ type: "loader", id: id2 }),
1444
+ fileName: getFileName({ type: "loader", id: id2 })
1445
+ })
1446
+ );
1447
+ }
1448
+ } else {
1449
+ if (manifest2.content_scripts)
1450
+ for (const { js = [], matches = [] } of manifest2.content_scripts)
1451
+ for (const file of js) {
1452
+ const id2 = join(config.root, file);
1453
+ const refId2 = this.emitFile({
1454
+ type: "chunk",
1455
+ id: id2,
1456
+ name: basename(file)
1457
+ });
1458
+ contentScripts.set(
1459
+ file,
1460
+ formatFileData({
1461
+ type: "loader",
1462
+ id: file,
1463
+ refId: refId2,
1464
+ matches
1465
+ })
1466
+ );
1467
+ }
2886
1468
  if (manifest2.background?.service_worker) {
2887
1469
  const file = manifest2.background.service_worker;
1470
+ const id2 = join(config.root, file);
2888
1471
  const refId2 = this.emitFile({
2889
1472
  type: "chunk",
2890
- id: file,
1473
+ id: id2,
2891
1474
  name: basename(file)
2892
1475
  });
2893
1476
  manifest2.background.service_worker = refId2;
2894
1477
  }
2895
1478
  for (const file of htmlFiles(manifest2)) {
1479
+ const id2 = join(config.root, file);
2896
1480
  this.emitFile({
2897
1481
  type: "chunk",
2898
- id: file,
1482
+ id: id2,
2899
1483
  name: basename(file)
2900
1484
  });
2901
1485
  }
@@ -2907,15 +1491,36 @@ const pluginManifest = (_manifest) => () => {
2907
1491
  const manifestName = this.getFileName(refId);
2908
1492
  const manifestJs = bundle[manifestName];
2909
1493
  let manifest2 = decodeManifest.call(this, manifestJs.code);
2910
- if (manifest2.background?.service_worker && !this.meta.watchMode) {
2911
- const ref = manifest2.background.service_worker;
2912
- const name = this.getFileName(ref);
2913
- manifest2.background.service_worker = name;
1494
+ if (config.command === "serve") {
1495
+ if (manifest2.content_scripts)
1496
+ for (const script of manifest2.content_scripts) {
1497
+ script.js = script.js?.map(
1498
+ (id) => getFileName({ id, type: "loader" })
1499
+ );
1500
+ }
1501
+ } else {
1502
+ if (manifest2.background?.service_worker) {
1503
+ const ref = manifest2.background.service_worker;
1504
+ const name = this.getFileName(ref);
1505
+ manifest2.background.service_worker = name;
1506
+ }
1507
+ manifest2.content_scripts = manifest2.content_scripts?.map(
1508
+ ({ js = [], ...rest }) => {
1509
+ return {
1510
+ js: js.map((id) => {
1511
+ const script = contentScripts.get(id);
1512
+ const fileName = script?.loaderName ?? script?.fileName;
1513
+ if (typeof fileName === "undefined")
1514
+ throw new Error(
1515
+ `Content script fileName is undefined: "${id}"`
1516
+ );
1517
+ return fileName;
1518
+ }),
1519
+ ...rest
1520
+ };
1521
+ }
1522
+ );
2914
1523
  }
2915
- manifest2.content_scripts = manifest2.content_scripts?.map(({ js = [], ...rest }) => {
2916
- const refJS = js.map((ref) => this.getFileName(ref));
2917
- return { js: refJS, ...rest };
2918
- });
2919
1524
  for (const plugin of plugins) {
2920
1525
  try {
2921
1526
  const m = structuredClone(manifest2);
@@ -2925,7 +1530,9 @@ const pluginManifest = (_manifest) => () => {
2925
1530
  const name = `[${plugin.name}]`;
2926
1531
  let message = error;
2927
1532
  if (error instanceof Error) {
2928
- message = colors.red(`${name} ${error.stack ? error.stack : error.message}`);
1533
+ message = colors.red(
1534
+ `${name} ${error.stack ? error.stack : error.message}`
1535
+ );
2929
1536
  } else if (typeof error === "string") {
2930
1537
  message = colors.red(`${name} ${error}`);
2931
1538
  }
@@ -2939,24 +1546,46 @@ const pluginManifest = (_manifest) => () => {
2939
1546
  "rulesets",
2940
1547
  "webAccessibleResources"
2941
1548
  ];
2942
- const files = await manifestFiles(manifest2);
2943
- await Promise.all(assetTypes.map((k) => files[k]).flat().map(async (f) => {
2944
- if (typeof bundle[f] === "undefined") {
2945
- let filename = join(config.root, f);
2946
- if (!existsSync(filename))
2947
- filename = join(config.publicDir, f);
2948
- if (!existsSync(filename))
2949
- throw new Error(`ENOENT: Could not load manifest asset "${f}".
1549
+ const files = await manifestFiles(manifest2, { cwd: config.root });
1550
+ await Promise.all(
1551
+ assetTypes.map((k) => files[k]).flat().map(async (f) => {
1552
+ if (typeof bundle[f] === "undefined") {
1553
+ let filename = join(config.root, f);
1554
+ if (!existsSync(filename))
1555
+ filename = join(config.publicDir, f);
1556
+ if (!existsSync(filename))
1557
+ throw new Error(
1558
+ `ENOENT: Could not load manifest asset "${f}".
2950
1559
  Manifest assets must exist in one of these directories:
2951
1560
  Project root: "${config.root}"
2952
- Public dir: "${config.publicDir}"`);
2953
- this.emitFile({
1561
+ Public dir: "${config.publicDir}"`
1562
+ );
1563
+ this.emitFile({
1564
+ type: "asset",
1565
+ fileName: f,
1566
+ source: await readFile(filename)
1567
+ });
1568
+ }
1569
+ })
1570
+ );
1571
+ if (config.command === "serve" && files.html.length) {
1572
+ const refId2 = this.emitFile({
1573
+ type: "asset",
1574
+ name: "precontroller.js",
1575
+ source: precontrollerJs
1576
+ });
1577
+ const precontrollerJsName = this.getFileName(refId2);
1578
+ files.html.map(
1579
+ (f) => this.emitFile({
2954
1580
  type: "asset",
2955
1581
  fileName: f,
2956
- source: await readFile(filename)
2957
- });
2958
- }
2959
- }));
1582
+ source: precontrollerHtml.replace(
1583
+ "%SCRIPT%",
1584
+ `/${precontrollerJsName}`
1585
+ )
1586
+ })
1587
+ );
1588
+ }
2960
1589
  const manifestJson = bundle["manifest.json"];
2961
1590
  if (typeof manifestJson === "undefined") {
2962
1591
  this.emitFile({
@@ -2973,570 +1602,226 @@ Public dir: "${config.publicDir}"`);
2973
1602
  ];
2974
1603
  };
2975
1604
 
2976
- 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";
2977
-
2978
- 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";
2979
-
2980
- 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";
2981
-
2982
- function getScriptId({
2983
- format,
2984
- id
1605
+ function compileFileResources(fileName, {
1606
+ chunks,
1607
+ files,
1608
+ config
1609
+ }, resources = {
1610
+ assets: /* @__PURE__ */ new Set(),
1611
+ css: /* @__PURE__ */ new Set(),
1612
+ imports: /* @__PURE__ */ new Set()
2985
1613
  }) {
2986
- return createHash$1("sha1").update(format).update(id).digest("base64").replace(/[^A-Za-z0-9]/g, "").slice(0, 8);
2987
- }
2988
- const debug = _debug("content-scripts");
2989
- const dynamicResourcesName = "<dynamic_resource>";
2990
- const pluginResources = ({ contentScripts = {} }) => {
2991
- const { hmrTimeout = 5e3, injectCss = true } = contentScripts;
2992
- const dynamicScriptsById = /* @__PURE__ */ new Map();
2993
- const dynamicScriptsByLoaderRefId = /* @__PURE__ */ new Map();
2994
- const dynamicScriptsByRefId = /* @__PURE__ */ new Map();
2995
- const dynamicScriptsByScriptId = /* @__PURE__ */ new Map();
2996
- function emitDynamicScript(data) {
2997
- if (data.format === "iife") {
2998
- throw new Error(`Dynamic script format IIFE is unimplemented (imported in file: ${data.importer})`.trim());
2999
- } else {
3000
- data.refId = this.emitFile({ type: "chunk", id: data.id });
3001
- dynamicScriptsByRefId.set(data.refId, data);
3002
- }
3003
- if (data.format === "loader") {
3004
- data.loaderRefId = this.emitFile({
3005
- type: "asset",
3006
- name: `content-script-loader.${parse(data.id).name}.js`,
3007
- source: JSON.stringify(data)
3008
- });
3009
- dynamicScriptsByLoaderRefId.set(data.loaderRefId, data);
3010
- }
3011
- }
3012
- async function resolveDynamicScript(_source, importer) {
3013
- if (importer && _source.includes("?script")) {
3014
- const url = new URL(_source, "stub://stub");
3015
- if (url.searchParams.has("scriptId")) {
3016
- const scriptId = url.searchParams.get("scriptId");
3017
- const { finalId } = dynamicScriptsByScriptId.get(scriptId);
3018
- return finalId;
3019
- } else if (url.searchParams.has("script")) {
3020
- const [source] = _source.split("?");
3021
- const resolved = await this.resolve(source, importer, {
3022
- skipSelf: true
3023
- });
3024
- if (!resolved)
3025
- throw new Error(`Could not resolve dynamic script: "${_source}" from "${importer}"`);
3026
- const { id } = resolved;
3027
- let format = "loader";
3028
- if (url.searchParams.has("module")) {
3029
- format = "module";
3030
- } else if (url.searchParams.has("iife")) {
3031
- format = "iife";
3032
- }
3033
- const scriptId = getScriptId({ format, id });
3034
- const finalId = `${id}?scriptId=${scriptId}`;
3035
- const data = dynamicScriptsByScriptId.get(scriptId) ?? {
3036
- format,
3037
- id,
3038
- importer,
3039
- scriptId,
3040
- finalId
3041
- };
3042
- dynamicScriptsByScriptId.set(scriptId, data);
3043
- dynamicScriptsById.set(finalId, data);
3044
- return finalId;
1614
+ const chunk = chunks.get(fileName);
1615
+ if (chunk) {
1616
+ const { modules, facadeModuleId, imports, dynamicImports } = chunk;
1617
+ for (const x of imports)
1618
+ resources.imports.add(x);
1619
+ for (const x of dynamicImports)
1620
+ resources.imports.add(x);
1621
+ for (const x of [...imports, ...dynamicImports])
1622
+ compileFileResources(x, { chunks, files, config }, resources);
1623
+ for (const m of Object.keys(modules))
1624
+ if (m !== facadeModuleId) {
1625
+ const key = prefix$1("/", relative(config.root, m.split("?")[0]));
1626
+ const script = contentScripts.get(key);
1627
+ if (script)
1628
+ if (typeof script.fileName === "undefined") {
1629
+ throw new Error(`Content script fileName for ${m} is undefined`);
1630
+ } else {
1631
+ resources.imports.add(script.fileName);
1632
+ compileFileResources(
1633
+ script.fileName,
1634
+ { chunks, files, config },
1635
+ resources
1636
+ );
1637
+ }
3045
1638
  }
3046
- }
3047
1639
  }
3048
- function loadDynamicScript(id) {
3049
- const data = dynamicScriptsById.get(id);
3050
- if (data)
3051
- return `export default import.meta.CRX_DYNAMIC_SCRIPT_${data.scriptId};`;
1640
+ const file = files.get(fileName);
1641
+ if (file) {
1642
+ const { assets = [], css = [] } = file;
1643
+ for (const x of assets)
1644
+ resources.assets.add(x);
1645
+ for (const x of css)
1646
+ resources.css.add(x);
3052
1647
  }
3053
- let port;
3054
- let server;
3055
- let { preambleCode } = contentScripts;
3056
- let preambleRefId;
3057
- let contentClientRefId;
1648
+ return resources;
1649
+ }
1650
+
1651
+ const defineManifest = (manifest) => manifest;
1652
+ const defineDynamicResource = ({
1653
+ matches = ["http://*/*", "https://*/*"],
1654
+ use_dynamic_url = true
1655
+ }) => ({
1656
+ matches,
1657
+ resources: [DYNAMIC_RESOURCE],
1658
+ use_dynamic_url
1659
+ });
1660
+ const DYNAMIC_RESOURCE = "<dynamic_resource>";
1661
+
1662
+ _debug("web-acc-res");
1663
+ const pluginWebAccessibleResources = () => {
1664
+ let config;
1665
+ let injectCss;
3058
1666
  return [
3059
1667
  {
3060
- name: "crx:content-scripts-pre",
3061
- apply: "build",
3062
- enforce: "pre",
3063
- async fileWriterStart(_server) {
3064
- server = _server;
3065
- port = server.config.server.port.toString();
3066
- if (process.env.NODE_ENV !== "test" && typeof preambleCode === "undefined" && server.config.plugins.some(({ name }) => name.toLowerCase().includes("react"))) {
3067
- try {
3068
- const react = await import('@vitejs/plugin-react');
3069
- preambleCode = react.default.preambleCode;
3070
- } catch (error) {
3071
- preambleCode = false;
3072
- }
3073
- }
3074
- },
3075
- buildStart() {
3076
- if (this.meta.watchMode) {
3077
- if (preambleCode) {
3078
- preambleRefId = this.emitFile({
3079
- type: "chunk",
3080
- id: preambleId,
3081
- name: "content-script-preamble.js"
3082
- });
3083
- }
3084
- contentClientRefId = this.emitFile({
3085
- type: "chunk",
3086
- id: "/@vite/client",
3087
- name: "content-script-client.js"
3088
- });
3089
- }
3090
- },
3091
- resolveId(source) {
3092
- if (source === preambleId)
3093
- return preambleId;
3094
- if (source === contentHmrPortId)
3095
- return contentHmrPortId;
3096
- },
3097
- load(id) {
3098
- if (server && id === preambleId && typeof preambleCode === "string") {
3099
- const defined = preambleCode.replace(/__BASE__/g, server.config.base);
3100
- return defined;
3101
- }
3102
- if (id === contentHmrPortId) {
3103
- const defined = contentHmrPort.replace("__CRX_HMR_TIMEOUT__", JSON.stringify(hmrTimeout));
3104
- return defined;
3105
- }
3106
- }
3107
- },
3108
- {
3109
- name: "crx:dynamic-scripts-load",
1668
+ name: "crx:web-accessible-resources",
3110
1669
  apply: "serve",
3111
- enforce: "pre",
3112
- resolveId: resolveDynamicScript,
3113
- load: loadDynamicScript
3114
- },
3115
- {
3116
- name: "crx:dynamic-scripts-load",
3117
- apply: "build",
3118
- enforce: "pre",
3119
- resolveId(id, importer) {
3120
- if (!this.meta.watchMode)
3121
- return resolveDynamicScript.call(this, id, importer);
3122
- },
3123
- load(id) {
3124
- if (!this.meta.watchMode)
3125
- return loadDynamicScript.call(this, id);
1670
+ enforce: "post",
1671
+ renderCrxManifest(manifest) {
1672
+ manifest.web_accessible_resources = manifest.web_accessible_resources ?? [];
1673
+ manifest.web_accessible_resources = manifest.web_accessible_resources.map(({ resources, ...rest }) => ({
1674
+ resources: resources.filter((r) => r !== DYNAMIC_RESOURCE),
1675
+ ...rest
1676
+ })).filter(({ resources }) => resources.length);
1677
+ manifest.web_accessible_resources.push({
1678
+ use_dynamic_url: true,
1679
+ matches: ["<all_urls>"],
1680
+ resources: ["**/*", "*"]
1681
+ });
1682
+ return manifest;
3126
1683
  }
3127
1684
  },
3128
1685
  {
3129
- name: "crx:dynamic-scripts-build",
1686
+ name: "crx:web-accessible-resources",
3130
1687
  apply: "build",
3131
- buildStart() {
3132
- dynamicScriptsByLoaderRefId.clear();
3133
- dynamicScriptsByRefId.clear();
3134
- for (const [, data] of dynamicScriptsByScriptId) {
3135
- emitDynamicScript.call(this, data);
3136
- }
3137
- },
3138
- async transform(code) {
3139
- if (code.includes("import.meta.CRX_DYNAMIC_SCRIPT_")) {
3140
- const match = code.match(/import.meta.CRX_DYNAMIC_SCRIPT_(.+?);/);
3141
- const index = match.index;
3142
- const [statement, scriptId] = match;
3143
- const data = dynamicScriptsByScriptId.get(scriptId);
3144
- if (!data.refId)
3145
- emitDynamicScript.call(this, data);
3146
- const magic = new MagicString(code);
3147
- magic.overwrite(index, index + statement.length, `import.meta.ROLLUP_FILE_URL_${data.loaderRefId ?? data.refId};`);
3148
- return { code: magic.toString(), map: magic.generateMap() };
3149
- }
3150
- },
3151
- resolveFileUrl({ referenceId, fileName, moduleId }) {
3152
- if (moduleId && referenceId) {
3153
- if (dynamicScriptsByRefId.has(referenceId) || dynamicScriptsByLoaderRefId.has(referenceId)) {
3154
- return `"/${fileName}"`;
3155
- }
3156
- }
1688
+ enforce: "post",
1689
+ async config({ build, ...config2 }, { command }) {
1690
+ const { contentScripts: contentScripts2 = {} } = await getOptions(config2);
1691
+ injectCss = contentScripts2.injectCss ?? true;
1692
+ return { ...config2, build: { ...build, manifest: command === "build" } };
3157
1693
  },
3158
- generateBundle(options, bundle) {
3159
- const preambleName = this.meta.watchMode && preambleRefId ? this.getFileName(preambleRefId) : "";
3160
- const contentClientName = this.meta.watchMode && contentClientRefId ? this.getFileName(contentClientRefId) : "";
3161
- for (const data of dynamicScriptsByScriptId.values()) {
3162
- if (data.refId && data.loaderRefId) {
3163
- const scriptName = this.getFileName(data.refId);
3164
- const loaderName = this.getFileName(data.loaderRefId);
3165
- 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));
3166
- const asset = bundle[loaderName];
3167
- if (asset?.type === "asset")
3168
- asset.source = source;
3169
- }
3170
- }
1694
+ configResolved(_config) {
1695
+ config = _config;
3171
1696
  },
3172
- writeBundle() {
3173
- for (const [, data] of dynamicScriptsByScriptId) {
3174
- if (data.refId) {
3175
- data.fileName = this.getFileName(data.refId);
3176
- delete data.refId;
3177
- }
3178
- if (data.loaderRefId) {
3179
- data.loaderName = this.getFileName(data.loaderRefId);
3180
- delete data.loaderRefId;
3181
- }
3182
- }
3183
- }
3184
- },
3185
- {
3186
- name: "crx:dynamic-scripts-serve",
3187
- apply: "serve",
3188
- configureServer(server2) {
3189
- server2.middlewares.use(injector((req) => {
3190
- return !!req.url?.includes("?scriptId");
3191
- }, async (content, req, res, callback) => {
3192
- const code = isString(content) ? content : content.toString();
3193
- if (code.includes("import.meta.CRX_DYNAMIC_SCRIPT_")) {
3194
- const matches = Array.from(code.matchAll(/import.meta.CRX_DYNAMIC_SCRIPT_(.+?);/g)).map((m) => ({
3195
- statement: m[0],
3196
- index: m.index,
3197
- data: dynamicScriptsByScriptId.get(m[1])
3198
- }));
3199
- if (matches.some(({ data }) => data.refId))
3200
- await filesReady();
3201
- if (matches.some(({ data }) => !(data.loaderName ?? data.fileName))) {
3202
- await rebuildFiles();
3203
- server2.ws.send(crxRuntimeReload);
3204
- }
3205
- const magic = new MagicString(code);
3206
- for (const { index, statement, data } of matches)
3207
- if (typeof index === "number") {
3208
- magic.overwrite(index, index + statement.length, `"/${data.loaderName ?? data.fileName}"`);
3209
- }
3210
- callback(null, magic.toString());
3211
- } else {
3212
- callback(null, code);
1697
+ async renderCrxManifest(manifest, bundle) {
1698
+ const { web_accessible_resources: _war = [] } = manifest;
1699
+ const dynamicScriptMatches = /* @__PURE__ */ new Set();
1700
+ let dynamicScriptDynamicUrl = false;
1701
+ const web_accessible_resources = [];
1702
+ for (const r of _war) {
1703
+ const i = r.resources.indexOf(DYNAMIC_RESOURCE);
1704
+ if (i > -1 && isResourceByMatch(r)) {
1705
+ r.resources = [...r.resources];
1706
+ r.resources.splice(i, 1);
1707
+ for (const p of r.matches)
1708
+ dynamicScriptMatches.add(p);
1709
+ dynamicScriptDynamicUrl = r.use_dynamic_url ?? false;
3213
1710
  }
3214
- }));
3215
- }
3216
- },
3217
- {
3218
- name: "crx:content-script-resources",
3219
- apply: "build",
3220
- enforce: "post",
3221
- config({ build, ...config }, { command }) {
3222
- return { ...config, build: { ...build, manifest: command === "build" } };
3223
- },
3224
- renderCrxManifest(manifest, bundle) {
3225
- manifest.web_accessible_resources = manifest.web_accessible_resources ?? [];
3226
- if (manifest.content_scripts?.length || dynamicScriptsByRefId.size)
3227
- if (this.meta.watchMode) {
3228
- manifest.web_accessible_resources = manifest.web_accessible_resources.map(({ resources, ...rest }) => ({
3229
- resources: resources.filter((r) => r !== dynamicResourcesName),
3230
- ...rest
3231
- })).filter(({ resources }) => resources.length);
3232
- manifest.web_accessible_resources.push({
3233
- use_dynamic_url: true,
3234
- matches: ["<all_urls>"],
3235
- resources: ["**/*", "*"]
3236
- });
3237
- } else {
3238
- const vmAsset = bundle["manifest.json"];
3239
- if (!vmAsset)
3240
- throw new Error("vite manifest is missing");
3241
- const viteManifest = JSON.parse(vmAsset.source);
3242
- debug("vite manifest %O", viteManifest);
3243
- if (Object.keys(viteManifest).length === 0)
3244
- return;
3245
- const filesByName = /* @__PURE__ */ new Map();
3246
- for (const file of Object.values(viteManifest))
3247
- filesByName.set(file.file, file);
3248
- const chunksById = /* @__PURE__ */ new Map();
3249
- for (const [name, chunk] of Object.entries(bundle))
3250
- if (chunk.type === "chunk" && chunk.facadeModuleId)
3251
- chunksById.set(chunk.facadeModuleId, name);
3252
- const getChunkResources = (chunk) => {
3253
- const chunks = /* @__PURE__ */ new Set();
3254
- const assets = /* @__PURE__ */ new Set();
3255
- if (chunk.type === "asset")
3256
- return { chunks, assets };
3257
- const { dynamicImports, imports, modules } = chunk;
3258
- for (const i of dynamicImports)
3259
- chunks.add(i);
3260
- for (const i of imports)
3261
- chunks.add(i);
3262
- for (const id of Object.keys(modules))
3263
- if (dynamicScriptsById.has(id)) {
3264
- const data = dynamicScriptsById.get(id);
3265
- const fileName = this.getFileName(data.refId);
3266
- const chunk2 = bundle[fileName];
3267
- if (chunk2.type === "chunk")
3268
- chunks.add(fileName);
3269
- else
3270
- assets.add(fileName);
3271
- }
3272
- return { chunks, assets };
3273
- };
3274
- const getResources = (name, sets = {
3275
- assets: /* @__PURE__ */ new Set(),
3276
- css: /* @__PURE__ */ new Set(),
3277
- imports: /* @__PURE__ */ new Set()
3278
- }) => {
3279
- const {
3280
- assets = [],
3281
- css = [],
3282
- dynamicImports = [],
3283
- imports = [],
3284
- file
3285
- } = filesByName.get(name) ?? viteManifest[name] ?? {};
3286
- const chunk = bundle[file];
3287
- if (chunk?.type === "chunk") {
3288
- const r = getChunkResources(chunk);
3289
- assets.push(...r.assets);
3290
- for (const chunk2 of r.chunks) {
3291
- sets.imports.add(chunk2);
3292
- getResources(chunk2, sets);
3293
- }
3294
- }
3295
- for (const a of assets)
3296
- sets.assets.add(a);
3297
- for (const c of css)
3298
- sets.css.add(c);
3299
- for (const key of [...dynamicImports, ...imports]) {
3300
- const i = viteManifest[key].file;
3301
- sets.imports.add(i);
3302
- getResources(key, sets);
3303
- }
3304
- return sets;
3305
- };
3306
- for (const script of manifest.content_scripts ?? [])
3307
- if (script.js?.length) {
3308
- for (const name of script.js)
3309
- if (script.matches?.length) {
3310
- const { assets, css, imports } = getResources(name);
3311
- imports.add(name);
3312
- const resource = {
3313
- matches: script.matches,
3314
- resources: [...assets, ...imports],
3315
- use_dynamic_url: true
3316
- };
3317
- if (css.size)
3318
- if (injectCss) {
3319
- script.css = script.css ?? [];
3320
- script.css.push(...css);
3321
- } else {
3322
- resource.resources.push(...css);
3323
- }
3324
- if (resource.resources.length) {
3325
- resource.matches = resource.matches.map(stubMatchPattern);
3326
- manifest.web_accessible_resources.push(resource);
3327
- }
1711
+ if (r.resources.length > 0)
1712
+ web_accessible_resources.push(r);
1713
+ }
1714
+ if (dynamicScriptMatches.size === 0) {
1715
+ dynamicScriptMatches.add("http://*/*");
1716
+ dynamicScriptMatches.add("https://*/*");
1717
+ }
1718
+ if (contentScripts.size > 0) {
1719
+ const viteManifest = parseJsonAsset(
1720
+ bundle,
1721
+ "manifest.json"
1722
+ );
1723
+ const viteFiles = /* @__PURE__ */ new Map();
1724
+ for (const [, file] of Object.entries(viteManifest))
1725
+ viteFiles.set(file.file, file);
1726
+ if (viteFiles.size === 0)
1727
+ return null;
1728
+ const bundleChunks = /* @__PURE__ */ new Map();
1729
+ for (const chunk of Object.values(bundle))
1730
+ if (chunk.type === "chunk")
1731
+ bundleChunks.set(chunk.fileName, chunk);
1732
+ const moduleScriptResources = /* @__PURE__ */ new Map();
1733
+ for (const [
1734
+ key,
1735
+ { id, fileName, matches, type, isDynamicScript = false }
1736
+ ] of contentScripts)
1737
+ if (key === id) {
1738
+ if (isDynamicScript || matches.length)
1739
+ if (typeof fileName === "undefined") {
1740
+ throw new Error(
1741
+ `Content script filename is undefined for "${id}"`
1742
+ );
1743
+ } else {
1744
+ const { assets, css, imports } = compileFileResources(
1745
+ fileName,
1746
+ { chunks: bundleChunks, files: viteFiles, config }
1747
+ );
1748
+ contentScripts.get(key).css = [...css];
1749
+ if (type === "loader")
1750
+ imports.add(fileName);
1751
+ const resource = {
1752
+ matches: isDynamicScript ? [...dynamicScriptMatches] : matches,
1753
+ resources: [...assets, ...imports],
1754
+ use_dynamic_url: isDynamicScript ? dynamicScriptDynamicUrl : true
1755
+ };
1756
+ if (isDynamicScript || !injectCss) {
1757
+ resource.resources.push(...css);
3328
1758
  }
3329
- }
3330
- const dynamicResourceSet = /* @__PURE__ */ new Set();
3331
- for (const [refId, { format }] of dynamicScriptsByRefId)
3332
- if (format === "loader") {
3333
- const name = this.getFileName(refId);
3334
- const { assets, css, imports } = getResources(name);
3335
- dynamicResourceSet.add(name);
3336
- for (const a of assets)
3337
- dynamicResourceSet.add(a);
3338
- for (const c of css)
3339
- dynamicResourceSet.add(c);
3340
- for (const i of imports)
3341
- dynamicResourceSet.add(i);
3342
- }
3343
- if (dynamicResourceSet.size) {
3344
- let resource = manifest.web_accessible_resources.find(({ resources: [r] }) => r === dynamicResourcesName);
3345
- if (!resource) {
3346
- resource = {
3347
- resources: [dynamicResourcesName],
3348
- matches: ["http://*/*", "https://*/*"]
3349
- };
3350
- manifest.web_accessible_resources.push(resource);
3351
- }
3352
- resource.resources = [...dynamicResourceSet];
1759
+ if (resource.resources.length)
1760
+ if (type === "module") {
1761
+ moduleScriptResources.set(fileName, resource);
1762
+ } else {
1763
+ resource.matches = resource.matches.map(
1764
+ getMatchPatternOrigin
1765
+ );
1766
+ web_accessible_resources.push(resource);
1767
+ }
1768
+ }
3353
1769
  }
1770
+ for (const r of web_accessible_resources)
1771
+ if (isResourceByMatch(r))
1772
+ for (const res of r.resources)
1773
+ moduleScriptResources.delete(res);
1774
+ web_accessible_resources.push(...moduleScriptResources.values());
1775
+ }
1776
+ const hashedResources = /* @__PURE__ */ new Map();
1777
+ const combinedResources = [];
1778
+ for (const r of web_accessible_resources)
1779
+ if (isResourceByMatch(r)) {
1780
+ const { matches, resources, use_dynamic_url = false } = r;
1781
+ const key = JSON.stringify([use_dynamic_url, matches.sort()]);
1782
+ const combined = hashedResources.get(key) ?? /* @__PURE__ */ new Set();
1783
+ for (const res of resources)
1784
+ combined.add(res);
1785
+ hashedResources.set(key, combined);
1786
+ } else {
1787
+ combinedResources.push(r);
3354
1788
  }
3355
- if (manifest.web_accessible_resources?.length) {
3356
- const war = manifest.web_accessible_resources;
3357
- manifest.web_accessible_resources = [];
3358
- const map = /* @__PURE__ */ new Map();
3359
- for (const r of war)
3360
- if (isResourceByMatch(r)) {
3361
- const { matches, resources, use_dynamic_url = false } = r;
3362
- const key = [use_dynamic_url, matches.sort()].map((x) => JSON.stringify(x)).join("::");
3363
- const set = map.get(key) ?? /* @__PURE__ */ new Set();
3364
- resources.forEach((r2) => set.add(r2));
3365
- map.set(key, set);
3366
- } else {
3367
- manifest.web_accessible_resources.push(r);
3368
- }
3369
- for (const [key, set] of map) {
3370
- const [use_dynamic_url, matches] = key.split("::").map((x) => JSON.parse(x));
3371
- manifest.web_accessible_resources.push({
1789
+ for (const [key, resources] of hashedResources)
1790
+ if (resources.size > 0) {
1791
+ const [use_dynamic_url, matches] = JSON.parse(key);
1792
+ combinedResources.push({
3372
1793
  matches,
3373
- resources: [...set],
1794
+ resources: [...resources],
3374
1795
  use_dynamic_url
3375
1796
  });
3376
1797
  }
3377
- } else {
1798
+ if (combinedResources.length === 0)
3378
1799
  delete manifest.web_accessible_resources;
3379
- }
3380
- return manifest;
3381
- }
3382
- },
3383
- {
3384
- name: "crx:content-scripts-post",
3385
- apply: "build",
3386
- enforce: "post",
3387
- renderCrxManifest(manifest, bundle) {
3388
- if (this.meta.watchMode && typeof port === "undefined")
3389
- throw new Error("server port is undefined");
3390
- const preambleName = this.meta.watchMode && preambleRefId ? this.getFileName(preambleRefId) : "";
3391
- const contentClientName = this.meta.watchMode && contentClientRefId ? this.getFileName(contentClientRefId) : "";
3392
- if (!manifest.content_scripts?.length && !dynamicScriptsByRefId.size) {
3393
- delete bundle[contentClientName];
3394
- return manifest;
3395
- }
3396
- manifest.content_scripts = manifest.content_scripts?.map(({ js, ...rest }) => ({
3397
- js: js?.map((f) => {
3398
- const name = `content-script-loader.${parse(f).name}.js`;
3399
- 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));
3400
- const refId = this.emitFile({
3401
- type: "asset",
3402
- name,
3403
- source
3404
- });
3405
- return this.getFileName(refId);
3406
- }),
3407
- ...rest
3408
- }));
1800
+ else
1801
+ manifest.web_accessible_resources = combinedResources;
3409
1802
  return manifest;
3410
1803
  }
3411
1804
  }
3412
1805
  ];
3413
1806
  };
3414
1807
 
3415
- 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";
3416
-
3417
- function defineClientValues(code, config) {
3418
- let options = config.server.hmr;
3419
- options = options && typeof options !== "boolean" ? options : {};
3420
- const host = options.host || null;
3421
- const protocol = options.protocol || null;
3422
- const timeout = options.timeout || 3e4;
3423
- const overlay = options.overlay !== false;
3424
- let hmrPort;
3425
- if (isObject(config.server.hmr)) {
3426
- hmrPort = config.server.hmr.clientPort || config.server.hmr.port;
3427
- }
3428
- if (config.server.middlewareMode) {
3429
- hmrPort = String(hmrPort || 24678);
3430
- } else {
3431
- hmrPort = String(hmrPort || options.port || config.server.port);
3432
- }
3433
- let hmrBase = config.base;
3434
- if (options.path) {
3435
- hmrBase = join(hmrBase, options.path);
3436
- }
3437
- if (hmrBase !== "/") {
3438
- hmrPort = normalize(`${hmrPort}${hmrBase}`);
3439
- }
3440
- 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()));
3441
- function serializeDefine(define) {
3442
- let res = `{`;
3443
- for (const key in define) {
3444
- const val = define[key];
3445
- res += `${JSON.stringify(key)}: ${typeof val === "string" ? `(${val})` : JSON.stringify(val)}, `;
3446
- }
3447
- return res + `}`;
3448
- }
3449
- }
3450
-
3451
- const pluginBackground = () => {
3452
- let port;
3453
- let server;
1808
+ const crx = (options) => {
3454
1809
  return [
3455
- {
3456
- name: "crx:background-client",
3457
- apply: "serve",
3458
- configureServer(_server) {
3459
- server = _server;
3460
- },
3461
- resolveId(source) {
3462
- if (source === `/${workerClientId}`)
3463
- return workerClientId;
3464
- },
3465
- load(id) {
3466
- if (id === workerClientId) {
3467
- const base = `http://localhost:${server.config.server.port}/`;
3468
- return defineClientValues(workerHmrClient.replace("__BASE__", JSON.stringify(base)), server.config);
3469
- }
3470
- }
3471
- },
3472
- {
3473
- name: "crx:background-loader-file",
3474
- apply: "build",
3475
- enforce: "post",
3476
- fileWriterStart(server2) {
3477
- port = server2.config.server.port.toString();
3478
- },
3479
- renderCrxManifest(manifest) {
3480
- const worker = manifest.background?.service_worker;
3481
- let loader;
3482
- if (this.meta.watchMode) {
3483
- if (typeof port === "undefined")
3484
- throw new Error("server port is undefined in watch mode");
3485
- loader = `import 'http:/localhost:${port}/@vite/env';
3486
- `;
3487
- loader += `import 'http://localhost:${port}${workerClientId}';
3488
- `;
3489
- if (worker)
3490
- loader += `import 'http://localhost:${port}/${worker}';
3491
- `;
3492
- } else if (worker) {
3493
- loader = `import './${worker}';
3494
- `;
3495
- } else {
3496
- return null;
3497
- }
3498
- const refId = this.emitFile({
3499
- type: "asset",
3500
- fileName: "service-worker-loader.js",
3501
- source: loader
3502
- });
3503
- manifest.background = {
3504
- service_worker: this.getFileName(refId),
3505
- type: "module"
3506
- };
3507
- return manifest;
3508
- }
3509
- }
3510
- ];
3511
- };
3512
-
3513
- const defineManifest = (manifest) => manifest;
3514
- const defineDynamicResource = ({
3515
- matches = ["http://*/*", "https://*/*"],
3516
- use_dynamic_url = true
3517
- }) => ({
3518
- matches,
3519
- resources: [dynamicResourcesName],
3520
- use_dynamic_url
3521
- });
3522
-
3523
- function init(options, plugins) {
3524
- return plugins.map((p) => p?.(options)).flat().filter((p) => !!p && typeof p.name === "string");
3525
- }
3526
- const crx = ({
3527
- manifest,
3528
- ...options
3529
- }) => {
3530
- const plugins = init(options, [
3531
- pluginHMR,
3532
- pluginHtmlAuditor,
3533
- pluginResources,
3534
- pluginBackground,
3535
- pluginManifest(manifest)
3536
- ]);
3537
- plugins.unshift(...init(options, [pluginFileWriter(plugins)]));
3538
- return plugins;
1810
+ pluginOptionsProvider(options),
1811
+ pluginBackground(),
1812
+ pluginContentScripts(),
1813
+ pluginDeclaredContentScripts(),
1814
+ pluginDynamicContentScripts(),
1815
+ pluginFileWriter(),
1816
+ pluginFileWriterPublic(),
1817
+ pluginFileWriterPolyfill(),
1818
+ pluginHtmlInlineScripts(),
1819
+ pluginWebAccessibleResources(),
1820
+ pluginContentScriptsCss(),
1821
+ pluginHMR(),
1822
+ pluginManifest()
1823
+ ].flat();
3539
1824
  };
3540
1825
  const chromeExtension = crx;
3541
1826
 
3542
- export { chromeExtension, crx, defineDynamicResource, defineManifest, filesReady, rebuildFiles };
1827
+ export { allFilesReady, chromeExtension, crx, defineDynamicResource, defineManifest, fileReady as filesReady };