You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
async module loader is useful for loading code from network, or requiring execute external process like esbuild/swc
since this fork is already support top level await, it can be (partially) implemented in pure js (aka add an fake source for async module which will await an unresolved promise) but I think it would be better if add an the module loader interface which can do this without the workaround
IIRC the main problem is the module loader must populate a JSModuleDef as it's called, you can't perform an async operation and call some API to complete it later.
typedefenumJSModuleLoadingResultEnum {
JS_ASYNC_MODULE_SYNC,
JS_ASYNC_MODULE_ASYNC
} JSModuleLoadingResultEnum;
// also reserve the import attribute struct for future extend// to support something like `import { main } from './foo.wasm' with { type: "webassembly" }`// or `import { xyz } 'xyz.ts' with { type: "typescript", compiler: "tsc" }`typedefstructJSImportAttribute {
char*key; /* 0 if end */JSValuevalue;
} JSImportAttribute;
typedefstructJSModuleRequest {
char*specifier;
JSImportAttribute*attributes;
} JSModuleRequest;
typedefJSModuleLoadingResultEnumJSModuleLoaderFunc2(
JSContext*ctx,
constchar*module_name,
/* only be used in sync mode */JSModuleDef**out_sync_module_def,
void*opaque);
// Changed the normalize function to allow serialize import attribute array into stringtypedefchar*JSModuleNormalizeFunc2(JSContext*ctx,
constchar*referrer,
constJSModuleRequest*request,
void*opaque);
voidJS_SetModuleLoaderFunc2(JSRuntime*rt,
JSModuleNormalizeFunc2*module_normalize,
JSModuleLoaderFunc2*module_loader, void*opaque);
// used when JSModuleLoaderFunc2 returns JS_ASYNC_MODULE_ASYNCvoidJS_FinishLoadingModule(JSRuntime*rt,
constchar*module_name,
// null if failedJSModuleDef*module_def);
So the ask is to make the module loader interruptible? More specifically, that the JSModuleLoaderfunc callback can somehow signal that it will complete at a later time?
I'm not saying 'no' outright but I expect it will be a big effort, with lots of edge cases that need dealing with, like should JS_Eval(JS_EVAL_TYPE_MODULE) return some kind of sentinel when it can't continue?
Maybe an easier way forward is to have a special parse mode for modules that doesn't evaluate the module but returns its imports (and maybe exports?)
Then you fetch and parse its imports in the same way (and those imports' imports, etc.) until you're done and evaluate everything.
actually I think it is how most of existing js engine works, two pass for esm, resolve module is first pass (InitializeEnvironment() 1), eval is second part (ExecuteModule() 2)
but I suggest to create a new api for module loading and eval. not just reuse JS_Eval, so we can avoid parse code twice...
maybe a dedicated JS_LoadModule which only return module records (contains import and export information, and set unresolved module as null, let caller to filling the gap), and JS_EvalModule to execute the resolved module (I known the old JS_Eval has module mode, but the api is only accept js source code)
a possible user code for sync module loading would be:
// not JS_ModuleDef since it cannot be same structure
JS_ModuleRecord *record = JS_LoadModuleRecord(rt, file);
/* "link" the module */// use c++ ranged loop as pesudo codefor (JS_ModuleImportInfo *it : record->imports) {
JS_ModuleRecord *dependentModule = UserCode_ResolveImport(record->specifier, record->attributes);
it->resolved = dependentModule;
}
JS_EvalModule(rt, record);
That can't be avoided but the upside is it only needs to run the first pass of the three parse/code-gen passes. Maybe we can keep the pass 1 bytecode around, maybe not.
it should be able to handle dynamic import too
Only dynamic imports where the path is a static string. That's so restricting it probably isn't worth bothering with though.
my suggestion for non-dynamic imports is a static analysis pass; no bytecode executes
ok, thats make sense (for static analysis pass), but my suggestion is also change the js_dynamic_import_job to allow async import too
aka allow customize how js_dynamic_import is execute, current implementation is just call JS_RunModule(ctx, basename, filename); in js_dynamic_import_job, which will only works with sync module loading mode
Picking up @bnoordhuis's suggestion from earlier in this thread: a parse mode for modules that returns their imports without resolving them.
#1860 made dynamic import() asynchronous, which is great. Static imports still go through the synchronous JSModuleLoaderFunc, though, and the header comment for JSDynamicImportFunc (step 6) says as much: the module a dynamic import fetches pulls in its own static graph through that loader. An embedder that fetches modules over a network, such as a development server that serves an application as hundreds of separate modules, therefore has to either block in the loader once per module or know a module's imports before it is linked. There is no way to get that today:
JS_EVAL_FLAG_COMPILE_ONLY still resolves. __JS_EvalInternal calls js_resolve_module() before it tests the flag (with the comment "Could add a flag to avoid resolution if necessary"), so the loader runs during a compile-only call. qjsc relies on that behaviour to walk the graph, so changing the existing flag isn't an option.
The requested specifiers live in JSModuleDef.req_module_entries, which is private.
Proposed API
/* With JS_EVAL_TYPE_MODULE | JS_EVAL_FLAG_COMPILE_ONLY: compile the module but do not resolve its imports; the module loader is not called. */#defineJS_EVAL_FLAG_NO_RESOLVE (1 << 8) /* or the next free bit *//* The import requests of a compiled module value, in source order. The name is the specifier as written, before normalization. */JS_EXTERNintJS_GetModuleRequestCount(JSContext*ctx, JSValueConstmodule);
JS_EXTERNJSAtomJS_GetModuleRequestName(JSContext*ctx, JSValueConstmodule, intindex);
JS_EXTERNJSValueJS_GetModuleRequestAttributes(JSContext*ctx, JSValueConstmodule, intindex);
How it would be used
Compile the entry module with JS_EVAL_FLAG_NO_RESOLVE and read its requests.
Normalize each specifier, fetch the sources asynchronously (in parallel), and compile each one the same way under its normalized name. Repeat until the graph is complete.
Call the existing JS_ResolveModule() on the entry module, then evaluate it.
Step 3 needs no further change: js_host_resolve_imported_module() already looks a normalized name up in ctx->loaded_modules before it calls the loader, and every compiled module is in that list. The loader is then only reached for a module the embedder failed to fetch.
The same functions would let a JSDynamicImportFunc fetch a dynamically imported module's whole static graph before it calls JS_LoadModule().
If this shape looks acceptable, I'm happy to send a PR with tests (cycles, import attributes, a module that fails to compile half-way through the graph). Names and the choice between an eval flag and a new JSEvalOptions field are open to whatever you prefer.
Activity
bnoordhuis commentedon Dec 9, 2023
It's easier to discuss details if you can give a quick sketch of what you think the C API should look like and how it would be used.
saghul commentedon Dec 9, 2023
IIRC the main problem is the module loader must populate a JSModuleDef as it's called, you can't perform an async operation and call some API to complete it later.
codehz commentedon Dec 10, 2023
ref
https://html.spec.whatwg.org/#hostloadimportedmodule
https://tc39.es/ecma262/#sec-HostLoadImportedModule
https://tc39.es/proposal-import-attributes/#importattribute-record
HostLoadImportedModule(referrer, moduleRequest, loadState, payload)
FinishLoadingImportedModule(referrer, moduleRequest, payload, result)
bnoordhuis commentedon Dec 10, 2023
So the ask is to make the module loader interruptible? More specifically, that the JSModuleLoaderfunc callback can somehow signal that it will complete at a later time?
I'm not saying 'no' outright but I expect it will be a big effort, with lots of edge cases that need dealing with, like should
JS_Eval(JS_EVAL_TYPE_MODULE)return some kind of sentinel when it can't continue?Maybe an easier way forward is to have a special parse mode for modules that doesn't evaluate the module but returns its imports (and maybe exports?)
Then you fetch and parse its imports in the same way (and those imports' imports, etc.) until you're done and evaluate everything.
codehz commentedon Dec 10, 2023
btw, I found current implementation is actually cannot handle top-level-await in module... so no js workaround at first place....
it sounds good, and I think it should be able to handle dynamic import too
codehz commentedon Dec 10, 2023
ref: https://tc39.es/ecma262/#sec-source-text-module-records
actually I think it is how most of existing js engine works, two pass for esm, resolve module is first pass (InitializeEnvironment() 1), eval is second part (ExecuteModule() 2)
Footnotes
https://tc39.es/ecma262/#sec-source-text-module-record-initialize-environment ↩
https://tc39.es/ecma262/#sec-source-text-module-record-execute-module ↩
codehz commentedon Dec 10, 2023
but I suggest to create a new api for module loading and eval. not just reuse JS_Eval, so we can avoid parse code twice...
maybe a dedicated JS_LoadModule which only return module records (contains import and export information, and set unresolved module as null, let caller to filling the gap), and JS_EvalModule to execute the resolved module (I known the old JS_Eval has module mode, but the api is only accept js source code)
a possible user code for sync module loading would be:
bnoordhuis commentedon Dec 10, 2023
That can't be avoided but the upside is it only needs to run the first pass of the three parse/code-gen passes. Maybe we can keep the pass 1 bytecode around, maybe not.
Only dynamic imports where the path is a static string. That's so restricting it probably isn't worth bothering with though.
codehz commentedon Dec 10, 2023
but dynamic import is already return a promise, I mean it is possible to change the behavior for dynamic import...
bnoordhuis commentedon Dec 10, 2023
I think you're confusing parsing and execution:
dynamic imports are done when bytecode is executed (and they have in fact their own opcode, OP_import)
my suggestion for non-dynamic imports is a static analysis pass; no bytecode executes
codehz commentedon Dec 10, 2023
ok, thats make sense (for static analysis pass), but my suggestion is also change the js_dynamic_import_job to allow async import too
aka allow customize how js_dynamic_import is execute, current implementation is just call
JS_RunModule(ctx, basename, filename);in js_dynamic_import_job, which will only works with sync module loading modebnoordhuis commentedon Dec 10, 2023
Okay, but that's something of an orthogonal issue. It'd be best to open a new issue so it can be tracked separately.
karlseguin commentedon Oct 17, 2025
moved my comment to #196
bnoordhuis commentedon Oct 17, 2025
@karlseguin that's #196, this issue is about static imports.
nakisen commentedon Nov 20, 2026
Picking up @bnoordhuis's suggestion from earlier in this thread: a parse mode for modules that returns their imports without resolving them.
#1860 made dynamic
import()asynchronous, which is great. Static imports still go through the synchronousJSModuleLoaderFunc, though, and the header comment forJSDynamicImportFunc(step 6) says as much: the module a dynamic import fetches pulls in its own static graph through that loader. An embedder that fetches modules over a network, such as a development server that serves an application as hundreds of separate modules, therefore has to either block in the loader once per module or know a module's imports before it is linked. There is no way to get that today:JS_EVAL_FLAG_COMPILE_ONLYstill resolves.__JS_EvalInternalcallsjs_resolve_module()before it tests the flag (with the comment "Could add a flag to avoid resolution if necessary"), so the loader runs during a compile-only call.qjscrelies on that behaviour to walk the graph, so changing the existing flag isn't an option.JSModuleDef.req_module_entries, which is private.Proposed API
How it would be used
JS_EVAL_FLAG_NO_RESOLVEand read its requests.JS_ResolveModule()on the entry module, then evaluate it.Step 3 needs no further change:
js_host_resolve_imported_module()already looks a normalized name up inctx->loaded_modulesbefore it calls the loader, and every compiled module is in that list. The loader is then only reached for a module the embedder failed to fetch.The same functions would let a
JSDynamicImportFuncfetch a dynamically imported module's whole static graph before it callsJS_LoadModule().If this shape looks acceptable, I'm happy to send a PR with tests (cycles, import attributes, a module that fails to compile half-way through the graph). Names and the choice between an eval flag and a new
JSEvalOptionsfield are open to whatever you prefer.