-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathindex.js
More file actions
executable file
·250 lines (215 loc) · 7.26 KB
/
Copy pathindex.js
File metadata and controls
executable file
·250 lines (215 loc) · 7.26 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
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
#!/usr/bin/env node
import { existsSync, readFileSync, writeFileSync } from 'node:fs';
import { hostname, platform, userInfo } from 'node:os';
import { dirname, resolve } from 'node:path';
import { fileURLToPath } from 'node:url';
import chalk from 'chalk';
import { program } from 'commander';
import { build as esbuild } from 'esbuild';
import { DateTime } from 'luxon';
import updateNotifier from 'update-notifier';
import externals from './externals.js';
// Constants
const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);
const packageJSON = JSON.parse(readFileSync(new URL('./package.json', import.meta.url)));
const CURRENT_FOLDER = process.cwd();
const TSCONFIG_FILENAME = 'tsconfig.json';
// CLI Configuration
function configureCLI() {
program
.version(packageJSON.version)
.argument('<input_file>', 'Original file to make build, can be a javascript or typescript file')
.argument('[output_file]', '[optional] Destination name')
.option(
'--legacy',
'use legacy behavior - exclude modules that already exist on TagoIO context',
false
)
.option('--removeBanner', 'Remove banner on output file', false)
.option('--obfuscate', 'Make the output file hard to understand', false)
.option(
'-w, --watch',
"Enabling watch mode on Analysis Build, it's listen for changes on the file system and to rebuild whenever a file changes",
false
)
.option('--tsconfig', 'Generate a tsconfig.json file on current folder');
program.addHelpText('before', `TagoIO Builder V${packageJSON.version} (https://git.io/JJ8Si)\n`);
return program;
}
// Update Notifier
function checkForUpdates() {
const notifier = updateNotifier({ pkg: packageJSON });
notifier.notify({
defer: false,
isGlobal: true,
boxenOptions: {
padding: 1,
margin: 1,
align: 'center',
borderColor: '#347AB7',
borderStyle: 'bold',
},
});
}
// Generate Banner
function generateBanner(inputFile, outputFile, options = {}) {
const username = userInfo().username || 'Unknown';
const timestamp = DateTime.utc().toFormat('ffff');
const nodeVersion = process.version;
const fileType = inputFile.endsWith('.ts') ? 'TypeScript' : 'JavaScript';
const buildOptions = [];
if (options.obfuscate) buildOptions.push('minified');
if (options.legacy) buildOptions.push('legacy');
if (options.watch) buildOptions.push('watch');
const optionsStr = buildOptions.length > 0 ? ` [${buildOptions.join(', ')}]` : '';
return `/*
* TagoIO (https://tago.io/)
* TagoIO Builder V${packageJSON.version} (https://git.io/JJ8Si)
* -------------------
* Generated by :: ${username}
* Generated at :: ${timestamp}
* Machine :: ${hostname()} <${platform()}> - Node.js ${nodeVersion}
* Origin file :: ${inputFile} <${fileType}>
* Destination file :: ${outputFile}${optionsStr}
* -------------------
*/
`;
}
// Generate TSConfig
function generateTSConfig() {
const sourcePath = resolve(__dirname, TSCONFIG_FILENAME);
const destPath = resolve(CURRENT_FOLDER, TSCONFIG_FILENAME);
try {
const tsFile = readFileSync(sourcePath, 'utf-8');
writeFileSync(destPath, tsFile);
console.info(chalk.green(`✓ Generated ${TSCONFIG_FILENAME} in current directory`));
return true;
} catch (error) {
console.error(chalk.red(`✗ Failed to generate ${TSCONFIG_FILENAME}: ${error.message}`));
return false;
}
}
// Validate Input
function validateInput(inputFile) {
if (!inputFile) {
console.error(chalk.red('✗ Input file is required'));
process.exit(1);
}
if (!existsSync(inputFile)) {
console.error(chalk.red(`✗ Input file "${inputFile}" does not exist`));
process.exit(1);
}
if (!inputFile.endsWith('.js') && !inputFile.endsWith('.ts')) {
console.error(chalk.red('✗ Input file must be a JavaScript (.js) or TypeScript (.ts) file'));
process.exit(1);
}
}
// Get TSConfig Path
function getTSConfigPath() {
const customTSConfig = resolve(CURRENT_FOLDER, TSCONFIG_FILENAME);
const defaultTSConfig = resolve(__dirname, TSCONFIG_FILENAME);
if (existsSync(customTSConfig)) {
console.info(chalk.cyan('ℹ Using custom tsconfig.json\n'));
return customTSConfig;
}
console.info(chalk.cyan('ℹ Using analysis-builder tsconfig.json\n'));
return defaultTSConfig;
}
// Build Configuration
function createBuildConfig(inputFile, outputFile, options) {
const config = {
platform: 'node',
target: 'node20',
absWorkingDir: CURRENT_FOLDER,
entryPoints: [`./${inputFile}`],
bundle: true,
outfile: outputFile,
minify: options.obfuscate || false,
external: externals(options.legacy),
tsconfig: getTSConfigPath(),
};
if (options.watch) {
config.watch = {
onRebuild(error) {
const time = DateTime.local().toFormat('tt');
if (error) {
console.error(chalk.red(`[${time}] ✗ Build failed: ${error.message}`));
} else {
console.info(chalk.green(`[${time}] ✓ Rebuild successful`));
}
},
};
}
if (!options.removeBanner) {
config.banner = {
js: generateBanner(inputFile, outputFile, options),
};
}
return config;
}
// Build Process
async function build(inputFile, outputFile, options) {
const buildConfig = createBuildConfig(inputFile, outputFile, options);
try {
console.info(chalk.yellow('⚡ Building... (this may take a while)'));
const startTime = Date.now();
await esbuild(buildConfig);
const buildTime = ((Date.now() - startTime) / 1000).toFixed(2);
console.info(chalk.green(`\n✓ Build completed in ${buildTime}s`));
console.info(chalk.green(`✓ Analysis file saved at: ./${outputFile}\n`));
if (options.watch) {
console.info(
chalk.bgMagenta.white(
'👁 Watch Mode activated - monitoring for changes... (Press CTRL+C to exit)\n'
)
);
}
} catch (error) {
console.error(chalk.red(`\n✗ Build failed: ${error.message}`));
if (error.errors && error.errors.length > 0) {
error.errors.forEach((err) => {
console.error(chalk.red(` - ${err.text}`));
if (err.location) {
console.error(
chalk.gray(` at ${err.location.file}:${err.location.line}:${err.location.column}`)
);
}
});
}
process.exit(1);
}
}
// Main Function
async function main() {
const cli = configureCLI();
const options = cli.parse(process.argv).opts();
const files = cli.parse(process.argv).args;
// Check for updates
checkForUpdates();
// Handle tsconfig generation
if (options.tsconfig) {
const success = generateTSConfig();
process.exit(success ? 0 : 1);
}
// Process input/output files
const inputFile = String(files[0]);
const outputFile = files[1] || `${inputFile.replace(/\.(ts|js)$/g, '')}.tago-io.js`;
// Validate input
validateInput(inputFile);
// Display banner
const banner = generateBanner(inputFile, outputFile, options);
console.info(chalk.green(banner), '\n');
// Start build
await build(inputFile, outputFile, options);
}
// Error Handler
process.on('unhandledRejection', (error) => {
console.error(chalk.red('\n✗ Unhandled error:', error));
process.exit(1);
});
// Run
main().catch((error) => {
console.error(chalk.red('✗ Fatal error:', error));
process.exit(1);
});