-
Notifications
You must be signed in to change notification settings - Fork 0
/
bundlify.js
170 lines (132 loc) · 5.15 KB
/
bundlify.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
import fs from 'fs';
import path from 'path';
import { fileURLToPath } from 'url';
import { execa } from 'execa';
// Convert `import.meta.url` to file path
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
// Function to read a file and return its content
const readFile = (filePath) => {
return fs.readFileSync(filePath, 'utf-8');
};
// Function to resolve the module path
const resolveModule = (filePath, baseDir) => {
if (filePath.startsWith('.')) {
return path.resolve(baseDir, filePath);
}
return require.resolve(filePath, { paths: [baseDir] });
};
// Function to transpile code using Bun CLI
const transpileCode = async (filePath) => {
const { stdout } = await execa('bun', ['build', filePath, '--outfile', '/dev/stdout']);
// Filter out extraneous Bun messages
let filteredOutput = stdout
.split('\n')
.filter(line => !line.includes('stdout') && !line.match(/^\[\d+ms\]/))
.join('\n');
// Replace `export default` with `module.exports` for CommonJS compatibility
filteredOutput = filteredOutput.replace(/export\s+default\s+/g, 'module.exports = ');
return filteredOutput;
};
// Function to parse and bundle the files
const bundleFiles = async (entryFile) => {
// const baseDir = path.dirname(entryFile);
let modules = {};
let id = 0;
let moduleStack = [];
// add logic to detect circular dependency
const addModule = async (filePath) => {
if (modules[filePath]) {
return modules[filePath].id;
}
if (moduleStack.includes(filePath)) {
console.log("-----------------------------------------------------------------------")
console.log("-----------------------------------------------------------------------")
console.log("-----------------------------------------------------------------------")
console.warn(`Circular dependency detected: ${moduleStack.join(' -> ')} -> ${filePath}`);
console.log("-----------------------------------------------------------------------")
console.log("-----------------------------------------------------------------------")
console.log("-----------------------------------------------------------------------")
return;
}
moduleStack.push(filePath);
const moduleId = id++;
const content = readFile(filePath);
const dirName = path.dirname(filePath);
// Parse dependencies from the original content
const dependencies = [];
const requireRegex = /require\(['"](.+?)['"]\)/g;
const importRegex = /import .* from ['"](.+?)['"]/g;
let match;
while ((match = requireRegex.exec(content)) !== null) {
dependencies.push(match[1]);
}
while ((match = importRegex.exec(content)) !== null) {
dependencies.push(match[1]);
}
const resolvedDependencies = dependencies.map(dep => resolveModule(dep, dirName));
// Transpile code with Bun
const transpiledContent = await transpileCode(filePath);
modules[filePath] = {
id: moduleId,
filePath,
content: transpiledContent,
dependencies: resolvedDependencies,
};
await Promise.all(resolvedDependencies.map(async (dep) => {
if (moduleStack.includes(dep)) {
console.log("-----------------------------------------------------------------------")
console.log("-----------------------------------------------------------------------")
console.log("-----------------------------------------------------------------------")
console.warn(`Circular dependency detected: ${moduleStack.join(' -> ')} -> ${dep}`);
console.log("-----------------------------------------------------------------------")
console.log("-----------------------------------------------------------------------")
console.log("-----------------------------------------------------------------------")
} else {
await addModule(dep);
}
}));
moduleStack.pop();
return moduleId;
};
await addModule(entryFile);
const output = [];
output.push(`
(function(modules) {
var installedModules = {};
function require(moduleId) {
if (installedModules[moduleId]) {
return installedModules[moduleId].exports;
}
var module = installedModules[moduleId] = {
id: moduleId,
loaded: false,
exports: {}
};
modules[moduleId].call(module.exports, module, module.exports, require);
module.loaded = true;
return module.exports;
}
return require(${modules[entryFile].id});
})({
`);
Object.values(modules).forEach(module => {
output.push(` ${module.id}: function(module, exports, require) {`);
output.push(module.content);
output.push(` },`);
});
output.push(`});`);
return output.join('\n');
};
// Main function to bundle the project
const main = async () => {
const entryFile = path.resolve(__dirname, 'target', 'index.js');
const bundle = await bundleFiles(entryFile);
const outputPath = path.resolve(__dirname, 'dist', 'bundle.js');
if (!fs.existsSync(path.dirname(outputPath))) {
fs.mkdirSync(path.dirname(outputPath), { recursive: true });
}
fs.writeFileSync(outputPath, bundle, 'utf-8');
console.log(`Bundle created at ${outputPath}`);
};
main();