-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathbuild.js
More file actions
208 lines (178 loc) · 6.29 KB
/
Copy pathbuild.js
File metadata and controls
208 lines (178 loc) · 6.29 KB
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
import { promises as fs } from 'fs';
import path from 'path';
import { fileURLToPath } from 'url';
import { minify } from 'terser';
import { js as jsBeautify } from 'js-beautify';
// -----------------------------
// Config
// -----------------------------
const beautifyOptions = {
indent_size: 2,
indent_char: ' ',
quote_style: 'single',
max_preserve_newlines: 5,
preserve_newlines: true,
keep_array_indentation: true,
break_chained_methods: false,
indent_scripts: 'normal',
brace_style: 'collapse,preserve-inline',
space_before_conditional: true,
unescape_strings: false,
jslint_happy: false,
end_with_newline: true,
wrap_line_length: 0,
indent_inner_html: false,
comma_first: false,
e4x: false,
indent_empty_lines: false,
};
const terserOptions = {
module: true,
mangle: false,
compress: false,
format: { comments: false, quote_style: 1 },
};
// -----------------------------
// Paths
// -----------------------------
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
const root = path.resolve(__dirname, '..');
const libsDirectory = path.join(root, 'libs');
const userscriptsDirectory = path.join(root, 'userscripts');
// -----------------------------
// Utilities
// -----------------------------
const isJsFile = (name) => name.endsWith('.js') && !name.endsWith('.min.js');
async function walk(directory) {
const entries = await fs.readdir(directory, { withFileTypes: true });
const files = [];
for (const ent of entries) {
const full = path.join(directory, ent.name);
if (ent.isDirectory()) files.push(...(await walk(full)));
else if (ent.isFile() && isJsFile(ent.name)) files.push(full);
}
return files;
}
function extractHeader(content) {
const lines = content.split(/\r?\n/);
if (!lines[0]?.trim().startsWith('// ==UserScript==')) return { header: '', body: content };
const headerLines = [];
let index = 0;
for (; index < lines.length; index++) {
headerLines.push(lines[index]);
if (lines[index].trim().startsWith('// ==/UserScript==')) {
index++;
break;
}
}
return { header: headerLines.join('\n'), body: lines.slice(index).join('\n') };
}
function normalizeEnding(content) {
return content.endsWith('\n') ? content : content + '\n';
}
function normalizeLineEndings(content) {
return content.replace(/\r\n?/g, '\n');
}
// -----------------------------
// Pipeline
// -----------------------------
async function processFile(file, options = {}) {
const { shouldMinify = false } = options;
const source = await fs.readFile(file, 'utf8');
const { header, body } = extractHeader(source);
const beautifiedBody = jsBeautify(body, beautifyOptions);
// Validate with terser (parse-only via compress: false / mangle: false)
let valid = false;
try {
const r = await minify(beautifiedBody, terserOptions);
if (!r?.code) throw new Error('No output from terser');
valid = true;
} catch (error) {
console.error(`Terser error for ${path.relative(root, file)}:`, error.message || error);
}
// Write formatted source if it changed
const out = (header ? header + '\n\n' : '') + beautifiedBody;
const finalOut = normalizeEnding(out);
const normalizedSource = normalizeLineEndings(source);
const normalizedFinalOut = normalizeLineEndings(finalOut);
let changed = false;
if (normalizedFinalOut !== normalizedSource) {
await fs.writeFile(file, finalOut, 'utf8');
changed = true;
console.log(`Formatted: ${path.relative(root, file)}`);
} else {
console.log(`Unchanged: ${path.relative(root, file)}`);
}
// Write minified version if needed
if (shouldMinify) {
const result = await minify(beautifiedBody, terserOptions);
if (!result?.code) throw new Error(`Terser failed for ${file}`);
const minified = (header ? header + '\n\n' : '') + result.code;
const finalMinified = normalizeEnding(minified);
const outPath = file.replace(/\.js$/, '.min.js');
let minChanged = true;
try {
const existing = await fs.readFile(outPath, 'utf8');
if (normalizeLineEndings(existing) === normalizeLineEndings(finalMinified)) minChanged = false;
} catch (error) {
if (error.code !== 'ENOENT') throw error;
}
if (minChanged) {
await fs.writeFile(outPath, finalMinified, 'utf8');
console.log(`Wrote: ${path.relative(root, outPath)}`);
} else {
console.log(`Unchanged: ${path.relative(root, outPath)}`);
}
}
return { changed, valid, error: valid ? null : 'Validation failed' };
}
// -----------------------------
// Main
// -----------------------------
async function main() {
try {
const libs = await walk(libsDirectory);
if (!libs.length) console.log('No JS source files found under libs/');
let userFiles = [];
try {
userFiles = await walk(userscriptsDirectory);
} catch (error) {
if (error.code !== 'ENOENT') throw error;
}
const libResults = await Promise.allSettled(
libs.map(f => processFile(f, { shouldMinify: true }))
);
const userResults = await Promise.allSettled(
userFiles.map(f => processFile(f, { shouldMinify: false }))
);
const libsChanged = libResults.filter(
r => r.status === 'fulfilled' && r.value.changed
).length;
const libErrors = libResults.filter(
r => r.status === 'rejected' || (r.status === 'fulfilled' && !r.value.valid)
);
const userErrors = userResults.filter(
r => r.status === 'rejected' || (r.status === 'fulfilled' && !r.value.valid)
);
for (const r of [...libResults, ...userResults]) {
if (r.status === 'rejected') console.error('Build error:', r.reason);
}
console.log(
`Built ${libs.length} lib${libs.length !== 1 ? 's' : ''} (${libsChanged} changed), ` +
`validated ${userFiles.length} userscript${userFiles.length !== 1 ? 's' : ''}.`
);
const hasValidationFailures = libErrors.length > 0 || userErrors.length > 0;
const hasHardErrors = [...libResults, ...userResults].some(r => r.status === 'rejected');
if (hasHardErrors) {
process.exitCode = 1;
} else if (hasValidationFailures) {
process.exitCode = 2;
}
console.log('Build complete.');
} catch (error) {
console.error(error);
process.exitCode = 1;
}
}
if (path.resolve(fileURLToPath(import.meta.url)) === path.resolve(process.argv[1])) main();