@noego/testing 0.1.0 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -20,702 +20,752 @@ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: tru
20
20
  // src/index.ts
21
21
  var index_exports = {};
22
22
  __export(index_exports, {
23
- LeakDetector: () => LeakDetector,
24
- ManualClock: () => ManualClock,
25
- ManualScheduler: () => ManualScheduler,
26
- MemoryKeyValueStore: () => MemoryKeyValueStore,
27
- MemoryObjectStore: () => MemoryObjectStore,
28
- NoopLogSink: () => NoopLogSink,
29
- RecordingEventBus: () => RecordingEventBus,
30
- RecordingLogSink: () => RecordingLogSink,
31
- RecordingTelemetrySink: () => RecordingTelemetrySink,
32
- RecordingTraceSink: () => RecordingTraceSink,
33
- ScriptedFetchClient: () => ScriptedFetchClient,
34
- ScriptedProcessRunner: () => ScriptedProcessRunner,
35
- SeededRandomSource: () => SeededRandomSource,
36
- SequenceIdGenerator: () => SequenceIdGenerator,
37
- runClockContract: () => runClockContract,
38
- runEventBusContract: () => runEventBusContract,
39
- runKeyValueStoreContract: () => runKeyValueStoreContract,
40
- runObjectStoreContract: () => runObjectStoreContract,
41
- testEvent: () => testEvent
23
+ AmbiguousNameKeyError: () => AmbiguousNameKeyError,
24
+ CallScriptExhaustedError: () => CallScriptExhaustedError,
25
+ ENV_REGISTRY: () => ENV_REGISTRY,
26
+ ExpectationOverflowError: () => ExpectationOverflowError,
27
+ InvalidDescriptorError: () => InvalidDescriptorError,
28
+ MethodNotCallableError: () => MethodNotCallableError,
29
+ MissingIocSeamError: () => MissingIocSeamError,
30
+ NonObjectMethodTargetError: () => NonObjectMethodTargetError,
31
+ TestIocBuilder: () => TestIocBuilder,
32
+ TestingError: () => TestingError,
33
+ TokenIdentitySplitError: () => TokenIdentitySplitError,
34
+ UnknownTokenKeyError: () => UnknownTokenKeyError,
35
+ UnwatchedInspectionError: () => UnwatchedInspectionError,
36
+ VerificationError: () => VerificationError,
37
+ test: () => test,
38
+ testIoc: () => testIoc
42
39
  });
43
40
  module.exports = __toCommonJS(index_exports);
44
41
 
45
- // src/time/manual_clock.ts
46
- var import_runtime = require("@noego/runtime");
47
- var ManualClock = class _ManualClock extends import_runtime.Clock {
48
- static defaultStart = import_runtime.Instant.ofEpochMilliseconds(Date.UTC(2020, 0, 1));
49
- current;
50
- constructor(start = _ManualClock.defaultStart) {
51
- super();
52
- this.current = start;
53
- }
54
- now() {
55
- return this.current;
56
- }
57
- set(instant) {
58
- if (instant.isBefore(this.current)) {
59
- throw new RangeError(`ManualClock cannot move backwards: ${this.current.toString()} -> ${instant.toString()}`);
60
- }
61
- this.current = instant;
42
+ // src/builder.ts
43
+ var import_ioc = require("@noego/ioc");
44
+
45
+ // src/errors.ts
46
+ var TestingError = class extends Error {
47
+ constructor(message) {
48
+ super(message);
49
+ this.name = new.target.name;
62
50
  }
63
- advanceBy(duration) {
64
- this.current = this.current.plus(duration);
51
+ };
52
+ var MissingIocSeamError = class extends TestingError {
53
+ constructor() {
54
+ super(
55
+ "@noego/testing requires an @noego/ioc version that provides Container.setInstanceDecorator (>= 0.5.x with the instance-decoration seam). Upgrade @noego/ioc."
56
+ );
65
57
  }
66
58
  };
67
-
68
- // src/time/manual_scheduler.ts
69
- var import_runtime2 = require("@noego/runtime");
70
- var ManualScheduler = class extends import_runtime2.Scheduler {
71
- constructor(clock) {
72
- super();
73
- this.clock = clock;
74
- }
75
- clock;
76
- tasks = [];
77
- nextSequence = 0;
78
- nextId = 0;
79
- schedule(input) {
80
- const id = (0, import_runtime2.brandId)(`task-${++this.nextId}`, "ScheduledTask");
81
- const internal = {
82
- id,
83
- label: input.label,
84
- deadline: this.clock.now().plus(input.delay),
85
- sequence: this.nextSequence++,
86
- task: input.task,
87
- cancelled: false
88
- };
89
- this.tasks.push(internal);
90
- return {
91
- id,
92
- cancel: () => {
93
- internal.cancelled = true;
94
- }
95
- };
59
+ var UnwatchedInspectionError = class extends TestingError {
60
+ constructor(token, method) {
61
+ super(
62
+ `Method "${method}" on ${token} is not watched in this environment. Only watched methods are inspectable \u2014 install test.watch() or any test.* behavior/expectation descriptor for it.`
63
+ );
96
64
  }
97
- pending() {
98
- return this.live().sort(compareTasks).map(({ id, label, deadline }) => ({ id, label, deadline }));
99
- }
100
- /** Advance the clock, running every task due inside the window in order. */
101
- async advanceBy(duration) {
102
- const target = this.clock.now().plus(duration);
103
- for (; ; ) {
104
- const next = this.nextDue(target);
105
- if (next === null) break;
106
- if (next.deadline.isAfter(this.clock.now())) {
107
- this.clock.set(next.deadline);
108
- }
109
- await this.execute(next);
110
- }
111
- if (target.isAfter(this.clock.now())) {
112
- this.clock.set(target);
113
- }
65
+ };
66
+ var CallScriptExhaustedError = class extends TestingError {
67
+ constructor(token, method, scriptLength, callIndex) {
68
+ super(
69
+ `Call #${callIndex} to ${token}.${method} exceeds its test.calls() script of ${scriptLength} ${scriptLength === 1 ? "entry" : "entries"}.`
70
+ );
114
71
  }
115
- /** Advance to the earliest pending deadline and run exactly that task. */
116
- async runNext() {
117
- const next = this.live().sort(compareTasks)[0];
118
- if (next === void 0) {
119
- throw new Error("ManualScheduler.runNext: no pending tasks");
120
- }
121
- if (next.deadline.isAfter(this.clock.now())) {
122
- this.clock.set(next.deadline);
123
- }
124
- await this.execute(next);
125
- }
126
- /** Run tasks (advancing time as needed) until none remain. */
127
- async runUntilIdle(options) {
128
- const maxTasks = options?.maxTasks ?? 1e4;
129
- let executed = 0;
130
- while (this.live().length > 0) {
131
- if (executed >= maxTasks) {
132
- const labels = this.pending().slice(0, 5).map((t) => t.label).join(", ");
133
- throw new Error(
134
- `ManualScheduler.runUntilIdle: still not idle after ${maxTasks} tasks \u2014 probable infinite reschedule loop (next: ${labels})`
135
- );
136
- }
137
- await this.runNext();
138
- executed += 1;
139
- }
72
+ };
73
+ var ExpectationOverflowError = class extends TestingError {
74
+ constructor(token, method, expected, attempted) {
75
+ super(
76
+ expected === 0 ? `${token}.${method} was expected never to be called, but it was invoked.` : `${token}.${method} was expected exactly ${expected} ${expected === 1 ? "call" : "calls"}, but call #${attempted} arrived.`
77
+ );
140
78
  }
141
- /** Teardown assertion: fails when pending tasks remain, unless allowed. */
142
- assertNoPendingTasks(options) {
143
- if (options?.allow === true) return;
144
- const remaining = this.pending();
145
- if (remaining.length > 0) {
146
- const labels = remaining.map((t) => `${t.label} @ ${t.deadline.toString()}`).join("; ");
147
- throw new Error(`ManualScheduler: ${remaining.length} pending task(s) at teardown: ${labels}`);
148
- }
79
+ };
80
+ var VerificationError = class extends TestingError {
81
+ constructor(failures) {
82
+ super(
83
+ "Exact method expectations were not satisfied:\n" + failures.map(
84
+ (f) => ` - ${f.token}.${f.method}: expected exactly ${f.expected} ${f.expected === 1 ? "call" : "calls"}, observed ${f.actual}`
85
+ ).join("\n")
86
+ );
149
87
  }
150
- live() {
151
- return this.tasks.filter((t) => !t.cancelled);
88
+ };
89
+ var MethodNotCallableError = class extends TestingError {
90
+ constructor(token, method) {
91
+ super(
92
+ `Cannot install a test.* descriptor on ${token}.${method}: the resolved instance has no callable method with that name.`
93
+ );
152
94
  }
153
- nextDue(target) {
154
- const candidates = this.live().filter((t) => !t.deadline.isAfter(target)).sort(compareTasks);
155
- return candidates[0] ?? null;
95
+ };
96
+ var NonObjectMethodTargetError = class extends TestingError {
97
+ constructor(token) {
98
+ super(
99
+ `.methods() is configured for ${token}, but that token resolved to a non-object value. Method descriptors apply only to IoC-managed instances.`
100
+ );
156
101
  }
157
- async execute(task) {
158
- this.remove(task);
159
- await task.task();
102
+ };
103
+ var UnknownTokenKeyError = class extends TestingError {
104
+ constructor(key, space, known) {
105
+ super(
106
+ `Unknown ${space} key "${key}" \u2014 it does not match any token known to this builder. Pass the class/token itself via a Map, or include the registration through .use(...). Known tokens: ` + (known.length ? known.join(", ") : "(none)")
107
+ );
160
108
  }
161
- remove(task) {
162
- const index = this.tasks.indexOf(task);
163
- this.tasks.splice(index, 1);
109
+ };
110
+ var InvalidDescriptorError = class extends TestingError {
111
+ };
112
+ var AmbiguousNameKeyError = class extends TestingError {
113
+ constructor(name, space) {
114
+ super(
115
+ `.${space}() key "${name}" is ambiguous: multiple distinct tokens share that display name. Use the canonical tuple form with the exact token: .${space}([[TheToken, ...]]).`
116
+ );
117
+ this.name = "AmbiguousNameKeyError";
164
118
  }
165
119
  };
166
- function compareTasks(a, b) {
167
- const byDeadline = a.deadline.compareTo(b.deadline);
168
- return byDeadline !== 0 ? byDeadline : a.sequence - b.sequence;
169
- }
170
-
171
- // src/identity/sequence_id_generator.ts
172
- var import_runtime3 = require("@noego/runtime");
173
- var SequenceIdGenerator = class extends import_runtime3.IdGenerator {
174
- counters = /* @__PURE__ */ new Map();
175
- next(brand) {
176
- const current = (this.counters.get(brand) ?? 0) + 1;
177
- this.counters.set(brand, current);
178
- return (0, import_runtime3.brandId)(`${brand.toLowerCase()}-${current}`, brand);
120
+ var TokenIdentitySplitError = class extends TestingError {
121
+ constructor(names) {
122
+ super(
123
+ `token identity split: .methods() entr${names.length === 1 ? "y" : "ies"} for ${names.map((name) => `"${name}"`).join(", ")} never matched a constructed instance, but a DIFFERENT class with the same name was constructed. Two module registries have loaded the same class file (test-file import vs harness graph import) \u2014 the configured behavior did not apply. Route the harness's imports through your registry (e.g. testApp .importer((p) => import(p))) or pass the exact token the graph uses.`
124
+ );
125
+ this.name = "TokenIdentitySplitError";
179
126
  }
180
127
  };
181
128
 
182
- // src/identity/seeded_random_source.ts
183
- var import_runtime4 = require("@noego/runtime");
184
- var SeededRandomSource = class extends import_runtime4.RandomSource {
185
- state;
186
- constructor(seed = 1) {
187
- super();
188
- if (!Number.isInteger(seed)) {
189
- throw new RangeError(`SeededRandomSource seed must be an integer, got ${seed}`);
190
- }
191
- this.state = seed >>> 0;
192
- }
193
- nextUint32() {
194
- this.state = this.state + 1831565813 >>> 0;
195
- let t = this.state;
196
- t = Math.imul(t ^ t >>> 15, t | 1);
197
- t ^= t + Math.imul(t ^ t >>> 7, t | 61);
198
- return (t ^ t >>> 14) >>> 0;
199
- }
200
- bytes(length) {
201
- if (!Number.isInteger(length) || length < 0) {
202
- throw new RangeError(`bytes length must be a non-negative integer, got ${length}`);
203
- }
204
- const out = new Uint8Array(length);
205
- for (let i = 0; i < length; i += 1) {
206
- out[i] = this.nextUint32() & 255;
207
- }
208
- return out;
129
+ // src/descriptors.ts
130
+ var DESCRIPTOR = /* @__PURE__ */ Symbol.for("noego:testing:descriptor");
131
+ function isDescriptor(value) {
132
+ return typeof value === "object" && value !== null && value[DESCRIPTOR] === true;
133
+ }
134
+ function frozen(value) {
135
+ return Object.freeze(value);
136
+ }
137
+ function assertBehavior(value, where) {
138
+ if (!isDescriptor(value) || !["returns", "throws", "original", "calls"].includes(value.kind)) {
139
+ throw new InvalidDescriptorError(
140
+ `${where} requires a behavior descriptor (test.returns/throws/original/calls).`
141
+ );
209
142
  }
210
- integer(minInclusive, maxExclusive) {
211
- if (maxExclusive <= minInclusive) {
212
- throw new RangeError(`integer range is empty: [${minInclusive}, ${maxExclusive})`);
143
+ }
144
+ var test = {
145
+ /** Return the supplied value when the method is called. Auto-watches. */
146
+ returns(value) {
147
+ return frozen({ [DESCRIPTOR]: true, kind: "returns", value });
148
+ },
149
+ /** Throw/reject with the supplied error. Auto-watches. */
150
+ throws(error) {
151
+ return frozen({ [DESCRIPTOR]: true, kind: "throws", error });
152
+ },
153
+ /** Invoke the original effective method. Auto-watches. */
154
+ original() {
155
+ return frozen({ [DESCRIPTOR]: true, kind: "original" });
156
+ },
157
+ /**
158
+ * Per-invocation behavior script: call 1 uses entry 1, and so on. A call
159
+ * after exhaustion fails immediately. Unused entries do not fail verification.
160
+ */
161
+ calls(script) {
162
+ if (!Array.isArray(script)) {
163
+ throw new InvalidDescriptorError("test.calls() requires an array of behavior descriptors.");
213
164
  }
214
- const span = maxExclusive - minInclusive;
215
- return minInclusive + this.nextUint32() % span;
216
- }
217
- };
218
-
219
- // src/network/scripted_fetch_client.ts
220
- var import_runtime5 = require("@noego/runtime");
221
- var ScriptedFetchClient = class extends import_runtime5.FetchClient {
222
- script;
223
- cursor = 0;
224
- executed = [];
225
- constructor(script) {
226
- super();
227
- this.script = [...script];
228
- }
229
- execute(request) {
230
- const entry = this.script[this.cursor];
231
- if (entry === void 0) {
232
- return Promise.reject(
233
- new Error(`ScriptedFetchClient: unexpected call #${this.cursor + 1} (${request.method} ${request.url}); script is exhausted`)
234
- );
165
+ script.forEach((entry, i) => assertBehavior(entry, `test.calls() entry #${i + 1}`));
166
+ return frozen({ [DESCRIPTOR]: true, kind: "calls", script: Object.freeze([...script]) });
167
+ },
168
+ /**
169
+ * Keep original behavior and record calls. With a raw wrapper argument, the
170
+ * wrapper's behavior runs and is recorded.
171
+ */
172
+ watch(wrapper) {
173
+ if (wrapper !== void 0 && typeof wrapper !== "function") {
174
+ throw new InvalidDescriptorError("test.watch() accepts only a raw wrapper function.");
235
175
  }
236
- if (!entry.matches(request)) {
237
- return Promise.reject(
238
- new Error(`ScriptedFetchClient: call #${this.cursor + 1} (${request.method} ${request.url}) does not match script entry "${entry.describe}"`)
176
+ return frozen({ [DESCRIPTOR]: true, kind: "watch", wrapper });
177
+ },
178
+ /** Require exactly one call; with no behavior, the original runs. */
179
+ once(behavior) {
180
+ if (behavior !== void 0) assertBehavior(behavior, "test.once()");
181
+ return frozen({ [DESCRIPTOR]: true, kind: "expect", expected: 1, behavior });
182
+ },
183
+ /** Require exactly `count` calls; with no behavior, the original runs. */
184
+ times(count, behavior) {
185
+ if (!Number.isInteger(count) || count < 0) {
186
+ throw new InvalidDescriptorError(
187
+ `test.times() requires a non-negative integer count, received ${String(count)}.`
239
188
  );
240
189
  }
241
- this.cursor += 1;
242
- this.executed.push(request);
243
- const outcome = entry.respond(request);
244
- return outcome instanceof import_runtime5.FetchError ? Promise.reject(outcome) : Promise.resolve(outcome);
245
- }
246
- /** Teardown assertion: every scripted call must have been consumed. */
247
- assertScriptConsumed() {
248
- if (this.cursor < this.script.length) {
249
- const remaining = this.script.slice(this.cursor).map((e) => e.describe).join(", ");
250
- throw new Error(`ScriptedFetchClient: ${this.script.length - this.cursor} unconsumed script entr(ies): ${remaining}`);
190
+ if (behavior !== void 0) assertBehavior(behavior, "test.times()");
191
+ return frozen({ [DESCRIPTOR]: true, kind: "expect", expected: count, behavior });
192
+ },
193
+ /** Require zero calls; the first invocation fails and skips the original. */
194
+ never() {
195
+ return frozen({ [DESCRIPTOR]: true, kind: "expect", expected: 0 });
196
+ },
197
+ /** Read the recorded history for a watched method in one environment. */
198
+ inspect(environment, token, method) {
199
+ const registry = environment?.[ENV_REGISTRY];
200
+ if (!registry) {
201
+ throw new InvalidDescriptorError(
202
+ "test.inspect() requires a built @noego/testing environment as its first argument."
203
+ );
251
204
  }
205
+ return registry.inspect(token, method);
252
206
  }
253
207
  };
208
+ Object.freeze(test);
209
+ var ENV_REGISTRY = /* @__PURE__ */ Symbol.for("noego:testing:env-registry");
254
210
 
255
- // src/process/scripted_process_runner.ts
256
- var import_runtime6 = require("@noego/runtime");
257
- var ScriptedProcessRunner = class extends import_runtime6.ProcessRunner {
258
- script;
259
- cursor = 0;
260
- openHandles = /* @__PURE__ */ new Set();
261
- constructor(script) {
262
- super();
263
- this.script = [...script];
264
- }
265
- consume(command, kind) {
266
- const entry = this.script[this.cursor];
267
- if (entry === void 0) {
268
- throw new Error(`ScriptedProcessRunner: unexpected ${kind} of "${command.executable}"; script is exhausted`);
211
+ // src/method_state.ts
212
+ var CONTEXT_WRAPPED = /* @__PURE__ */ Symbol.for("ioc:context-wrapped");
213
+ var CONTEXT_OWNER = /* @__PURE__ */ Symbol.for("ioc:context-owner");
214
+ function tokenLabel(token) {
215
+ if (typeof token === "function") return token.name || "[anonymous class]";
216
+ if (typeof token === "symbol") return String(token);
217
+ return String(token);
218
+ }
219
+ var MethodState = class {
220
+ constructor(tokenName, method, descriptor) {
221
+ this.tokenName = tokenName;
222
+ this.method = method;
223
+ this.descriptor = descriptor;
224
+ }
225
+ tokenName;
226
+ method;
227
+ descriptor;
228
+ calls = [];
229
+ /** Actual invocation count (includes the call currently executing). */
230
+ actual = 0;
231
+ /** Cursor into a test.calls() script. */
232
+ scriptCursor = 0;
233
+ get expectation() {
234
+ return this.descriptor.kind === "expect" ? this.descriptor : void 0;
235
+ }
236
+ inspection() {
237
+ return {
238
+ count: this.calls.length,
239
+ calls: this.calls.map((c) => ({ ...c, args: [...c.args] }))
240
+ };
241
+ }
242
+ };
243
+ var WatchRegistry = class {
244
+ /** entry-identity → method → state. Entries share states across instances. */
245
+ states = /* @__PURE__ */ new Map();
246
+ nameIndex = /* @__PURE__ */ new Map();
247
+ entries = [];
248
+ /** Class-token entries that identity-matched at least one construction. */
249
+ matchedEntryKeys = /* @__PURE__ */ new Set();
250
+ /** Constructed class tokens that matched NO entry, by display name. */
251
+ unmatchedConstructedByName = /* @__PURE__ */ new Map();
252
+ addEntry(entry) {
253
+ this.entries.push(entry);
254
+ const byMethod = /* @__PURE__ */ new Map();
255
+ for (const [method, descriptor] of entry.methods) {
256
+ if (typeof descriptor === "function") continue;
257
+ byMethod.set(method, new MethodState(this.entryLabel(entry), method, descriptor));
269
258
  }
270
- if (!entry.matches(command)) {
271
- throw new Error(`ScriptedProcessRunner: ${kind} of "${command.executable}" does not match script entry "${entry.describe}"`);
259
+ this.states.set(entry.key, byMethod);
260
+ if (entry.byName) this.nameIndex.set(entry.key, entry.key);
261
+ else if (typeof entry.key === "function" && entry.key.name) {
262
+ this.nameIndex.set(entry.key.name, entry.key);
272
263
  }
273
- this.cursor += 1;
274
- return entry;
275
264
  }
276
- run(command) {
277
- try {
278
- const entry = this.consume(command, "run");
279
- return Promise.resolve(foldEvents(entry.events));
280
- } catch (error) {
281
- return Promise.reject(error);
265
+ entryLabel(entry) {
266
+ return entry.byName ? String(entry.key) : tokenLabel(entry.key);
267
+ }
268
+ /** Entries applying to a resolving token (exact identity or name match). */
269
+ matchEntries(token) {
270
+ const name = typeof token === "function" ? token.name : typeof token === "string" ? token : void 0;
271
+ const matched = this.entries.filter(
272
+ (entry) => entry.key === token || entry.byName && name !== void 0 && entry.key === name
273
+ );
274
+ if (matched.length) {
275
+ for (const entry of matched) this.matchedEntryKeys.add(entry.key);
276
+ } else if (typeof token === "function" && name) {
277
+ this.unmatchedConstructedByName.set(name, token);
282
278
  }
283
- }
284
- spawn(command) {
285
- const entry = this.consume(command, "spawn");
286
- const handle = new ScriptedProcessHandle(command.label, entry.events, () => {
287
- this.openHandles.delete(handle);
288
- });
289
- this.openHandles.add(handle);
290
- return handle;
291
- }
292
- /** Teardown assertion: no spawned process may remain open. */
293
- assertNoOpenHandles() {
294
- if (this.openHandles.size > 0) {
295
- const labels = [...this.openHandles].map((h) => h.label).join(", ");
296
- throw new Error(`ScriptedProcessRunner: ${this.openHandles.size} open process handle(s) at teardown: ${labels}`);
279
+ return matched;
280
+ }
281
+ state(entryKey, method) {
282
+ return this.states.get(entryKey)?.get(method);
283
+ }
284
+ inspect(token, method) {
285
+ const label = tokenLabel(token);
286
+ const keys = [token];
287
+ const name = typeof token === "function" ? token.name : typeof token === "string" ? token : void 0;
288
+ if (name !== void 0 && this.nameIndex.has(name)) keys.push(this.nameIndex.get(name));
289
+ for (const key of keys) {
290
+ const state = this.states.get(key)?.get(method);
291
+ if (state) return state.inspection();
297
292
  }
298
- }
299
- };
300
- var ScriptedProcessHandle = class {
301
- constructor(label, events, onClosed) {
302
- this.label = label;
303
- this.events = events;
304
- this.onClosed = onClosed;
305
- this.resultPromise = new Promise((resolve) => {
306
- this.resolveResult = resolve;
307
- });
308
- }
309
- label;
310
- events;
311
- onClosed;
312
- listeners = [];
313
- resultPromise;
314
- resolveResult;
315
- flushed = false;
316
- killed = false;
317
- onEvent(listener) {
318
- this.listeners.push(listener);
319
- }
320
- /** Deliver all scripted events now (deterministic, test-controlled). */
321
- flush() {
322
- if (this.flushed || this.killed) return;
323
- this.flushed = true;
324
- for (const event of this.events) {
325
- for (const listener of this.listeners) listener(event);
326
- if (event.kind === "exit") {
327
- this.resolveResult(foldEvents(this.events));
328
- this.onClosed();
293
+ throw new UnwatchedInspectionError(label, method);
294
+ }
295
+ /**
296
+ * Class-token entries that never identity-matched a construction while a
297
+ * DIFFERENT class with the same display name did construct. This is the
298
+ * split-module-registry signature (a test-file class object vs the graph's
299
+ * own load of the same file) — or two genuinely distinct same-named tokens
300
+ * where the configured one never resolved. Either way the configured
301
+ * behavior silently did not apply, which must be loud.
302
+ */
303
+ identitySplits() {
304
+ const splits = [];
305
+ for (const entry of this.entries) {
306
+ if (entry.byName || typeof entry.key !== "function") continue;
307
+ if (this.matchedEntryKeys.has(entry.key)) continue;
308
+ const name = entry.key.name;
309
+ if (!name) continue;
310
+ const constructed = this.unmatchedConstructedByName.get(name);
311
+ if (constructed !== void 0 && constructed !== entry.key) {
312
+ splits.push({ name, entryToken: entry.key });
329
313
  }
330
314
  }
315
+ return splits;
331
316
  }
332
- kill(signal = "SIGTERM") {
333
- if (this.flushed || this.killed) return;
334
- this.killed = true;
335
- const exit = { kind: "exit", exitCode: null, signal };
336
- for (const listener of this.listeners) listener(exit);
337
- this.resolveResult({ exitCode: null, signal, stdout: "", stderr: "" });
338
- this.onClosed();
339
- }
340
- wait() {
341
- return this.resultPromise;
342
- }
343
- };
344
- function foldEvents(events) {
345
- let stdout = "";
346
- let stderr = "";
347
- let exitCode = null;
348
- let signal = null;
349
- for (const event of events) {
350
- if (event.kind === "stdout") stdout += event.chunk;
351
- else if (event.kind === "stderr") stderr += event.chunk;
352
- else {
353
- exitCode = event.exitCode;
354
- signal = event.signal;
317
+ /** Repeatable snapshot check of all exact expectations. */
318
+ verify() {
319
+ const splits = this.identitySplits();
320
+ if (splits.length) {
321
+ throw new TokenIdentitySplitError(splits.map((split) => split.name));
355
322
  }
356
- }
357
- return { exitCode, signal, stdout, stderr };
358
- }
359
-
360
- // src/storage/memory_key_value_store.ts
361
- var import_runtime7 = require("@noego/runtime");
362
- var MemoryKeyValueStore = class extends import_runtime7.KeyValueStore {
363
- constructor(clock) {
364
- super();
365
- this.clock = clock;
366
- }
367
- clock;
368
- entries = /* @__PURE__ */ new Map();
369
- get(key, codec) {
370
- const entry = this.entries.get(key);
371
- if (entry === void 0) return Promise.resolve(null);
372
- if (entry.expiresAt !== null && !this.clock.now().isBefore(entry.expiresAt)) {
373
- this.entries.delete(key);
374
- return Promise.resolve(null);
323
+ const failures = [];
324
+ for (const byMethod of this.states.values()) {
325
+ for (const state of byMethod.values()) {
326
+ const expectation = state.expectation;
327
+ if (!expectation) continue;
328
+ if (state.actual !== expectation.expected) {
329
+ failures.push({
330
+ token: state.tokenName,
331
+ method: state.method,
332
+ expected: expectation.expected,
333
+ actual: state.actual
334
+ });
335
+ }
336
+ }
375
337
  }
376
- return Promise.resolve(codec.decode(entry.encoded));
377
- }
378
- put(key, value, codec, options) {
379
- const expiresAt = options?.timeToLive !== void 0 ? this.clock.now().plus(options.timeToLive) : null;
380
- this.entries.set(key, { encoded: codec.encode(value), expiresAt });
381
- return Promise.resolve();
382
- }
383
- delete(key) {
384
- this.entries.delete(key);
385
- return Promise.resolve();
338
+ if (failures.length) throw new VerificationError(failures);
386
339
  }
387
340
  };
388
-
389
- // src/storage/memory_object_store.ts
390
- var import_runtime8 = require("@noego/runtime");
391
- var MemoryObjectStore = class extends import_runtime8.ObjectStore {
392
- objects = /* @__PURE__ */ new Map();
393
- nextVersion = 0;
394
- read(key) {
395
- return Promise.resolve(this.objects.get(key) ?? null);
396
- }
397
- write(key, object) {
398
- const version = (0, import_runtime8.brandId)(`v${++this.nextVersion}`, "ObjectVersion");
399
- this.objects.set(key, {
400
- bytes: object.bytes.slice(),
401
- contentType: object.contentType,
402
- metadata: object.metadata !== void 0 ? new Map(object.metadata) : void 0,
403
- version
404
- });
405
- return Promise.resolve(version);
406
- }
407
- delete(key) {
408
- this.objects.delete(key);
409
- return Promise.resolve();
341
+ function isPromiseLike(value) {
342
+ return !!value && typeof value.then === "function";
343
+ }
344
+ function recordOutcome(call, outcome, threw) {
345
+ if (!threw && isPromiseLike(outcome)) {
346
+ call.pending = true;
347
+ outcome.then(
348
+ (value) => {
349
+ call.result = value;
350
+ call.pending = false;
351
+ },
352
+ (error) => {
353
+ call.error = error;
354
+ call.pending = false;
355
+ }
356
+ );
357
+ return outcome;
410
358
  }
411
- };
412
-
413
- // src/events/recording_event_bus.ts
414
- var import_runtime9 = require("@noego/runtime");
415
- var RecordingEventBus = class extends import_runtime9.EventBus {
416
- constructor(mode = "immediate") {
417
- super();
418
- this.mode = mode;
419
- }
420
- mode;
421
- published = [];
422
- handlers = /* @__PURE__ */ new Set();
423
- queue = [];
424
- async publish(event) {
425
- this.published.push(event);
426
- if (this.mode === "queued") {
427
- this.queue.push(event);
428
- return;
359
+ call.pending = false;
360
+ if (threw) call.error = outcome;
361
+ else call.result = outcome;
362
+ return outcome;
363
+ }
364
+ function createMethodDecorator(registry) {
365
+ const wrappers = /* @__PURE__ */ new WeakMap();
366
+ return function decorate(instance, token) {
367
+ const entries = registry.matchEntries(token);
368
+ if (entries.length === 0) return instance;
369
+ if (instance === null || typeof instance !== "object" && typeof instance !== "function") {
370
+ throw new NonObjectMethodTargetError(tokenLabel(token));
429
371
  }
430
- await this.deliver(event);
431
- }
432
- subscribe(handler) {
433
- this.handlers.add(handler);
434
- const bus = this;
435
- const subscription = {
436
- active: true,
437
- unsubscribe() {
438
- if (!subscription.active) return;
439
- subscription.active = false;
440
- bus.handlers.delete(handler);
372
+ if (wrappers.has(instance)) return wrappers.get(instance);
373
+ const effective = /* @__PURE__ */ new Map();
374
+ for (const entry of entries) {
375
+ for (const [method, descriptor] of entry.methods) {
376
+ effective.set(method, { entryKey: entry.key, descriptor });
441
377
  }
442
- };
443
- return subscription;
444
- }
445
- /** Deliver buffered events (queued mode) in publication order. */
446
- async deliverQueued() {
447
- while (this.queue.length > 0) {
448
- const event = this.queue.shift();
449
- await this.deliver(event);
450
378
  }
379
+ for (const method of effective.keys()) {
380
+ if (typeof instance[method] !== "function") {
381
+ throw new MethodNotCallableError(tokenLabel(token), method);
382
+ }
383
+ }
384
+ const methodCache = /* @__PURE__ */ new Map();
385
+ const proxy = new Proxy(instance, {
386
+ get(target, prop, receiver) {
387
+ if (typeof prop === "string" && effective.has(prop)) {
388
+ let wrapped = methodCache.get(prop);
389
+ if (!wrapped) {
390
+ const { entryKey, descriptor } = effective.get(prop);
391
+ wrapped = buildMethodWrapper(target, prop, descriptor, registry.state(entryKey, prop));
392
+ methodCache.set(prop, wrapped);
393
+ }
394
+ return wrapped;
395
+ }
396
+ if (prop === CONTEXT_WRAPPED || prop === CONTEXT_OWNER) return target[prop];
397
+ return Reflect.get(target, prop, receiver);
398
+ }
399
+ });
400
+ wrappers.set(instance, proxy);
401
+ return proxy;
402
+ };
403
+ }
404
+ function buildMethodWrapper(target, method, descriptor, state) {
405
+ const callOriginal = (self, args) => {
406
+ const fn = target[method];
407
+ return fn.apply(self === void 0 ? target : self, args);
408
+ };
409
+ if (typeof descriptor === "function") {
410
+ const replacement = descriptor((...args) => callOriginal(target, args));
411
+ return function(...args) {
412
+ return replacement.apply(this, args);
413
+ };
451
414
  }
452
- get activeSubscriptionCount() {
453
- return this.handlers.size;
415
+ if (!isDescriptor(descriptor)) {
416
+ throw new TypeError(`Invalid method descriptor for ${method}`);
454
417
  }
455
- assertNoActiveSubscriptions() {
456
- if (this.handlers.size > 0) {
457
- throw new Error(`RecordingEventBus: ${this.handlers.size} active subscription(s) at teardown`);
418
+ return function(...args) {
419
+ if (!state) throw new TypeError(`Missing method state for ${method}`);
420
+ const expectation = state.expectation;
421
+ const attempted = state.actual + 1;
422
+ if (expectation && attempted > expectation.expected) {
423
+ state.actual = attempted;
424
+ throw new ExpectationOverflowError(state.tokenName, method, expectation.expected, attempted);
458
425
  }
459
- }
460
- async deliver(event) {
461
- for (const handler of [...this.handlers]) {
462
- await handler(event);
426
+ state.actual = attempted;
427
+ const call = {
428
+ index: attempted,
429
+ args: [...args],
430
+ pending: false,
431
+ timestamp: Date.now()
432
+ };
433
+ state.calls.push(call);
434
+ let behavior;
435
+ const base = descriptor.kind === "expect" ? descriptor.behavior ?? "original-effective" : descriptor.kind === "watch" ? descriptor.wrapper ?? "original-effective" : descriptor;
436
+ if (base !== "original-effective" && typeof base !== "function" && base !== void 0 && base.kind === "calls") {
437
+ if (state.scriptCursor >= base.script.length) {
438
+ throw new CallScriptExhaustedError(state.tokenName, method, base.script.length, attempted);
439
+ }
440
+ behavior = base.script[state.scriptCursor];
441
+ state.scriptCursor += 1;
442
+ } else {
443
+ behavior = base;
463
444
  }
464
- }
465
- };
445
+ try {
446
+ let outcome;
447
+ if (behavior === "original-effective") {
448
+ outcome = callOriginal(this, args);
449
+ } else if (typeof behavior === "function") {
450
+ outcome = behavior((...inner) => callOriginal(this, inner)).apply(this, args);
451
+ } else if (behavior.kind === "returns") {
452
+ outcome = behavior.value;
453
+ } else if (behavior.kind === "throws") {
454
+ throw behavior.error;
455
+ } else if (behavior.kind === "original") {
456
+ outcome = callOriginal(this, args);
457
+ } else {
458
+ throw new TypeError(`Nested test.calls() scripts are not supported (${method}).`);
459
+ }
460
+ return recordOutcome(call, outcome, false);
461
+ } catch (error) {
462
+ recordOutcome(call, error, true);
463
+ throw error;
464
+ }
465
+ };
466
+ }
466
467
 
467
- // src/observability/recording_sinks.ts
468
- var import_runtime10 = require("@noego/runtime");
469
- var RecordingLogSink = class extends import_runtime10.LogSink {
470
- envelopes = [];
471
- emit(envelope) {
472
- this.envelopes.push(envelope);
473
- }
474
- };
475
- var RecordingTraceSink = class extends import_runtime10.TraceSink {
476
- envelopes = [];
477
- emit(envelope) {
478
- this.envelopes.push(envelope);
479
- }
480
- };
481
- var RecordingTelemetrySink = class extends import_runtime10.TelemetrySink {
482
- envelopes = [];
483
- emit(envelope) {
484
- this.envelopes.push(envelope);
485
- }
486
- };
487
- var NoopLogSink = class extends import_runtime10.LogSink {
488
- emit(_envelope) {
468
+ // src/builder.ts
469
+ var COMPONENT_OPTIONS_KEY = /* @__PURE__ */ Symbol.for("ioc:component:options");
470
+ function* configEntries(config) {
471
+ if (Array.isArray(config)) {
472
+ for (const entry of config) {
473
+ if (!Array.isArray(entry) || entry.length !== 2) {
474
+ throw new InvalidDescriptorError(
475
+ "canonical composition entries are [token, value] tuples, e.g. .classes([[Token, Impl]])"
476
+ );
477
+ }
478
+ yield [entry[0], false, entry[1]];
479
+ }
480
+ } else if (config instanceof Map) {
481
+ for (const [key, value] of config) yield [key, false, value];
482
+ } else {
483
+ for (const key of [...Object.getOwnPropertyNames(config), ...Object.getOwnPropertySymbols(config)]) {
484
+ yield [key, typeof key === "string", config[key]];
485
+ }
489
486
  }
490
- };
491
-
492
- // src/contracts/clock.contract.ts
493
- function runClockContract(name, setup) {
494
- describe(`Clock contract: ${name}`, () => {
495
- it("returns a monotonically non-decreasing instant across consecutive reads", () => {
496
- const { clock } = setup();
497
- const first = clock.now();
498
- const second = clock.now();
499
- expect(second.isBefore(first)).toBe(false);
500
- });
501
- it("nowMs agrees with now()", () => {
502
- const { clock } = setup();
503
- const instant = clock.now();
504
- const ms = clock.nowMs();
505
- expect(ms).toBeGreaterThanOrEqual(instant.epochMilliseconds);
506
- });
507
- });
508
487
  }
509
-
510
- // src/contracts/key_value_store.contract.ts
511
- var import_runtime11 = require("@noego/runtime");
512
- function runKeyValueStoreContract(name, setup) {
513
- const codec = (0, import_runtime11.jsonCodec)();
514
- describe(`KeyValueStore contract: ${name}`, () => {
515
- it("returns null for a missing key", async () => {
516
- const { store } = setup();
517
- await expect(store.get((0, import_runtime11.storageKey)("missing"), codec)).resolves.toBeNull();
518
- });
519
- it("round-trips a stored value", async () => {
520
- const { store } = setup();
521
- const key = (0, import_runtime11.storageKey)("k1");
522
- await store.put(key, { n: 42 }, codec);
523
- await expect(store.get(key, codec)).resolves.toEqual({ n: 42 });
524
- });
525
- it("overwrites an existing value", async () => {
526
- const { store } = setup();
527
- const key = (0, import_runtime11.storageKey)("k1");
528
- await store.put(key, { n: 1 }, codec);
529
- await store.put(key, { n: 2 }, codec);
530
- await expect(store.get(key, codec)).resolves.toEqual({ n: 2 });
531
- });
532
- it("deletes a value and tolerates deleting a missing key", async () => {
533
- const { store } = setup();
534
- const key = (0, import_runtime11.storageKey)("k1");
535
- await store.put(key, { n: 1 }, codec);
536
- await store.delete(key);
537
- await expect(store.get(key, codec)).resolves.toBeNull();
538
- await expect(store.delete((0, import_runtime11.storageKey)("missing"))).resolves.toBeUndefined();
539
- });
540
- it("expires values after their TTL when TTL is supported", async () => {
541
- const context = setup();
542
- if (!context.supportsTtl) return;
543
- const key = (0, import_runtime11.storageKey)("expiring");
544
- await context.store.put(key, { n: 7 }, codec, { timeToLive: import_runtime11.Duration.ofSeconds(30) });
545
- await expect(context.store.get(key, codec)).resolves.toEqual({ n: 7 });
546
- await context.advanceBy(import_runtime11.Duration.ofSeconds(31));
547
- await expect(context.store.get(key, codec)).resolves.toBeNull();
548
- });
549
- it("keeps values without a TTL alive as time passes", async () => {
550
- const context = setup();
551
- const key = (0, import_runtime11.storageKey)("durable");
552
- await context.store.put(key, { n: 9 }, codec);
553
- await context.advanceBy(import_runtime11.Duration.ofMinutes(60));
554
- await expect(context.store.get(key, codec)).resolves.toEqual({ n: 9 });
555
- });
556
- });
488
+ function componentScope(cls) {
489
+ const options = typeof Reflect !== "undefined" && Reflect.getMetadata ? Reflect.getMetadata(COMPONENT_OPTIONS_KEY, cls) : void 0;
490
+ return options?.scope;
557
491
  }
558
-
559
- // src/contracts/object_store.contract.ts
560
- var import_runtime12 = require("@noego/runtime");
561
- function runObjectStoreContract(name, setup) {
562
- const bytes = (...values) => new Uint8Array(values);
563
- describe(`ObjectStore contract: ${name}`, () => {
564
- it("returns null for a missing object", async () => {
565
- const { store } = setup();
566
- await expect(store.read((0, import_runtime12.objectKey)("missing"))).resolves.toBeNull();
567
- });
568
- it("round-trips bytes, content type, and metadata", async () => {
569
- const { store } = setup();
570
- const key = (0, import_runtime12.objectKey)("docs/a.bin");
571
- await store.write(key, {
572
- bytes: bytes(1, 2, 3),
573
- contentType: "application/octet-stream",
574
- metadata: /* @__PURE__ */ new Map([["owner", "alice"]])
575
- });
576
- const stored = await store.read(key);
577
- expect(stored).not.toBeNull();
578
- expect([...stored.bytes]).toEqual([1, 2, 3]);
579
- expect(stored.contentType).toBe("application/octet-stream");
580
- expect(stored.metadata?.get("owner")).toBe("alice");
581
- });
582
- it("issues a new version on every write", async () => {
583
- const { store } = setup();
584
- const key = (0, import_runtime12.objectKey)("docs/a.bin");
585
- const v1 = await store.write(key, { bytes: bytes(1), contentType: "text/plain" });
586
- const v2 = await store.write(key, { bytes: bytes(2), contentType: "text/plain" });
587
- expect(v1).not.toBe(v2);
588
- const stored = await store.read(key);
589
- expect(stored.version).toBe(v2);
590
- expect([...stored.bytes]).toEqual([2]);
591
- });
592
- it("deletes an object and tolerates deleting a missing key", async () => {
593
- const { store } = setup();
594
- const key = (0, import_runtime12.objectKey)("docs/a.bin");
595
- await store.write(key, { bytes: bytes(1), contentType: "text/plain" });
596
- await store.delete(key);
597
- await expect(store.read(key)).resolves.toBeNull();
598
- await expect(store.delete((0, import_runtime12.objectKey)("missing"))).resolves.toBeUndefined();
599
- });
600
- it("does not expose caller mutations of written bytes", async () => {
601
- const { store } = setup();
602
- const key = (0, import_runtime12.objectKey)("docs/mutable.bin");
603
- const input = bytes(9);
604
- await store.write(key, { bytes: input, contentType: "text/plain" });
605
- input[0] = 0;
606
- const stored = await store.read(key);
607
- expect([...stored.bytes]).toEqual([9]);
608
- });
609
- });
492
+ function lifetimeToLoadAs(lifetime) {
493
+ if (lifetime === "singleton") return import_ioc.LoadAs.Singleton;
494
+ if (lifetime === "scoped") return import_ioc.LoadAs.Scoped;
495
+ return import_ioc.LoadAs.Transient;
610
496
  }
611
-
612
- // src/contracts/event_bus.contract.ts
613
- var testEvent = (value) => ({ type: "test-event", value });
614
- function runEventBusContract(name, setup) {
615
- describe(`EventBus contract: ${name}`, () => {
616
- it("delivers published events to subscribers in order", async () => {
617
- const { bus, deliver } = setup();
618
- const seen = [];
619
- const subscription = bus.subscribe((event) => {
620
- seen.push(event.value);
621
- });
622
- await bus.publish(testEvent(1));
623
- await bus.publish(testEvent(2));
624
- await deliver();
625
- expect(seen).toEqual([1, 2]);
626
- subscription.unsubscribe();
627
- });
628
- it("stops delivering after unsubscribe", async () => {
629
- const { bus, deliver } = setup();
630
- const seen = [];
631
- const subscription = bus.subscribe((event) => {
632
- seen.push(event.value);
633
- });
634
- await bus.publish(testEvent(1));
635
- await deliver();
636
- subscription.unsubscribe();
637
- await bus.publish(testEvent(2));
638
- await deliver();
639
- expect(seen).toEqual([1]);
640
- });
641
- it("supports multiple subscribers", async () => {
642
- const { bus, deliver } = setup();
643
- const a = [];
644
- const b = [];
645
- const sa = bus.subscribe((event) => {
646
- a.push(event.value);
647
- });
648
- const sb = bus.subscribe((event) => {
649
- b.push(event.value);
650
- });
651
- await bus.publish(testEvent(5));
652
- await deliver();
653
- expect(a).toEqual([5]);
654
- expect(b).toEqual([5]);
655
- sa.unsubscribe();
656
- sb.unsubscribe();
657
- });
658
- it("marks subscriptions inactive after unsubscribe and tolerates double unsubscribe", async () => {
659
- const { bus, deliver } = setup();
660
- const seen = [];
661
- const subscription = bus.subscribe((event) => {
662
- seen.push(event.value);
663
- });
664
- await bus.publish(testEvent(1));
665
- await deliver();
666
- expect(seen).toEqual([1]);
667
- expect(subscription.active).toBe(true);
668
- subscription.unsubscribe();
669
- expect(subscription.active).toBe(false);
670
- subscription.unsubscribe();
671
- expect(subscription.active).toBe(false);
672
- });
673
- });
674
- }
675
-
676
- // src/leak/leak_detector.ts
677
- var LeakDetector = class {
678
- checks = [];
679
- register(check) {
680
- this.checks.push(check);
681
- }
682
- findLeaks() {
683
- const leaks = [];
684
- for (const { name, check } of this.checks) {
685
- for (const description of check()) {
686
- leaks.push(`[${name}] ${description}`);
497
+ var TestIocBuilder = class _TestIocBuilder {
498
+ constructor(log) {
499
+ this.log = log;
500
+ Object.freeze(this);
501
+ }
502
+ log;
503
+ /** @internal */
504
+ static create(inputs) {
505
+ return new _TestIocBuilder([]).useAll(inputs);
506
+ }
507
+ /** @internal — read by .use(builderPreset) */
508
+ get writes() {
509
+ return this.log;
510
+ }
511
+ derive(writes) {
512
+ return new _TestIocBuilder([...this.log, ...writes]);
513
+ }
514
+ useAll(inputs) {
515
+ let builder = this;
516
+ for (const input of inputs) builder = builder.use(input);
517
+ return builder;
518
+ }
519
+ /** Apply a reusable composition preset: an ApplicationModule or a builder. */
520
+ use(preset) {
521
+ if (preset instanceof _TestIocBuilder) {
522
+ return this.derive([...preset.writes]);
523
+ }
524
+ return this.derive([{ op: "use", module: preset }]);
525
+ }
526
+ /** Replace the implementation for IoC class tokens in the built environment. */
527
+ classes(config) {
528
+ const writes = [];
529
+ for (const [key, byName, implementation] of configEntries(config)) {
530
+ if (typeof implementation !== "function" || !implementation.prototype) {
531
+ throw new InvalidDescriptorError(
532
+ `.classes() value for "${tokenLabel(key)}" must be a class constructor.`
533
+ );
687
534
  }
535
+ writes.push({ op: "classes", key, byName, implementation });
688
536
  }
689
- return leaks;
537
+ return this.derive(writes);
538
+ }
539
+ /** Replace IoC factory/provider registrations. */
540
+ functions(config) {
541
+ const writes = [];
542
+ for (const [key, byName, factory] of configEntries(config)) {
543
+ if (typeof factory !== "function") {
544
+ throw new InvalidDescriptorError(`.functions() value for "${tokenLabel(key)}" must be a function.`);
545
+ }
546
+ writes.push({ op: "functions", key, byName, factory });
547
+ }
548
+ return this.derive(writes);
690
549
  }
691
- assertNoLeaks() {
692
- const leaks = this.findLeaks();
693
- if (leaks.length > 0) {
694
- throw new Error(`LeakDetector: ${leaks.length} leaked resource(s):
695
- ${leaks.join("\n")}`);
550
+ /** Provide/replace IoC value registrations. */
551
+ values(config) {
552
+ const writes = [];
553
+ for (const [key, byName, value] of configEntries(config)) {
554
+ writes.push({ op: "values", key, byName, value });
555
+ }
556
+ return this.derive(writes);
557
+ }
558
+ /** Install method behavior/observation descriptors on IoC-managed instances. */
559
+ methods(config) {
560
+ const writes = [];
561
+ for (const [key, byName, methodsInput] of configEntries(config)) {
562
+ const methods = /* @__PURE__ */ new Map();
563
+ const entries = methodsInput instanceof Map ? methodsInput.entries() : Object.entries(methodsInput);
564
+ for (const [name, descriptor] of entries) {
565
+ if (typeof descriptor !== "function" && !isDescriptor(descriptor)) {
566
+ throw new InvalidDescriptorError(
567
+ `.methods() entry ${tokenLabel(key)}.${name} must be a test.* descriptor or a raw wrapper function.`
568
+ );
569
+ }
570
+ methods.set(name, descriptor);
571
+ }
572
+ writes.push({ op: "methods", key, byName, methods });
573
+ }
574
+ return this.derive(writes);
575
+ }
576
+ /** Materialize a fresh, isolated real-IoC environment. Non-consuming. */
577
+ async build() {
578
+ const root = (0, import_ioc.createContainer)();
579
+ if (typeof root.setInstanceDecorator !== "function") {
580
+ throw new MissingIocSeamError();
581
+ }
582
+ const knownByName = /* @__PURE__ */ new Map();
583
+ const ambiguousNames = /* @__PURE__ */ new Set();
584
+ const knownLifetimes = /* @__PURE__ */ new Map();
585
+ const note = (token, loadAs) => {
586
+ const name = typeof token === "function" && token.name ? token.name : typeof token === "string" ? token : null;
587
+ if (name !== null) {
588
+ const existing = knownByName.get(name);
589
+ if (existing !== void 0 && existing !== token) ambiguousNames.add(name);
590
+ knownByName.set(name, token);
591
+ }
592
+ if (loadAs !== void 0) knownLifetimes.set(token, loadAs);
593
+ };
594
+ const effective = /* @__PURE__ */ new Map();
595
+ const methodWrites = [];
596
+ const resolveKey = (key, byName, space) => {
597
+ if (!byName) return key;
598
+ if (ambiguousNames.has(key)) {
599
+ throw new AmbiguousNameKeyError(key, space);
600
+ }
601
+ const known = knownByName.get(key);
602
+ if (known !== void 0) return known;
603
+ if (space === "values" || space === "functions") return key;
604
+ throw new UnknownTokenKeyError(key, space, [...knownByName.keys()]);
605
+ };
606
+ for (const write of this.log) {
607
+ switch (write.op) {
608
+ case "use": {
609
+ for (const reg of (0, import_ioc.flattenModule)(write.module)) {
610
+ const loadAs = lifetimeToLoadAs(reg.lifetime);
611
+ note(reg.token, loadAs);
612
+ if (reg.kind === "class") {
613
+ note(reg.implementation, loadAs);
614
+ effective.set(reg.token, {
615
+ space: "class",
616
+ token: reg.token,
617
+ implementation: reg.implementation,
618
+ loadAs
619
+ });
620
+ knownLifetimes.set(reg.token, loadAs);
621
+ knownLifetimes.set(reg.implementation, loadAs);
622
+ } else if (reg.kind === "factory") {
623
+ effective.set(reg.token, {
624
+ space: "factory",
625
+ token: reg.token,
626
+ factory: reg.implementation,
627
+ loadAs,
628
+ deps: [...reg.dependencies]
629
+ });
630
+ } else {
631
+ effective.set(reg.token, { space: "value", token: reg.token, value: reg.implementation });
632
+ knownLifetimes.set(reg.token, import_ioc.LoadAs.Singleton);
633
+ }
634
+ }
635
+ break;
636
+ }
637
+ case "classes": {
638
+ const token = resolveKey(write.key, write.byName, "classes");
639
+ note(write.implementation, void 0);
640
+ if (!write.byName) note(token, void 0);
641
+ effective.set(token, {
642
+ space: "class",
643
+ token,
644
+ implementation: write.implementation,
645
+ // Lifetime priority: the replacement's own @Component scope, then
646
+ // the lifetime the composition already knows for the token, then
647
+ // the TOKEN class's declared @Component scope — a plain stub
648
+ // class replacing a Singleton-scoped production service must not
649
+ // silently degrade to Transient (captive-lifetime validation
650
+ // would reject the production dependents).
651
+ loadAs: componentScope(write.implementation) ?? knownLifetimes.get(token) ?? componentScope(token)
652
+ });
653
+ break;
654
+ }
655
+ case "functions": {
656
+ const token = resolveKey(write.key, write.byName, "functions");
657
+ const prior = effective.get(token);
658
+ effective.set(token, {
659
+ space: "factory",
660
+ token,
661
+ factory: write.factory,
662
+ // preserve configured lifetime unless the scenario overrides it
663
+ loadAs: prior && prior.space === "factory" ? prior.loadAs : knownLifetimes.get(token),
664
+ deps: prior && prior.space === "factory" ? prior.deps : void 0
665
+ });
666
+ note(token, void 0);
667
+ break;
668
+ }
669
+ case "values": {
670
+ const token = resolveKey(write.key, write.byName, "values");
671
+ effective.set(token, { space: "value", token, value: write.value });
672
+ note(token, import_ioc.LoadAs.Singleton);
673
+ break;
674
+ }
675
+ case "methods": {
676
+ if (write.byName && ambiguousNames.has(write.key)) {
677
+ throw new AmbiguousNameKeyError(write.key, "methods");
678
+ }
679
+ const token = write.byName && knownByName.has(write.key) ? knownByName.get(write.key) : write.key;
680
+ methodWrites.push({
681
+ key: token,
682
+ byName: write.byName && !knownByName.has(write.key),
683
+ methods: new Map(write.methods)
684
+ });
685
+ break;
686
+ }
687
+ }
688
+ }
689
+ for (const entry of effective.values()) {
690
+ if (entry.space === "class") {
691
+ this.registerClassBinding(root, entry.token, entry.implementation, entry.loadAs);
692
+ } else if (entry.space === "factory") {
693
+ root.registerFunction(entry.token, entry.factory, {
694
+ loadAs: entry.loadAs,
695
+ param: entry.deps
696
+ });
697
+ } else {
698
+ const value = entry.value;
699
+ root.registerFunction(entry.token, () => value, { loadAs: import_ioc.LoadAs.Singleton });
700
+ }
701
+ }
702
+ const registry = new WatchRegistry();
703
+ const mergedMethods = /* @__PURE__ */ new Map();
704
+ for (const write of methodWrites) {
705
+ const existing = mergedMethods.get(write.key);
706
+ if (existing) {
707
+ for (const [name, descriptor] of write.methods) existing.methods.set(name, descriptor);
708
+ } else {
709
+ mergedMethods.set(write.key, { byName: write.byName, methods: new Map(write.methods) });
710
+ }
711
+ }
712
+ for (const [key, { byName, methods }] of mergedMethods) {
713
+ registry.addEntry({ key, byName, methods });
714
+ }
715
+ root.setInstanceDecorator(createMethodDecorator(registry));
716
+ const env = {
717
+ root,
718
+ get: (token, params) => root.get(token, params),
719
+ instance: (cls, params) => root.instance(cls, params),
720
+ extend: () => root.extend(),
721
+ verify: async () => registry.verify(),
722
+ dispose: () => root.dispose(),
723
+ [ENV_REGISTRY]: registry
724
+ };
725
+ return env;
726
+ }
727
+ /**
728
+ * Register a class binding. When token === implementation this is a plain
729
+ * class registration. Otherwise an alias factory resolves the implementation
730
+ * through real IoC, mirroring the implementation's effective lifetime so
731
+ * lifetime validation (captive-lifetime checks) stays honest.
732
+ */
733
+ registerClassBinding(root, token, implementation, configuredLoadAs) {
734
+ const loadAs = configuredLoadAs ?? componentScope(implementation) ?? import_ioc.LoadAs.Transient;
735
+ root.registerClass(implementation, configuredLoadAs !== void 0 ? { loadAs } : void 0);
736
+ if (token === implementation) return;
737
+ if (loadAs === import_ioc.LoadAs.Singleton) {
738
+ root.registerFunction(token, () => root.get(implementation), {
739
+ loadAs: import_ioc.LoadAs.Singleton
740
+ });
741
+ } else {
742
+ root.registerFunction(token, (scope) => scope.get(implementation), {
743
+ loadAs,
744
+ param: [import_ioc.SCOPED_CONTAINER]
745
+ });
696
746
  }
697
747
  }
698
748
  };
749
+ function testIoc(...inputs) {
750
+ return TestIocBuilder.create(inputs);
751
+ }
699
752
  // Annotate the CommonJS export names for ESM import in node:
700
753
  0 && (module.exports = {
701
- LeakDetector,
702
- ManualClock,
703
- ManualScheduler,
704
- MemoryKeyValueStore,
705
- MemoryObjectStore,
706
- NoopLogSink,
707
- RecordingEventBus,
708
- RecordingLogSink,
709
- RecordingTelemetrySink,
710
- RecordingTraceSink,
711
- ScriptedFetchClient,
712
- ScriptedProcessRunner,
713
- SeededRandomSource,
714
- SequenceIdGenerator,
715
- runClockContract,
716
- runEventBusContract,
717
- runKeyValueStoreContract,
718
- runObjectStoreContract,
719
- testEvent
754
+ AmbiguousNameKeyError,
755
+ CallScriptExhaustedError,
756
+ ENV_REGISTRY,
757
+ ExpectationOverflowError,
758
+ InvalidDescriptorError,
759
+ MethodNotCallableError,
760
+ MissingIocSeamError,
761
+ NonObjectMethodTargetError,
762
+ TestIocBuilder,
763
+ TestingError,
764
+ TokenIdentitySplitError,
765
+ UnknownTokenKeyError,
766
+ UnwatchedInspectionError,
767
+ VerificationError,
768
+ test,
769
+ testIoc
720
770
  });
721
771
  //# sourceMappingURL=index.cjs.map