Files
browser-scripts/esbuild.mjs
2022-06-06 15:01:55 -05:00

129 lines
3.0 KiB
JavaScript

import { build } from 'esbuild'
import {
lstatSync,
readdirSync,
readFileSync,
unlinkSync,
writeFileSync,
} from 'fs'
const BaseUrl = `https://git.zomo.dev/zomo/browser-scripts`
const FileUrl = name =>
`https://git.zomo.dev/zomo/browser-scripts/raw/branch/main/dist/${name}.zomo.js`
function isValueNotEmpty(val) {
return (
val !== '' &&
val !== false &&
val !== [] &&
val !== undefined &&
val !== null
)
}
function padr(str, len) {
return str + ' '.repeat(len - str.length)
}
function MetadataArgs(name) {
var meta = {
name: name,
namespace: 'zomo.dev',
match: '',
excludematch: '',
version: '0.0.0',
description: '',
icon: '',
require: '',
resource: '',
runat: '',
noframes: false,
grant: '',
injectinto: '',
downloadURL: FileUrl(name),
supportURL: `${BaseUrl}/issues`,
homepageURL: BaseUrl,
unwrap: false,
}
try {
let args = JSON.parse(
readFileSync(`scripts/${name}/meta.json`).toString()
)
for (let key in meta) {
if (isValueNotEmpty(args[key])) {
meta[key] = args[key]
}
}
} catch (e) {
console.log(e)
console.log(
`scripts/${name}/meta.json not found, using default metadata`
)
}
const keyConversion = {
injectinto: 'inject-into',
excludematch: 'exclude-match',
}
return `// ==UserScript==
${Object.keys(meta)
.filter(key => isValueNotEmpty(meta[key]))
.map(key => {
let val = meta[key],
key_str = padr(key in keyConversion ? keyConversion[key] : key, 12)
if (typeof val === 'boolean') {
if (val) return `// @${key_str}`
} else if (typeof val === 'string') {
return `// @${key_str} ${val}`
} else if (Array.isArray(val)) {
return val.map(v => `// @${key_str} ${v}`).join('\n')
}
return ''
})
.filter(l => l.length)
.join('\n')}
// ==/UserScript==
`
}
async function compileProject(name) {
await build({
entryPoints: [`scripts/${name}/main.ts`],
outfile: `dist/${name}.user.js`,
target: 'esnext',
platform: 'node',
format: 'cjs',
watch: false,
bundle: true,
minify: false,
sourcemap: false,
define: {
UserScriptProjectName: `'${name}'`,
UserScriptFileUrl: `'${FileUrl(name)}'`,
},
})
//add UserScript header
let meta = MetadataArgs(name)
let content = readFileSync(`dist/${name}.user.js`).toString()
writeFileSync(`dist/${name}.user.js`, meta + content)
}
//delete compiled scripts
readdirSync('dist').forEach(file => unlinkSync(`dist/${file}`))
//compile scripts
readdirSync('scripts').forEach(name => {
if (
lstatSync(`scripts/${name}`).isDirectory() &&
lstatSync(`scripts/${name}/main.ts`).isFile()
) {
compileProject(name)
}
})