Refactor node:module (#14227)

This commit is contained in:
Jarred Sumner
2024-10-03 00:54:56 -07:00
committed by GitHub
parent dd6554294e
commit 4d4dd1c180
15 changed files with 969 additions and 592 deletions

View File

@@ -29,19 +29,14 @@ export function createInternalModuleRegistry(basedir: string) {
moduleList.push("internal-for-testing.ts");
internalRegistry.set("bun:internal-for-testing", moduleList.length - 1);
// Native Module registry
const nativeModuleH = fs.readFileSync(path.join(basedir, "../bun.js/modules/_NativeModule.h"), "utf8");
const nativeModuleDefine = nativeModuleH.match(/BUN_FOREACH_NATIVE_MODULE\(macro\)\s*\\\n((.*\\\n)*\n)/);
if (!nativeModuleDefine) {
throw new Error(
"Could not find BUN_FOREACH_NATIVE_MODULE in _NativeModule.h. Knowing native module IDs is a part of the codegen process.",
);
}
let nextNativeModuleId = 0;
const nativeModuleIds: Record<string, number> = {};
const nativeModuleEnums: Record<string, string> = {};
const nativeModuleEnumToId: Record<string, number> = {};
for (const [_, idString, enumValue] of nativeModuleDefine[0].matchAll(/macro\((.*?),(.*?)\)/g)) {
// Native Module registry
const nativeModuleH = fs.readFileSync(path.join(basedir, "../bun.js/modules/_NativeModule.h"), "utf8");
for (const [_, idString, enumValue] of nativeModuleH.matchAll(/macro\((.*?),(.*?)\)/g)) {
const processedIdString = JSON.parse(idString.trim().replace(/_s$/, ""));
const processedEnumValue = enumValue.trim();
const processedNumericId = nextNativeModuleId++;
@@ -50,6 +45,12 @@ export function createInternalModuleRegistry(basedir: string) {
nativeModuleEnumToId[processedEnumValue] = processedNumericId;
}
if (nextNativeModuleId === 0) {
throw new Error(
"Could not find BUN_FOREACH_ESM_AND_CJS_NATIVE_MODULE in _NativeModule.h. Knowing native module IDs is a part of the codegen process.",
);
}
function codegenRequireId(id: string) {
return `(__intrinsic__getInternalField(__intrinsic__internalModuleRegistry, ${id}) || __intrinsic__createInternalModuleById(${id}))`;
}