Skip to content
Open
Show file tree
Hide file tree
Changes from 12 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions docs/test/mocks.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -807,6 +807,7 @@ test("lazy import", async () => {
- A factory that uses `importOriginal` is called after the original module is evaluated, not before, so after the factories that don't use it. A factory that declares the parameter counts as using it, so the original is evaluated even if the factory never calls it.
- `export * from` a mocked module re-exports the original's export names if the factory uses `importOriginal`. Names the factory adds aren't re-exported, and names it leaves out are re-exported as `undefined`.
- If two files import each other and both have hoisted calls, they wait on each other and the run fails with an error that names both files. Keep the hoisted calls in only one of them.
- If a factory awaits a module that is itself waiting at an `await import()` for that factory's mock, they wait on each other. A file with hoisted calls awaits most of its imports this way. If the test file then fails to load, a note of the error names the mocked module: `a mock.module() factory never settled for`. In a test, a hook or a `describe()` callback, the same wait ends in a timeout or in `never settled`, without that note. Load such a module after the factory returns, for example in a function that the mock exports.

## Implementation Details

Expand Down
43 changes: 43 additions & 0 deletions src/jsc/bindings/BunPlugin.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -8969,6 +8969,49 @@ bool moduleMockImportsByKey(Zig::GlobalObject* globalObject, const String& key)
return mock && mock->importsOriginal;
}

bool isModuleMockFactoryRunning(Zig::GlobalObject* globalObject, const String& key)
{
return globalObject->onLoadPlugins.runningModuleMocks.containsIf([&](const auto& running) {
auto* mock = uncheckedDowncast<Zig::JSModuleMock>(running.mock.get());
// A compiled run waits for the body of the original before it calls a factory that takes it.
return mock->factory && mock->factory.get().isCallable() && !mock->isAwaitingRunningBody && mock->specifier->tryGetValue().data == key;
});
}

// The loader has no entry for a mocked module while an import() of it waits for the factory. Adds those that a module of `evaluating` awaits.
__attribute__((minsize)) void appendModuleMocksWhoseFactoryAnImportAwaits(Zig::GlobalObject* globalObject, std::span<JSC::CyclicModuleRecord* const> evaluating, Vector<String>& keys)
{
JSValue dynamicImports = globalObject->mockModule.dynamicImports.get();
if (globalObject->onLoadPlugins.runningModuleMocks.isEmpty() || !dynamicImports)
return;

auto& vm = JSC::getVM(globalObject);
auto* loader = testFileModuleLoader(globalObject);
// Each step walks the reactions of one import(). A program with very many of them is not searched to the end.
size_t stepsLeft = 1024;
auto* iterator = JSC::JSMapIterator::create(vm, globalObject->mapIteratorStructure(), uncheckedDowncast<JSC::JSMap>(dynamicImports), JSC::IterationKind::Entries);
while (true) {
auto [import, key] = iterator->nextWithAdvance(vm);
if (!import)
break;
if (!key.isString())
continue;
String mocked = asString(key)->tryGetValue();
// With an entry, the import() waits for the fetch, for the original that the mock patches in place, or for the module of the mock.
if (keys.contains(mocked) || !isModuleMockFactoryRunning(globalObject, mocked) || loader->registryEntry(JSC::Identifier::fromString(vm, mocked)))
continue;
for (auto* record : evaluating) {
if (!stepsLeft)
return;
stepsLeft--;
if (JSC::AbstractModuleRecord::importPromiseGatesAsyncDependency(uncheckedDowncast<JSC::JSPromise>(import), record)) {
keys.append(mocked);
break;
}
}
}
}

bool isModuleMockWaitingForFactory(Zig::GlobalObject* globalObject, const String& key)
{
auto* mock = Zig::registeredModuleMock(globalObject, key);
Expand Down
3 changes: 3 additions & 0 deletions src/jsc/bindings/BunPlugin.h
Original file line number Diff line number Diff line change
Expand Up @@ -335,6 +335,7 @@ class GlobalObject;
} // namespace Zig

namespace JSC {
class CyclicModuleRecord;
class JSModuleNamespaceObject;
class JSSourceCode;
}
Expand Down Expand Up @@ -372,6 +373,8 @@ bool moduleMockImportsByKey(Zig::GlobalObject*, const String& key);
String keyOfImportWhileModuleMocksRun(Zig::GlobalObject*, const String& key, const String& importer, bool isESM);
String packageImportKey(Zig::GlobalObject*, const String& key, const String& importer, bool isESM);
bool isModuleMockWaitingForFactory(Zig::GlobalObject*, const String& key);
bool isModuleMockFactoryRunning(Zig::GlobalObject*, const String& key);
void appendModuleMocksWhoseFactoryAnImportAwaits(Zig::GlobalObject*, std::span<JSC::CyclicModuleRecord* const> evaluating, Vector<String>& keys);
JSC::JSObject* objectHoldingExportOfModuleMock(JSC::JSGlobalObject*, JSC::JSModuleNamespaceObject*, const JSC::Identifier& name);
#if ENABLE(AOT)
// The same for the namespace object of a compiled module. Null for any other object.
Expand Down
25 changes: 20 additions & 5 deletions src/jsc/bindings/ZigGlobalObject.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -995,14 +995,19 @@ extern "C" [[ZIG_EXPORT(nothrow)]] __attribute__((minsize)) BunString Bun__evict
Vector<JSC::Identifier> unfinished;
Vector<std::pair<int64_t, String>> awaiting;
Vector<String> fetching;
Vector<JSC::CyclicModuleRecord*, 8> evaluating;
Bun::forEachModuleRegistrySpecifier(loader, [&](UniquedStringImpl* specifier, JSC::ModuleRegistryEntry* entry) {
if (isModuleLoadSettled(entry))
return;
auto key = JSC::Identifier::fromUid(vm, specifier);
auto* cyclic = dynamicDowncast<JSC::CyclicModuleRecord>(entry->record());
if (!entry->record())
if (cyclic && cyclic->status() == JSC::CyclicModuleRecord::Status::EvaluatingAsync)
evaluating.append(cyclic);
bool isSuspended = cyclic && cyclic->status() == JSC::CyclicModuleRecord::Status::EvaluatingAsync && cyclic->hasTLA() && !cyclic->pendingAsyncDependencies().value_or(0);
// The module of a mock is suspended where it awaits its factory.
if (!entry->record() || (isSuspended && cyclic->hasLiveExports() && Bun::isModuleMockFactoryRunning(globalObject, key.string())))
fetching.append(key.string());
else if (cyclic && cyclic->status() == JSC::CyclicModuleRecord::Status::EvaluatingAsync && cyclic->hasTLA() && !cyclic->pendingAsyncDependencies().value_or(0)) {
else if (isSuspended) {
int64_t order = loader->asyncEvaluationOrderForKey(key);
size_t index = awaiting.size();
while (index && awaiting[index - 1].first > order)
Expand Down Expand Up @@ -1033,6 +1038,8 @@ extern "C" [[ZIG_EXPORT(nothrow)]] __attribute__((minsize)) BunString Bun__evict
}
}
#endif
// While the records are still in the registry.
Bun::appendModuleMocksWhoseFactoryAnImportAwaits(globalObject, evaluating.span(), fetching);
for (auto& key : unfinished)
loader->removeEntry(key);

Expand All @@ -1054,7 +1061,8 @@ extern "C" [[ZIG_EXPORT(nothrow)]] __attribute__((minsize)) BunString Bun__evict
}
}
for (auto& specifier : fetching) {
if (count++ < maxNotes) {
// The others wait for a factory that never settled, so it is named beyond the limit too.
if (Bun::isModuleMockFactoryRunning(globalObject, specifier) || count++ < maxNotes) {
notes.append("\nnote: an onLoad() plugin or a mock.module() factory never settled for "_s);
notes.appendQuotedJSONString(specifier);
}
Expand Down Expand Up @@ -4318,6 +4326,13 @@ JSC::Identifier StandaloneGlobalObject::moduleLoaderResolve(JSGlobalObject* glob
return GlobalObject::moduleLoaderResolve(globalObject, loader, key, referrer, WTF::move(fetcher), useImportMap);
}

// The key that the resolution of this import() call left. A resolution that ended another way leaves its key too: that one is not this call's.
static String takeKeyOfImportCall(Zig::GlobalObject* globalObject, const String& key)
{
String left = std::exchange(globalObject->onLoadPlugins.keyOfImportCall, {});
return left == key ? left : String();
}

JSC::JSPromise* GlobalObject::moduleLoaderImportModule(JSGlobalObject* jsGlobalObject,
JSModuleLoader* loader,
JSString* moduleNameValue,
Expand Down Expand Up @@ -4392,7 +4407,7 @@ JSC::JSPromise* GlobalObject::moduleLoaderImportModule(JSGlobalObject* jsGlobalO
return JSC::JSPromise::rejectedPromiseWithCaughtException(globalObject, scope);
#if ENABLE(AOT)
if (imported && globalObject->m_lazyTestModuleObject.isInitialized()) [[unlikely]] {
Bun::didStartDynamicImport(globalObject, imported, std::exchange(globalObject->onLoadPlugins.keyOfImportCall, {}));
Bun::didStartDynamicImport(globalObject, imported, takeKeyOfImportCall(globalObject, key.string()));
RETURN_IF_EXCEPTION(scope, nullptr);
}
#endif
Expand All @@ -4407,7 +4422,7 @@ JSC::JSPromise* GlobalObject::moduleLoaderImportModule(JSGlobalObject* jsGlobalO

ASSERT(result);
if (globalObject->m_lazyTestModuleObject.isInitialized()) [[unlikely]] {
Bun::didStartDynamicImport(globalObject, result, std::exchange(globalObject->onLoadPlugins.keyOfImportCall, {}));
Bun::didStartDynamicImport(globalObject, result, takeKeyOfImportCall(globalObject, key.string()));
RETURN_IF_EXCEPTION(scope, nullptr);
}
return result;
Expand Down
7 changes: 5 additions & 2 deletions test/aot/mocks-are-hoisted-above-the-imports.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,9 @@ const differs = {
"an error of the build has its number in front": [
"errors > an import statement in a CommonJS file is still rejected",
],
"the runner is not told of a compiled import of a builtin module": [
"errors > a factory for a builtin module is named too",
],
};

// How many cases of each section of the specification pass.
Expand All @@ -35,7 +38,7 @@ const sections = {
"modes": 7,
"a top-level variable in a factory of jest.mock": 18,
"a top-level variable in a factory of vi.mock": 18,
"errors": 3,
"errors": 13,
"source locations": 4,
};

Expand Down Expand Up @@ -67,6 +70,6 @@ test.each(Object.entries(sections))(
expect(named("fail")).toEqual(differing.sort());
expect(named("pass")).toHaveLength(passing);
// A section that is not listed here would run in no case.
expect(Number(/^ *(\d+) filtered out$/m.exec(stderr)?.[1])).toBe(122 + 12 - passing - differing.length);
expect(Number(/^ *(\d+) filtered out$/m.exec(stderr)?.[1])).toBe(132 + 13 - passing - differing.length);
},
);
2 changes: 2 additions & 0 deletions test/aot/runner-suites.known.txt
Original file line number Diff line number Diff line change
Expand Up @@ -85,6 +85,8 @@ test/cli/test/test-changed.test.ts: bun test --changed --watch > trigger file pa
test/cli/test/test-environment.test.ts: test environment > without --isolate > switching environments works even if a file leaves builtins patched
test/cli/test/test-shard.test.ts: --timings > --parallel with --timings cuts chunks by duration and dispatches each chunk slowest-first
test/cli/test/test-shard.test.ts: --timings > --shard with --timings cuts path-sorted files into runs of equal total time
# The next one mocks `node:os`. The runner is not told of a compiled import of a builtin module, so it cannot say that the file waits for the factory.
test/js/bun/test/mock/mock-hoist.test.ts: errors > a factory for a builtin module is named too
test/js/bun/test/mock/mock-hoist.test.ts: errors > a jest.mock() factory can read a later const though an earlier file or a preload loaded the module: ["--isolate"]
test/js/bun/test/mock/mock-hoist.test.ts: errors > a jest.mock() factory can read a later const though an earlier file or a preload loaded the module: ["--isolate=modules"]
test/js/bun/test/mock/mock-hoist.test.ts: errors > a jest.mock() factory can read a later const though an earlier file or a preload loaded the module: []
Expand Down
Loading
Loading