-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathfixup-global-scope.js
46 lines (39 loc) · 1.82 KB
/
fixup-global-scope.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
const fs = require('fs');
const path = require('path');
const srcDir = path.join(__dirname, 'tcnapi-grpc-web/src');
const globalContent = `const global = {proto: {}};\nmodule.exports = global;\n`;
// Function to write or overwrite the global.js file at the root of src
function createGlobalFile() {
const globalFilePath = path.join(srcDir, 'global.js');
fs.writeFileSync(globalFilePath, globalContent, 'utf8');
}
// Function to recursively traverse the src directory and modify files
function modifyFiles(dirPath, depth) {
const files = fs.readdirSync(dirPath);
files.forEach(file => {
const filePath = path.join(dirPath, file);
const stat = fs.statSync(filePath);
if (stat.isDirectory()) {
// Recurse into a subdirectory
modifyFiles(filePath, depth + 1);
} else if (stat.isFile() && path.extname(file) === '.js') {
// Modify .js files
let content = fs.readFileSync(filePath, 'utf8');
if (content.includes("var jspb = require('google-protobuf');")) {
const relativePath = '../'.repeat(depth) + 'global.js';
const replacement = `var jspb = require('google-protobuf');\nvar localGlobalThis = require("${relativePath}");\nvar proto = localGlobalThis.proto;`;
content = content.replace("var global =", "var global = localGlobalThis || ");
content = content.replace(
"var jspb = require('google-protobuf');",
replacement
);
fs.writeFileSync(filePath, content, 'utf8');
console.log(`Modified: ${filePath}`);
}
}
});
}
// Create or overwrite global.js in the src directory
createGlobalFile();
// Start modifying files from the root of the src directory
modifyFiles(srcDir, 0);