MCPcopy Create free account
hub / github.com/buke/quickjs-go / CreateModule

Function CreateModule

bridge.c:1094–1151  ·  view source on GitHub ↗

CreateModule - encapsulates QuickJS module creation logic This function handles all the C API calls needed to create a JavaScript module: 1. Create C module with initialization function (JS_NewCModule) 2. Pre-declare all exports (JS_AddModuleExport) 3. Set module private value for initialization access (JS_SetModulePrivateValue) Parameters: - ctx: JavaScript context - module_name: Module name (C

Source from the content-addressed store, hash-verified

1092// - 0 on success
1093// - -1 on failure (JS exception will be set)
1094int CreateModule(JSContext *ctx, const char *module_name,
1095 const char **export_names, int export_count,
1096 int32_t builder_id) {
1097 JSModuleDef *module;
1098 JSValue builder_value;
1099
1100 // Input validation
1101 if (!ctx || !module_name || !export_names) {
1102 JS_ThrowInternalError(ctx, "CreateModule: invalid parameters");
1103 return -1;
1104 }
1105
1106 if (strlen(module_name) == 0) {
1107 JS_ThrowInternalError(ctx, "CreateModule: module name cannot be empty");
1108 return -1;
1109 }
1110
1111 // Step 1: Create C module with initialization function
1112 // Corresponds to JS_NewCModule(ctx, module_name, GoModuleInitProxy)
1113 module = JS_NewCModule(ctx, module_name, GoModuleInitProxy);
1114 if (!module) {
1115 JS_ThrowInternalError(ctx, "CreateModule: failed to create C module: %s", module_name);
1116 return -1;
1117 }
1118
1119 // Step 2: Pre-declare all exports (JS_AddModuleExport phase)
1120 // This must be done before module instantiation
1121 for (int i = 0; i < export_count; i++) {
1122 const char *export_name = export_names[i];
1123
1124 // Validate export name
1125 if (!export_name || strlen(export_name) == 0) {
1126 JS_ThrowInternalError(ctx, "CreateModule: export name cannot be empty at index %d", i);
1127 return -1;
1128 }
1129
1130 // Add module export declaration
1131 int result = JS_AddModuleExport(ctx, module, export_name);
1132 if (result < 0) {
1133 JS_ThrowInternalError(ctx, "CreateModule: failed to add module export: %s", export_name);
1134 return -1;
1135 }
1136 }
1137
1138 // Step 3: Set module private value for initialization access
1139 // Create JSValue from builder_id for storage
1140 builder_value = JS_NewInt32(ctx, builder_id);
1141 if (JS_IsException(builder_value)) {
1142 JS_ThrowInternalError(ctx, "CreateModule: failed to create builder value");
1143 return -1;
1144 }
1145
1146 // Store builder_id as module private value
1147 JS_SetModulePrivateValue(ctx, module, builder_value);
1148
1149 // Success
1150 return 0;
1151}

Callers

nothing calls this directly

Calls 2

JS_NewInt32Function · 0.85
JS_IsExceptionFunction · 0.85

Tested by

no test coverage detected