68 lines
1.9 KiB
TypeScript
68 lines
1.9 KiB
TypeScript
import { Plugin } from "vite";
|
|
|
|
export function strip(): Plugin {
|
|
const p: Plugin = {
|
|
name: "debug-strip",
|
|
enforce: "pre",
|
|
apply: "build",
|
|
transform(code: string, id: string) {
|
|
if (!id.endsWith(".ts") || import.meta.env.DEV) {
|
|
return code;
|
|
}
|
|
|
|
const keyword = "override debugDraw";
|
|
const results = [];
|
|
let currentIndex = 0;
|
|
|
|
while (true) {
|
|
// Find the next occurrence of the keyword starting from currentIndex.
|
|
const startIndex = code.indexOf(keyword, currentIndex);
|
|
if (startIndex === -1) {
|
|
break; // No more occurrences.
|
|
}
|
|
|
|
// Find the first opening brace '{' after the keyword.
|
|
const braceStart = code.indexOf("{", startIndex);
|
|
if (braceStart === -1) {
|
|
// No opening brace found; skip this occurrence.
|
|
currentIndex = startIndex + keyword.length;
|
|
continue;
|
|
}
|
|
|
|
// Use a counter to find the matching closing brace.
|
|
let openBraces = 0;
|
|
let endIndex = -1;
|
|
for (let i = braceStart; i < code.length; i++) {
|
|
if (code[i] === "{") {
|
|
openBraces++;
|
|
} else if (code[i] === "}") {
|
|
openBraces--;
|
|
}
|
|
|
|
// When openBraces returns to 0, we found the matching closing brace.
|
|
if (openBraces === 0) {
|
|
endIndex = i;
|
|
break;
|
|
}
|
|
}
|
|
|
|
// If a matching closing brace was found, extract the substring.
|
|
if (endIndex !== -1) {
|
|
results.push(code.substring(startIndex, endIndex + 1));
|
|
// Move the currentIndex past the extracted block.
|
|
currentIndex = endIndex + 1;
|
|
} else {
|
|
// If no matching closing brace is found, skip this occurrence.
|
|
currentIndex = startIndex + keyword.length;
|
|
}
|
|
}
|
|
|
|
for (const result of results) {
|
|
code = code.replace(result, "");
|
|
}
|
|
return code;
|
|
},
|
|
};
|
|
return p;
|
|
}
|