llm-agent-plugin/esbuild.config.mjs
2026-06-06 23:43:54 +03:00

112 lines
4.2 KiB
JavaScript

import esbuild from 'esbuild'
import process from 'process'
import builtins from 'builtin-modules'
import fs from 'fs'
import path from 'path'
import { ObfuscatorPlugin } from 'esbuild-plugin-obfuscator' // Импорт плагина
const banner = `/*
THIS IS A GENERATED/BUNDLED FILE BY ESBUILD
if you want to view the source, please visit the github repository of this plugin
*/
`
const arg = process.argv[2] || ''
const prod = arg === 'production'
const obfuscate = arg === 'dev-obfuscate'
const outputFolder = '../llm-agent-plugin-build';
console.log(arg)
console.log(obfuscate)
const renameCssPlugin = () => ({
name: 'rename-css',
setup (build) {
build.onEnd(() => {
const outDir = path.dirname(build.initialOptions.outfile || 'main.js')
const mainCss = path.join(outDir, 'main.css')
const stylesCss = path.join(outDir, 'styles.css')
if (fs.existsSync(mainCss)) {
fs.renameSync(mainCss, stylesCss)
console.log(`Renamed ${mainCss} to ${stylesCss}`)
}
})
}
})
const copyManifestPlugin = () => ({
name: 'copy-manifest',
setup(build) {
build.onEnd(() => {
const outDir = path.dirname(build.initialOptions.outfile || 'main.js'); // Целевая директория сборки
const manifestSourcePath = path.join(process.cwd(), 'src', 'json', 'manifest.json'); // Исходный путь к manifest.json
const manifestDestPath = path.join(outDir, 'manifest.json'); // Целевой путь в папке сборки
if (fs.existsSync(manifestSourcePath)) {
fs.copyFileSync(manifestSourcePath, manifestDestPath);
console.log(`Copied manifest.json from ${manifestSourcePath} to ${manifestDestPath}`);
} else {
console.warn(`Warning: manifest.json not found at ${manifestSourcePath}, skipping copy.`);
}
});
},
});
const context = await esbuild.context({
banner: {
js: banner
},
entryPoints: ['main.ts'],
bundle: true,
external: [
'obsidian',
'electron',
'@codemirror/autocomplete',
'@codemirror/collab',
'@codemirror/commands',
'@codemirror/language',
'@codemirror/lint',
'@codemirror/search',
'@codemirror/state',
'@codemirror/view',
'@lezer/common',
'@lezer/highlight',
'@lezer/lr',
...builtins
],
format: 'cjs',
target: 'es2019',
logLevel: 'info',
sourcemap: prod ? false : 'inline',
treeShaking: true,
outfile: path.join(outputFolder, 'main.js'),
minify: prod,
loader: {
'.css': 'css'
},
plugins: [
renameCssPlugin(),
copyManifestPlugin(),
...(prod || obfuscate ? [ObfuscatorPlugin({
compact: true, // Уплотняет код в одну строку
identifierNamesGenerator: 'mangled', // Заменяет имена переменных на короткие бессмысленные комбинации
renameGlobals: true, // Включает обфускацию глобальных переменных и функций в том числе классов
controlFlowFlattening: true, // Усложняет структуру выполнения (перемешивает логику)
controlFlowFlatteningThreshold: 0.75, // Вероятность применения изменения потока управления для узлов
debugProtection: true, // Вставляет код, блокирующий инструменты разработчика (DevTools)
debugProtectionInterval: true, // Регулярно перезапускает проверку защиты от отладки
disableConsoleOutput: true, // Запрещает вывод логов в консоль (console.log и др.)
// Можно добавить filter, чтобы обфусцировать только нужные файлы, например ['**/*.js']
})] : [])
]
})
if (prod) {
await context.rebuild()
process.exit(0)
} else {
await context.watch()
}