@henrikvilhelmberglund/vite-plugin-monkey 4.0.4

Sign up to get free protection for your applications and to get access to all the features.
@@ -0,0 +1,2487 @@
1
+ var __defProp = Object.defineProperty;
2
+ var __export = (target, all) => {
3
+ for (var name in all)
4
+ __defProp(target, name, { get: all[name], enumerable: true });
5
+ };
6
+
7
+ // src/node/_logger.ts
8
+ import pc from "picocolors";
9
+ var log = (tag, message, options) => {
10
+ console.log(
11
+ [
12
+ ((options == null ? void 0 : options.time) ?? false) === true ? pc.dim((/* @__PURE__ */ new Date()).toLocaleTimeString()) : "",
13
+ pc.bold(pc.blue(`[${tag}]`)),
14
+ message
15
+ ].filter((s) => s).join(" ")
16
+ );
17
+ };
18
+ var info = (tag, message, options) => {
19
+ log(tag, pc.white(message), options);
20
+ };
21
+ var warn = (tag, message, options) => {
22
+ log(tag, pc.yellow(message), options);
23
+ };
24
+ var error = (tag, message, options) => {
25
+ log(tag, pc.red(message), options);
26
+ };
27
+ var createLogger = (tag) => ({
28
+ info: async (message, options) => {
29
+ info(tag, message, options);
30
+ },
31
+ warn: async (message, options) => {
32
+ warn(tag, message, options);
33
+ },
34
+ error: async (message, options) => {
35
+ error(tag, message, options);
36
+ }
37
+ });
38
+ var logger = createLogger("plugin-monkey");
39
+
40
+ // src/node/_util.ts
41
+ import * as acornWalk from "acorn-walk";
42
+ import { readFileSync } from "fs";
43
+ import fs from "fs/promises";
44
+ import path from "path";
45
+ import { normalizePath, transformWithEsbuild } from "vite";
46
+ import { resolve } from "import-meta-resolve";
47
+ import { pathToFileURL } from "url";
48
+
49
+ // src/node/unimport.ts
50
+ var GmApiNames = [
51
+ "GM",
52
+ "GM_addElement",
53
+ "GM_addStyle",
54
+ "GM_addValueChangeListener",
55
+ "GM_cookie",
56
+ "GM_deleteValue",
57
+ "GM_download",
58
+ "GM_getResourceText",
59
+ "GM_getResourceURL",
60
+ "GM_getTab",
61
+ "GM_getTabs",
62
+ "GM_getValue",
63
+ "GM_info",
64
+ "GM_listValues",
65
+ "GM_log",
66
+ "GM_notification",
67
+ "GM_openInTab",
68
+ "GM_registerMenuCommand",
69
+ "GM_removeValueChangeListener",
70
+ "GM_saveTab",
71
+ "GM_setClipboard",
72
+ "GM_setValue",
73
+ "GM_unregisterMenuCommand",
74
+ "GM_xmlhttpRequest",
75
+ "GM_webRequest"
76
+ ];
77
+ var preset = {
78
+ from: "vite-plugin-monkey/dist/client",
79
+ imports: [...GmApiNames, "unsafeWindow", "monkeyWindow"]
80
+ };
81
+
82
+ // src/node/_util.ts
83
+ var get_vite_start_time = () => {
84
+ const n = Reflect.get(globalThis, "__vite_start_time") ?? 0;
85
+ if (typeof n != "number") {
86
+ return 0;
87
+ } else {
88
+ return n;
89
+ }
90
+ };
91
+ var isFirstBoot = (n = 1e3) => get_vite_start_time() < n;
92
+ var GM_keywords = [
93
+ "GM.addElement",
94
+ "GM.addStyle",
95
+ "GM.deleteValue",
96
+ "GM.getResourceUrl",
97
+ "GM.getValue",
98
+ "GM.info",
99
+ "GM.listValues",
100
+ "GM.notification",
101
+ "GM.openInTab",
102
+ "GM.registerMenuCommand",
103
+ "GM.setClipboard",
104
+ "GM.setValue",
105
+ "GM.xmlHttpRequest",
106
+ "GM.cookie",
107
+ ...GmApiNames.filter((s) => s.startsWith("GM_")),
108
+ "unsafeWindow",
109
+ "window.close",
110
+ "window.focus",
111
+ "window.onurlchange"
112
+ ];
113
+ var projectPkg = (() => {
114
+ var _a, _b, _c, _d, _e;
115
+ let rawTarget = {};
116
+ try {
117
+ rawTarget = JSON.parse(
118
+ readFileSync(path.resolve(process.cwd(), "package.json"), "utf-8")
119
+ );
120
+ } catch {
121
+ rawTarget = {};
122
+ }
123
+ const target = {
124
+ name: "monkey",
125
+ version: "1.0.0"
126
+ };
127
+ Object.entries(rawTarget).forEach(([k, v]) => {
128
+ if (typeof v == "string") {
129
+ Reflect.set(target, k, v);
130
+ }
131
+ });
132
+ if (rawTarget.author instanceof Object && typeof ((_a = rawTarget.author) == null ? void 0 : _a.name) == "string") {
133
+ target.author = (_b = rawTarget.author) == null ? void 0 : _b.name;
134
+ }
135
+ if (rawTarget.bugs instanceof Object && typeof ((_c = rawTarget.bugs) == null ? void 0 : _c.url) == "string") {
136
+ target.bugs = (_d = rawTarget.bugs) == null ? void 0 : _d.url;
137
+ }
138
+ if (rawTarget.repository instanceof Object && typeof ((_e = rawTarget.repository) == null ? void 0 : _e.url) == "string") {
139
+ const { url } = rawTarget.repository;
140
+ if (url.startsWith("http")) {
141
+ target.repository = url;
142
+ } else if (url.startsWith("git+http")) {
143
+ target.repository = url.slice(4);
144
+ }
145
+ }
146
+ return target;
147
+ })();
148
+ var compatResolve = (id) => {
149
+ return resolve(id, pathToFileURL(process.cwd() + "/any.js").href);
150
+ };
151
+ var existFile = async (path5) => {
152
+ try {
153
+ return (await fs.stat(path5)).isFile();
154
+ } catch {
155
+ return false;
156
+ }
157
+ };
158
+ var resolvePackageJsonFromPath = async (name) => {
159
+ const p = normalizePath(process.cwd()).split("/");
160
+ for (let i = p.length; i > 0; i--) {
161
+ const p2 = `${p.slice(0, i).join("/")}/node_modules/${name}/package.json`;
162
+ if (await existFile(p2)) {
163
+ return p2;
164
+ }
165
+ }
166
+ };
167
+ var getModuleRealInfo = async (importName) => {
168
+ const importName2 = normalizePath(importName.split("?")[0]);
169
+ const resolveName = normalizePath(compatResolve(importName2)).replace(
170
+ /.*\/node_modules\/[^/]+\//,
171
+ ""
172
+ );
173
+ let version = void 0;
174
+ const nameList = importName2.split("/");
175
+ let pkgName = importName2;
176
+ while (nameList.length > 0) {
177
+ pkgName = nameList.join("/");
178
+ const filePath = await (async () => {
179
+ const p = await resolvePackageJsonFromPath(pkgName);
180
+ if (p) {
181
+ return p;
182
+ }
183
+ try {
184
+ return compatResolve(`${pkgName}/package.json`);
185
+ } catch {
186
+ return void 0;
187
+ }
188
+ })();
189
+ if (filePath === void 0 || !await existFile(filePath)) {
190
+ nameList.pop();
191
+ continue;
192
+ }
193
+ const modulePack = JSON.parse(
194
+ await fs.readFile(filePath, "utf-8")
195
+ );
196
+ version = modulePack.version;
197
+ break;
198
+ }
199
+ if (version === void 0) {
200
+ logger.warn(
201
+ `not found module ${importName2} version, use ${importName2}@latest`
202
+ );
203
+ pkgName = importName2;
204
+ version = "latest";
205
+ }
206
+ return { version, name: pkgName, resolveName };
207
+ };
208
+ var miniCode = async (code, type = "js") => {
209
+ return (await transformWithEsbuild(code, "any_name." + type, {
210
+ minify: true,
211
+ sourcemap: false,
212
+ legalComments: "none"
213
+ })).code.trimEnd();
214
+ };
215
+ var toValidURL = (url) => {
216
+ if (typeof url != "string")
217
+ return;
218
+ try {
219
+ return new URL(url);
220
+ } catch {
221
+ }
222
+ };
223
+ var moduleExportExpressionWrapper = (expression) => {
224
+ let n = 0;
225
+ let identifier = ``;
226
+ while (expression.includes(identifier)) {
227
+ identifier = `_${(n || ``).toString(16)}`;
228
+ n++;
229
+ }
230
+ return `(()=>{const ${identifier}=${expression};('default' in ${identifier})||(${identifier}.default=${identifier});return ${identifier}})()`;
231
+ };
232
+ var cyrb53hash = (str = ``, seed = 0) => {
233
+ let h1 = 3735928559 ^ seed, h2 = 1103547991 ^ seed;
234
+ for (let i = 0, ch; i < str.length; i++) {
235
+ ch = str.charCodeAt(i);
236
+ h1 = Math.imul(h1 ^ ch, 2654435761);
237
+ h2 = Math.imul(h2 ^ ch, 1597334677);
238
+ }
239
+ h1 = Math.imul(h1 ^ h1 >>> 16, 2246822507);
240
+ h1 ^= Math.imul(h2 ^ h2 >>> 13, 3266489909);
241
+ h2 = Math.imul(h2 ^ h2 >>> 16, 2246822507);
242
+ h2 ^= Math.imul(h1 ^ h1 >>> 13, 3266489909);
243
+ return (4294967296 * (2097151 & h2) + (h1 >>> 0)).toString(36).substring(0, 8);
244
+ };
245
+ async function* walk(dirPath) {
246
+ const pathnames = (await fs.readdir(dirPath)).map(
247
+ (s) => path.join(dirPath, s)
248
+ );
249
+ while (pathnames.length > 0) {
250
+ const pathname = pathnames.pop();
251
+ const state = await fs.lstat(pathname);
252
+ if (state.isFile()) {
253
+ yield pathname;
254
+ } else if (state.isDirectory()) {
255
+ pathnames.push(
256
+ ...(await fs.readdir(pathname)).map((s) => path.join(pathname, s))
257
+ );
258
+ }
259
+ }
260
+ }
261
+ var collectGrant = (context, bundleOrCode) => {
262
+ const codes = [];
263
+ if (typeof bundleOrCode == "string") {
264
+ codes.push(bundleOrCode);
265
+ } else if (Array.isArray(bundleOrCode)) {
266
+ codes.push(...bundleOrCode);
267
+ } else {
268
+ Object.values(bundleOrCode).forEach((chunk) => {
269
+ if (chunk.type == "chunk") {
270
+ codes.push(chunk.code);
271
+ }
272
+ });
273
+ }
274
+ const unusedMembers = new Set(GM_keywords.filter((s) => s.includes(`.`)));
275
+ const unusedIdentifiers = new Set(
276
+ GM_keywords.filter((s) => !s.includes(`.`))
277
+ );
278
+ const usedGm = /* @__PURE__ */ new Set();
279
+ for (const code of codes) {
280
+ if (!code.trim())
281
+ continue;
282
+ const ast = context.parse(code);
283
+ acornWalk.simple(
284
+ ast,
285
+ {
286
+ MemberExpression(node) {
287
+ var _a, _b;
288
+ if (unusedMembers.size == 0)
289
+ return;
290
+ const memberName = ((_a = node.object) == null ? void 0 : _a.name) + "." + ((_b = node.property) == null ? void 0 : _b.name);
291
+ for (const unusedName of unusedMembers.values()) {
292
+ if (memberName.endsWith(unusedName)) {
293
+ usedGm.add(unusedName);
294
+ unusedMembers.delete(unusedName);
295
+ break;
296
+ }
297
+ }
298
+ },
299
+ Identifier(node) {
300
+ if (unusedIdentifiers.size == 0)
301
+ return;
302
+ const identifier = node.name;
303
+ if (unusedIdentifiers.has(identifier)) {
304
+ usedGm.add(identifier);
305
+ unusedIdentifiers.delete(identifier);
306
+ }
307
+ }
308
+ },
309
+ { ...acornWalk.base }
310
+ );
311
+ if (unusedMembers.size == 0 && unusedIdentifiers.size == 0) {
312
+ break;
313
+ }
314
+ }
315
+ return usedGm;
316
+ };
317
+ var getInjectCssCode = async (finalOption, rawBundle) => {
318
+ const cssTexts = [];
319
+ Object.entries(rawBundle).forEach(([k, v]) => {
320
+ if (v.type == "asset" && k.endsWith(".css")) {
321
+ cssTexts.push(v.source.toString());
322
+ delete rawBundle[k];
323
+ }
324
+ });
325
+ const css = cssTexts.join("").trim();
326
+ if (css) {
327
+ return await finalOption.cssSideEffects(` ` + css + ` `);
328
+ }
329
+ };
330
+
331
+ // src/node/cdn.ts
332
+ var cdn_exports = {};
333
+ __export(cdn_exports, {
334
+ baomitu: () => baomitu,
335
+ bdstatic: () => bdstatic,
336
+ bootcdn: () => bootcdn,
337
+ bytecdntp: () => bytecdntp,
338
+ cdnjs: () => cdnjs,
339
+ elemecdn: () => elemecdn,
340
+ jsdelivr: () => jsdelivr,
341
+ jsdelivrFastly: () => jsdelivrFastly,
342
+ npmmirror: () => npmmirror,
343
+ staticfile: () => staticfile,
344
+ unpkg: () => unpkg,
345
+ zhimg: () => zhimg
346
+ });
347
+ var jsdelivr = (exportVarName = "", pathname = "") => {
348
+ return [
349
+ exportVarName,
350
+ (version, name, _importName = "", resolveName = "") => {
351
+ const p = pathname || resolveName;
352
+ if (p) {
353
+ return `https://cdn.jsdelivr.net/npm/${name}@${version}/${p}`;
354
+ } else {
355
+ return `https://cdn.jsdelivr.net/npm/${name}@${version}`;
356
+ }
357
+ }
358
+ ];
359
+ };
360
+ var jsdelivrFastly = (exportVarName = "", pathname = "") => {
361
+ return [
362
+ exportVarName,
363
+ (version, name, _importName = "", resolveName = "") => {
364
+ const p = pathname || resolveName;
365
+ if (p) {
366
+ return `https://fastly.jsdelivr.net/npm/${name}@${version}/${p}`;
367
+ } else {
368
+ return `https://fastly.jsdelivr.net/npm/${name}@${version}`;
369
+ }
370
+ }
371
+ ];
372
+ };
373
+ var unpkg = (exportVarName = "", pathname = "") => {
374
+ return [
375
+ exportVarName,
376
+ (version, name, _importName = "", resolveName = "") => {
377
+ const p = pathname || resolveName;
378
+ if (p) {
379
+ return `https://unpkg.com/${name}@${version}/${p}`;
380
+ } else {
381
+ return `https://unpkg.com/${name}@${version}`;
382
+ }
383
+ }
384
+ ];
385
+ };
386
+ var bytecdntp = (exportVarName = "", pathname = "") => {
387
+ return [
388
+ exportVarName,
389
+ (version, name, _importName = "", resolveName = "") => {
390
+ const p = pathname || resolveName;
391
+ return `https://lf9-cdn-tos.bytecdntp.com/cdn/expire-10-y/${name}/${version}/${p}`;
392
+ }
393
+ ];
394
+ };
395
+ var bootcdn = (exportVarName = "", pathname = "") => {
396
+ console.warn(
397
+ "bootcdn will return virus-infected code. Please stop using it and switch to other sources. now it will return jsdelivr url."
398
+ );
399
+ return [
400
+ exportVarName,
401
+ (version, name, _importName = "", resolveName = "") => {
402
+ const p = pathname || resolveName;
403
+ return `https://fastly.jsdelivr.net/npm/${name}@${version}/${p}`;
404
+ }
405
+ ];
406
+ };
407
+ var baomitu = (exportVarName = "", pathname = "") => {
408
+ return [
409
+ exportVarName,
410
+ (version, name, _importName = "", resolveName = "") => {
411
+ const p = pathname || resolveName;
412
+ return `https://lib.baomitu.com/${name}/${version}/${p}`;
413
+ }
414
+ ];
415
+ };
416
+ var staticfile = (exportVarName = "", pathname = "") => {
417
+ return [
418
+ exportVarName,
419
+ (version, name, _importName = "", resolveName = "") => {
420
+ const p = pathname || resolveName;
421
+ return `https://cdn.staticfile.org/${name}/${version}/${p}`;
422
+ }
423
+ ];
424
+ };
425
+ var cdnjs = (exportVarName = "", pathname = "") => {
426
+ return [
427
+ exportVarName,
428
+ (version, name, _importName = "", resolveName = "") => {
429
+ const p = pathname || resolveName;
430
+ return `https://cdnjs.cloudflare.com/ajax/libs/${name}/${version}/${p}`;
431
+ }
432
+ ];
433
+ };
434
+ var zhimg = (exportVarName = "", pathname = "") => {
435
+ return [
436
+ exportVarName,
437
+ (version, name, _importName = "", resolveName = "") => {
438
+ const p = pathname || resolveName;
439
+ return `https://unpkg.zhimg.com/${name}@${version}/${p}`;
440
+ }
441
+ ];
442
+ };
443
+ var elemecdn = (exportVarName = "", pathname = "") => {
444
+ return [
445
+ exportVarName,
446
+ (version, name, _importName = "", resolveName = "") => {
447
+ const p = pathname || resolveName;
448
+ return `https://npm.elemecdn.com/${name}@${version}/${p}`;
449
+ }
450
+ ];
451
+ };
452
+ var bdstatic = (exportVarName = "", pathname = "") => {
453
+ return [
454
+ exportVarName,
455
+ (version, name, _importName = "", resolveName = "") => {
456
+ const p = pathname || resolveName;
457
+ return `https://code.bdstatic.com/npm/${name}@${version}/${p}`;
458
+ }
459
+ ];
460
+ };
461
+ var npmmirror = (exportVarName = "", pathname = "") => {
462
+ return [
463
+ exportVarName,
464
+ (version, name, _importName = "", resolveName = "") => {
465
+ const p = pathname || resolveName;
466
+ if (p) {
467
+ return `https://registry.npmmirror.com/${name}/${version}/files/${p}`;
468
+ } else {
469
+ return `https://registry.npmmirror.com/${name}/${version}/files`;
470
+ }
471
+ }
472
+ ];
473
+ };
474
+
475
+ // src/node/inject_template.ts
476
+ var fn2string = (fn, ...args) => {
477
+ return `;(${fn})(...${JSON.stringify(args, void 0, 2)});`;
478
+ };
479
+ var htmlText = (
480
+ /* html */
481
+ `
482
+ <!DOCTYPE html>
483
+ <html>
484
+ <head>
485
+ <meta charset="UTF-8" />
486
+ <link rel="icon" type="image/svg+xml" href="https://vitejs.dev/logo.svg" />
487
+ <title>Vite</title>
488
+ </head>
489
+ <script type="module" data-source="vite-plugin-monkey">
490
+ __CODE__
491
+ </script>
492
+ </html>
493
+ `.trimStart()
494
+ );
495
+ var fcToHtml = (fn, ...args) => {
496
+ return htmlText.replace(
497
+ `__CODE__`,
498
+ `;(${fn})(...${JSON.stringify(args, void 0, 2)});`
499
+ );
500
+ };
501
+ var serverInjectFn = ({ entrySrc = `` }) => {
502
+ window.GM;
503
+ const key = `__monkeyWindow-` + new URL(entrySrc).origin;
504
+ document[key] = window;
505
+ console.log(`[vite-plugin-monkey] mount monkeyWindow to document`);
506
+ const entryScript = document.createElement("script");
507
+ entryScript.type = "module";
508
+ entryScript.src = entrySrc;
509
+ document.head.insertBefore(entryScript, document.head.firstChild);
510
+ console.log(`[vite-plugin-monkey] mount entry module to document.head`);
511
+ };
512
+ var mountGmApiFn = (meta, apiNames = []) => {
513
+ const key = `__monkeyWindow-` + new URL(meta.url).origin;
514
+ const monkeyWindow = document[key];
515
+ if (!monkeyWindow) {
516
+ console.log(`[vite-plugin-monkey] not found monkeyWindow`);
517
+ return;
518
+ }
519
+ window.unsafeWindow = window;
520
+ console.log(`[vite-plugin-monkey] mount unsafeWindow to unsafeWindow`);
521
+ let mountedApiSize = 0;
522
+ apiNames.forEach((apiName) => {
523
+ const fn = monkeyWindow[apiName];
524
+ if (fn) {
525
+ window[apiName] = monkeyWindow[apiName];
526
+ mountedApiSize++;
527
+ }
528
+ });
529
+ console.log(
530
+ `[vite-plugin-monkey] mount ${mountedApiSize}/${apiNames.length} GM_api to unsafeWindow`
531
+ );
532
+ };
533
+ var virtualHtmlTemplate = async (url) => {
534
+ const delay = (n = 0) => new Promise((res) => setTimeout(res, n));
535
+ await delay();
536
+ const u = new URL(url, location.origin);
537
+ u.searchParams.set("origin", u.origin);
538
+ if (window == window.parent) {
539
+ location.href = u.href;
540
+ await delay(500);
541
+ window.close();
542
+ return;
543
+ }
544
+ const style = document.createElement("style");
545
+ document.head.append(style);
546
+ style.innerText = /* css */
547
+ `
548
+ body {
549
+ font-family: Arial, sans-serif;
550
+ margin: 0;
551
+ }
552
+ .App {
553
+ margin: 25px;
554
+ }
555
+ p {
556
+ font-size: 1.5em;
557
+ }
558
+ a {
559
+ color: blue;
560
+ text-decoration: none;
561
+ font-size: 1.5em;
562
+ }
563
+ a:hover {
564
+ text-decoration: underline;
565
+ }
566
+ `.trim();
567
+ document.body.innerHTML = /* html */
568
+ `
569
+ <div class="App">
570
+ <h1>PREVIEW PAGE</h1>
571
+ <p>Click the links below to install userscripts:</p>
572
+ <a target="_blank"></a></th>
573
+ </div>
574
+ `.trim();
575
+ await delay();
576
+ const a = document.querySelector("a");
577
+ a.href = location.href;
578
+ a.text = location.href;
579
+ };
580
+ var previewTemplate = async (urls) => {
581
+ const delay = (n = 0) => new Promise((res) => setTimeout(res, n));
582
+ await delay();
583
+ const style = document.createElement("style");
584
+ document.head.append(style);
585
+ style.innerText = /* css */
586
+ `
587
+ body {
588
+ font-family: Arial, sans-serif;
589
+ margin: 0;
590
+ }
591
+ .App {
592
+ margin: 25px;
593
+ }
594
+ p {
595
+ font-size: 1.5em;
596
+ }
597
+ table {
598
+ width: 100%;
599
+ border-collapse: collapse;
600
+ font-size: 1.5em;
601
+ }
602
+ th, td {
603
+ border: 1px solid black;
604
+ padding: 8px;
605
+ text-align: left;
606
+ }
607
+ th {
608
+ background-color: #f2f2f2;
609
+ }
610
+ a {
611
+ color: blue;
612
+ text-decoration: none;
613
+ }
614
+ a:hover {
615
+ text-decoration: underline;
616
+ }
617
+ `.trim();
618
+ if (window == window.parent && urls.length == 1) {
619
+ const u = new URL(urls[0], location.origin);
620
+ location.href = u.href;
621
+ await delay(500);
622
+ window.close();
623
+ return;
624
+ } else if (urls.length == 0) {
625
+ document.body.innerHTML = /* html */
626
+ `
627
+ <div class="App">
628
+ <h1> There is no script to install </h1>
629
+ </div>
630
+ `.trim();
631
+ return;
632
+ } else {
633
+ document.body.innerHTML = /* html */
634
+ `
635
+ <div class="App">
636
+ <h1>PREVIEW PAGE</h1>
637
+ <p>Click the links below to install userscripts:</p>
638
+ <table>
639
+ <tr>
640
+ <th>No.</th>
641
+ <th>Install Link</th>
642
+ </tr>
643
+ </table>
644
+ </div>
645
+ `.trim();
646
+ await delay();
647
+ const table = document.querySelector(`table`);
648
+ urls.sort().forEach((u, index) => {
649
+ const tr = document.createElement("tr");
650
+ const td1 = document.createElement("td");
651
+ const td2 = document.createElement("td");
652
+ const a = document.createElement("a");
653
+ td1.innerText = `${index + 1}`;
654
+ if (window != window.parent) {
655
+ a.target = "_blank";
656
+ }
657
+ a.href = u;
658
+ a.textContent = new URL(u, location.origin).href;
659
+ td2.append(a);
660
+ tr.append(td1);
661
+ tr.append(td2);
662
+ table.append(tr);
663
+ });
664
+ }
665
+ };
666
+
667
+ // src/node/option.ts
668
+ var resolvedOption = (pluginOption) => {
669
+ var _a, _b;
670
+ const build2 = pluginOption.build ?? {};
671
+ if (build2.minifyCss !== void 0) {
672
+ logger.warn(
673
+ `monkeyConfig.build.minifyCss is deprecated, use viteConfig.build.cssMinify in vite>=4.2.0`,
674
+ { time: false }
675
+ );
676
+ }
677
+ const { externalResource = {} } = build2;
678
+ const externalResource2 = {};
679
+ for (const [k, v] of Object.entries(externalResource)) {
680
+ if (typeof v == "string") {
681
+ externalResource2[k] = {
682
+ resourceName: () => k,
683
+ resourceUrl: () => v
684
+ };
685
+ } else if (typeof v == "function") {
686
+ externalResource2[k] = {
687
+ resourceName: () => k,
688
+ resourceUrl: v
689
+ };
690
+ } else if (v instanceof Array) {
691
+ let resourceUrl2;
692
+ let resourceName2 = () => k;
693
+ const [resourceName, resourceUrl] = v;
694
+ if (typeof resourceName == "string") {
695
+ resourceName2 = (pkg) => resourceName || pkg.importName;
696
+ } else {
697
+ resourceName2 = (pkg) => resourceName(pkg.version, pkg.name, pkg.importName, pkg.resolveName);
698
+ }
699
+ if (typeof resourceUrl == "string") {
700
+ resourceUrl2 = () => resourceUrl;
701
+ } else {
702
+ resourceUrl2 = (pkg) => resourceUrl(pkg.version, pkg.name, pkg.importName, pkg.resolveName);
703
+ }
704
+ externalResource2[k] = {
705
+ resourceName: resourceName2,
706
+ resourceUrl: resourceUrl2
707
+ };
708
+ } else {
709
+ const { resourceUrl, loader, nodeLoader, resourceName } = v;
710
+ let resourceUrl2;
711
+ let resourceName2 = () => k;
712
+ let nodeLoader2 = void 0;
713
+ if (typeof resourceUrl == "string") {
714
+ resourceUrl2 = () => resourceUrl;
715
+ } else {
716
+ resourceUrl2 = resourceUrl;
717
+ }
718
+ if (typeof resourceName == "string") {
719
+ resourceName2 = () => resourceName;
720
+ } else if (typeof resourceName == "function") {
721
+ resourceName2 = resourceName;
722
+ }
723
+ if (typeof nodeLoader == "function") {
724
+ nodeLoader2 = nodeLoader;
725
+ } else if (typeof nodeLoader == "string") {
726
+ nodeLoader2 = () => nodeLoader;
727
+ }
728
+ externalResource2[k] = {
729
+ resourceName: resourceName2,
730
+ resourceUrl: resourceUrl2,
731
+ loader,
732
+ nodeLoader: nodeLoader2
733
+ };
734
+ }
735
+ }
736
+ const server = pluginOption.server ?? {};
737
+ const { prefix } = server;
738
+ let prefix2 = (s) => "server:" + s;
739
+ if (typeof prefix == "function") {
740
+ prefix2 = prefix;
741
+ } else if (typeof prefix == "string") {
742
+ prefix2 = () => prefix;
743
+ } else if (prefix === false) {
744
+ prefix2 = (name2) => name2;
745
+ }
746
+ const externalGlobals2 = (build2 == null ? void 0 : build2.externalGlobals) ?? {};
747
+ const externalGlobals = [];
748
+ if (externalGlobals2 instanceof Array) {
749
+ externalGlobals2.forEach((s) => externalGlobals.push(s));
750
+ } else {
751
+ Object.entries(externalGlobals2).forEach((s) => externalGlobals.push(s));
752
+ }
753
+ let {
754
+ name = {},
755
+ description = {},
756
+ "exclude-match": excludeMatch = [],
757
+ match = [],
758
+ exclude = [],
759
+ include = [],
760
+ antifeature = [],
761
+ require: require2 = [],
762
+ connect = [],
763
+ grant = [],
764
+ webRequest = [],
765
+ $extra = []
766
+ } = pluginOption.userscript ?? {};
767
+ if (typeof name == "string") {
768
+ name = { "": name };
769
+ } else if (!("" in name)) {
770
+ name = { "": projectPkg.name, ...name };
771
+ }
772
+ if (typeof description == "string") {
773
+ description = {
774
+ "": description
775
+ };
776
+ } else if (!("" in description) && projectPkg.description) {
777
+ description = { "": projectPkg.description, ...description };
778
+ }
779
+ if (!(excludeMatch instanceof Array)) {
780
+ excludeMatch = [excludeMatch];
781
+ }
782
+ if (!(match instanceof Array)) {
783
+ match = [match];
784
+ }
785
+ if (!(exclude instanceof Array)) {
786
+ exclude = [exclude];
787
+ }
788
+ if (!(include instanceof Array)) {
789
+ include = [include];
790
+ }
791
+ if (!(antifeature instanceof Array)) {
792
+ antifeature = [antifeature];
793
+ }
794
+ if (!(require2 instanceof Array)) {
795
+ require2 = [require2];
796
+ }
797
+ if (!(connect instanceof Array)) {
798
+ connect = [connect];
799
+ }
800
+ if (!(webRequest instanceof Array)) {
801
+ webRequest = [webRequest];
802
+ }
803
+ const grantSet = /* @__PURE__ */ new Set();
804
+ if (typeof grant == "string") {
805
+ grantSet.add(grant);
806
+ } else if (grant instanceof Array) {
807
+ grant.forEach((s) => grantSet.add(s));
808
+ }
809
+ const extra = [];
810
+ ($extra instanceof Array ? $extra : Object.entries($extra)).forEach(
811
+ ([k, v]) => {
812
+ extra.push([k, ...v instanceof Array ? v : [v]]);
813
+ }
814
+ );
815
+ const {
816
+ icon64,
817
+ icon64URL,
818
+ icon,
819
+ iconURL,
820
+ namespace = `vite-plugin-monkey`,
821
+ version = projectPkg.version,
822
+ author = projectPkg.author ?? "monkey",
823
+ copyright,
824
+ downloadURL,
825
+ defaulticon,
826
+ contributionURL,
827
+ updateURL,
828
+ supportURL = projectPkg.bugs,
829
+ homepageURL = projectPkg.homepage,
830
+ homepage = projectPkg.homepage,
831
+ website,
832
+ license = projectPkg.license,
833
+ incompatible,
834
+ source = projectPkg.repository,
835
+ resource = {},
836
+ noframes = false,
837
+ "run-at": runAt,
838
+ "inject-into": injectInto,
839
+ contributionAmount,
840
+ compatible,
841
+ sandbox,
842
+ unwrap = false
843
+ } = pluginOption.userscript ?? {};
844
+ const { fileName = projectPkg.name + ".user.js" } = build2;
845
+ let { metaFileName } = build2;
846
+ if (typeof metaFileName == "string") {
847
+ const t = metaFileName;
848
+ metaFileName = () => t;
849
+ } else if (metaFileName === true) {
850
+ metaFileName = () => fileName.replace(/\.user\.js$/, ".meta.js");
851
+ } else if (metaFileName === false) {
852
+ metaFileName = void 0;
853
+ }
854
+ const metaFileFc = metaFileName;
855
+ const cssSideEffects = build2.cssSideEffects || (() => {
856
+ return (e) => {
857
+ if (typeof GM_addStyle == "function") {
858
+ GM_addStyle(e);
859
+ return;
860
+ }
861
+ const o = document.createElement("style");
862
+ o.textContent = e;
863
+ document.head.append(o);
864
+ };
865
+ });
866
+ const config = {
867
+ userscript: {
868
+ name,
869
+ namespace,
870
+ version,
871
+ icon64,
872
+ icon64URL,
873
+ icon,
874
+ iconURL,
875
+ author,
876
+ copyright,
877
+ downloadURL,
878
+ defaulticon,
879
+ contributionURL,
880
+ updateURL,
881
+ supportURL,
882
+ homepageURL,
883
+ homepage,
884
+ website,
885
+ license,
886
+ incompatible,
887
+ source,
888
+ resource,
889
+ noframes,
890
+ "run-at": runAt,
891
+ "inject-into": injectInto,
892
+ contributionAmount,
893
+ compatible,
894
+ "exclude-match": excludeMatch.map((s) => String(s)),
895
+ match: match.map((s) => String(s)),
896
+ include: include.map((s) => String(s)),
897
+ exclude: exclude.map((s) => String(s)),
898
+ antifeature,
899
+ require: require2,
900
+ connect,
901
+ description,
902
+ $extra: extra,
903
+ grant: grantSet,
904
+ sandbox,
905
+ unwrap,
906
+ webRequest: webRequest.map((w) => JSON.stringify(w))
907
+ },
908
+ clientAlias: pluginOption.clientAlias ?? "$",
909
+ entry: pluginOption.entry,
910
+ format: {
911
+ align: ((_a = pluginOption.format) == null ? void 0 : _a.align) ?? 2,
912
+ generate: ((_b = pluginOption.format) == null ? void 0 : _b.generate) ?? ((o) => o.userscript)
913
+ },
914
+ server: {
915
+ mountGmApi: server.mountGmApi ?? false,
916
+ open: server.open ?? (process.platform == "win32" || process.platform == "darwin"),
917
+ prefix: prefix2,
918
+ closePreviewAutomatically: server.closePreviewAutomatically ?? false
919
+ },
920
+ build: {
921
+ fileName,
922
+ metaFileName: metaFileFc ? () => metaFileFc(fileName) : void 0,
923
+ autoGrant: build2.autoGrant ?? true,
924
+ externalGlobals,
925
+ externalResource: externalResource2
926
+ },
927
+ collectRequireUrls: [],
928
+ collectResource: {},
929
+ globalsPkg2VarName: {},
930
+ requirePkgList: [],
931
+ systemjs: build2.systemjs ?? jsdelivr()[1],
932
+ cssSideEffects: async (css) => {
933
+ const codeOrFc = await cssSideEffects(css);
934
+ if (typeof codeOrFc == "string") {
935
+ return codeOrFc;
936
+ }
937
+ return miniCode(fn2string(codeOrFc, css), "js");
938
+ }
939
+ };
940
+ return config;
941
+ };
942
+
943
+ // src/node/plugins/server.ts
944
+ import { DomUtils, ElementType, parseDocument } from "htmlparser2";
945
+ import fs2 from "fs/promises";
946
+ import path3 from "path";
947
+ import { normalizePath as normalizePath2 } from "vite";
948
+
949
+ // src/node/open_browser.ts
950
+ import spawn from "cross-spawn";
951
+ import { execSync } from "child_process";
952
+ import path2 from "path";
953
+ import colors from "picocolors";
954
+ var OSX_CHROME = "google chrome";
955
+ function openBrowser(url, opt, logger2) {
956
+ const browser = typeof opt === "string" ? opt : process.env.BROWSER || "";
957
+ if (browser.toLowerCase().endsWith(".js")) {
958
+ return executeNodeScript(browser, url, logger2);
959
+ } else if (browser.toLowerCase() !== "none") {
960
+ return startBrowserProcess(browser, url);
961
+ }
962
+ return false;
963
+ }
964
+ function executeNodeScript(scriptPath, url, logger2) {
965
+ const extraArgs = process.argv.slice(2);
966
+ const child = spawn(process.execPath, [scriptPath, ...extraArgs, url], {
967
+ stdio: "inherit"
968
+ });
969
+ child.on("close", (code) => {
970
+ if (code !== 0) {
971
+ logger2.error(
972
+ colors.red(
973
+ `
974
+ The script specified as BROWSER environment variable failed.
975
+
976
+ ${colors.cyan(
977
+ scriptPath
978
+ )} exited with code ${code}.`
979
+ ),
980
+ { time: true }
981
+ );
982
+ }
983
+ });
984
+ return true;
985
+ }
986
+ function startBrowserProcess(browser, url) {
987
+ const shouldTryOpenChromeWithAppleScript = process.platform === "darwin" && (browser === "" || browser === OSX_CHROME);
988
+ if (shouldTryOpenChromeWithAppleScript) {
989
+ try {
990
+ execSync('ps cax | grep "Google Chrome"');
991
+ execSync('osascript openChrome.applescript "' + encodeURI(url) + '"', {
992
+ cwd: path2.dirname(compatResolve("vite/bin/openChrome.applescript")),
993
+ stdio: "ignore"
994
+ });
995
+ return true;
996
+ } catch (err) {
997
+ }
998
+ }
999
+ if (process.platform === "darwin" && browser === "open") {
1000
+ browser = void 0;
1001
+ }
1002
+ try {
1003
+ const options = browser ? { app: { name: browser } } : {};
1004
+ import("open").then(({ default: open }) => {
1005
+ open(url, options).catch(() => {
1006
+ });
1007
+ });
1008
+ return true;
1009
+ } catch (err) {
1010
+ return false;
1011
+ }
1012
+ }
1013
+
1014
+ // src/node/userscript/greasemonkey.ts
1015
+ var GreaseGrantValueList = [
1016
+ "GM.info",
1017
+ "GM.deleteValue",
1018
+ "GM.getValue",
1019
+ "GM.listValues",
1020
+ "GM.setValue",
1021
+ "GM.getResourceUrl",
1022
+ "GM.notification",
1023
+ "GM.openInTab",
1024
+ "GM.registerMenuCommand",
1025
+ "GM.setClipboard",
1026
+ "GM.xmlHttpRequest",
1027
+ "unsafeWindow"
1028
+ ];
1029
+
1030
+ // src/node/userscript/tampermonkey.ts
1031
+ var TamperGrantValueList = [
1032
+ "unsafeWindow",
1033
+ "window.close",
1034
+ "window.focus",
1035
+ "window.onurlchange",
1036
+ "GM_addStyle",
1037
+ "GM_addElement",
1038
+ "GM_deleteValue",
1039
+ "GM_listValues",
1040
+ "GM_addValueChangeListener",
1041
+ "GM_removeValueChangeListener",
1042
+ "GM_setValue",
1043
+ "GM_getValue",
1044
+ "GM_log",
1045
+ "GM_getResourceText",
1046
+ "GM_getResourceURL",
1047
+ "GM_registerMenuCommand",
1048
+ "GM_unregisterMenuCommand",
1049
+ "GM_openInTab",
1050
+ "GM_xmlhttpRequest",
1051
+ "GM_download",
1052
+ "GM_getTab",
1053
+ "GM_saveTab",
1054
+ "GM_getTabs",
1055
+ "GM_notification",
1056
+ "GM_setClipboard",
1057
+ "GM_info",
1058
+ "GM_cookie",
1059
+ "GM_webRequest"
1060
+ ];
1061
+
1062
+ // src/node/userscript/violentmonkey.ts
1063
+ var ViolentGrantValueList = [
1064
+ "window.close",
1065
+ "window.focus",
1066
+ "GM_info",
1067
+ "GM_getValue",
1068
+ "GM_setValue",
1069
+ "GM_deleteValue",
1070
+ "GM_listValues",
1071
+ "GM_addValueChangeListener",
1072
+ "GM_removeValueChangeListener",
1073
+ "GM_getResourceText",
1074
+ "GM_getResourceURL",
1075
+ "GM_addElement",
1076
+ "GM_addStyle",
1077
+ "GM_openInTab",
1078
+ "GM_registerMenuCommand",
1079
+ "GM_unregisterMenuCommand",
1080
+ "GM_notification",
1081
+ "GM_setClipboard",
1082
+ "GM_xmlhttpRequest",
1083
+ "GM_download",
1084
+ "GM.addStyle",
1085
+ "GM.addElement",
1086
+ "GM.registerMenuCommand",
1087
+ "GM.deleteValue",
1088
+ "GM.getResourceUrl",
1089
+ "GM.getValue",
1090
+ "GM.info",
1091
+ "GM.listValues",
1092
+ "GM.notification",
1093
+ "GM.openInTab",
1094
+ "GM.setClipboard",
1095
+ "GM.setValue",
1096
+ "GM.xmlHttpRequest"
1097
+ ];
1098
+
1099
+ // src/node/userscript/index.ts
1100
+ var finalMonkeyOptionToComment = async ({
1101
+ userscript,
1102
+ format,
1103
+ collectRequireUrls,
1104
+ collectResource
1105
+ }, collectGrantSet, mode) => {
1106
+ let attrList = [];
1107
+ const {
1108
+ name,
1109
+ namespace,
1110
+ version,
1111
+ author,
1112
+ description,
1113
+ license,
1114
+ copyright,
1115
+ icon,
1116
+ iconURL,
1117
+ icon64,
1118
+ icon64URL,
1119
+ defaulticon,
1120
+ homepage,
1121
+ homepageURL,
1122
+ website,
1123
+ source,
1124
+ supportURL,
1125
+ downloadURL,
1126
+ updateURL,
1127
+ include,
1128
+ match,
1129
+ exclude,
1130
+ require: require2,
1131
+ "exclude-match": excludeMatch,
1132
+ "inject-into": injectInto,
1133
+ "run-at": runAt,
1134
+ compatible,
1135
+ incompatible,
1136
+ antifeature,
1137
+ contributionAmount,
1138
+ contributionURL,
1139
+ connect,
1140
+ sandbox,
1141
+ resource,
1142
+ grant,
1143
+ noframes,
1144
+ unwrap,
1145
+ webRequest,
1146
+ $extra
1147
+ } = userscript;
1148
+ Object.entries({
1149
+ namespace,
1150
+ version,
1151
+ author,
1152
+ license,
1153
+ copyright,
1154
+ icon,
1155
+ iconURL,
1156
+ icon64,
1157
+ icon64URL,
1158
+ defaulticon,
1159
+ homepage,
1160
+ homepageURL,
1161
+ website,
1162
+ source,
1163
+ supportURL,
1164
+ downloadURL,
1165
+ updateURL,
1166
+ "inject-into": injectInto,
1167
+ "run-at": runAt,
1168
+ compatible,
1169
+ incompatible,
1170
+ contributionAmount,
1171
+ contributionURL,
1172
+ sandbox
1173
+ }).forEach(([k, v]) => {
1174
+ if (typeof v == "string") {
1175
+ attrList.push([k, v]);
1176
+ }
1177
+ });
1178
+ Object.entries(name).forEach(([k, v]) => {
1179
+ if (k == "") {
1180
+ attrList.push(["name", v]);
1181
+ } else {
1182
+ attrList.push(["name:" + k, v]);
1183
+ }
1184
+ });
1185
+ Object.entries(description).forEach(([k, v]) => {
1186
+ if (k == "") {
1187
+ attrList.push(["description", v]);
1188
+ } else {
1189
+ attrList.push(["description:" + k, v]);
1190
+ }
1191
+ });
1192
+ Object.entries({
1193
+ include,
1194
+ match,
1195
+ exclude,
1196
+ "exclude-match": excludeMatch
1197
+ }).forEach(([k, v]) => {
1198
+ v.forEach((v2) => {
1199
+ attrList.push([k, v2]);
1200
+ });
1201
+ });
1202
+ [...require2, ...collectRequireUrls].forEach((s) => {
1203
+ attrList.push(["require", s]);
1204
+ });
1205
+ Object.entries({ ...resource, ...collectResource }).forEach(([k, v]) => {
1206
+ attrList.push(["resource", k, v]);
1207
+ });
1208
+ connect.forEach((s) => {
1209
+ attrList.push(["connect", s]);
1210
+ });
1211
+ webRequest.forEach((s) => {
1212
+ attrList.push(["webRequest", s]);
1213
+ });
1214
+ if (grant.has("none")) {
1215
+ attrList.push(["grant", "none"]);
1216
+ } else if (grant.has("*")) {
1217
+ (/* @__PURE__ */ new Set([
1218
+ ...GreaseGrantValueList,
1219
+ ...ViolentGrantValueList,
1220
+ ...TamperGrantValueList
1221
+ ])).forEach((s) => {
1222
+ attrList.push(["grant", s]);
1223
+ });
1224
+ } else {
1225
+ (/* @__PURE__ */ new Set([...Array.from(collectGrantSet.values()).flat(), ...grant])).forEach(
1226
+ (s) => {
1227
+ if (!s.trim())
1228
+ return;
1229
+ attrList.push(["grant", s]);
1230
+ }
1231
+ );
1232
+ }
1233
+ antifeature.forEach(({ description: description2, type, tag }) => {
1234
+ attrList.push([
1235
+ tag ? `antifeature:${tag}` : "antifeature",
1236
+ type,
1237
+ description2
1238
+ ]);
1239
+ });
1240
+ if (noframes) {
1241
+ attrList.push(["noframes"]);
1242
+ }
1243
+ if (unwrap) {
1244
+ attrList.push(["unwrap"]);
1245
+ }
1246
+ attrList.push(...$extra);
1247
+ attrList = defaultSortFormat(attrList);
1248
+ let { align = 2 } = format;
1249
+ if (align === true) {
1250
+ align = 2;
1251
+ }
1252
+ if (typeof align == "number" && Number.isInteger(align) && align >= 1) {
1253
+ const alignN = align;
1254
+ const formatKey = (subAttrList) => {
1255
+ if (subAttrList.length == 0)
1256
+ return;
1257
+ const maxLen2 = Math.max(...subAttrList.map((s) => s[1].length));
1258
+ subAttrList.forEach((s) => {
1259
+ s[1] = s[1].padEnd(alignN + maxLen2);
1260
+ });
1261
+ };
1262
+ formatKey(attrList.filter((s) => s[0] == "resource"));
1263
+ formatKey(
1264
+ attrList.filter(
1265
+ (s) => s[0] == "antifeature" || s[0].startsWith("antifeature:")
1266
+ )
1267
+ );
1268
+ const maxLen = Math.max(...attrList.map((s) => s[0].length));
1269
+ attrList.forEach((s) => {
1270
+ s[0] = s[0].padEnd(alignN + maxLen);
1271
+ });
1272
+ } else if (typeof align == "function") {
1273
+ attrList = await align(attrList);
1274
+ }
1275
+ const uString = [
1276
+ "==UserScript==",
1277
+ ...attrList.map(
1278
+ (attr) => "@" + attr.map((v) => {
1279
+ return v.endsWith(" ") ? v : v + " ";
1280
+ }).join("").trimEnd()
1281
+ ),
1282
+ "==/UserScript=="
1283
+ ].map((s) => "// " + s).join("\n");
1284
+ return format.generate({ userscript: uString, mode });
1285
+ };
1286
+ var stringSort = (a, b) => {
1287
+ const minLen = Math.min(a.length, b.length);
1288
+ for (let i = 0; i < minLen; i++) {
1289
+ if (a[i] > b[i]) {
1290
+ return 1;
1291
+ } else if (a[i] < b[i]) {
1292
+ return -1;
1293
+ }
1294
+ }
1295
+ if (a.length > b.length) {
1296
+ return 1;
1297
+ } else if (a.length < b.length) {
1298
+ return -1;
1299
+ }
1300
+ return 0;
1301
+ };
1302
+ var defaultSortFormat = (p0) => {
1303
+ const filter = (predicate) => {
1304
+ const notMatchList = [];
1305
+ const matchList = [];
1306
+ p0.forEach((value, index) => {
1307
+ if (!predicate(value, index)) {
1308
+ notMatchList.push(value);
1309
+ } else {
1310
+ matchList.push(value);
1311
+ }
1312
+ });
1313
+ p0 = notMatchList;
1314
+ return matchList;
1315
+ };
1316
+ return [
1317
+ filter(([k]) => k == "name"),
1318
+ filter(([k]) => k.startsWith("name:")),
1319
+ filter(([k]) => k == "namespace"),
1320
+ filter(([k]) => k == "version"),
1321
+ filter(([k]) => k == "author"),
1322
+ filter(([k]) => k == "description"),
1323
+ filter(([k]) => k.startsWith("description:")),
1324
+ filter(([k]) => k == "license"),
1325
+ filter(([k]) => k == "copyright"),
1326
+ filter(([k]) => k == "icon"),
1327
+ filter(([k]) => k == "iconURL"),
1328
+ filter(([k]) => k == "icon64"),
1329
+ filter(([k]) => k == "icon64URL"),
1330
+ filter(([k]) => k == "defaulticon"),
1331
+ filter(([k]) => k == "homepage"),
1332
+ filter(([k]) => k == "homepageURL"),
1333
+ filter(([k]) => k == "website"),
1334
+ filter(([k]) => k == "source"),
1335
+ filter(([k]) => k == "supportURL"),
1336
+ filter(([k]) => k == "downloadURL"),
1337
+ filter(([k]) => k == "updateURL"),
1338
+ filter(([k]) => k == "include"),
1339
+ filter(([k]) => k == "match"),
1340
+ filter(([k]) => k == "exclude"),
1341
+ filter(([k]) => k == "exclude-match"),
1342
+ filter(([k]) => k == "webRequest"),
1343
+ filter(([k]) => k == "require"),
1344
+ filter(([k]) => k == "resource").sort(stringSort),
1345
+ filter(([k]) => k == "sandbox"),
1346
+ filter(([k]) => k == "connect"),
1347
+ filter(([k]) => k == "grant").sort(stringSort),
1348
+ filter(([k]) => k == "inject-into"),
1349
+ filter(([k]) => k == "run-at"),
1350
+ filter(([k]) => k == "compatible"),
1351
+ filter(([k]) => k == "incompatible"),
1352
+ filter(([k]) => k == "antifeature").sort(stringSort),
1353
+ filter(([k]) => k.startsWith("antifeature:")).sort(stringSort),
1354
+ filter(([k]) => k == "contributionAmount"),
1355
+ filter(([k]) => k == "contributionURL"),
1356
+ filter(([k]) => k == "noframes"),
1357
+ filter(([k]) => k == "unwrap"),
1358
+ p0
1359
+ ].flat(1);
1360
+ };
1361
+
1362
+ // src/node/plugins/server.ts
1363
+ var installUserPath = "/__vite-plugin-monkey.install.user.js";
1364
+ var gmApiPath = "/__vite-plugin-monkey.gm.api.js";
1365
+ var entryPath = "/__vite-plugin-monkey.entry.js";
1366
+ var pullPath = "/__vite-plugin-monkey.pull.js";
1367
+ var restartStoreKey = "__vite_plugin_monkey_install_url";
1368
+ var serverPlugin = (finalOption) => {
1369
+ let viteConfig;
1370
+ return {
1371
+ name: "monkey:server",
1372
+ apply: "serve",
1373
+ async config(userConfig) {
1374
+ var _a, _b, _c;
1375
+ return {
1376
+ preview: {
1377
+ host: ((_a = userConfig.preview) == null ? void 0 : _a.host) ?? "127.0.0.1",
1378
+ cors: true
1379
+ },
1380
+ server: {
1381
+ host: ((_b = userConfig.server) == null ? void 0 : _b.host) ?? "127.0.0.1",
1382
+ open: ((_c = userConfig.server) == null ? void 0 : _c.open) ?? finalOption.server.open,
1383
+ cors: true
1384
+ }
1385
+ };
1386
+ },
1387
+ async configResolved(resolvedConfig) {
1388
+ viteConfig = resolvedConfig;
1389
+ },
1390
+ async configureServer(server) {
1391
+ for (const [k, v] of Object.entries(finalOption.userscript.name)) {
1392
+ Reflect.set(
1393
+ finalOption.userscript.name,
1394
+ k,
1395
+ finalOption.server.prefix(v)
1396
+ );
1397
+ }
1398
+ finalOption.userscript.grant.add("*");
1399
+ server.middlewares.use(async (req, res, next) => {
1400
+ var _a;
1401
+ const reqUrl = req.url;
1402
+ if (reqUrl && [installUserPath, entryPath, pullPath, gmApiPath].some(
1403
+ (u) => reqUrl.startsWith(u)
1404
+ )) {
1405
+ Object.entries({
1406
+ "access-control-allow-origin": "*",
1407
+ "content-type": "application/javascript"
1408
+ }).forEach(([k, v]) => {
1409
+ res.setHeader(k, v);
1410
+ });
1411
+ const usp = new URLSearchParams(reqUrl.split("?", 2)[1]);
1412
+ if (reqUrl.startsWith(installUserPath)) {
1413
+ let origin = (_a = toValidURL(usp.get(`origin`))) == null ? void 0 : _a.origin;
1414
+ if (!origin) {
1415
+ let { https, host, port } = viteConfig.server;
1416
+ if (host == "0.0.0.0") {
1417
+ host = "127.0.0.1";
1418
+ }
1419
+ origin = `${https ? "https" : "http"}://${host}:${port}`;
1420
+ logger.warn(
1421
+ `can not get origin from install url query parameter, use ${origin}`,
1422
+ {
1423
+ time: true
1424
+ }
1425
+ );
1426
+ }
1427
+ Reflect.set(globalThis, restartStoreKey, origin);
1428
+ const u = new URL(entryPath, origin);
1429
+ res.end(
1430
+ [
1431
+ await finalMonkeyOptionToComment(
1432
+ finalOption,
1433
+ /* @__PURE__ */ new Set(),
1434
+ "serve"
1435
+ ),
1436
+ fn2string(serverInjectFn, {
1437
+ entrySrc: u.href
1438
+ }),
1439
+ ""
1440
+ ].join("\n\n")
1441
+ );
1442
+ } else if (reqUrl.startsWith(entryPath)) {
1443
+ const htmlText2 = await server.transformIndexHtml(
1444
+ "/",
1445
+ `<html><head></head></html>`,
1446
+ req.originalUrl
1447
+ );
1448
+ const doc = parseDocument(htmlText2);
1449
+ const scriptList = DomUtils.getElementsByTagType(
1450
+ ElementType.Script,
1451
+ doc
1452
+ );
1453
+ const entryList = finalOption.server.mountGmApi ? [gmApiPath] : [];
1454
+ scriptList.forEach((p) => {
1455
+ const src = p.attribs.src ?? "";
1456
+ const textNode = p.firstChild;
1457
+ let text = "";
1458
+ if ((textNode == null ? void 0 : textNode.type) == ElementType.Text) {
1459
+ text = textNode.data ?? "";
1460
+ }
1461
+ if (src) {
1462
+ entryList.push(src);
1463
+ } else {
1464
+ const usp2 = new URLSearchParams({
1465
+ text: Buffer.from(text, "utf-8").toString("base64url")
1466
+ });
1467
+ entryList.push(pullPath + `?` + usp2.toString());
1468
+ }
1469
+ });
1470
+ let realEntry = finalOption.entry;
1471
+ if (path3.isAbsolute(realEntry)) {
1472
+ realEntry = normalizePath2(
1473
+ path3.relative(viteConfig.root, realEntry)
1474
+ );
1475
+ }
1476
+ const entryUrl = new URL(realEntry, "http://127.0.0.1");
1477
+ entryList.push(entryUrl.pathname + entryUrl.search);
1478
+ res.end(
1479
+ entryList.map((s) => `import ${JSON.stringify(s)};`).join("\n")
1480
+ );
1481
+ } else if (reqUrl.startsWith(pullPath)) {
1482
+ res.end(
1483
+ Buffer.from(usp.get("text") ?? "", "base64url").toString("utf-8")
1484
+ );
1485
+ } else if (reqUrl.startsWith(gmApiPath)) {
1486
+ if (finalOption.server.mountGmApi) {
1487
+ res.end(
1488
+ `;(${mountGmApiFn})(import.meta, ${JSON.stringify(GmApiNames)});`
1489
+ );
1490
+ } else {
1491
+ res.end("");
1492
+ }
1493
+ }
1494
+ return;
1495
+ }
1496
+ next();
1497
+ });
1498
+ if (finalOption.server.open) {
1499
+ const cacheUserPath = `node_modules/.vite/__vite-plugin-monkey.cache.${cyrb53hash(
1500
+ viteConfig.configFile
1501
+ )}.user.js`;
1502
+ let cacheComment = "";
1503
+ if (await existFile(cacheUserPath)) {
1504
+ cacheComment = (await fs2.readFile(cacheUserPath)).toString("utf-8");
1505
+ } else {
1506
+ await fs2.mkdir(path3.dirname(cacheUserPath)).catch(() => {
1507
+ });
1508
+ }
1509
+ const newComment = await finalMonkeyOptionToComment(
1510
+ finalOption,
1511
+ /* @__PURE__ */ new Set(),
1512
+ "serve"
1513
+ );
1514
+ const installUrl = Reflect.get(globalThis, restartStoreKey);
1515
+ if (!isFirstBoot() && cacheComment != newComment && installUrl) {
1516
+ openBrowser(installUrl, true, logger);
1517
+ logger.info("reopen, config comment has changed", { time: true });
1518
+ }
1519
+ await fs2.writeFile(cacheUserPath, newComment).catch(() => {
1520
+ });
1521
+ }
1522
+ }
1523
+ };
1524
+ };
1525
+
1526
+ // src/node/plugins/virtualHtml.ts
1527
+ var virtualHtmlPlugin = (finalOption) => {
1528
+ return {
1529
+ name: "monkey:virtualHtml",
1530
+ apply: "serve",
1531
+ configureServer(server) {
1532
+ server.middlewares.use(async (req, res, next) => {
1533
+ const url = req.url || "/";
1534
+ if (["/", "/index.html"].includes(url)) {
1535
+ res.setHeader("content-type", "text/html");
1536
+ res.setHeader("cache-control", "no-cache");
1537
+ res.setHeader("access-control-allow-origin", "*");
1538
+ return res.end(fcToHtml(virtualHtmlTemplate, installUserPath));
1539
+ }
1540
+ next();
1541
+ });
1542
+ }
1543
+ };
1544
+ };
1545
+
1546
+ // src/node/plugins/fixViteAsset.ts
1547
+ var template = `
1548
+ export default ((()=>{
1549
+ try{
1550
+ return new URL(__VALUE__, import.meta['url']).href
1551
+ }catch(_){
1552
+ return __VALUE__
1553
+ }
1554
+ })())
1555
+ `.trimStart();
1556
+ var fixViteAssetPlugin = (finalOption) => {
1557
+ let viteConfig;
1558
+ return {
1559
+ name: "monkey:fixViteAsset",
1560
+ apply: "serve",
1561
+ async configResolved(resolvedConfig) {
1562
+ viteConfig = resolvedConfig;
1563
+ },
1564
+ async transform(code, id) {
1565
+ var _a;
1566
+ const [_, query = "url"] = id.split("?", 2);
1567
+ if ((query.split("&").includes("url") || viteConfig.assetsInclude(id)) && code.match(/^\s*export\s+default/)) {
1568
+ const ast = this.parse(code);
1569
+ if (ast.type == "Program") {
1570
+ const defaultNode = (_a = ast.body) == null ? void 0 : _a[0];
1571
+ if ((defaultNode == null ? void 0 : defaultNode.type) == "ExportDefaultDeclaration") {
1572
+ const declarationNode = defaultNode == null ? void 0 : defaultNode.declaration;
1573
+ const value = declarationNode == null ? void 0 : declarationNode.value;
1574
+ if ((declarationNode == null ? void 0 : declarationNode.type) == "Literal" && typeof value == "string") {
1575
+ return template.replace(/__VALUE__/g, JSON.stringify(value));
1576
+ }
1577
+ }
1578
+ }
1579
+ }
1580
+ }
1581
+ };
1582
+ };
1583
+
1584
+ // src/node/plugins/fixViteClient.ts
1585
+ var fixViteClientPlugin = (finalOption) => {
1586
+ return {
1587
+ name: "monkey:fixViteClient",
1588
+ apply: "serve",
1589
+ async transform(code, id) {
1590
+ if (id.endsWith("node_modules/vite/dist/client/client.mjs")) {
1591
+ code = code.replace(
1592
+ /__HMR_PROTOCOL__/g,
1593
+ `(__HMR_PROTOCOL__ || ((()=>{const u = new URL(import.meta['url'], location.origin);return u.protocol === 'https:' ? 'wss' : 'ws'})()))`
1594
+ );
1595
+ code = code.replace(
1596
+ /__BASE__/g,
1597
+ `((()=>{const b = __BASE__; const u = new URL(import.meta['url'], location.origin); return b !== '/' ? b : (u.origin+'/');})())`
1598
+ );
1599
+ code = code.replace(
1600
+ "`${location.protocol}//${hostAndPath}`",
1601
+ "`${new URL(import.meta['url'], location.origin).protocol}//${hostAndPath}`"
1602
+ );
1603
+ return code;
1604
+ }
1605
+ }
1606
+ };
1607
+ };
1608
+
1609
+ // src/node/plugins/externalGlobals.ts
1610
+ import { normalizePath as normalizePath3 } from "vite";
1611
+ var externalGlobalsPlugin = (finalOption) => {
1612
+ const { globalsPkg2VarName, requirePkgList } = finalOption;
1613
+ return {
1614
+ name: "monkey:externalGlobals",
1615
+ enforce: "pre",
1616
+ apply: "build",
1617
+ async config() {
1618
+ for (const [moduleName, varName2LibUrl] of finalOption.build.externalGlobals) {
1619
+ const { name, version } = await getModuleRealInfo(moduleName);
1620
+ if (typeof varName2LibUrl == "string") {
1621
+ globalsPkg2VarName[moduleName] = varName2LibUrl;
1622
+ } else if (typeof varName2LibUrl == "function") {
1623
+ globalsPkg2VarName[moduleName] = await varName2LibUrl(
1624
+ version,
1625
+ name,
1626
+ moduleName
1627
+ );
1628
+ } else if (varName2LibUrl instanceof Array) {
1629
+ const [varName, ...libUrlList] = varName2LibUrl;
1630
+ if (typeof varName == "string") {
1631
+ globalsPkg2VarName[moduleName] = varName;
1632
+ } else if (typeof varName == "function") {
1633
+ globalsPkg2VarName[moduleName] = await varName(
1634
+ version,
1635
+ name,
1636
+ moduleName
1637
+ );
1638
+ }
1639
+ for (const libUrl of libUrlList) {
1640
+ if (typeof libUrl == "string") {
1641
+ requirePkgList.push({ url: libUrl, moduleName });
1642
+ } else if (typeof libUrl == "function") {
1643
+ requirePkgList.push({
1644
+ url: await libUrl(version, name, moduleName),
1645
+ moduleName
1646
+ });
1647
+ }
1648
+ }
1649
+ }
1650
+ }
1651
+ return {
1652
+ build: {
1653
+ rollupOptions: {
1654
+ external(source, _importer, _isResolved) {
1655
+ return source in globalsPkg2VarName;
1656
+ }
1657
+ // output: {
1658
+ // globals: globalsPkg2VarName,
1659
+ // inlineDynamicImports: true, // see https://rollupjs.org/guide/en/#outputinlinedynamicimports
1660
+ // },
1661
+ }
1662
+ }
1663
+ };
1664
+ },
1665
+ // async resolveDynamicImport(specifier, _importer) {
1666
+ // if (typeof specifier == 'string' && specifier in globalsPkg2VarName) {
1667
+ // return dynamicImportPrefix + specifier + '\0';
1668
+ // }
1669
+ // },
1670
+ // async load(id) {
1671
+ // if (id.startsWith(dynamicImportPrefix) && id.endsWith('\0')) {
1672
+ // const rawId = id.slice(dynamicImportPrefix.length, id.length - 1);
1673
+ // if (rawId in globalsPkg2VarName) {
1674
+ // return `export {default} from '${rawId}';export * from '${rawId}';`;
1675
+ // }
1676
+ // }
1677
+ // },
1678
+ async generateBundle() {
1679
+ const usedModIdSet = new Set(
1680
+ Array.from(this.getModuleIds()).map((s) => normalizePath3(s))
1681
+ );
1682
+ finalOption.collectRequireUrls = requirePkgList.filter((p) => usedModIdSet.has(p.moduleName)).map((p) => p.url);
1683
+ }
1684
+ };
1685
+ };
1686
+
1687
+ // src/node/plugins/externalLoader.ts
1688
+ import { transformWithEsbuild as transformWithEsbuild2 } from "vite";
1689
+ var cssLoader = (resourceName) => {
1690
+ const css = GM_getResourceText(resourceName);
1691
+ GM_addStyle(css);
1692
+ return css;
1693
+ };
1694
+ var jsonLoader = (resourceName) => (
1695
+ // @ts-ignore
1696
+ JSON.parse(GM_getResourceText(resourceName))
1697
+ );
1698
+ var urlLoader = (resourceName, mediaType) => (
1699
+ // @ts-ignore
1700
+ GM_getResourceURL(resourceName, false).replace(
1701
+ /^data:application;base64,/,
1702
+ `data:${mediaType};base64,`
1703
+ )
1704
+ );
1705
+ var rawLoader = (resourceName) => (
1706
+ // @ts-ignore
1707
+ GM_getResourceText(resourceName)
1708
+ );
1709
+ var moduleSourceCode = [
1710
+ `export const cssLoader = ${cssLoader}`,
1711
+ `export const jsonLoader = ${jsonLoader}`,
1712
+ `export const urlLoader = ${urlLoader}`,
1713
+ `export const rawLoader = ${rawLoader}`
1714
+ ].join(";");
1715
+ var externalLoaderPlugin = (finalOption) => {
1716
+ return {
1717
+ name: "monkey:externalLoader",
1718
+ enforce: "pre",
1719
+ apply: "build",
1720
+ async resolveId(id) {
1721
+ if (id == "virtual:plugin-monkey-loader") {
1722
+ return "\0" + id;
1723
+ }
1724
+ },
1725
+ async load(id) {
1726
+ if (id == "\0virtual:plugin-monkey-loader") {
1727
+ return transformWithEsbuild2(
1728
+ moduleSourceCode,
1729
+ "/virtual/plugin-monkey-loader/index.js",
1730
+ {
1731
+ minify: true,
1732
+ sourcemap: true,
1733
+ legalComments: "none"
1734
+ }
1735
+ );
1736
+ }
1737
+ }
1738
+ };
1739
+ };
1740
+
1741
+ // src/node/plugins/externalResource.ts
1742
+ import { normalizePath as normalizePath4 } from "vite";
1743
+ import { lookup, mimes } from "mrmime";
1744
+ import { URLSearchParams as URLSearchParams2 } from "url";
1745
+ var resourceImportPrefix = "\0monkey-resource-import:";
1746
+ var externalResourcePlugin = (finalOption) => {
1747
+ const resourceRecord = {};
1748
+ let viteConfig;
1749
+ return {
1750
+ name: "monkey:externalResource",
1751
+ enforce: "pre",
1752
+ apply: "build",
1753
+ configResolved(config) {
1754
+ viteConfig = config;
1755
+ },
1756
+ async resolveId(id) {
1757
+ const { externalResource } = finalOption.build;
1758
+ if (id in externalResource) {
1759
+ return resourceImportPrefix + id + "\0";
1760
+ }
1761
+ const [resource, query] = id.split("?", 2);
1762
+ if (resource.endsWith(".css") && query) {
1763
+ const id2 = [
1764
+ resource,
1765
+ "?",
1766
+ query.split("&").filter((e) => e != "used").join(`&`)
1767
+ ].join("");
1768
+ if (id2 in externalResource) {
1769
+ return resourceImportPrefix + id2 + "\0";
1770
+ }
1771
+ }
1772
+ },
1773
+ async load(id) {
1774
+ if (id.startsWith(resourceImportPrefix) && id.endsWith("\0")) {
1775
+ const { externalResource } = finalOption.build;
1776
+ const importName = id.substring(
1777
+ resourceImportPrefix.length,
1778
+ id.length - 1
1779
+ );
1780
+ if (!(importName in externalResource)) {
1781
+ return;
1782
+ }
1783
+ const pkg = await getModuleRealInfo(importName);
1784
+ const {
1785
+ resourceName: resourceNameFn,
1786
+ resourceUrl: resourceUrlFn,
1787
+ loader,
1788
+ nodeLoader
1789
+ } = externalResource[importName];
1790
+ const resourceName = await resourceNameFn({ ...pkg, importName });
1791
+ const resourceUrl = await resourceUrlFn({ ...pkg, importName });
1792
+ resourceRecord[importName] = {
1793
+ resourceName,
1794
+ resourceUrl
1795
+ };
1796
+ if (nodeLoader) {
1797
+ return miniCode(
1798
+ await nodeLoader({
1799
+ ...pkg,
1800
+ resourceName,
1801
+ resourceUrl,
1802
+ importName
1803
+ })
1804
+ );
1805
+ } else if (loader) {
1806
+ let fnText;
1807
+ if (loader.prototype && // not arrow function
1808
+ loader.name.length > 0 && loader.name != "function") {
1809
+ if (Reflect.get(loader, Symbol.toStringTag) == "AsyncFunction") {
1810
+ fnText = loader.toString().replace(/^[\s\S]+?\(/, "async function(");
1811
+ } else {
1812
+ fnText = loader.toString().replace(/^[\s\S]+?\(/, "function(");
1813
+ }
1814
+ } else {
1815
+ fnText = loader.toString();
1816
+ }
1817
+ return miniCode(
1818
+ `export default (${fnText})(${JSON.stringify({
1819
+ resourceUrl,
1820
+ importName,
1821
+ ...pkg
1822
+ })})`
1823
+ );
1824
+ }
1825
+ let moduleCode = void 0;
1826
+ const [resource, query] = importName.split("?", 2);
1827
+ const ext = resource.split(".").pop();
1828
+ const mimeType = lookup(ext) ?? "application/octet-stream";
1829
+ const suffixSet = new URLSearchParams2(query);
1830
+ if (suffixSet.has("url") || suffixSet.has("inline")) {
1831
+ moduleCode = [
1832
+ `import {urlLoader as loader} from 'virtual:plugin-monkey-loader'`,
1833
+ `export default loader(...${JSON.stringify([
1834
+ resourceName,
1835
+ mimeType
1836
+ ])})`
1837
+ ].join(";");
1838
+ } else if (suffixSet.has("raw")) {
1839
+ moduleCode = [
1840
+ `import {rawLoader as loader} from 'virtual:plugin-monkey-loader'`,
1841
+ `export default loader(...${JSON.stringify([resourceName])})`
1842
+ ].join(";");
1843
+ } else if (ext == "json") {
1844
+ moduleCode = [
1845
+ `import {jsonLoader as loader} from 'virtual:plugin-monkey-loader'`,
1846
+ `export default loader(...${JSON.stringify([resourceName])})`
1847
+ ].join(";");
1848
+ } else if (ext == "css") {
1849
+ moduleCode = [
1850
+ `import {cssLoader as loader} from 'virtual:plugin-monkey-loader'`,
1851
+ `export default loader(...${JSON.stringify([resourceName])})`
1852
+ ].join(";");
1853
+ } else if (viteConfig.assetsInclude(importName.split("?", 1)[0])) {
1854
+ const mediaType = mimes[ext];
1855
+ moduleCode = [
1856
+ `import {urlLoader as loader} from 'virtual:plugin-monkey-loader'`,
1857
+ `export default loader(...${JSON.stringify([
1858
+ resourceName,
1859
+ mediaType
1860
+ ])})`
1861
+ ].join(";");
1862
+ }
1863
+ if (moduleCode) {
1864
+ if (moduleCode.includes("rawLoader") || moduleCode.includes("jsonLoader") || moduleCode.includes("cssLoader")) {
1865
+ finalOption.userscript.grant.add("GM_getResourceText");
1866
+ } else if (moduleCode.includes("urlLoader")) {
1867
+ finalOption.userscript.grant.add("GM_getResourceURL");
1868
+ }
1869
+ return miniCode(moduleCode);
1870
+ }
1871
+ throw new Error(`module: ${importName} not found loader`);
1872
+ }
1873
+ },
1874
+ generateBundle() {
1875
+ const usedModIdSet = new Set(
1876
+ Array.from(this.getModuleIds()).map((s) => normalizePath4(s))
1877
+ );
1878
+ Array.from(usedModIdSet).forEach((id) => {
1879
+ if (id.startsWith(resourceImportPrefix) && id.endsWith("\0")) {
1880
+ usedModIdSet.add(
1881
+ id.substring(resourceImportPrefix.length, id.length - 1)
1882
+ );
1883
+ }
1884
+ });
1885
+ const collectResource = {};
1886
+ Object.entries(resourceRecord).forEach(
1887
+ ([importName, { resourceName, resourceUrl }]) => {
1888
+ if (usedModIdSet.has(importName)) {
1889
+ collectResource[resourceName] = resourceUrl;
1890
+ }
1891
+ }
1892
+ );
1893
+ finalOption.collectResource = collectResource;
1894
+ }
1895
+ };
1896
+ };
1897
+
1898
+ // src/node/plugins/finalBundle.ts
1899
+ import { build } from "vite";
1900
+
1901
+ // src/node/_lazy.ts
1902
+ var lazyValuePlaceholder = {};
1903
+ var lazyValue = (fn) => {
1904
+ let temp = lazyValuePlaceholder;
1905
+ return {
1906
+ get value() {
1907
+ if (temp === lazyValuePlaceholder) {
1908
+ temp = fn();
1909
+ }
1910
+ return temp;
1911
+ }
1912
+ };
1913
+ };
1914
+
1915
+ // src/node/systemjs.ts
1916
+ import module from "module";
1917
+ import fs3 from "fs/promises";
1918
+
1919
+ // src/node/util.ts
1920
+ var util_exports = {};
1921
+ __export(util_exports, {
1922
+ dataUrl: () => dataUrl,
1923
+ fn2dataUrl: () => fn2dataUrl,
1924
+ unimportPreset: () => unimportPreset
1925
+ });
1926
+ import { transformWithEsbuild as transformWithEsbuild3 } from "vite";
1927
+ var fn2dataUrl = async (fn, ...args) => {
1928
+ return "data:application/javascript," + encodeURIComponent(
1929
+ (await transformWithEsbuild3(
1930
+ `;(${fn})(...${JSON.stringify(args)})`,
1931
+ "any_name.js",
1932
+ {
1933
+ minify: true,
1934
+ sourcemap: false,
1935
+ legalComments: "none"
1936
+ }
1937
+ )).code.trimEnd()
1938
+ );
1939
+ };
1940
+ function dataUrl(p0, ...args) {
1941
+ if (typeof p0 == "string") {
1942
+ return `data:application/javascript,` + encodeURIComponent(p0);
1943
+ }
1944
+ return fn2dataUrl(p0, ...args);
1945
+ }
1946
+ var unimportPreset = preset;
1947
+
1948
+ // src/node/systemjs.ts
1949
+ var _require = module.createRequire(import.meta.url);
1950
+ var systemjsPkg = _require(`systemjs/package.json`);
1951
+ var systemjsSubPaths = [
1952
+ "dist/system.min.js",
1953
+ "dist/extras/named-register.min.js"
1954
+ ];
1955
+ var customSystemInstanceCode = `;(typeof System!='undefined')&&(System=new System.constructor());`;
1956
+ var systemjsAbsolutePaths = systemjsSubPaths.map((s) => {
1957
+ return _require.resolve(`systemjs/` + s);
1958
+ });
1959
+ var systemjsTexts = lazyValue(() => {
1960
+ return Promise.all(
1961
+ systemjsAbsolutePaths.map(
1962
+ (s) => fs3.readFile(s, "utf-8").then(
1963
+ (s2) => s2.trim().replace(/^\/\*[\s\S]*?\*\//, "").replace(/\/\/.*map$/, "").trim()
1964
+ )
1965
+ ).concat([Promise.resolve(customSystemInstanceCode)])
1966
+ );
1967
+ });
1968
+ var getSystemjsRequireUrls = (fn) => {
1969
+ return systemjsSubPaths.map((p) => {
1970
+ return fn(systemjsPkg.version, systemjsPkg.name, p, p);
1971
+ }).concat([dataUrl(customSystemInstanceCode)]);
1972
+ };
1973
+
1974
+ // src/node/topLevelAwait.ts
1975
+ import * as acornWalk2 from "acorn-walk";
1976
+ import MagicString from "magic-string";
1977
+ var awaitOffset = `await`.length;
1978
+ var initTlaIdentifier = `_TLA_`;
1979
+ var findSafeTlaIdentifier = (rawBundle) => {
1980
+ const codes = [];
1981
+ for (const chunk of Object.values(rawBundle)) {
1982
+ if (chunk.type == "chunk") {
1983
+ codes.push(chunk.code);
1984
+ }
1985
+ }
1986
+ let x = 0;
1987
+ let identifier = initTlaIdentifier;
1988
+ while (codes.some((code) => code.includes(identifier))) {
1989
+ x++;
1990
+ identifier = initTlaIdentifier + x.toString(36);
1991
+ }
1992
+ return identifier;
1993
+ };
1994
+ var startWith = (text, searchString, position = 0, ignoreString) => {
1995
+ for (let i = position; i < text.length; i++) {
1996
+ if (ignoreString.includes(text[i])) {
1997
+ continue;
1998
+ }
1999
+ return text.startsWith(searchString, i);
2000
+ }
2001
+ return false;
2002
+ };
2003
+ var transformTlaToIdentifier = (context, chunk, identifier) => {
2004
+ if (chunk.type == "chunk") {
2005
+ const code = chunk.code;
2006
+ if (!code.includes(`await`)) {
2007
+ return;
2008
+ }
2009
+ const ast = context.parse(code);
2010
+ const tlaNodes = [];
2011
+ const tlaForOfNodes = [];
2012
+ acornWalk2.simple(
2013
+ ast,
2014
+ {
2015
+ AwaitExpression(node) {
2016
+ tlaNodes.push(node);
2017
+ },
2018
+ // @ts-ignore
2019
+ ForOfStatement(node) {
2020
+ if (node.await === true) {
2021
+ tlaForOfNodes.push(node);
2022
+ }
2023
+ }
2024
+ },
2025
+ { ...acornWalk2.base, Function: () => {
2026
+ } }
2027
+ );
2028
+ if (tlaNodes.length > 0 || tlaForOfNodes.length > 0) {
2029
+ const ms = new MagicString(code);
2030
+ tlaNodes.forEach((node) => {
2031
+ if (!startWith(chunk.code, "(", node.start + awaitOffset, " \r\n")) {
2032
+ ms.appendLeft(node.start + awaitOffset, `(`);
2033
+ ms.appendRight(node.end, `)`);
2034
+ }
2035
+ ms.update(node.start, node.start + awaitOffset, identifier);
2036
+ });
2037
+ tlaForOfNodes.forEach((node) => {
2038
+ ms.appendLeft(node.start, `${identifier + `FOR`}((async()=>{`);
2039
+ ms.appendRight(node.end, `})());`);
2040
+ });
2041
+ return {
2042
+ code: ms.toString(),
2043
+ map: ms.generateMap()
2044
+ };
2045
+ }
2046
+ }
2047
+ };
2048
+ var transformIdentifierToTla = (context, chunk, identifier) => {
2049
+ if (chunk.type == "chunk") {
2050
+ if (!chunk.code.includes(identifier)) {
2051
+ return;
2052
+ }
2053
+ const base3 = Object.keys(acornWalk2.base).reduce((p, key) => {
2054
+ if (key in p)
2055
+ return p;
2056
+ p[key] = (node, state, callback) => {
2057
+ if (chunk.code.substring(node.start, node.end).includes(identifier)) {
2058
+ return acornWalk2.base[key](node, state, callback);
2059
+ }
2060
+ };
2061
+ return p;
2062
+ }, {});
2063
+ const ast = context.parse(chunk.code);
2064
+ const tlaCallNodes = [];
2065
+ const forTlaCallNodes = [];
2066
+ const topFnNodes = [];
2067
+ acornWalk2.simple(
2068
+ ast,
2069
+ {
2070
+ // @ts-ignore
2071
+ CallExpression(node) {
2072
+ const { name, type } = node.callee ?? {};
2073
+ if (type === `Identifier`) {
2074
+ if (name === identifier) {
2075
+ tlaCallNodes.push(node);
2076
+ } else if (name === identifier + `FOR`) {
2077
+ forTlaCallNodes.push(node);
2078
+ }
2079
+ }
2080
+ }
2081
+ },
2082
+ {
2083
+ ...base3,
2084
+ Function: (node, state, callback) => {
2085
+ if (topFnNodes.length == 0) {
2086
+ topFnNodes.push(node);
2087
+ }
2088
+ if (chunk.code.substring(node.start, node.end).includes(identifier)) {
2089
+ return acornWalk2.base.Function(node, state, callback);
2090
+ }
2091
+ }
2092
+ }
2093
+ );
2094
+ if (tlaCallNodes.length > 0 || forTlaCallNodes.length > 0) {
2095
+ const ms = new MagicString(chunk.code, {});
2096
+ tlaCallNodes.forEach((node) => {
2097
+ const callee = node.callee;
2098
+ ms.update(callee.start, callee.end, "await");
2099
+ });
2100
+ forTlaCallNodes.forEach((node) => {
2101
+ var _a, _b, _c, _d, _e;
2102
+ const forOfNode = (_e = (_d = (_c = (_b = (_a = node.arguments) == null ? void 0 : _a[0]) == null ? void 0 : _b.callee) == null ? void 0 : _c.body) == null ? void 0 : _d.body) == null ? void 0 : _e[0];
2103
+ ms.update(node.start, forOfNode.start, "");
2104
+ ms.update(forOfNode.end, node.end, "");
2105
+ });
2106
+ topFnNodes.forEach((node) => {
2107
+ ms.appendLeft(node.start, `async `);
2108
+ });
2109
+ chunk.code = ms.toString();
2110
+ if (chunk.map) {
2111
+ chunk.map;
2112
+ }
2113
+ }
2114
+ }
2115
+ };
2116
+
2117
+ // src/node/plugins/finalBundle.ts
2118
+ var __entry_name = `__monkey.entry.js`;
2119
+ var polyfillId = "\0vite/legacy-polyfills";
2120
+ var systemJsImportMapPrefix = `user`;
2121
+ var finalBundlePlugin = (finalOption) => {
2122
+ return {
2123
+ name: "monkey:finalBundle",
2124
+ apply: "build",
2125
+ enforce: "post",
2126
+ async generateBundle(_, rawBundle) {
2127
+ const entryChunks = [];
2128
+ const chunks = [];
2129
+ Object.values(rawBundle).forEach((chunk) => {
2130
+ if (chunk.type == "chunk") {
2131
+ if (chunk.facadeModuleId != polyfillId) {
2132
+ chunks.push(chunk);
2133
+ }
2134
+ if (chunk.isEntry) {
2135
+ if (chunk.facadeModuleId == polyfillId) {
2136
+ entryChunks.unshift(chunk);
2137
+ } else {
2138
+ entryChunks.push(chunk);
2139
+ }
2140
+ }
2141
+ }
2142
+ });
2143
+ const fristEntryChunk = entryChunks.find(
2144
+ (s) => s.facadeModuleId != polyfillId
2145
+ );
2146
+ const hasDynamicImport = entryChunks.some(
2147
+ (e) => e.dynamicImports.length > 0
2148
+ );
2149
+ const usedModules = /* @__PURE__ */ new Set();
2150
+ const tlaIdentifier = lazyValue(() => findSafeTlaIdentifier(rawBundle));
2151
+ const buildResult = await build({
2152
+ logLevel: "error",
2153
+ configFile: false,
2154
+ esbuild: false,
2155
+ plugins: [
2156
+ {
2157
+ name: "mokey:mock",
2158
+ enforce: "pre",
2159
+ resolveId(source, importer, options) {
2160
+ if (!importer && options.isEntry) {
2161
+ return "\0" + source;
2162
+ }
2163
+ const chunk = Object.values(rawBundle).find(
2164
+ (chunk2) => chunk2.type == "chunk" && source.endsWith(chunk2.fileName)
2165
+ );
2166
+ if (chunk) {
2167
+ return "\0" + source;
2168
+ }
2169
+ },
2170
+ async load(id) {
2171
+ if (!id.startsWith("\0"))
2172
+ return;
2173
+ if (id.endsWith(__entry_name)) {
2174
+ return entryChunks.map((a) => `import ${JSON.stringify(`./${a.fileName}`)};`).join("\n");
2175
+ }
2176
+ const [k, chunk] = Object.entries(rawBundle).find(
2177
+ ([k2, chunk2]) => id.endsWith(chunk2.fileName)
2178
+ ) ?? [];
2179
+ if (chunk && chunk.type == "chunk" && k) {
2180
+ usedModules.add(k);
2181
+ if (!hasDynamicImport) {
2182
+ const ch = transformTlaToIdentifier(
2183
+ this,
2184
+ chunk,
2185
+ tlaIdentifier.value
2186
+ );
2187
+ if (ch)
2188
+ return ch;
2189
+ }
2190
+ return {
2191
+ code: chunk.code,
2192
+ map: chunk.map
2193
+ };
2194
+ }
2195
+ },
2196
+ generateBundle(_2, iifeBundle) {
2197
+ if (hasDynamicImport) {
2198
+ return;
2199
+ }
2200
+ Object.entries(iifeBundle).forEach(([k, chunk]) => {
2201
+ transformIdentifierToTla(this, chunk, tlaIdentifier.value);
2202
+ });
2203
+ }
2204
+ }
2205
+ ],
2206
+ build: {
2207
+ write: false,
2208
+ minify: false,
2209
+ target: "esnext",
2210
+ rollupOptions: {
2211
+ external(source) {
2212
+ return source in finalOption.globalsPkg2VarName;
2213
+ },
2214
+ output: {
2215
+ globals: finalOption.globalsPkg2VarName
2216
+ }
2217
+ },
2218
+ lib: {
2219
+ entry: __entry_name,
2220
+ formats: [hasDynamicImport ? "system" : "iife"],
2221
+ name: hasDynamicImport ? void 0 : "__expose__",
2222
+ fileName: () => `__entry.js`
2223
+ }
2224
+ }
2225
+ });
2226
+ usedModules.forEach((k) => {
2227
+ if (fristEntryChunk != rawBundle[k]) {
2228
+ delete rawBundle[k];
2229
+ }
2230
+ });
2231
+ const buildBundle = buildResult[0].output.flat();
2232
+ let finalJsCode = ``;
2233
+ if (hasDynamicImport) {
2234
+ const systemJsModules = [];
2235
+ let entryName = "";
2236
+ Object.entries(buildBundle).forEach(([k, chunk]) => {
2237
+ if (chunk.type == "chunk") {
2238
+ const name = JSON.stringify(`./` + chunk.fileName);
2239
+ systemJsModules.push(
2240
+ chunk.code.trimStart().replace(/^System\.register\(/, `System.register(${name}, `)
2241
+ );
2242
+ if (chunk.isEntry) {
2243
+ entryName = name;
2244
+ }
2245
+ }
2246
+ });
2247
+ systemJsModules.push(`System.import(${entryName}, "./");`);
2248
+ finalJsCode = systemJsModules.join("\n");
2249
+ const usedModuleIds = Array.from(this.getModuleIds()).filter(
2250
+ (d) => d in finalOption.globalsPkg2VarName
2251
+ );
2252
+ const importsMap = usedModuleIds.reduce(
2253
+ (p, c) => {
2254
+ p[c] = `${systemJsImportMapPrefix}:${c}`;
2255
+ return p;
2256
+ },
2257
+ {}
2258
+ );
2259
+ finalJsCode = [
2260
+ Object.keys(importsMap).length > 0 ? `System.addImportMap({ imports: ${JSON.stringify(importsMap)} });` : ``,
2261
+ ...usedModuleIds.map(
2262
+ (id) => `System.set(${JSON.stringify(
2263
+ `${systemJsImportMapPrefix}:${id}`
2264
+ )}, ${moduleExportExpressionWrapper(
2265
+ finalOption.globalsPkg2VarName[id]
2266
+ )});`
2267
+ ),
2268
+ "\n" + finalJsCode
2269
+ ].filter((s) => s).join("\n");
2270
+ if (typeof finalOption.systemjs == "function") {
2271
+ finalOption.collectRequireUrls.push(
2272
+ ...getSystemjsRequireUrls(finalOption.systemjs)
2273
+ );
2274
+ } else {
2275
+ finalJsCode = (await systemjsTexts.value).join("\n") + "\n" + finalJsCode;
2276
+ }
2277
+ } else {
2278
+ Object.entries(buildBundle).forEach(([k, chunk]) => {
2279
+ if (chunk.type == "chunk" && chunk.isEntry) {
2280
+ finalJsCode = chunk.code;
2281
+ }
2282
+ });
2283
+ }
2284
+ const injectCssCode = await getInjectCssCode(finalOption, rawBundle);
2285
+ let collectGrantSet;
2286
+ if (finalOption.build.autoGrant) {
2287
+ collectGrantSet = collectGrant(
2288
+ this,
2289
+ chunks.map((s) => s.code).concat(injectCssCode || ``)
2290
+ );
2291
+ } else {
2292
+ collectGrantSet = /* @__PURE__ */ new Set();
2293
+ }
2294
+ const comment = await finalMonkeyOptionToComment(
2295
+ finalOption,
2296
+ collectGrantSet,
2297
+ "build"
2298
+ );
2299
+ const mergedCode = [comment, injectCssCode, finalJsCode].filter((s) => s).join(`
2300
+
2301
+ `).trimEnd();
2302
+ if (fristEntryChunk) {
2303
+ fristEntryChunk.fileName = finalOption.build.fileName;
2304
+ fristEntryChunk.code = mergedCode;
2305
+ } else {
2306
+ this.emitFile({
2307
+ type: "asset",
2308
+ fileName: finalOption.build.fileName,
2309
+ source: mergedCode
2310
+ });
2311
+ }
2312
+ if (finalOption.build.metaFileName) {
2313
+ this.emitFile({
2314
+ type: "asset",
2315
+ fileName: finalOption.build.metaFileName(),
2316
+ source: await finalMonkeyOptionToComment(
2317
+ finalOption,
2318
+ collectGrantSet,
2319
+ "meta"
2320
+ )
2321
+ });
2322
+ }
2323
+ }
2324
+ };
2325
+ };
2326
+
2327
+ // src/node/plugins/perview.ts
2328
+ import path4 from "path";
2329
+ import { normalizePath as normalizePath5 } from "vite";
2330
+ var perviewPlugin = (finalOption) => {
2331
+ let viteConfig;
2332
+ return {
2333
+ name: "monkey:perview",
2334
+ apply: "serve",
2335
+ configResolved(config) {
2336
+ viteConfig = config;
2337
+ },
2338
+ async configurePreviewServer(server) {
2339
+ server.middlewares.use(async (req, res, next) => {
2340
+ if (["/", "/index.html"].includes((req.url ?? "").split("?")[0])) {
2341
+ const distDirPath = path4.join(process.cwd(), viteConfig.build.outDir);
2342
+ const urls = [];
2343
+ for await (const pathname of walk(distDirPath)) {
2344
+ if (pathname.endsWith(".user.js")) {
2345
+ const fileName = normalizePath5(
2346
+ path4.relative(distDirPath, pathname)
2347
+ );
2348
+ urls.push(`/` + fileName);
2349
+ }
2350
+ }
2351
+ res.setHeader("content-type", "text/html; charset=utf-8");
2352
+ res.end(fcToHtml(previewTemplate, urls));
2353
+ return;
2354
+ }
2355
+ next();
2356
+ if (finalOption.server.closePreviewAutomatically) {
2357
+ setTimeout(() => {
2358
+ server.close();
2359
+ }, 3e3);
2360
+ }
2361
+ });
2362
+ }
2363
+ };
2364
+ };
2365
+
2366
+ // src/node/plugins/redirectClient.ts
2367
+ var redirectClientPlugin = (finalOption) => {
2368
+ return {
2369
+ name: "monkey:redirectClient",
2370
+ enforce: "pre",
2371
+ apply: "build",
2372
+ resolveId(source, importer, options) {
2373
+ if (source == "vite-plugin-monkey/dist/client") {
2374
+ return this.resolve(
2375
+ "vite-plugin-monkey/dist/native",
2376
+ importer,
2377
+ options
2378
+ );
2379
+ }
2380
+ }
2381
+ };
2382
+ };
2383
+
2384
+ // src/node/plugins/inlinesAsset.ts
2385
+ import fs4 from "fs/promises";
2386
+ var inlinesAssetPlugin = (finalOption) => {
2387
+ let viteConfig;
2388
+ return {
2389
+ name: "monkey:inlinesAsset",
2390
+ enforce: "post",
2391
+ apply: "build",
2392
+ async configResolved(resolvedConfig) {
2393
+ viteConfig = resolvedConfig;
2394
+ },
2395
+ async transform(code, id) {
2396
+ if (viteConfig.assetsInclude(id) && [`.svg`, `.svg?inline`, `.svg?url`].some((s) => id.endsWith(s)) && code.includes(`__VITE_ASSET__`)) {
2397
+ const base64Text = (await fs4.readFile(id.split("?")[0])).toString(
2398
+ "base64"
2399
+ );
2400
+ return `export default ${JSON.stringify(
2401
+ `data:image/svg+xml;base64,` + base64Text
2402
+ )}`;
2403
+ }
2404
+ },
2405
+ generateBundle(opts, bundle) {
2406
+ for (const key in bundle) {
2407
+ if ([`.svg`].some((s) => key.endsWith(s))) {
2408
+ delete bundle[key];
2409
+ }
2410
+ }
2411
+ }
2412
+ };
2413
+ };
2414
+
2415
+ // src/node/plugins/index.ts
2416
+ var monkeyPluginList = [
2417
+ // only serve
2418
+ virtualHtmlPlugin,
2419
+ fixViteAssetPlugin,
2420
+ fixViteClientPlugin,
2421
+ serverPlugin,
2422
+ // only build pre
2423
+ redirectClientPlugin,
2424
+ externalLoaderPlugin,
2425
+ externalResourcePlugin,
2426
+ externalGlobalsPlugin,
2427
+ // only build post
2428
+ inlinesAssetPlugin,
2429
+ // only build, final build
2430
+ finalBundlePlugin,
2431
+ // only preview
2432
+ perviewPlugin
2433
+ ];
2434
+ var plugins_default = monkeyPluginList;
2435
+
2436
+ // src/node/index.ts
2437
+ var node_default = (pluginOption) => {
2438
+ const finalPluginOption = resolvedOption(pluginOption);
2439
+ const monkeyPlugin = {
2440
+ name: "monkey:entry",
2441
+ enforce: "post",
2442
+ async config(userConfig, { command }) {
2443
+ var _a, _b, _c;
2444
+ const isServe = command == "serve";
2445
+ return {
2446
+ resolve: {
2447
+ alias: {
2448
+ [finalPluginOption.clientAlias]: "vite-plugin-monkey/dist/client"
2449
+ }
2450
+ },
2451
+ define: {
2452
+ "process.env.NODE_ENV": ((_a = userConfig.define) == null ? void 0 : _a["process.env.NODE_ENV"]) ?? JSON.stringify(
2453
+ userConfig.mode ?? (isServe ? "development" : "production")
2454
+ )
2455
+ },
2456
+ esbuild: {
2457
+ supported: {
2458
+ "top-level-await": true
2459
+ }
2460
+ },
2461
+ build: {
2462
+ assetsInlineLimit: Number.MAX_SAFE_INTEGER,
2463
+ chunkSizeWarningLimit: Number.MAX_SAFE_INTEGER,
2464
+ modulePreload: false,
2465
+ assetsDir: "./",
2466
+ cssCodeSplit: false,
2467
+ minify: ((_b = userConfig.build) == null ? void 0 : _b.minify) ?? false,
2468
+ cssMinify: ((_c = userConfig.build) == null ? void 0 : _c.cssMinify) ?? true,
2469
+ rollupOptions: {
2470
+ // serve pre-bundling need
2471
+ input: finalPluginOption.entry
2472
+ },
2473
+ sourcemap: false
2474
+ // TODO
2475
+ // sourcemap: sourcemap,
2476
+ }
2477
+ };
2478
+ }
2479
+ };
2480
+ return [monkeyPlugin, ...plugins_default.map((m) => m(finalPluginOption))];
2481
+ };
2482
+ export {
2483
+ cdn_exports as cdn,
2484
+ node_default as default,
2485
+ util_exports as util
2486
+ };
2487
+ //# sourceMappingURL=index.mjs.map