Files
ame/scripts/utils/userscript.ts

76 lines
1.7 KiB
TypeScript
Raw Permalink Normal View History

2023-07-28 22:25:29 +03:00
import { readFile } from "fs/promises";
2023-08-04 00:30:31 +03:00
import { join, basename, dirname } from "path";
2023-07-28 22:25:29 +03:00
import { LibraryFormats, Plugin, ResolvedConfig } from "vite";
2022-12-30 02:03:51 +02:00
export interface UserScriptOptions {
entry: string;
format: LibraryFormats;
name?: string;
port?: number;
cdn?: string;
}
2023-07-28 22:25:29 +03:00
export function UserScriptPlugin(options: UserScriptOptions): Plugin {
2022-12-30 02:03:51 +02:00
let config: ResolvedConfig;
return {
2023-07-28 22:25:29 +03:00
name: "userscript",
2022-12-30 19:18:50 +02:00
config() {
2022-12-30 02:03:51 +02:00
const name = options.name ?? basename(dirname(options.entry));
return {
build: {
lib: {
name: name,
2023-07-28 22:25:29 +03:00
formats: [options.format],
2022-12-30 02:03:51 +02:00
entry: {
[name]: options.entry
}
},
rollupOptions: {
output: {
2023-07-28 22:25:29 +03:00
entryFileNames: "[name].user.js"
2022-12-30 02:03:51 +02:00
}
}
}
};
},
configResolved(resolvedConfig) {
config = resolvedConfig;
},
async generateBundle(outputOptions, bundle) {
for (const chunk of Object.values(bundle)) {
2023-07-28 22:25:29 +03:00
if (chunk.type !== "chunk") continue;
2022-12-30 02:03:51 +02:00
if (!chunk.isEntry) continue;
if (!chunk.facadeModuleId) continue;
2023-07-28 22:25:29 +03:00
const code = await readFile(chunk.facadeModuleId, { encoding: "utf8" });
2022-12-30 02:03:51 +02:00
2023-07-28 22:25:29 +03:00
let header = "";
for (const line of code.split("\n")) {
if (!line.startsWith("//")) break;
header += line + "\n";
2022-12-30 02:03:51 +02:00
}
2023-07-28 22:25:29 +03:00
let url = "";
if (config.mode === "production") {
2022-12-30 02:03:51 +02:00
if (options.cdn) url = `${options.cdn}${chunk.name}.user.js`;
} else {
2023-08-04 00:30:31 +03:00
if (options.port) url = `http://localhost:${join(options.port.toString(), config.build.outDir, chunk.name).replaceAll("\\", "/")}.user.js`;
2022-12-30 02:03:51 +02:00
}
if (url) {
header = header.replaceAll(
2023-07-28 22:25:29 +03:00
`// ==/UserScript==`,
2022-12-30 02:03:51 +02:00
`// @downloadURL ${url}\n` +
`// @updateURL ${url}\n` +
2023-07-28 22:25:29 +03:00
`// ==/UserScript==`
2022-12-30 02:03:51 +02:00
);
}
2023-07-28 22:25:29 +03:00
chunk.code = header + "\n" + chunk.code;
2022-12-30 02:03:51 +02:00
}
}
};
}