Skip to content
This repository was archived by the owner on Nov 4, 2026. It is now read-only.
Merged
Show file tree
Hide file tree
Changes from all 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
15 changes: 15 additions & 0 deletions .changeset/7271-localstorage-probe-node26.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
---
---

Repair the test-environment storage globals so a `Storage.prototype` instrument
cannot go silently blind on a newer Node (objectui#7271). Test only; no package
is released by this change.

From Node 26 the experimental Web Storage globals are on by default, and
Vitest's `populateGlobal` copies happy-dom's `Storage` class but not its
`localStorage`/`sessionStorage` — so the class and the stores came from two
different implementations, and instrumentation of `Storage.prototype` observed
nothing. `vitest.setup.base.ts` now states the rule positively (in a DOM
environment every storage global is that environment's own `Storage`) and
verifies it, and `anonSeedScope-5746.enumeration.test.tsx` names the failure
mode instead of reporting seven anonymous zeros.
Original file line number Diff line number Diff line change
Expand Up @@ -86,7 +86,44 @@ function record(op: Op['op'], key: string, detail: string) {

let restoreInstrument: (() => void) | null = null;

/**
* The instrument below patches `Storage.prototype`, so it can only observe an
* operation issued through an object that INHERITS from the same `Storage`.
* That is an invariant of the test ENVIRONMENT, and it is not one this file or
* the code under test can hold up on its own: from Node 26 the experimental Web
* Storage globals are on by default, and Vitest's `populateGlobal` then leaves
* `localStorage`/`sessionStorage` pointing at NODE's implementation while
* `Storage` itself is happy-dom's (measured, v26.7.0 — objectui#7271).
*
* When that holds, the patch observes nothing: S0 reports `expected 0 to be
* greater than 0` and S1-S6 read "no `@anon` seed was written" off a ledger
* that is empty for a reason that has nothing to do with what they measure.
* Seven simultaneous zeros invite "the probe is stale, relax it", so this says
* the true thing by name instead — and it says it BEFORE the ledger is
* consulted, not through it.
*
* It does NOT replace S0. This catches exactly one cause of blindness, the one
* that has actually happened; S0's counter-probe is what catches the rest, and
* `expect(writes().length).toBeGreaterThan(0)` still has to hold on its own.
*/
function assertStoresAreInstrumentable() {
for (const name of ['sessionStorage', 'localStorage'] as const) {
const store: unknown = globalThis[name];
if (store instanceof Storage) continue;
const proto = store == null ? 'n/a' : (Object.getPrototypeOf(store)?.constructor?.name ?? 'null-prototype');
throw new Error(
`test environment: \`${name}\` is not an instance of the \`Storage\` whose ` +
'prototype this file patches, so the instrument would observe NOTHING and ' +
'S1-S6 would pass vacuously off an empty ledger. Got ' +
`${Object.prototype.toString.call(store)} (prototype ${proto}); node=${process.version}. ` +
'The repair belongs in `vitest.setup.base.ts` — NOT in these assertions. ' +
'See objectui#7271.',
);
}
}

function installInstrument() {
assertStoresAreInstrumentable();
const origSet = Storage.prototype.setItem;
const origGet = Storage.prototype.getItem;
const origRemove = Storage.prototype.removeItem;
Expand Down
116 changes: 104 additions & 12 deletions vitest.setup.base.ts
Original file line number Diff line number Diff line change
Expand Up @@ -42,11 +42,49 @@ if (typeof (globalThis as any).ResizeObserver === 'undefined') {
};
}

// Node 22+/25 ships a stubbed native `localStorage` / `sessionStorage` that
// needs `--localstorage-file=<path>` to be functional. Without the flag,
// `clear()` and `removeItem()` are missing, which breaks tests relying on a
// working Storage. Replace with an in-memory Storage for deterministic behavior
// across Node versions.
// Storage globals: the DOM environment's own `Storage` must be the one every
// test sees. Stated positively on purpose - the old rule here was "replace a
// store that looks broken", and it half-fired.
//
// Node ships experimental Web Storage globals (`--experimental-webstorage` on
// v22, ON BY DEFAULT from v26). Vitest's `populateGlobal` refuses to copy a
// window key that already exists on `globalThis` unless the name is on its own
// hardcoded list - `Storage` is on that list, `localStorage` and
// `sessionStorage` are not. So inside a happy-dom environment on Node 26 the
// three globals come from TWO different implementations (measured, v26.7.0):
//
// globalThis.Storage -> happy-dom's class (copied)
// globalThis.sessionStorage -> Node's native store (NOT copied)
// globalThis.localStorage -> Node's getter, which warns
// "localStorage is not available because
// --localstorage-file was not provided"
// and answers `undefined` (NOT copied)
//
// The previous shim only replaced a store that was missing or lacked
// `clear`/`removeItem`, so it replaced `localStorage` (with a plain object
// literal) and LEFT `sessionStorage` as Node's. Neither is an instance of
// `globalThis.Storage`, and both failure modes that follow are SILENT:
//
// * patching `Storage.prototype` observes NOTHING, so a suite instrumenting
// writes reads an empty ledger and its assertions pass vacuously;
// * `Object.keys(localStorage)` never answers the store's ENTRIES. The plain
// object kept those in a closed-over Map, so its own keys are its own six
// members - measured, `["length","clear","getItem","key","removeItem",
// "setItem"]` - and a caller filtering them by key prefix sees nothing.
// happy-dom's Storage is a Proxy that exposes the entries instead.
//
// Measured on v26.7.0 before this rule, over the 102 storage-touching suites:
// 3 files went red, 12 tests - `anonSeedScope-5746.enumeration.test.tsx`,
// `signOut-client-cache-purge-5198.test.tsx`, `sessionUserChangePurge-5664
// .test.tsx` - and they went red only because all three read back a write they
// had made themselves. Two more suites that instrument `Storage.prototype`
// stayed GREEN in the same run while the instrument was proven blind. That is
// the general case, and the reason this rule is stated positively rather than
// left to each suite to notice - see objectui#7271.
//
// So: in a DOM environment every storage global is (re)built from that
// environment's own `Storage`; without one, both are the in-memory shim,
// unconditionally, so the `node` project behaves the same on every Node.
function createMemoryStorage(): Storage {
const store = new Map<string, string>();
return {
Expand All @@ -71,14 +109,68 @@ function createMemoryStorage(): Storage {
} as Storage;
}

/**
* The DOM environment's `Storage` constructor, or `null` when there is no DOM.
*
* happy-dom's `Storage` is publicly constructible; Node's native one answers
* `Illegal constructor`. That is what tells the two apart when both classes
* carry the same method names.
*/
const globalScope = globalThis as unknown as Record<string, unknown>;

function domStorageConstructor(): (new () => Storage) | null {
const Ctor = globalScope.Storage as (new () => Storage) | undefined;
if (typeof Ctor !== 'function') return null;
try {
const probe = new Ctor();
return typeof probe?.setItem === 'function' ? Ctor : null;
} catch {
return null;
}
}

const DomStorage = domStorageConstructor();

for (const name of ['localStorage', 'sessionStorage'] as const) {
const existing = (globalThis as any)[name];
if (!existing || typeof existing.clear !== 'function' || typeof existing.removeItem !== 'function') {
Object.defineProperty(globalThis, name, {
configurable: true,
writable: true,
value: createMemoryStorage(),
});
if (DomStorage) {
let existing: unknown;
// Reading Node's `localStorage` getter is what emits its ExperimentalWarning;
// it never throws on the versions in play, but a future one may.
try {
existing = globalScope[name];
} catch {
existing = undefined;
}
// `instanceof` only - do NOT probe the store by reading `setItem` & co.
// happy-dom's Storage is a Proxy that BINDS a method onto the instance as an
// own property the first time that method is read, freezing whatever
// `Storage.prototype` held at that moment. Reading one here would therefore
// make every later `Storage.prototype` patch invisible to this store - which
// is precisely the blindness this block exists to prevent. Measured: adding
// a four-method liveness probe here turned all 7 assertions of
// `anonSeedScope-5746.enumeration.test.tsx` red on Node 22.
if (existing instanceof DomStorage) continue;
}
Object.defineProperty(globalThis, name, {
configurable: true,
writable: true,
value: DomStorage ? new DomStorage() : createMemoryStorage(),
});
}

// Verified, not assumed - by identity, for the reason above. If a future Node or
// Vitest breaks the reasoning in a way this repair does not cover, EVERY suite
// fails here by name instead of one of them quietly measuring a store nobody
// wrote to.
if (DomStorage) {
for (const name of ['localStorage', 'sessionStorage'] as const) {
if (globalScope[name] instanceof DomStorage) continue;
throw new Error(
`vitest.setup.base: globalThis.${name} is not an instance of this ` +
"environment's own `Storage`, so patching `Storage.prototype` would observe " +
'nothing and a suite reading back its own writes would pass VACUOUSLY. ' +
`node=${(globalScope.process as { version?: string } | undefined)?.version}. See objectui#7271.`,
);
}
}

Expand Down
Loading