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