forked from mbnuqw/sidebery
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathscripts.js
320 lines (290 loc) · 8.99 KB
/
scripts.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
/* eslint no-console: off */
const path = require('path')
const fs = require('fs')
const esbuild = require('esbuild')
const { parse, compileTemplate, compileScript } = require('@vue/compiler-sfc')
const { IS_DEV, ADDON_PATH, VUE_DIST } = require('./utils')
const { treeToList, getTSConfig, colorize, watch, log, logOk, logErr } = require('./utils')
const forChromium = process.argv.includes('--chromium')
const SRC_DIR = './src'
const OUTPUT_DIR = ADDON_PATH
const NORM_SRC_DIR = path.normalize(SRC_DIR)
const TS_CONFIG = getTSConfig()
const BUNDLES = {
'src/page.group/group.ts': true,
'src/page.url/url.ts': true,
}
const IMPORT_RE = /(^|\n|\r\n|;)(im|ex)port\s?(.*?)"(\.\.?|src|vue)(\/.+?)?"/g
const ESBUILD_DEFINE = forChromium ? { browser: 'chrome' } : undefined
function fixModuleImports(data) {
return data.replace(IMPORT_RE, (match, p1, p2, p3, p4, p5) => {
if (p4 === 'src') return `${p1}${p2}port ${p3}'${p5}.js'`
else if (p4 === 'vue') return `${p1}${p2}port ${p3}'/vendor/${VUE_DIST}'`
else return `${p1}${p2}port ${p3}'${p4}${p5}.js'`
})
}
/**
* Get list of .ts files
*/
async function getSrcFiles() {
const result = []
const files = await treeToList(SRC_DIR)
for (const f of files) {
if (!f.file) continue
const isTS = f.file.endsWith('.ts') && !f.file.endsWith('.d.ts')
const isVUE = f.file.endsWith('.vue')
if (!isTS && !isVUE) continue
const srcPath = path.join(f.dir, f.file)
const outDir = path.join(OUTPUT_DIR, f.dir.replace(NORM_SRC_DIR, ''))
const outFile = isTS ? f.file.slice(0, -3) + '.js' : f.file + '.js'
const outPath = path.join(outDir, outFile)
result.push({ srcDir: f.dir, srcFile: f.file, srcPath, outDir, outFile, outPath, isTS, isVUE })
}
return result
}
/**
* @type esbuild.Plugin
*/
const vueComponentsPlugin = {
name: 'vueComponentsPlugin',
setup: build => {
build.onResolve({ filter: /^vue$/ }, () => {
return { path: `/vendor/${VUE_DIST}`, external: true }
})
build.onResolve({ filter: /.*\.vue$/ }, args => {
const impDir = path.dirname(args.importer)
let fullPath
if (args.path[0] === '.') fullPath = path.resolve(impDir, args.path)
else if (args.path.startsWith('src/')) fullPath = path.resolve(args.path)
return { path: fullPath, namespace: 'vue-component', sideEffects: false }
})
build.onLoad({ filter: /.*/, namespace: 'vue-component' }, async args => {
const resolveDir = path.dirname(args.path)
const resultCode = await compileVueComponent(args.path, path.basename(args.path))
return {
contents: resultCode,
loader: 'ts',
resolveDir,
}
})
},
}
const PREPROC_OPTIONS = { pug: { doctype: 'html' } }
function getTemplateOptions(descriptor, bindingMetadata, filePath, fileName) {
return {
id: filePath + 'template',
source: descriptor.template.content,
isProd: !IS_DEV,
filename: fileName,
preprocessLang: descriptor.template.attrs.lang,
preprocessOptions: PREPROC_OPTIONS[descriptor.template.attrs.lang],
compilerOptions: {
bindingMetadata: bindingMetadata,
filename: fileName + '.html',
sourceMap: IS_DEV,
comments: false,
},
}
}
/**
* Compile component
*/
async function compileVueComponent(filePath, fileName) {
const fileContent = await fs.promises.readFile(filePath, { encoding: 'utf-8' })
const { descriptor, errors } = parse(fileContent, { filename: filePath, sourceMap: IS_DEV })
const inlineTemplate = !!descriptor.scriptSetup
if (errors && errors.length) {
logErr(`Vue: Error[s] in ${filePath}:`)
errors.forEach(e => console.log(e.toString()))
return ''
}
// Get script
let script, bindings
if (descriptor.scriptSetup) {
try {
const result = compileScript(descriptor, {
id: filePath + 'script',
isProd: !IS_DEV,
refSugar: false,
inlineTemplate,
templateOptions: getTemplateOptions(descriptor, bindings, filePath, fileName),
})
script = result.content
bindings = result.bindings
} catch (err) {
logErr(`Vue: Error[s] in ${filePath}:`)
console.log(colorize(`|r>${err.toString()}|x|`))
}
} else if (descriptor.script) {
script = descriptor.script?.content.trim()
}
if (!script) script = '\nexport default {\n}\n'
// Compile template into render function
if (descriptor.template && !inlineTemplate) {
const result = compileTemplate(getTemplateOptions(descriptor, bindings, filePath, fileName))
if (result.errors && result.errors.length) {
logErr(`Vue: Error[s] in ${filePath}:`)
result.errors.forEach(e => console.log(colorize(`|r>${e.toString()}|x|`)))
return ''
}
// Inject render function
if (result.code) {
script =
result.code +
'\n' +
script.replace('export default', 'const _C =') +
'\n\n_C.render = render' +
'\nexport default _C'
}
}
return script
}
async function compileTSFile(file) {
let result
if (BUNDLES[file.srcPath]) {
await esbuild.build({
entryPoints: [file.srcPath],
tsconfig: 'tsconfig.json',
charset: 'utf8',
minify: !IS_DEV,
treeShaking: true,
bundle: true,
format: 'esm',
incremental: true,
outfile: file.outPath,
})
return
} else {
const codeStr = await fs.promises.readFile(file.srcPath, { encoding: 'utf-8' })
result = await esbuild.transform(codeStr, {
tsconfigRaw: { compilerOptions: TS_CONFIG },
sourcefile: file.srcPath,
loader: 'ts',
minify: !IS_DEV,
charset: 'utf8',
sourcemap: 'inline',
define: ESBUILD_DEFINE,
})
}
if (result.warnings && result.warnings.length) {
logErr(`Vue: Error[s] in ${file.srcPath}:`)
for (const msg of result.warnings) {
console.log(colorize(` |r>${msg.text}|x|`))
if (msg.location) {
console.log(colorize(` |_>${msg.location.line}:|r>${msg.location.lineText}|x|`))
}
}
}
return result.code
}
async function compileTSCode(codeStr, filePath) {
const result = await esbuild.transform(codeStr, {
tsconfigRaw: { compilerOptions: TS_CONFIG },
sourcefile: filePath,
loader: 'ts',
define: ESBUILD_DEFINE,
})
if (result.warnings && result.warnings.length) {
logErr(`Vue: Error[s] in ${filePath}:`)
for (const msg of result.warnings) {
console.log(colorize(` |r>${msg.text}|x|`))
if (msg.location) {
console.log(colorize(` |_>${msg.location.line}:|r>${msg.location.lineText}|x|`))
}
}
}
return result.code
}
async function writeTSFile(code, fileInfo) {
if (!code) return
await fs.promises.mkdir(fileInfo.outDir, { recursive: true })
await fs.promises.writeFile(fileInfo.outPath, code)
}
async function compile(srcFiles) {
for (const info of srcFiles) {
try {
let resultCode
if (info.isTS) resultCode = await compileTSFile(info)
else if (info.isVUE) {
resultCode = await compileVueComponent(info.srcPath, info.srcFile)
resultCode = await compileTSCode(resultCode, info.srcPath)
}
if (resultCode) {
resultCode = fixModuleImports(resultCode)
await writeTSFile(resultCode, info)
}
} catch (err) {
logErr(`Scripts: Cannot build ${info.srcPath}:\n${err}`)
}
}
}
async function compileAndWatch(files) {
await compile(files)
const tasks = files.map(f => {
f.files = [f.srcPath]
return f
})
watch(
tasks,
async tasks => {
tasks.forEach(t => log(`Scripts: Changed source: ${t.srcPath}`))
await compile(tasks)
},
(task, file) => {
log(`Scripts: File ${file} was renamed, restart this script`)
tasks.forEach(t => t.watchers.forEach(w => w.close()))
}
)
}
/**
* Main
*/
async function main() {
log('Scripts: Building')
if (IS_DEV) {
const files = await getSrcFiles()
await compileAndWatch(files)
logOk('Scripts: Watching')
} else {
// ESM allowed code
await esbuild.build({
entryPoints: [
'src/bg/background.ts',
'src/sidebar/sidebar.ts',
'src/page.setup/setup.ts',
'src/popup.proxy/proxy.ts',
'src/popup.search/search.ts',
'src/injections/playMedia.ts',
'src/injections/pauseMedia.ts',
'src/_locales/dict.common.ts',
'src/_locales/dict.sidebar.ts',
'src/_locales/dict.setup-page.ts',
],
tsconfig: 'tsconfig.json',
charset: 'utf8',
splitting: true,
minify: false, // temprorary for beta
treeShaking: true,
bundle: true,
format: 'esm',
outdir: ADDON_PATH,
plugins: [vueComponentsPlugin],
define: ESBUILD_DEFINE,
})
// Bundled scripts for injecting
await esbuild.build({
entryPoints: ['src/page.group/group.ts', 'src/page.url/url.ts'],
tsconfig: 'tsconfig.json',
charset: 'utf8',
splitting: false,
minify: false, // temprorary for beta
treeShaking: true,
bundle: true,
format: 'esm',
outdir: ADDON_PATH,
define: ESBUILD_DEFINE,
})
logOk('Scripts: Done')
}
}
main()