@entifix/testing-unit 0.14.0 → 0.15.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.
@@ -6,7 +6,6 @@ export * from './flow-engine.contract.js';
6
6
  export * from './idempotency-store.contract.js';
7
7
  export * from './outbox.contract.js';
8
8
  export * from './push-channel.contract.js';
9
- export * from './saga-store.contract.js';
10
9
  export * from './server-push.contract.js';
11
10
  export * from './transaction-ports.contract.js';
12
11
  export * from './unit-of-work.contract.js';
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/contracts/index.ts"],"names":[],"mappings":"AAAA,cAAc,uBAAuB,CAAC;AACtC,cAAc,oCAAoC,CAAC;AACnD,cAAc,iCAAiC,CAAC;AAChD,cAAc,uBAAuB,CAAC;AACtC,cAAc,2BAA2B,CAAC;AAC1C,cAAc,iCAAiC,CAAC;AAChD,cAAc,sBAAsB,CAAC;AACrC,cAAc,4BAA4B,CAAC;AAC3C,cAAc,0BAA0B,CAAC;AACzC,cAAc,2BAA2B,CAAC;AAC1C,cAAc,iCAAiC,CAAC;AAChD,cAAc,4BAA4B,CAAC;AAC3C,cAAc,wBAAwB,CAAC"}
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/contracts/index.ts"],"names":[],"mappings":"AAAA,cAAc,uBAAuB,CAAC;AACtC,cAAc,oCAAoC,CAAC;AACnD,cAAc,iCAAiC,CAAC;AAChD,cAAc,uBAAuB,CAAC;AACtC,cAAc,2BAA2B,CAAC;AAC1C,cAAc,iCAAiC,CAAC;AAChD,cAAc,sBAAsB,CAAC;AACrC,cAAc,4BAA4B,CAAC;AAC3C,cAAc,2BAA2B,CAAC;AAC1C,cAAc,iCAAiC,CAAC;AAChD,cAAc,4BAA4B,CAAC;AAC3C,cAAc,wBAAwB,CAAC"}
@@ -6,7 +6,6 @@ export * from './flow-engine.contract.js';
6
6
  export * from './idempotency-store.contract.js';
7
7
  export * from './outbox.contract.js';
8
8
  export * from './push-channel.contract.js';
9
- export * from './saga-store.contract.js';
10
9
  export * from './server-push.contract.js';
11
10
  export * from './transaction-ports.contract.js';
12
11
  export * from './unit-of-work.contract.js';
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/contracts/index.ts"],"sourcesContent":["export * from './breaker.contract.js';\nexport * from './entity-facet-counter.contract.js';\nexport * from './entity-repository.contract.js';\nexport * from './failure.contract.js';\nexport * from './flow-engine.contract.js';\nexport * from './idempotency-store.contract.js';\nexport * from './outbox.contract.js';\nexport * from './push-channel.contract.js';\nexport * from './saga-store.contract.js';\nexport * from './server-push.contract.js';\nexport * from './transaction-ports.contract.js';\nexport * from './unit-of-work.contract.js';\nexport * from './variants.contract.js';\n"],"names":[],"mappings":"AAAA,cAAc,wBAAwB;AACtC,cAAc,qCAAqC;AACnD,cAAc,kCAAkC;AAChD,cAAc,wBAAwB;AACtC,cAAc,4BAA4B;AAC1C,cAAc,kCAAkC;AAChD,cAAc,uBAAuB;AACrC,cAAc,6BAA6B;AAC3C,cAAc,2BAA2B;AACzC,cAAc,4BAA4B;AAC1C,cAAc,kCAAkC;AAChD,cAAc,6BAA6B;AAC3C,cAAc,yBAAyB"}
1
+ {"version":3,"sources":["../../src/contracts/index.ts"],"sourcesContent":["export * from './breaker.contract.js';\nexport * from './entity-facet-counter.contract.js';\nexport * from './entity-repository.contract.js';\nexport * from './failure.contract.js';\nexport * from './flow-engine.contract.js';\nexport * from './idempotency-store.contract.js';\nexport * from './outbox.contract.js';\nexport * from './push-channel.contract.js';\nexport * from './server-push.contract.js';\nexport * from './transaction-ports.contract.js';\nexport * from './unit-of-work.contract.js';\nexport * from './variants.contract.js';\n"],"names":[],"mappings":"AAAA,cAAc,wBAAwB;AACtC,cAAc,qCAAqC;AACnD,cAAc,kCAAkC;AAChD,cAAc,wBAAwB;AACtC,cAAc,4BAA4B;AAC1C,cAAc,kCAAkC;AAChD,cAAc,uBAAuB;AACrC,cAAc,6BAA6B;AAC3C,cAAc,4BAA4B;AAC1C,cAAc,kCAAkC;AAChD,cAAc,6BAA6B;AAC3C,cAAc,yBAAyB"}
@@ -1,19 +1,5 @@
1
1
  import { type DomainEvent } from '@entifix/core';
2
- import type { EventBus, LockService, SequenceService, TransactionInbox } from '@entifix/transactions';
3
- /**
4
- * What every {@link LockService} must guarantee: exclusivity while held,
5
- * availability after release, and a release that only frees the caller's own
6
- * lock. The last one is why `release` takes a handle rather than a key — a lock
7
- * that lapsed and was re-acquired by someone else must not be freed by the
8
- * previous holder.
9
- */
10
- export declare const describeLockServiceContract: (name: string, makeLockService: () => LockService | Promise<LockService>) => void;
11
- /**
12
- * What every {@link SequenceService} must guarantee: strictly increasing values
13
- * per name, never repeating, with names independent of one another. This is the
14
- * property incremental codes rest on.
15
- */
16
- export declare const describeSequenceServiceContract: (name: string, makeSequenceService: () => SequenceService | Promise<SequenceService>) => void;
2
+ import type { EventBus, TransactionInbox } from '@entifix/transactions';
17
3
  export interface EventBusContractHarness {
18
4
  bus: EventBus;
19
5
  /** Delivers `event` to whatever subscribed, as the broker would. */
@@ -1 +1 @@
1
- {"version":3,"file":"transaction-ports.contract.d.ts","sourceRoot":"","sources":["../../src/contracts/transaction-ports.contract.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,KAAK,WAAW,EAAiB,MAAM,eAAe,CAAC;AAChE,OAAO,KAAK,EACV,QAAQ,EACR,WAAW,EACX,eAAe,EAEf,gBAAgB,EACjB,MAAM,uBAAuB,CAAC;AAqB/B;;;;;;GAMG;AACH,eAAO,MAAM,2BAA2B,GACtC,MAAM,MAAM,EACZ,iBAAiB,MAAM,WAAW,GAAG,OAAO,CAAC,WAAW,CAAC,KACxD,IAqDF,CAAC;AAEF;;;;GAIG;AACH,eAAO,MAAM,+BAA+B,GAC1C,MAAM,MAAM,EACZ,qBAAqB,MAAM,eAAe,GAAG,OAAO,CAAC,eAAe,CAAC,KACpE,IA6BF,CAAC;AAEF,MAAM,WAAW,uBAAuB;IACtC,GAA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,7 @@
1
1
  import { registerEvent } from '@entifix/core';
2
- import { Duration, Effect, Exit, Fiber, Schema } from 'effect';
3
- import { TestClock } from 'effect/testing';
2
+ import { Effect, Schema } from 'effect';
4
3
  import { describe, expect, it } from 'vitest';
5
- /**
6
- * Runs an Effect test on a `TestClock`, so a retry budget measured in seconds
7
- * costs none of the wall clock.
8
- */ const effectIt = {
9
- effect: (name, body)=>it(name, ()=>Effect.runPromise(body().pipe(Effect.provide(TestClock.layer()), Effect.scoped)))
10
- };
11
4
  const run = (effect)=>Effect.runPromise(effect);
12
- /**
13
- * What every {@link LockService} must guarantee: exclusivity while held,
14
- * availability after release, and a release that only frees the caller's own
15
- * lock. The last one is why `release` takes a handle rather than a key — a lock
16
- * that lapsed and was re-acquired by someone else must not be freed by the
17
- * previous holder.
18
- */ export const describeLockServiceContract = (name, makeLockService)=>{
19
- describe(`LockService contract: ${name}`, ()=>{
20
- it('acquires an uncontended key', async ()=>{
21
- const locks = await makeLockService();
22
- const handle = await run(locks.acquire('contract:free'));
23
- expect(handle.key).toBe('contract:free');
24
- expect(handle.token).toBeTruthy();
25
- });
26
- // An implementation may retry before giving up (the Redis adapter waits out
27
- // a bounded budget), so this runs on a TestClock: the assertion is about
28
- // exclusivity, and it should not cost seconds of wall clock to make.
29
- effectIt.effect('refuses a key that is already held', ()=>Effect.gen(function*() {
30
- const locks = yield* Effect.promise(async ()=>makeLockService());
31
- yield* locks.acquire('contract:taken');
32
- const fiber = yield* Effect.forkChild(locks.acquire('contract:taken'));
33
- yield* TestClock.adjust(Duration.minutes(1));
34
- const exit = yield* Fiber.await(fiber);
35
- expect(Exit.isFailure(exit)).toBe(true);
36
- }));
37
- it('makes the key available again after release', async ()=>{
38
- const locks = await makeLockService();
39
- const handle = await run(locks.acquire('contract:cycle'));
40
- await run(locks.release(handle));
41
- const reacquired = await run(locks.acquire('contract:cycle'));
42
- expect(reacquired.key).toBe('contract:cycle');
43
- });
44
- effectIt.effect('ignores a release whose token does not match', ()=>Effect.gen(function*() {
45
- const locks = yield* Effect.promise(async ()=>makeLockService());
46
- const handle = yield* locks.acquire('contract:stolen');
47
- yield* locks.release({
48
- key: handle.key,
49
- token: 'not-mine'
50
- });
51
- // Still held, so a fresh acquisition must fail.
52
- const fiber = yield* Effect.forkChild(locks.acquire('contract:stolen'));
53
- yield* TestClock.adjust(Duration.minutes(1));
54
- const exit = yield* Fiber.await(fiber);
55
- expect(Exit.isFailure(exit)).toBe(true);
56
- }));
57
- });
58
- };
59
- /**
60
- * What every {@link SequenceService} must guarantee: strictly increasing values
61
- * per name, never repeating, with names independent of one another. This is the
62
- * property incremental codes rest on.
63
- */ export const describeSequenceServiceContract = (name, makeSequenceService)=>{
64
- describe(`SequenceService contract: ${name}`, ()=>{
65
- it('starts at 1', async ()=>{
66
- const sequences = await makeSequenceService();
67
- expect(await run(sequences.next('contract:fresh'))).toBe(1);
68
- });
69
- it('never returns the same value twice for a name', async ()=>{
70
- const sequences = await makeSequenceService();
71
- const drawn = [
72
- await run(sequences.next('contract:codes')),
73
- await run(sequences.next('contract:codes')),
74
- await run(sequences.next('contract:codes'))
75
- ];
76
- expect(drawn).toEqual([
77
- 1,
78
- 2,
79
- 3
80
- ]);
81
- expect(new Set(drawn).size).toBe(drawn.length);
82
- });
83
- it('keeps separate names independent', async ()=>{
84
- const sequences = await makeSequenceService();
85
- await run(sequences.next('contract:a'));
86
- await run(sequences.next('contract:a'));
87
- expect(await run(sequences.next('contract:b'))).toBe(1);
88
- });
89
- });
90
- };
91
5
  /** Every subscription in this contract, unless a test says otherwise. */ const ANY_WIDGET_EVENT = 'contract.widget.*';
92
6
  /**
93
7
  * A `work` subscription for `pattern`. The mode and the ceiling are broker
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/contracts/transaction-ports.contract.ts"],"sourcesContent":["import { type DomainEvent, registerEvent } from '@entifix/core';\nimport type {\n EventBus,\n LockService,\n SequenceService,\n Subscription,\n TransactionInbox,\n} from '@entifix/transactions';\nimport { Duration, Effect, Exit, Fiber, Schema } from 'effect';\nimport { TestClock } from 'effect/testing';\nimport { describe, expect, it } from 'vitest';\n\n/**\n * Runs an Effect test on a `TestClock`, so a retry budget measured in seconds\n * costs none of the wall clock.\n */\nconst effectIt = {\n effect: (name: string, body: () => Effect.Effect<unknown, unknown>) =>\n it(name, () =>\n Effect.runPromise(\n body().pipe(Effect.provide(TestClock.layer()), Effect.scoped),\n ),\n ),\n};\n\nconst run = <TValue, TError>(effect: Effect.Effect<TValue, TError>) =>\n Effect.runPromise(effect);\n\n/**\n * What every {@link LockService} must guarantee: exclusivity while held,\n * availability after release, and a release that only frees the caller's own\n * lock. The last one is why `release` takes a handle rather than a key — a lock\n * that lapsed and was re-acquired by someone else must not be freed by the\n * previous holder.\n */\nexport const describeLockServiceContract = (\n name: string,\n makeLockService: () => LockService | Promise<LockService>,\n): void => {\n describe(`LockService contract: ${name}`, () => {\n it('acquires an uncontended key', async () => {\n const locks = await makeLockService();\n\n const handle = await run(locks.acquire('contract:free'));\n\n expect(handle.key).toBe('contract:free');\n expect(handle.token).toBeTruthy();\n });\n\n // An implementation may retry before giving up (the Redis adapter waits out\n // a bounded budget), so this runs on a TestClock: the assertion is about\n // exclusivity, and it should not cost seconds of wall clock to make.\n effectIt.effect('refuses a key that is already held', () =>\n Effect.gen(function* () {\n const locks = yield* Effect.promise(async () => makeLockService());\n yield* locks.acquire('contract:taken');\n\n const fiber = yield* Effect.forkChild(locks.acquire('contract:taken'));\n yield* TestClock.adjust(Duration.minutes(1));\n const exit = yield* Fiber.await(fiber);\n\n expect(Exit.isFailure(exit)).toBe(true);\n }),\n );\n\n it('makes the key available again after release', async () => {\n const locks = await makeLockService();\n const handle = await run(locks.acquire('contract:cycle'));\n\n await run(locks.release(handle));\n const reacquired = await run(locks.acquire('contract:cycle'));\n\n expect(reacquired.key).toBe('contract:cycle');\n });\n\n effectIt.effect('ignores a release whose token does not match', () =>\n Effect.gen(function* () {\n const locks = yield* Effect.promise(async () => makeLockService());\n const handle = yield* locks.acquire('contract:stolen');\n\n yield* locks.release({ key: handle.key, token: 'not-mine' });\n\n // Still held, so a fresh acquisition must fail.\n const fiber = yield* Effect.forkChild(locks.acquire('contract:stolen'));\n yield* TestClock.adjust(Duration.minutes(1));\n const exit = yield* Fiber.await(fiber);\n\n expect(Exit.isFailure(exit)).toBe(true);\n }),\n );\n });\n};\n\n/**\n * What every {@link SequenceService} must guarantee: strictly increasing values\n * per name, never repeating, with names independent of one another. This is the\n * property incremental codes rest on.\n */\nexport const describeSequenceServiceContract = (\n name: string,\n makeSequenceService: () => SequenceService | Promise<SequenceService>,\n): void => {\n describe(`SequenceService contract: ${name}`, () => {\n it('starts at 1', async () => {\n const sequences = await makeSequenceService();\n\n expect(await run(sequences.next('contract:fresh'))).toBe(1);\n });\n\n it('never returns the same value twice for a name', async () => {\n const sequences = await makeSequenceService();\n\n const drawn = [\n await run(sequences.next('contract:codes')),\n await run(sequences.next('contract:codes')),\n await run(sequences.next('contract:codes')),\n ];\n\n expect(drawn).toEqual([1, 2, 3]);\n expect(new Set(drawn).size).toBe(drawn.length);\n });\n\n it('keeps separate names independent', async () => {\n const sequences = await makeSequenceService();\n await run(sequences.next('contract:a'));\n await run(sequences.next('contract:a'));\n\n expect(await run(sequences.next('contract:b'))).toBe(1);\n });\n });\n};\n\nexport interface EventBusContractHarness {\n bus: EventBus;\n /** Delivers `event` to whatever subscribed, as the broker would. */\n deliver(event: DomainEvent): Promise<void>;\n /** Everything the bus published, decoded back into events. */\n published(): DomainEvent[];\n}\n\n/** Every subscription in this contract, unless a test says otherwise. */\nconst ANY_WIDGET_EVENT = 'contract.widget.*';\n\n/**\n * A `work` subscription for `pattern`. The mode and the ceiling are broker\n * facts with no bearing on routing, so a test about routing states them once\n * here rather than repeating them at every call.\n */\nconst on = (pattern: string): Subscription => ({\n slice: 'contract',\n pattern,\n mode: 'work',\n maxAttempts: 5,\n});\n\n/**\n * A handler that records what it is given. Shared by both routing tests so the\n * \"nothing was delivered\" case asserts on the *same* handler the positive case\n * proves works — otherwise it could pass against a handler that was simply\n * never wired up.\n */\nconst collectInto = (sink: DomainEvent[]) => (event: DomainEvent) =>\n Effect.sync(() => {\n sink.push(event);\n });\n\n// A transport encodes and decodes through the registry, so the suite's own\n// event is registered like any other — audience-free, since nothing here\n// delivers to a person.\nregisterEvent(\n 'contract.widget.created',\n Schema.Struct({ entity: Schema.String }),\n { audience: 'none' },\n);\n\nconst anEvent = (\n id: string,\n name = 'contract.widget.created',\n): DomainEvent => ({\n name,\n id,\n source: 'contract-slice',\n at: new Date('2026-01-01T00:00:00.000Z').toISOString(),\n correlationId: id,\n data: { entity: 'contract-widget' },\n});\n\n/**\n * What every {@link EventBus} must guarantee: what goes out comes back\n * unchanged, subscribers receive deliveries, and a subscriber receives only what\n * its pattern matches. The transports differ wildly (an array here, a topic\n * exchange in RabbitMQ) — the observable contract does not.\n */\nexport const describeEventBusContract = (\n name: string,\n makeHarness: () => EventBusContractHarness | Promise<EventBusContractHarness>,\n): void => {\n describe(`EventBus contract: ${name}`, () => {\n it('publishes an event verbatim', async () => {\n const harness = await makeHarness();\n const event = anEvent('tx-1');\n\n await run(harness.bus.publish(event));\n\n expect(harness.published()).toEqual([event]);\n });\n\n it('delivers published events to a subscriber', async () => {\n const harness = await makeHarness();\n const received: DomainEvent[] = [];\n await run(\n harness.bus.subscribe(on(ANY_WIDGET_EVENT), collectInto(received)),\n );\n\n await harness.deliver(anEvent('tx-2'));\n\n expect(received.map(event => event.id)).toEqual(['tx-2']);\n });\n\n // Routing is the transport's job. A bus that hands every subscriber every\n // event lets a consumer pass while receiving traffic it never bound to —\n // which is precisely the fault the fanout exchange had.\n it('delivers nothing to a subscriber whose pattern does not match', async () => {\n const harness = await makeHarness();\n const received: DomainEvent[] = [];\n await run(\n harness.bus.subscribe(on('contract.other.*'), collectInto(received)),\n );\n\n await harness.deliver(anEvent('tx-5'));\n\n expect(received).toEqual([]);\n });\n\n it('preserves publication order', async () => {\n const harness = await makeHarness();\n\n await run(harness.bus.publish(anEvent('tx-3')));\n await run(harness.bus.publish(anEvent('tx-4')));\n\n expect(harness.published().map(event => event.id)).toEqual([\n 'tx-3',\n 'tx-4',\n ]);\n });\n });\n};\n\n/**\n * What every {@link TransactionInbox} must guarantee: a first claim is granted,\n * every repeat of it is refused, and one consumer's claim says nothing about\n * another's.\n *\n * That last one is the property with teeth. Two consumers legitimately process\n * the same event — the saga tracker's fold and the SSE hub both bind\n * `transaction.*` — so an implementation keyed on `eventId` alone passes the\n * first two cases and silently starves every consumer but the first. It looks\n * like exactly-once from inside one consumer, which is why it is asserted here\n * rather than left to each adapter's own spec.\n */\nexport const describeTransactionInboxContract = (\n name: string,\n makeInbox: (consumer: string) => TransactionInbox | Promise<TransactionInbox>,\n): void => {\n describe(`TransactionInbox contract: ${name}`, () => {\n it('grants a first claim', async () => {\n const inbox = await makeInbox('contract.consumer');\n\n expect(await run(inbox.claim('tx-1:completed'))).toBe('claimed');\n });\n\n it('refuses a redelivery of the same event', async () => {\n const inbox = await makeInbox('contract.consumer');\n await run(inbox.claim('tx-2:completed'));\n\n expect(await run(inbox.claim('tx-2:completed'))).toBe('duplicate');\n });\n\n it('refuses every repeat, not only the second', async () => {\n const inbox = await makeInbox('contract.consumer');\n await run(inbox.claim('tx-3:completed'));\n\n expect(await run(inbox.claim('tx-3:completed'))).toBe('duplicate');\n expect(await run(inbox.claim('tx-3:completed'))).toBe('duplicate');\n });\n\n it('claims each step of one transaction separately', async () => {\n // `<transactionId>:<step>`, never the transaction id alone: one\n // transaction emits up to three messages, and keying on the correlation\n // id would make `completed` read as a redelivery of `accepted`.\n const inbox = await makeInbox('contract.consumer');\n\n expect(await run(inbox.claim('tx-4:accepted'))).toBe('claimed');\n expect(await run(inbox.claim('tx-4:completed'))).toBe('claimed');\n });\n\n it('does not let one consumer consume another consumer’s claim', async () => {\n const first = await makeInbox('contract.first');\n const second = await makeInbox('contract.second');\n await run(first.claim('tx-5:completed'));\n\n expect(await run(second.claim('tx-5:completed'))).toBe('claimed');\n });\n });\n};\n"],"names":["registerEvent","Duration","Effect","Exit","Fiber","Schema","TestClock","describe","expect","it","effectIt","effect","name","body","runPromise","pipe","provide","layer","scoped","run","describeLockServiceContract","makeLockService","locks","handle","acquire","key","toBe","token","toBeTruthy","gen","promise","fiber","forkChild","adjust","minutes","exit","await","isFailure","release","reacquired","describeSequenceServiceContract","makeSequenceService","sequences","next","drawn","toEqual","Set","size","length","ANY_WIDGET_EVENT","on","pattern","slice","mode","maxAttempts","collectInto","sink","event","sync","push","Struct","entity","String","audience","anEvent","id","source","at","Date","toISOString","correlationId","data","describeEventBusContract","makeHarness","harness","bus","publish","published","received","subscribe","deliver","map","describeTransactionInboxContract","makeInbox","inbox","claim","first","second"],"mappings":"AAAA,SAA2BA,aAAa,QAAQ,gBAAgB;AAQhE,SAASC,QAAQ,EAAEC,MAAM,EAAEC,IAAI,EAAEC,KAAK,EAAEC,MAAM,QAAQ,SAAS;AAC/D,SAASC,SAAS,QAAQ,iBAAiB;AAC3C,SAASC,QAAQ,EAAEC,MAAM,EAAEC,EAAE,QAAQ,SAAS;AAE9C;;;CAGC,GACD,MAAMC,WAAW;IACfC,QAAQ,CAACC,MAAcC,OACrBJ,GAAGG,MAAM,IACPV,OAAOY,UAAU,CACfD,OAAOE,IAAI,CAACb,OAAOc,OAAO,CAACV,UAAUW,KAAK,KAAKf,OAAOgB,MAAM;AAGpE;AAEA,MAAMC,MAAM,CAAiBR,SAC3BT,OAAOY,UAAU,CAACH;AAEpB;;;;;;CAMC,GACD,OAAO,MAAMS,8BAA8B,CACzCR,MACAS;IAEAd,SAAS,CAAC,sBAAsB,EAAEK,MAAM,EAAE;QACxCH,GAAG,+BAA+B;YAChC,MAAMa,QAAQ,MAAMD;YAEpB,MAAME,SAAS,MAAMJ,IAAIG,MAAME,OAAO,CAAC;YAEvChB,OAAOe,OAAOE,GAAG,EAAEC,IAAI,CAAC;YACxBlB,OAAOe,OAAOI,KAAK,EAAEC,UAAU;QACjC;QAEA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,CAAC;YAEtB7E,OAAO,MAAMW,IAAIoE,OAAOF,KAAK,CAAC,oBAAoB3D,IAAI,CAAC;QACzD;IACF;AACF,EAAE"}
1
+ {"version":3,"sources":["../../src/contracts/transaction-ports.contract.ts"],"sourcesContent":["import { type DomainEvent, registerEvent } from '@entifix/core';\nimport type {\n EventBus,\n Subscription,\n TransactionInbox,\n} from '@entifix/transactions';\nimport { Effect, Schema } from 'effect';\nimport { describe, expect, it } from 'vitest';\n\nconst run = <TValue, TError>(effect: Effect.Effect<TValue, TError>) =>\n Effect.runPromise(effect);\n\nexport interface EventBusContractHarness {\n bus: EventBus;\n /** Delivers `event` to whatever subscribed, as the broker would. */\n deliver(event: DomainEvent): Promise<void>;\n /** Everything the bus published, decoded back into events. */\n published(): DomainEvent[];\n}\n\n/** Every subscription in this contract, unless a test says otherwise. */\nconst ANY_WIDGET_EVENT = 'contract.widget.*';\n\n/**\n * A `work` subscription for `pattern`. The mode and the ceiling are broker\n * facts with no bearing on routing, so a test about routing states them once\n * here rather than repeating them at every call.\n */\nconst on = (pattern: string): Subscription => ({\n slice: 'contract',\n pattern,\n mode: 'work',\n maxAttempts: 5,\n});\n\n/**\n * A handler that records what it is given. Shared by both routing tests so the\n * \"nothing was delivered\" case asserts on the *same* handler the positive case\n * proves works — otherwise it could pass against a handler that was simply\n * never wired up.\n */\nconst collectInto = (sink: DomainEvent[]) => (event: DomainEvent) =>\n Effect.sync(() => {\n sink.push(event);\n });\n\n// A transport encodes and decodes through the registry, so the suite's own\n// event is registered like any other — audience-free, since nothing here\n// delivers to a person.\nregisterEvent(\n 'contract.widget.created',\n Schema.Struct({ entity: Schema.String }),\n { audience: 'none' },\n);\n\nconst anEvent = (\n id: string,\n name = 'contract.widget.created',\n): DomainEvent => ({\n name,\n id,\n source: 'contract-slice',\n at: new Date('2026-01-01T00:00:00.000Z').toISOString(),\n correlationId: id,\n data: { entity: 'contract-widget' },\n});\n\n/**\n * What every {@link EventBus} must guarantee: what goes out comes back\n * unchanged, subscribers receive deliveries, and a subscriber receives only what\n * its pattern matches. The transports differ wildly (an array here, a topic\n * exchange in RabbitMQ) — the observable contract does not.\n */\nexport const describeEventBusContract = (\n name: string,\n makeHarness: () => EventBusContractHarness | Promise<EventBusContractHarness>,\n): void => {\n describe(`EventBus contract: ${name}`, () => {\n it('publishes an event verbatim', async () => {\n const harness = await makeHarness();\n const event = anEvent('tx-1');\n\n await run(harness.bus.publish(event));\n\n expect(harness.published()).toEqual([event]);\n });\n\n it('delivers published events to a subscriber', async () => {\n const harness = await makeHarness();\n const received: DomainEvent[] = [];\n await run(\n harness.bus.subscribe(on(ANY_WIDGET_EVENT), collectInto(received)),\n );\n\n await harness.deliver(anEvent('tx-2'));\n\n expect(received.map(event => event.id)).toEqual(['tx-2']);\n });\n\n // Routing is the transport's job. A bus that hands every subscriber every\n // event lets a consumer pass while receiving traffic it never bound to —\n // which is precisely the fault the fanout exchange had.\n it('delivers nothing to a subscriber whose pattern does not match', async () => {\n const harness = await makeHarness();\n const received: DomainEvent[] = [];\n await run(\n harness.bus.subscribe(on('contract.other.*'), collectInto(received)),\n );\n\n await harness.deliver(anEvent('tx-5'));\n\n expect(received).toEqual([]);\n });\n\n it('preserves publication order', async () => {\n const harness = await makeHarness();\n\n await run(harness.bus.publish(anEvent('tx-3')));\n await run(harness.bus.publish(anEvent('tx-4')));\n\n expect(harness.published().map(event => event.id)).toEqual([\n 'tx-3',\n 'tx-4',\n ]);\n });\n });\n};\n\n/**\n * What every {@link TransactionInbox} must guarantee: a first claim is granted,\n * every repeat of it is refused, and one consumer's claim says nothing about\n * another's.\n *\n * That last one is the property with teeth. Two consumers legitimately process\n * the same event — the saga tracker's fold and the SSE hub both bind\n * `transaction.*` — so an implementation keyed on `eventId` alone passes the\n * first two cases and silently starves every consumer but the first. It looks\n * like exactly-once from inside one consumer, which is why it is asserted here\n * rather than left to each adapter's own spec.\n */\nexport const describeTransactionInboxContract = (\n name: string,\n makeInbox: (consumer: string) => TransactionInbox | Promise<TransactionInbox>,\n): void => {\n describe(`TransactionInbox contract: ${name}`, () => {\n it('grants a first claim', async () => {\n const inbox = await makeInbox('contract.consumer');\n\n expect(await run(inbox.claim('tx-1:completed'))).toBe('claimed');\n });\n\n it('refuses a redelivery of the same event', async () => {\n const inbox = await makeInbox('contract.consumer');\n await run(inbox.claim('tx-2:completed'));\n\n expect(await run(inbox.claim('tx-2:completed'))).toBe('duplicate');\n });\n\n it('refuses every repeat, not only the second', async () => {\n const inbox = await makeInbox('contract.consumer');\n await run(inbox.claim('tx-3:completed'));\n\n expect(await run(inbox.claim('tx-3:completed'))).toBe('duplicate');\n expect(await run(inbox.claim('tx-3:completed'))).toBe('duplicate');\n });\n\n it('claims each step of one transaction separately', async () => {\n // `<transactionId>:<step>`, never the transaction id alone: one\n // transaction emits up to three messages, and keying on the correlation\n // id would make `completed` read as a redelivery of `accepted`.\n const inbox = await makeInbox('contract.consumer');\n\n expect(await run(inbox.claim('tx-4:accepted'))).toBe('claimed');\n expect(await run(inbox.claim('tx-4:completed'))).toBe('claimed');\n });\n\n it('does not let one consumer consume another consumer’s claim', async () => {\n const first = await makeInbox('contract.first');\n const second = await makeInbox('contract.second');\n await run(first.claim('tx-5:completed'));\n\n expect(await run(second.claim('tx-5:completed'))).toBe('claimed');\n });\n });\n};\n"],"names":["registerEvent","Effect","Schema","describe","expect","it","run","effect","runPromise","ANY_WIDGET_EVENT","on","pattern","slice","mode","maxAttempts","collectInto","sink","event","sync","push","Struct","entity","String","audience","anEvent","id","name","source","at","Date","toISOString","correlationId","data","describeEventBusContract","makeHarness","harness","bus","publish","published","toEqual","received","subscribe","deliver","map","describeTransactionInboxContract","makeInbox","inbox","claim","toBe","first","second"],"mappings":"AAAA,SAA2BA,aAAa,QAAQ,gBAAgB;AAMhE,SAASC,MAAM,EAAEC,MAAM,QAAQ,SAAS;AACxC,SAASC,QAAQ,EAAEC,MAAM,EAAEC,EAAE,QAAQ,SAAS;AAE9C,MAAMC,MAAM,CAAiBC,SAC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,MAAME,IAAIwC,MAAMC,KAAK,CAAC,oBAAoBC,IAAI,CAAC;QACxD;QAEA3C,GAAG,kDAAkD;YACnD,gEAAgE;YAChE,wEAAwE;YACxE,gEAAgE;YAChE,MAAMyC,QAAQ,MAAMD,UAAU;YAE9BzC,OAAO,MAAME,IAAIwC,MAAMC,KAAK,CAAC,mBAAmBC,IAAI,CAAC;YACrD5C,OAAO,MAAME,IAAIwC,MAAMC,KAAK,CAAC,oBAAoBC,IAAI,CAAC;QACxD;QAEA3C,GAAG,8DAA8D;YAC/D,MAAM4C,QAAQ,MAAMJ,UAAU;YAC9B,MAAMK,SAAS,MAAML,UAAU;YAC/B,MAAMvC,IAAI2C,MAAMF,KAAK,CAAC;YAEtB3C,OAAO,MAAME,IAAI4C,OAAOH,KAAK,CAAC,oBAAoBC,IAAI,CAAC;QACzD;IACF;AACF,EAAE"}
@@ -1,36 +1,6 @@
1
1
  import { type DomainEvent, type EntifixFailure } from '@entifix/core';
2
- import type { EventBus, LockService, SagaInstance, SagaStore, SequenceService, TransactionInbox } from '@entifix/transactions';
2
+ import type { EventBus, TransactionInbox } from '@entifix/transactions';
3
3
  import { Effect } from 'effect';
4
- export interface InMemoryLockService extends LockService {
5
- /** Keys currently held, in acquisition order. */
6
- readonly held: string[];
7
- /** Every acquire/release in the order it happened. */
8
- readonly log: ReadonlyArray<{
9
- action: 'acquire' | 'release';
10
- key: string;
11
- }>;
12
- /**
13
- * Marks `key` as already taken by someone else, so the next `acquire` fails
14
- * with {@link Contention} — the 409 path of the transaction facade.
15
- */
16
- contendOn(key: string): void;
17
- }
18
- /**
19
- * In-memory {@link LockService}. Acquisition is immediate and uncontended
20
- * unless {@link InMemoryLockService.contendOn} says otherwise, and `release`
21
- * only frees a lock whose token matches — the compare-and-delete rule the Redis
22
- * adapter enforces with a Lua script.
23
- */
24
- export declare const makeInMemoryLockService: () => InMemoryLockService;
25
- export interface InMemorySequenceService extends SequenceService {
26
- /** The current value of every sequence drawn from so far. */
27
- readonly values: Readonly<Record<string, number>>;
28
- }
29
- /**
30
- * In-memory {@link SequenceService} — a plain counter per name. Atomicity is
31
- * what the Redis `INCR` adapter buys; single-threaded JS gives it for free here.
32
- */
33
- export declare const makeInMemorySequenceService: () => InMemorySequenceService;
34
4
  export interface RecordingEventBus extends EventBus {
35
5
  /** Every event published, in order. */
36
6
  readonly published: DomainEvent[];
@@ -67,15 +37,4 @@ export declare const makeInMemoryInboxes: () => {
67
37
  eventId: string;
68
38
  }[];
69
39
  };
70
- export interface InMemorySagaStore extends SagaStore {
71
- /** Every instance, as stored — for a spec to assert on state, not calls. */
72
- readonly instances: readonly SagaInstance[];
73
- }
74
- /**
75
- * In-memory {@link SagaStore}, with the Mongo adapter's semantics: `start`
76
- * never overwrites, outcomes append, and a resume claim only takes an
77
- * unfinished instance whose `updatedAt` is past the deadline — counting the
78
- * attempt and re-stamping it, so the next sweep does not find it again.
79
- */
80
- export declare const makeInMemorySagaStore: () => InMemorySagaStore;
81
40
  //# sourceMappingURL=transaction-ports.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"transaction-ports.d.ts","sourceRoot":"","sources":["../../src/doubles/transaction-ports.ts"],"names":[],"mappings":"AAAA,OAAO,EAEL,KAAK,WAAW,EAChB,KAAK,cAAc,EAGpB,MAAM,eAAe,CAAC;AACvB,OAAO,KAAK,EACV,QAAQ,EAER,WAAW,EACX,YAAY,EACZ,SAAS,EACT,eAAe,EACf,gBAAgB,EACjB,MAAM,uBAAuB,CAAC;AAC/B,OAAO,EAAE,MAAM,EAAE,MAAM,QAAQ,CAAC;AAEhC,MAAM,WAAW,mBAAoB,SAAQ,WAAW;IACtD,iDAAiD;IACjD,QAAQ,CAAC,IAAI,EAAE,MAAM,EAAE,CAAC;IACxB,sDAAsD;IACtD,QAAQ,CAAC,GAAG,EAAE,aAAa,CAAC;QAAE,MAAM,EAAE,SAAS,GAAG,SAAS,CAAC;QAAC,GAAG,EAAE,MAAM,CAAA;KAAE,CAAC,CAAC;IAC5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Q,EAAE,gBAAgB,EAAE,MAAM,uBAAuB,CAAC;AACxE,OAAO,EAAE,MAAM,EAAE,MAAM,QAAQ,CAAC;AAEhC,MAAM,WAAW,iBAAkB,SAAQ,QAAQ;IACjD,uCAAuC;IACvC,QAAQ,CAAC,SAAS,EAAE,WAAW,EAAE,CAAC;IAClC;;;;;OAKG;IACH,OAAO,CAAC,KAAK,EAAE,WAAW,GAAG,MAAM,CAAC,MAAM,CAAC,IAAI,EAAE,cAAc,CAAC,CAAC;IACjE,wEAAwE;IACxE,eAAe,IAAI,IAAI,CAAC;CACzB;AAED;;;;GAIG;AACH,eAAO,MAAM,qBAAqB,QAAO,iBAwCxC,CAAC;AAEF;;;;;;;;GAQG;AACH,eAAO,MAAM,mBAAmB;IAI5B,0DAA0D;oBAC1C,MAAM,KAAG,gBAAgB;qBAS3B,SAAS;QAAE,QAAQ,EAAE,MAAM,CAAC;QAAC,OAAO,EAAE,MAAM,CAAA;KAAE,EAAE;CAOjE,CAAC"}
@@ -1,71 +1,5 @@
1
- import { _ as _extends } from "@swc/helpers/_/_extends";
2
- import { Contention, matchesEventPattern, Unavailable } from '@entifix/core';
1
+ import { matchesEventPattern, Unavailable } from '@entifix/core';
3
2
  import { Effect } from 'effect';
4
- /**
5
- * In-memory {@link LockService}. Acquisition is immediate and uncontended
6
- * unless {@link InMemoryLockService.contendOn} says otherwise, and `release`
7
- * only frees a lock whose token matches — the compare-and-delete rule the Redis
8
- * adapter enforces with a Lua script.
9
- */ export const makeInMemoryLockService = ()=>{
10
- const tokens = new Map();
11
- const contended = new Set();
12
- const log = [];
13
- let counter = 0;
14
- return {
15
- acquire: (key)=>Effect.suspend(()=>{
16
- if (contended.has(key) || tokens.has(key)) {
17
- return Effect.fail(new Contention());
18
- }
19
- const token = `token-${counter += 1}`;
20
- tokens.set(key, token);
21
- log.push({
22
- action: 'acquire',
23
- key
24
- });
25
- return Effect.succeed({
26
- key,
27
- token
28
- });
29
- }),
30
- release: (handle)=>Effect.sync(()=>{
31
- if (tokens.get(handle.key) === handle.token) {
32
- tokens.delete(handle.key);
33
- log.push({
34
- action: 'release',
35
- key: handle.key
36
- });
37
- }
38
- }),
39
- get held () {
40
- return [
41
- ...tokens.keys()
42
- ];
43
- },
44
- get log () {
45
- return log;
46
- },
47
- contendOn: (key)=>{
48
- contended.add(key);
49
- }
50
- };
51
- };
52
- /**
53
- * In-memory {@link SequenceService} — a plain counter per name. Atomicity is
54
- * what the Redis `INCR` adapter buys; single-threaded JS gives it for free here.
55
- */ export const makeInMemorySequenceService = ()=>{
56
- const sequences = new Map();
57
- return {
58
- next: (name)=>Effect.sync(()=>{
59
- var _sequences_get;
60
- const next = ((_sequences_get = sequences.get(name)) != null ? _sequences_get : 0) + 1;
61
- sequences.set(name, next);
62
- return next;
63
- }),
64
- get values () {
65
- return Object.fromEntries(sequences);
66
- }
67
- };
68
- };
69
3
  /**
70
4
  * In-memory {@link EventBus} that records what was published rather than
71
5
  * asserting on it. Prefer reading `bus.published` in a test over a mock's call
@@ -140,72 +74,5 @@ import { Effect } from 'effect';
140
74
  }
141
75
  };
142
76
  };
143
- /**
144
- * In-memory {@link SagaStore}, with the Mongo adapter's semantics: `start`
145
- * never overwrites, outcomes append, and a resume claim only takes an
146
- * unfinished instance whose `updatedAt` is past the deadline — counting the
147
- * attempt and re-stamping it, so the next sweep does not find it again.
148
- */ export const makeInMemorySagaStore = ()=>{
149
- const instances = new Map();
150
- const stamp = ()=>new Date().toISOString();
151
- const unfinished = (entry)=>entry.state === 'RUNNING' || entry.state === 'COMPENSATING';
152
- const pastDeadline = (entry, olderThanMs)=>entry.updatedAt < new Date(Date.now() - olderThanMs).toISOString();
153
- const update = (sagaId, change)=>Effect.sync(()=>{
154
- const current = instances.get(sagaId);
155
- if (current !== undefined) {
156
- instances.set(sagaId, _extends({}, change(current), {
157
- updatedAt: stamp()
158
- }));
159
- }
160
- });
161
- return {
162
- start: (started)=>Effect.sync(()=>{
163
- if (!instances.has(started.sagaId)) {
164
- instances.set(started.sagaId, _extends({}, started, {
165
- updatedAt: stamp()
166
- }));
167
- }
168
- }),
169
- beginStep: (sagaId, stepIndex)=>update(sagaId, (entry)=>_extends({}, entry, {
170
- stepIndex
171
- })),
172
- recordOutcome: (sagaId, outcome)=>update(sagaId, (entry)=>_extends({}, entry, {
173
- outcomes: [
174
- ...entry.outcomes,
175
- outcome
176
- ]
177
- })),
178
- settle: (sagaId, state, error)=>update(sagaId, (entry)=>_extends({}, entry, {
179
- state,
180
- error
181
- })),
182
- markCompensated: (sagaId, stepId)=>update(sagaId, (entry)=>_extends({}, entry, {
183
- outcomes: entry.outcomes.map((outcome)=>outcome.stepId === stepId ? _extends({}, outcome, {
184
- compensated: true
185
- }) : outcome)
186
- })),
187
- get: (sagaId)=>Effect.sync(()=>instances.get(sagaId)),
188
- findStale: (olderThanMs)=>Effect.sync(()=>[
189
- ...instances.values()
190
- ].filter((entry)=>unfinished(entry) && pastDeadline(entry, olderThanMs))),
191
- claimForResume: (sagaId, olderThanMs)=>Effect.sync(()=>{
192
- const current = instances.get(sagaId);
193
- if (current === undefined || !unfinished(current) || !pastDeadline(current, olderThanMs)) {
194
- return undefined;
195
- }
196
- const claimed = _extends({}, current, {
197
- resumeAttempts: current.resumeAttempts + 1,
198
- updatedAt: stamp()
199
- });
200
- instances.set(sagaId, claimed);
201
- return claimed;
202
- }),
203
- get instances () {
204
- return [
205
- ...instances.values()
206
- ];
207
- }
208
- };
209
- };
210
77
 
211
78
  //# sourceMappingURL=transaction-ports.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/doubles/transaction-ports.ts"],"sourcesContent":["import {\n Contention,\n type DomainEvent,\n type EntifixFailure,\n matchesEventPattern,\n Unavailable,\n} from '@entifix/core';\nimport type {\n EventBus,\n LockHandle,\n LockService,\n SagaInstance,\n SagaStore,\n SequenceService,\n TransactionInbox,\n} from '@entifix/transactions';\nimport { Effect } from 'effect';\n\nexport interface InMemoryLockService extends LockService {\n /** Keys currently held, in acquisition order. */\n readonly held: string[];\n /** Every acquire/release in the order it happened. */\n readonly log: ReadonlyArray<{ action: 'acquire' | 'release'; key: string }>;\n /**\n * Marks `key` as already taken by someone else, so the next `acquire` fails\n * with {@link Contention} — the 409 path of the transaction facade.\n */\n contendOn(key: string): void;\n}\n\n/**\n * In-memory {@link LockService}. Acquisition is immediate and uncontended\n * unless {@link InMemoryLockService.contendOn} says otherwise, and `release`\n * only frees a lock whose token matches — the compare-and-delete rule the Redis\n * adapter enforces with a Lua script.\n */\nexport const makeInMemoryLockService = (): InMemoryLockService => {\n const tokens = new Map<string, string>();\n const contended = new Set<string>();\n const log: Array<{ action: 'acquire' | 'release'; key: string }> = [];\n let counter = 0;\n\n return {\n acquire: key =>\n Effect.suspend(() => {\n if (contended.has(key) || tokens.has(key)) {\n return Effect.fail(new Contention());\n }\n const token = `token-${(counter += 1)}`;\n tokens.set(key, token);\n log.push({ action: 'acquire', key });\n return Effect.succeed({ key, token });\n }),\n release: (handle: LockHandle) =>\n Effect.sync(() => {\n if (tokens.get(handle.key) === handle.token) {\n tokens.delete(handle.key);\n log.push({ action: 'release', key: handle.key });\n }\n }),\n get held() {\n return [...tokens.keys()];\n },\n get log() {\n return log;\n },\n contendOn: key => {\n contended.add(key);\n },\n };\n};\n\nexport interface InMemorySequenceService extends SequenceService {\n /** The current value of every sequence drawn from so far. */\n readonly values: Readonly<Record<string, number>>;\n}\n\n/**\n * In-memory {@link SequenceService} — a plain counter per name. Atomicity is\n * what the Redis `INCR` adapter buys; single-threaded JS gives it for free here.\n */\nexport const makeInMemorySequenceService = (): InMemorySequenceService => {\n const sequences = new Map<string, number>();\n\n return {\n next: name =>\n Effect.sync(() => {\n const next = (sequences.get(name) ?? 0) + 1;\n sequences.set(name, next);\n return next;\n }),\n get values() {\n return Object.fromEntries(sequences);\n },\n };\n};\n\nexport interface RecordingEventBus extends EventBus {\n /** Every event published, in order. */\n readonly published: DomainEvent[];\n /**\n * Pushes an event to the subscribers whose pattern matches it, as a topic\n * exchange would. Deliberately not \"to all subscribers\": routing is the\n * broker's job in production, so a double that ignored it would let a\n * consumer pass its tests while receiving traffic it never bound to.\n */\n deliver(event: DomainEvent): Effect.Effect<void, EntifixFailure>;\n /** Makes the next `publish` fail, for the broker-unavailable branch. */\n failNextPublish(): void;\n}\n\n/**\n * In-memory {@link EventBus} that records what was published rather than\n * asserting on it. Prefer reading `bus.published` in a test over a mock's call\n * assertions: the expectation then reads as state, not as a spy protocol.\n */\nexport const makeRecordingEventBus = (): RecordingEventBus => {\n const published: DomainEvent[] = [];\n const handlers: Array<{\n pattern: string;\n handle: (event: DomainEvent) => Effect.Effect<void, EntifixFailure>;\n }> = [];\n let failNext = false;\n\n return {\n publish: event =>\n Effect.suspend(() => {\n if (failNext) {\n failNext = false;\n return Effect.fail(new Unavailable({ dependency: 'bus' }));\n }\n published.push(event);\n return Effect.void;\n }),\n subscribe: (subscription, handle) =>\n Effect.sync(() => {\n // Only the pattern is retained: queue durability and the delivery\n // ceiling are broker facts with no in-memory analogue, and faking them\n // would assert against the double rather than against a broker.\n handlers.push({ pattern: subscription.pattern, handle });\n }),\n deliver: event =>\n Effect.forEach(\n handlers.filter(({ pattern }) =>\n matchesEventPattern(pattern, event.name),\n ),\n ({ handle }) => handle(event),\n { discard: true },\n ),\n get published() {\n return published;\n },\n failNextPublish: () => {\n failNext = true;\n },\n };\n};\n\n/**\n * An in-memory {@link TransactionInbox}, one per consumer, over a shared claim\n * set.\n *\n * Sharing the set across the inboxes one factory hands out is what makes the\n * contract's \"one consumer cannot consume another's claim\" case a real\n * assertion, rather than one the double satisfies by only ever having seen a\n * single consumer.\n */\nexport const makeInMemoryInboxes = () => {\n const claimed = new Set<string>();\n\n return {\n /** An inbox for `consumer`, over the shared claim set. */\n for: (consumer: string): TransactionInbox => ({\n claim: eventId =>\n Effect.sync(() => {\n const key = JSON.stringify([consumer, eventId]);\n if (claimed.has(key)) return 'duplicate' as const;\n claimed.add(key);\n return 'claimed' as const;\n }),\n }),\n get claims(): readonly { consumer: string; eventId: string }[] {\n return [...claimed].map(key => {\n const [consumer, eventId] = JSON.parse(key) as [string, string];\n return { consumer, eventId };\n });\n },\n };\n};\n\nexport interface InMemorySagaStore extends SagaStore {\n /** Every instance, as stored — for a spec to assert on state, not calls. */\n readonly instances: readonly SagaInstance[];\n}\n\n/**\n * In-memory {@link SagaStore}, with the Mongo adapter's semantics: `start`\n * never overwrites, outcomes append, and a resume claim only takes an\n * unfinished instance whose `updatedAt` is past the deadline — counting the\n * attempt and re-stamping it, so the next sweep does not find it again.\n */\nexport const makeInMemorySagaStore = (): InMemorySagaStore => {\n const instances = new Map<string, SagaInstance>();\n const stamp = () => new Date().toISOString();\n const unfinished = (entry: SagaInstance) =>\n entry.state === 'RUNNING' || entry.state === 'COMPENSATING';\n const pastDeadline = (entry: SagaInstance, olderThanMs: number) =>\n entry.updatedAt < new Date(Date.now() - olderThanMs).toISOString();\n const update = (\n sagaId: string,\n change: (entry: SagaInstance) => SagaInstance,\n ) =>\n Effect.sync(() => {\n const current = instances.get(sagaId);\n if (current !== undefined) {\n instances.set(sagaId, { ...change(current), updatedAt: stamp() });\n }\n });\n\n return {\n start: started =>\n Effect.sync(() => {\n if (!instances.has(started.sagaId)) {\n instances.set(started.sagaId, { ...started, updatedAt: stamp() });\n }\n }),\n beginStep: (sagaId, stepIndex) =>\n update(sagaId, entry => ({ ...entry, stepIndex })),\n recordOutcome: (sagaId, outcome) =>\n update(sagaId, entry => ({\n ...entry,\n outcomes: [...entry.outcomes, outcome],\n })),\n settle: (sagaId, state, error) =>\n update(sagaId, entry => ({ ...entry, state, error })),\n markCompensated: (sagaId, stepId) =>\n update(sagaId, entry => ({\n ...entry,\n outcomes: entry.outcomes.map(outcome =>\n outcome.stepId === stepId\n ? { ...outcome, compensated: true }\n : outcome,\n ),\n })),\n get: sagaId => Effect.sync(() => instances.get(sagaId)),\n findStale: olderThanMs =>\n Effect.sync(() =>\n [...instances.values()].filter(\n entry => unfinished(entry) && pastDeadline(entry, olderThanMs),\n ),\n ),\n claimForResume: (sagaId, olderThanMs) =>\n Effect.sync(() => {\n const current = instances.get(sagaId);\n if (\n current === undefined ||\n !unfinished(current) ||\n !pastDeadline(current, olderThanMs)\n ) {\n return undefined;\n }\n const claimed = {\n ...current,\n resumeAttempts: current.resumeAttempts + 1,\n updatedAt: stamp(),\n };\n instances.set(sagaId, claimed);\n return claimed;\n }),\n get instances() {\n return [...instances.values()];\n },\n };\n};\n"],"names":["Contention","matchesEventPattern","Unavailable","Effect","makeInMemoryLockService","tokens","Map","contended","Set","log","counter","acquire","key","suspend","has","fail","token","set","push","action","succeed","release","handle","sync","get","delete","held","keys","contendOn","add","makeInMemorySequenceService","sequences","next","name","values","Object","fromEntries","makeRecordingEventBus","published","handlers","failNext","publish","event","dependency","void","subscribe","subscription","pattern","deliver","forEach","filter","discard","failNextPublish","makeInMemoryInboxes","claimed","for","consumer","claim","eventId","JSON","stringify","claims","map","parse","makeInMemorySagaStore","instances","stamp","Date","toISOString","unfinished","entry","state","pastDeadline","olderThanMs","updatedAt","now","update","sagaId","change","current","undefined","start","started","beginStep","stepIndex","recordOutcome","outcome","outcomes","settle","error","markCompensated","stepId","compensated","findStale","claimForResume","resumeAttempts"],"mappings":";AAAA,SACEA,UAAU,EAGVC,mBAAmB,EACnBC,WAAW,QACN,gBAAgB;AAUvB,SAASC,MAAM,QAAQ,SAAS;AAchC;;;;;CAKC,GACD,OAAO,MAAMC,0BAA0B;IACrC,MAAMC,SAAS,IAAIC;IACnB,MAAMC,YAAY,IAAIC;IACtB,MAAMC,MAA6D,EAAE;IACrE,IAAIC,UAAU;IAEd,OAAO;QACLC,SAASC,CAAAA,MACPT,OAAOU,OAAO,CAAC;gBACb,IAAIN,UAAUO,GAAG,CAACF,QAAQP,OAAOS,GAAG,CAACF,MAAM;oBACzC,OAAOT,OAAOY,IAAI,CAAC,IAAIf;gBACzB;gBACA,MAAMgB,QAAQ,CAAC,MAAM,EAAGN,WAAW,GAAI;gBACvCL,OAA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BoB,CAAAA,QAASD,WAAWC,UAAUE,aAAaF,OAAOG;QAGxDqB,gBAAgB,CAACjB,QAAQJ,cACvBtE,OAAOoB,IAAI,CAAC;gBACV,MAAMwD,UAAUd,UAAUzC,GAAG,CAACqD;gBAC9B,IACEE,YAAYC,aACZ,CAACX,WAAWU,YACZ,CAACP,aAAaO,SAASN,cACvB;oBACA,OAAOO;gBACT;gBACA,MAAM1B,UAAU,aACXyB;oBACHgB,gBAAgBhB,QAAQgB,cAAc,GAAG;oBACzCrB,WAAWR;;gBAEbD,UAAUhD,GAAG,CAAC4D,QAAQvB;gBACtB,OAAOA;YACT;QACF,IAAIW;YACF,OAAO;mBAAIA,UAAU/B,MAAM;aAAG;QAChC;IACF;AACF,EAAE"}
1
+ {"version":3,"sources":["../../src/doubles/transaction-ports.ts"],"sourcesContent":["import {\n type DomainEvent,\n type EntifixFailure,\n matchesEventPattern,\n Unavailable,\n} from '@entifix/core';\nimport type { EventBus, TransactionInbox } from '@entifix/transactions';\nimport { Effect } from 'effect';\n\nexport interface RecordingEventBus extends EventBus {\n /** Every event published, in order. */\n readonly published: DomainEvent[];\n /**\n * Pushes an event to the subscribers whose pattern matches it, as a topic\n * exchange would. Deliberately not \"to all subscribers\": routing is the\n * broker's job in production, so a double that ignored it would let a\n * consumer pass its tests while receiving traffic it never bound to.\n */\n deliver(event: DomainEvent): Effect.Effect<void, EntifixFailure>;\n /** Makes the next `publish` fail, for the broker-unavailable branch. */\n failNextPublish(): void;\n}\n\n/**\n * In-memory {@link EventBus} that records what was published rather than\n * asserting on it. Prefer reading `bus.published` in a test over a mock's call\n * assertions: the expectation then reads as state, not as a spy protocol.\n */\nexport const makeRecordingEventBus = (): RecordingEventBus => {\n const published: DomainEvent[] = [];\n const handlers: Array<{\n pattern: string;\n handle: (event: DomainEvent) => Effect.Effect<void, EntifixFailure>;\n }> = [];\n let failNext = false;\n\n return {\n publish: event =>\n Effect.suspend(() => {\n if (failNext) {\n failNext = false;\n return Effect.fail(new Unavailable({ dependency: 'bus' }));\n }\n published.push(event);\n return Effect.void;\n }),\n subscribe: (subscription, handle) =>\n Effect.sync(() => {\n // Only the pattern is retained: queue durability and the delivery\n // ceiling are broker facts with no in-memory analogue, and faking them\n // would assert against the double rather than against a broker.\n handlers.push({ pattern: subscription.pattern, handle });\n }),\n deliver: event =>\n Effect.forEach(\n handlers.filter(({ pattern }) =>\n matchesEventPattern(pattern, event.name),\n ),\n ({ handle }) => handle(event),\n { discard: true },\n ),\n get published() {\n return published;\n },\n failNextPublish: () => {\n failNext = true;\n },\n };\n};\n\n/**\n * An in-memory {@link TransactionInbox}, one per consumer, over a shared claim\n * set.\n *\n * Sharing the set across the inboxes one factory hands out is what makes the\n * contract's \"one consumer cannot consume another's claim\" case a real\n * assertion, rather than one the double satisfies by only ever having seen a\n * single consumer.\n */\nexport const makeInMemoryInboxes = () => {\n const claimed = new Set<string>();\n\n return {\n /** An inbox for `consumer`, over the shared claim set. */\n for: (consumer: string): TransactionInbox => ({\n claim: eventId =>\n Effect.sync(() => {\n const key = JSON.stringify([consumer, eventId]);\n if (claimed.has(key)) return 'duplicate' as const;\n claimed.add(key);\n return 'claimed' as const;\n }),\n }),\n get claims(): readonly { consumer: string; eventId: string }[] {\n return [...claimed].map(key => {\n const [consumer, eventId] = JSON.parse(key) as [string, string];\n return { consumer, eventId };\n });\n },\n };\n};\n"],"names":["matchesEventPattern","Unavailable","Effect","makeRecordingEventBus","published","handlers","failNext","publish","event","suspend","fail","dependency","push","void","subscribe","subscription","handle","sync","pattern","deliver","forEach","filter","name","discard","failNextPublish","makeInMemoryInboxes","claimed","Set","for","consumer","claim","eventId","key","JSON","stringify","has","add","claims","map","parse"],"mappings":"AAAA,SAGEA,mBAAmB,EACnBC,WAAW,QACN,gBAAgB;AAEvB,SAASC,MAAM,QAAQ,SAAS;AAgBhC;;;;CAIC,GACD,OAAO,MAAMC,wBAAwB;IACnC,MAAMC,YAA2B,EAAE;IACnC,MAAMC,WAGD,EAAE;IACP,I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ACF,EAAE"}
@@ -1,11 +1,9 @@
1
1
  /**
2
- * A fake of the ioredis client, not of the lock/sequence ports.
2
+ * A fake of the ioredis client, not of the stores built on it.
3
3
  *
4
- * `makeRedisLockService`, `makeRedisSequenceService`, the session store, the
5
- * one-time token store and the attempt limiter all run unchanged on top of it,
6
- * so their real behaviour — `SET NX PX`, the bounded retry loop, the
7
- * compare-and-delete release script, `INCR`, `GETDEL` — is what the specs
8
- * exercise.
4
+ * The session store, the one-time token store and the attempt limiter run
5
+ * unchanged on top of it, so their real behaviour — `SET NX PX`, the
6
+ * compare-and-delete script, `INCR`, `GETDEL` — is what the specs exercise.
9
7
  *
10
8
  * Time does not pass: `EX`/`EXPIRE` are remembered so `TTL` can report them, but
11
9
  * nothing here expires on its own. Adapters that must be tested across an expiry
@@ -1 +1 @@
1
- {"version":3,"file":"fake-redis.d.ts","sourceRoot":"","sources":["../../src/drivers/fake-redis.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;GAYG;AAEH,MAAM,WAAW,SAAS;IACxB,4EAA4E;IAC5E,IAAI,CAAC,GAAG,EAAE,MAAM,GAAG,MAAM,GAAG,SAAS,CAAC;IACtC,gFAAgF;IAChF,IAAI,CAAC,GAAG,EAAE,MAAM,EAAE,KAAK,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;IACxC,wCAAwC;IACxC,IAAI,CAAC,GAAG,EAAE,MAAM,GAAG,IAAI,CAAC;IACxB,0DAA0D;IAC1D,QAAQ,CAAC,KAAK,EAAE,OAAO,GAAG,IAAI,CAAC;IAC/B,sCAAsC;IACtC,QAAQ,CAAC,QAAQ,EAAE,aAAa,CAAC;QAAE,OAAO,EAAE,MAAM,CAAC;QAAC,IAAI,EAAE,OAAO,EAAE,CAAA;KAAE,CAAC,CAAC;IACvE,+DAA+D;IAC/D,QAAQ,CAAC,KAAK,EAAE,OAAO,CAAC;CACzB;AAED,eAAO,MAAM,aAAa,QAAO,SAiJhC,CAAC"}
1
+ {"version":3,"file":"fake-redis.d.ts","sourceRoot":"","sources":["../../src/drivers/fake-redis.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;GAUG;AAEH,MAAM,WAAW,SAAS;IACxB,4EAA4E;IAC5E,IAAI,CAAC,GAAG,EAAE,MAAM,GAAG,MAAM,GAAG,SAAS,CAAC;IACtC,gFAAgF;IAChF,IAAI,CAAC,GAAG,EAAE,MAAM,EAAE,KAAK,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;IACxC,wCAAwC;IACxC,IAAI,CAAC,GAAG,EAAE,MAAM,GAAG,IAAI,CAAC;IACxB,0DAA0D;IAC1D,QAAQ,CAAC,KAAK,EAAE,OAAO,GAAG,IAAI,CAAC;IAC/B,sCAAsC;IACtC,QAAQ,CAAC,QAAQ,EAAE,aAAa,CAAC;QAAE,OAAO,EAAE,MAAM,CAAC;QAAC,IAAI,EAAE,OAAO,EAAE,CAAA;KAAE,CAAC,CAAC;IACvE,+DAA+D;IAC/D,QAAQ,CAAC,KAAK,EAAE,OAAO,CAAC;CACzB;AAED,eAAO,MAAM,aAAa,QAAO,SAiJhC,CAAC"}
@@ -1,11 +1,9 @@
1
1
  /**
2
- * A fake of the ioredis client, not of the lock/sequence ports.
2
+ * A fake of the ioredis client, not of the stores built on it.
3
3
  *
4
- * `makeRedisLockService`, `makeRedisSequenceService`, the session store, the
5
- * one-time token store and the attempt limiter all run unchanged on top of it,
6
- * so their real behaviour — `SET NX PX`, the bounded retry loop, the
7
- * compare-and-delete release script, `INCR`, `GETDEL` — is what the specs
8
- * exercise.
4
+ * The session store, the one-time token store and the attempt limiter run
5
+ * unchanged on top of it, so their real behaviour — `SET NX PX`, the
6
+ * compare-and-delete script, `INCR`, `GETDEL` — is what the specs exercise.
9
7
  *
10
8
  * Time does not pass: `EX`/`EXPIRE` are remembered so `TTL` can report them, but
11
9
  * nothing here expires on its own. Adapters that must be tested across an expiry
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/drivers/fake-redis.ts"],"sourcesContent":["/**\n * A fake of the ioredis client, not of the lock/sequence ports.\n *\n * `makeRedisLockService`, `makeRedisSequenceService`, the session store, the\n * one-time token store and the attempt limiter all run unchanged on top of it,\n * so their real behaviour — `SET NX PX`, the bounded retry loop, the\n * compare-and-delete release script, `INCR`, `GETDEL` — is what the specs\n * exercise.\n *\n * Time does not pass: `EX`/`EXPIRE` are remembered so `TTL` can report them, but\n * nothing here expires on its own. Adapters that must be tested across an expiry\n * drive the clock themselves.\n */\n\nexport interface FakeRedis {\n /** Current keys and values, for assertions about what the adapter wrote. */\n read(key: string): string | undefined;\n /** Pre-set a key so the next `SET NX` finds it taken — i.e. lock contention. */\n hold(key: string, token?: string): void;\n /** Drop a key, releasing contention. */\n free(key: string): void;\n /** Makes every subsequent command reject with `error`. */\n failWith(error: unknown): void;\n /** Every command issued, in order. */\n readonly commands: ReadonlyArray<{ command: string; args: unknown[] }>;\n /** The object to pass where an ioredis `Redis` is expected. */\n readonly redis: unknown;\n}\n\nexport const makeFakeRedis = (): FakeRedis => {\n const store = new Map<string, string>();\n const sets = new Map<string, Set<string>>();\n /** Seconds last requested per key, so `TTL` can answer something plausible. */\n const ttls = new Map<string, number>();\n const commands: Array<{ command: string; args: unknown[] }> = [];\n let failure: unknown;\n\n const record = <TValue>(\n command: string,\n args: unknown[],\n produce: () => TValue,\n ): Promise<TValue> => {\n commands.push({ command, args });\n return failure !== undefined\n ? Promise.reject(failure)\n : Promise.resolve(produce());\n };\n\n const redis = {\n /**\n * Supports the one form the lock adapter issues:\n * `set(key, token, 'PX', ttl, 'NX')`. `NX` is what makes acquisition\n * atomic, so honouring it is the whole point of this fake.\n */\n set: (key: string, value: string, ...rest: unknown[]) =>\n record('set', [key, value, ...rest], () => {\n const nx = rest.some(\n argument => String(argument).toUpperCase() === 'NX',\n );\n if (nx && store.has(key)) return null;\n store.set(key, value);\n // Remember an `EX <seconds>` so a later `TTL` is not a lie.\n const exIndex = rest.findIndex(\n argument => String(argument).toUpperCase() === 'EX',\n );\n if (exIndex !== -1) ttls.set(key, Number(rest[exIndex + 1]));\n return 'OK';\n }),\n\n get: (key: string) => record('get', [key], () => store.get(key) ?? null),\n\n /**\n * `TTL`: seconds remaining, `-2` when the key is gone and `-1` when it has\n * no expiry. Time does not actually pass here, so this reports whatever TTL\n * was last set — enough for adapters that branch on \"is it still alive\".\n */\n ttl: (key: string) =>\n record('ttl', [key], () => {\n if (!store.has(key) && !sets.has(key)) return -2;\n return ttls.get(key) ?? -1;\n }),\n\n /** `GETDEL`: read and remove atomically — a single-use token redemption. */\n getdel: (key: string) =>\n record('getdel', [key], () => {\n const value = store.get(key) ?? null;\n store.delete(key);\n ttls.delete(key);\n return value;\n }),\n\n /** `SCARD`: how many members a set holds. */\n scard: (key: string) =>\n record('scard', [key], () => sets.get(key)?.size ?? 0),\n\n del: (key: string) =>\n record('del', [key], () => {\n // A key can hold a string or a set; drop whichever is there so the\n // session store's `del` frees both record keys and index-set keys.\n const hadString = store.delete(key);\n const hadSet = sets.delete(key);\n return hadString || hadSet ? 1 : 0;\n }),\n\n /** `SADD`: add a member to a set, returning how many were newly added (0/1). */\n sadd: (key: string, member: string) =>\n record('sadd', [key, member], () => {\n const set = sets.get(key) ?? new Set<string>();\n const isNew = !set.has(member);\n set.add(member);\n sets.set(key, set);\n return isNew ? 1 : 0;\n }),\n\n /** `SREM`: remove a member, returning how many were removed (0/1). */\n srem: (key: string, member: string) =>\n record('srem', [key, member], () =>\n sets.get(key)?.delete(member) ? 1 : 0,\n ),\n\n /** `SMEMBERS`: the set's members, or an empty array for a missing set. */\n smembers: (key: string) =>\n record('smembers', [key], () => [...(sets.get(key) ?? [])]),\n\n /**\n * `EXPIRE`: TTL is not enforced by this fake, so it only reports whether the\n * key exists (1) or not (0) — which is the branch the session adapter reads\n * to detect a vanished session on `touch`.\n */\n expire: (key: string, seconds: number) =>\n record('expire', [key, seconds], () => {\n if (!store.has(key) && !sets.has(key)) return 0;\n ttls.set(key, seconds);\n return 1;\n }),\n\n incr: (key: string) =>\n record('incr', [key], () => {\n const next = Number(store.get(key) ?? '0') + 1;\n store.set(key, String(next));\n return next;\n }),\n\n /**\n * The release script is a compare-and-delete: free the key only when it\n * still holds our own token. Rather than interpreting Lua, this reproduces\n * that one script's semantics.\n */\n eval: (_script: string, _numKeys: number, key: string, token: string) =>\n record('eval', [key, token], () => {\n if (store.get(key) !== token) return 0;\n store.delete(key);\n return 1;\n }),\n\n quit: () => record('quit', [], () => 'OK'),\n };\n\n return {\n read: key => store.get(key),\n hold: (key, token = 'someone-else') => {\n store.set(key, token);\n },\n free: key => {\n store.delete(key);\n },\n failWith: error => {\n failure = error;\n },\n get commands() {\n return commands;\n },\n redis,\n };\n};\n"],"names":["makeFakeRedis","store","Map","sets","ttls","commands","failure","record","command","args","produce","push","undefined","Promise","reject","resolve","redis","set","key","value","rest","nx","some","argument","String","toUpperCase","has","exIndex","findIndex","Number","get","ttl","getdel","delete","scard","size","del","hadString","hadSet","sadd","member","Set","isNew","add","srem","smembers","expire","seconds","incr","next","eval","_script","_numKeys","token","quit","read","hold","free","failWith","error"],"mappings":"AAAA;;;;;;;;;;;;CAYC,GAiBD,OAAO,MAAMA,gBAAgB;IAC3B,MAAMC,QAAQ,IAAIC;IAClB,MAAMC,OAAO,IAAID;IACjB,6EAA6E,GAC7E,MAAME,OAAO,IAAIF;IACjB,MAAMG,WAAwD,EAAE;IAChE,IAAIC;IAEJ,MAAMC,SAAS,CACbC,SACAC,MACAC;QAEAL,SAASM,IAAI,CAAC;YAAEH;YAASC;QAAK;QAC9B,OAAOH,YAAYM,YACfC,QAAQC,MAAM,CAACR,WACfO,QAAQE,OAAO,CAACL;IACtB;IAEA,MAAMM,QAAQ;QACZ;;;;KAIC,GACDC,KAAK,CAACC,KAAaC,OAAe,GAAGC,OACnCb,OAAO,OAAO;gBAACW;gBAAKC;mBAAUC;aAAK,EAAE;gBACnC,MAAMC,KAAKD,KAAKE,IAAI,CAClBC,CAAAA,WAAYC,OAAOD,UAAUE,WAAW,OAAO;gBAEj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,QACrD9C,OAAO,QAAQ;gBAACW;gBAAKmC;aAAM,EAAE;gBAC3B,IAAIpD,MAAM6B,GAAG,CAACZ,SAASmC,OAAO,OAAO;gBACrCpD,MAAMgC,MAAM,CAACf;gBACb,OAAO;YACT;QAEFoC,MAAM,IAAM/C,OAAO,QAAQ,EAAE,EAAE,IAAM;IACvC;IAEA,OAAO;QACLgD,MAAMrC,CAAAA,MAAOjB,MAAM6B,GAAG,CAACZ;QACvBsC,MAAM,CAACtC,KAAKmC,QAAQ,cAAc;YAChCpD,MAAMgB,GAAG,CAACC,KAAKmC;QACjB;QACAI,MAAMvC,CAAAA;YACJjB,MAAMgC,MAAM,CAACf;QACf;QACAwC,UAAUC,CAAAA;YACRrD,UAAUqD;QACZ;QACA,IAAItD;YACF,OAAOA;QACT;QACAW;IACF;AACF,EAAE"}
1
+ {"version":3,"sources":["../../src/drivers/fake-redis.ts"],"sourcesContent":["/**\n * A fake of the ioredis client, not of the stores built on it.\n *\n * The session store, the one-time token store and the attempt limiter run\n * unchanged on top of it, so their real behaviour — `SET NX PX`, the\n * compare-and-delete script, `INCR`, `GETDEL` — is what the specs exercise.\n *\n * Time does not pass: `EX`/`EXPIRE` are remembered so `TTL` can report them, but\n * nothing here expires on its own. Adapters that must be tested across an expiry\n * drive the clock themselves.\n */\n\nexport interface FakeRedis {\n /** Current keys and values, for assertions about what the adapter wrote. */\n read(key: string): string | undefined;\n /** Pre-set a key so the next `SET NX` finds it taken — i.e. lock contention. */\n hold(key: string, token?: string): void;\n /** Drop a key, releasing contention. */\n free(key: string): void;\n /** Makes every subsequent command reject with `error`. */\n failWith(error: unknown): void;\n /** Every command issued, in order. */\n readonly commands: ReadonlyArray<{ command: string; args: unknown[] }>;\n /** The object to pass where an ioredis `Redis` is expected. */\n readonly redis: unknown;\n}\n\nexport const makeFakeRedis = (): FakeRedis => {\n const store = new Map<string, string>();\n const sets = new Map<string, Set<string>>();\n /** Seconds last requested per key, so `TTL` can answer something plausible. */\n const ttls = new Map<string, number>();\n const commands: Array<{ command: string; args: unknown[] }> = [];\n let failure: unknown;\n\n const record = <TValue>(\n command: string,\n args: unknown[],\n produce: () => TValue,\n ): Promise<TValue> => {\n commands.push({ command, args });\n return failure !== undefined\n ? Promise.reject(failure)\n : Promise.resolve(produce());\n };\n\n const redis = {\n /**\n * Supports the one form the lock adapter issues:\n * `set(key, token, 'PX', ttl, 'NX')`. `NX` is what makes acquisition\n * atomic, so honouring it is the whole point of this fake.\n */\n set: (key: string, value: string, ...rest: unknown[]) =>\n record('set', [key, value, ...rest], () => {\n const nx = rest.some(\n argument => String(argument).toUpperCase() === 'NX',\n );\n if (nx && store.has(key)) return null;\n store.set(key, value);\n // Remember an `EX <seconds>` so a later `TTL` is not a lie.\n const exIndex = rest.findIndex(\n argument => String(argument).toUpperCase() === 'EX',\n );\n if (exIndex !== -1) ttls.set(key, Number(rest[exIndex + 1]));\n return 'OK';\n }),\n\n get: (key: string) => record('get', [key], () => store.get(key) ?? null),\n\n /**\n * `TTL`: seconds remaining, `-2` when the key is gone and `-1` when it has\n * no expiry. Time does not actually pass here, so this reports whatever TTL\n * was last set — enough for adapters that branch on \"is it still alive\".\n */\n ttl: (key: string) =>\n record('ttl', [key], () => {\n if (!store.has(key) && !sets.has(key)) return -2;\n return ttls.get(key) ?? -1;\n }),\n\n /** `GETDEL`: read and remove atomically — a single-use token redemption. */\n getdel: (key: string) =>\n record('getdel', [key], () => {\n const value = store.get(key) ?? null;\n store.delete(key);\n ttls.delete(key);\n return value;\n }),\n\n /** `SCARD`: how many members a set holds. */\n scard: (key: string) =>\n record('scard', [key], () => sets.get(key)?.size ?? 0),\n\n del: (key: string) =>\n record('del', [key], () => {\n // A key can hold a string or a set; drop whichever is there so the\n // session store's `del` frees both record keys and index-set keys.\n const hadString = store.delete(key);\n const hadSet = sets.delete(key);\n return hadString || hadSet ? 1 : 0;\n }),\n\n /** `SADD`: add a member to a set, returning how many were newly added (0/1). */\n sadd: (key: string, member: string) =>\n record('sadd', [key, member], () => {\n const set = sets.get(key) ?? new Set<string>();\n const isNew = !set.has(member);\n set.add(member);\n sets.set(key, set);\n return isNew ? 1 : 0;\n }),\n\n /** `SREM`: remove a member, returning how many were removed (0/1). */\n srem: (key: string, member: string) =>\n record('srem', [key, member], () =>\n sets.get(key)?.delete(member) ? 1 : 0,\n ),\n\n /** `SMEMBERS`: the set's members, or an empty array for a missing set. */\n smembers: (key: string) =>\n record('smembers', [key], () => [...(sets.get(key) ?? [])]),\n\n /**\n * `EXPIRE`: TTL is not enforced by this fake, so it only reports whether the\n * key exists (1) or not (0) — which is the branch the session adapter reads\n * to detect a vanished session on `touch`.\n */\n expire: (key: string, seconds: number) =>\n record('expire', [key, seconds], () => {\n if (!store.has(key) && !sets.has(key)) return 0;\n ttls.set(key, seconds);\n return 1;\n }),\n\n incr: (key: string) =>\n record('incr', [key], () => {\n const next = Number(store.get(key) ?? '0') + 1;\n store.set(key, String(next));\n return next;\n }),\n\n /**\n * The release script is a compare-and-delete: free the key only when it\n * still holds our own token. Rather than interpreting Lua, this reproduces\n * that one script's semantics.\n */\n eval: (_script: string, _numKeys: number, key: string, token: string) =>\n record('eval', [key, token], () => {\n if (store.get(key) !== token) return 0;\n store.delete(key);\n return 1;\n }),\n\n quit: () => record('quit', [], () => 'OK'),\n };\n\n return {\n read: key => store.get(key),\n hold: (key, token = 'someone-else') => {\n store.set(key, token);\n },\n free: key => {\n store.delete(key);\n },\n failWith: error => {\n failure = error;\n },\n get commands() {\n return commands;\n },\n redis,\n };\n};\n"],"names":["makeFakeRedis","store","Map","sets","ttls","commands","failure","record","command","args","produce","push","undefined","Promise","reject","resolve","redis","set","key","value","rest","nx","some","argument","String","toUpperCase","has","exIndex","findIndex","Number","get","ttl","getdel","delete","scard","size","del","hadString","hadSet","sadd","member","Set","isNew","add","srem","smembers","expire","seconds","incr","next","eval","_script","_numKeys","token","quit","read","hold","free","failWith","error"],"mappings":"AAAA;;;;;;;;;;CAUC,GAiBD,OAAO,MAAMA,gB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;;QAE5D;;;;KAIC,GACD2C,QAAQ,CAAC5B,KAAa6B,UACpBxC,OAAO,UAAU;gBAACW;gBAAK6B;aAAQ,EAAE;gBAC/B,IAAI,CAAC9C,MAAMyB,GAAG,CAACR,QAAQ,CAACf,KAAKuB,GAAG,CAACR,MAAM,OAAO;gBAC9Cd,KAAKa,GAAG,CAACC,KAAK6B;gBACd,OAAO;YACT;QAEFC,MAAM,CAAC9B,MACLX,OAAO,QAAQ;gBAACW;aAAI,EAAE;oBACAjB;gBAApB,MAAMgD,OAAOpB,QAAO5B,aAAAA,MAAM6B,GAAG,CAACZ,gBAAVjB,aAAkB,OAAO;gBAC7CA,MAAMgB,GAAG,CAACC,KAAKM,OAAOyB;gBACtB,OAAOA;YACT;QAEF;;;;KAIC,GACDC,MAAM,CAACC,SAAiBC,UAAkBlC,KAAamC,QACrD9C,OAAO,QAAQ;gBAACW;gBAAKmC;aAAM,EAAE;gBAC3B,IAAIpD,MAAM6B,GAAG,CAACZ,SAASmC,OAAO,OAAO;gBACrCpD,MAAMgC,MAAM,CAACf;gBACb,OAAO;YACT;QAEFoC,MAAM,IAAM/C,OAAO,QAAQ,EAAE,EAAE,IAAM;IACvC;IAEA,OAAO;QACLgD,MAAMrC,CAAAA,MAAOjB,MAAM6B,GAAG,CAACZ;QACvBsC,MAAM,CAACtC,KAAKmC,QAAQ,cAAc;YAChCpD,MAAMgB,GAAG,CAACC,KAAKmC;QACjB;QACAI,MAAMvC,CAAAA;YACJjB,MAAMgC,MAAM,CAACf;QACf;QACAwC,UAAUC,CAAAA;YACRrD,UAAUqD;QACZ;QACA,IAAItD;YACF,OAAOA;QACT;QACAW;IACF;AACF,EAAE"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@entifix/testing-unit",
3
- "version": "0.14.0",
3
+ "version": "0.15.0",
4
4
  "description": "Test doubles for entifix: in-memory ports, driver fakes for Mongo, Redis, RabbitMQ and SQL, MSW handlers and port contract suites.",
5
5
  "license": "MIT",
6
6
  "repository": {
@@ -72,9 +72,9 @@
72
72
  },
73
73
  "dependencies": {
74
74
  "@swc/helpers": "0.5.23",
75
- "@entifix/core": "0.14.0",
76
- "@entifix/business": "0.14.0",
77
- "@entifix/transactions": "0.14.0"
75
+ "@entifix/business": "0.15.0",
76
+ "@entifix/transactions": "0.15.0",
77
+ "@entifix/core": "0.15.0"
78
78
  },
79
79
  "peerDependencies": {
80
80
  "@testing-library/react": "*",
@@ -82,7 +82,7 @@
82
82
  "msw": ">=3",
83
83
  "react": "*",
84
84
  "vitest": "*",
85
- "@entifix/react-controls": "0.14.0"
85
+ "@entifix/react-controls": "0.15.0"
86
86
  },
87
87
  "peerDependenciesMeta": {
88
88
  "@entifix/react-controls": {
@@ -1,13 +0,0 @@
1
- import type { SagaStore } from '@entifix/transactions';
2
- /**
3
- * What every {@link SagaStore} must guarantee to the saga engine: an instance
4
- * that can be started twice without being overwritten, outcomes that append in
5
- * arrival order, a compensation flag that lands on one step, and a resume claim
6
- * that only ever takes an unfinished instance past its deadline.
7
- *
8
- * Deliberately not asserted: two concurrent claims producing one winner. That
9
- * is a property of the conditional write against a real server, and a contract
10
- * run in one process cannot interleave the two.
11
- */
12
- export declare const describeSagaStoreContract: (name: string, makeStore: () => SagaStore | Promise<SagaStore>) => void;
13
- //# sourceMappingURL=saga-store.contract.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"saga-store.contract.d.ts","sourceRoot":"","sources":["../../src/contracts/saga-store.contract.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAGV,SAAS,EACV,MAAM,uBAAuB,CAAC;AA6B/B;;;;;;;;;GASG;AACH,eAAO,MAAM,yBAAyB,GACpC,MAAM,MAAM,EACZ,WAAW,MAAM,SAAS,GAAG,OAAO,CAAC,SAAS,CAAC,KAC9C,IAiHF,CAAC"}
@@ -1,142 +0,0 @@
1
- import { _ as _extends } from "@swc/helpers/_/_extends";
2
- import { Effect } from 'effect';
3
- import { describe, expect, it } from 'vitest';
4
- const run = (effect)=>Effect.runPromise(effect);
5
- /** A threshold every instance is older than, so no spec waits on a clock. */ const ANY_AGE = -60000;
6
- /** A threshold no instance just written is older than. */ const AN_HOUR = 3600000;
7
- const instance = (sagaId, over = {})=>_extends({
8
- sagaId,
9
- definition: 'contract-flow',
10
- state: 'RUNNING',
11
- stepIndex: 0,
12
- outcomes: [],
13
- inputs: {},
14
- resumeAttempts: 0,
15
- createdAt: new Date().toISOString()
16
- }, over);
17
- const outcome = (stepId)=>({
18
- stepId,
19
- calls: []
20
- });
21
- /**
22
- * What every {@link SagaStore} must guarantee to the saga engine: an instance
23
- * that can be started twice without being overwritten, outcomes that append in
24
- * arrival order, a compensation flag that lands on one step, and a resume claim
25
- * that only ever takes an unfinished instance past its deadline.
26
- *
27
- * Deliberately not asserted: two concurrent claims producing one winner. That
28
- * is a property of the conditional write against a real server, and a contract
29
- * run in one process cannot interleave the two.
30
- */ export const describeSagaStoreContract = (name, makeStore)=>{
31
- describe(`SagaStore contract: ${name}`, ()=>{
32
- it('starts an instance and reads it back, stamped', async ()=>{
33
- const store = await makeStore();
34
- await run(store.start(instance('s-1')));
35
- const read = await run(store.get('s-1'));
36
- expect(read).toMatchObject({
37
- sagaId: 's-1',
38
- state: 'RUNNING'
39
- });
40
- expect(read == null ? void 0 : read.updatedAt).toEqual(expect.any(String));
41
- });
42
- it('answers undefined for an instance it never started', async ()=>{
43
- const store = await makeStore();
44
- expect(await run(store.get('absent'))).toBeUndefined();
45
- });
46
- // A coordinator restarted mid-flight re-enters `start` with an id it
47
- // already wrote; what it had recorded must survive that.
48
- it('does not overwrite an instance started twice', async ()=>{
49
- const store = await makeStore();
50
- await run(store.start(instance('s-1')));
51
- await run(store.recordOutcome('s-1', outcome('reserve')));
52
- await run(store.start(instance('s-1', {
53
- stepIndex: 9
54
- })));
55
- const read = await run(store.get('s-1'));
56
- expect(read == null ? void 0 : read.stepIndex).toBe(0);
57
- expect(read == null ? void 0 : read.outcomes.map((entry)=>entry.stepId)).toEqual([
58
- 'reserve'
59
- ]);
60
- });
61
- it('moves the step index and appends outcomes in arrival order', async ()=>{
62
- const store = await makeStore();
63
- await run(store.start(instance('s-1')));
64
- await run(store.beginStep('s-1', 1));
65
- await run(store.recordOutcome('s-1', outcome('reserve')));
66
- await run(store.recordOutcome('s-1', outcome('charge')));
67
- const read = await run(store.get('s-1'));
68
- expect(read == null ? void 0 : read.stepIndex).toBe(1);
69
- expect(read == null ? void 0 : read.outcomes.map((entry)=>entry.stepId)).toEqual([
70
- 'reserve',
71
- 'charge'
72
- ]);
73
- });
74
- it('settles with a state and the error that caused it', async ()=>{
75
- const store = await makeStore();
76
- await run(store.start(instance('s-1')));
77
- await run(store.settle('s-1', 'COMPENSATED', 'charge refused'));
78
- expect(await run(store.get('s-1'))).toMatchObject({
79
- state: 'COMPENSATED',
80
- error: 'charge refused'
81
- });
82
- });
83
- it('flags only the named step compensated', async ()=>{
84
- const store = await makeStore();
85
- await run(store.start(instance('s-1')));
86
- await run(store.recordOutcome('s-1', outcome('reserve')));
87
- await run(store.recordOutcome('s-1', outcome('charge')));
88
- await run(store.markCompensated('s-1', 'reserve'));
89
- const read = await run(store.get('s-1'));
90
- expect(read == null ? void 0 : read.outcomes).toEqual([
91
- expect.objectContaining({
92
- stepId: 'reserve',
93
- compensated: true
94
- }),
95
- expect.not.objectContaining({
96
- compensated: true
97
- })
98
- ]);
99
- });
100
- // `COMPENSATING` is stuck too: a coordinator that died while unwinding is
101
- // the state that leaves holds in place.
102
- it('finds unfinished instances past the deadline, and nothing else', async ()=>{
103
- const store = await makeStore();
104
- await run(store.start(instance('running')));
105
- await run(store.start(instance('unwinding', {
106
- state: 'COMPENSATING'
107
- })));
108
- await run(store.start(instance('done', {
109
- state: 'COMPLETED'
110
- })));
111
- const stale = await run(store.findStale(ANY_AGE));
112
- expect(stale.map((entry)=>entry.sagaId).sort()).toEqual([
113
- 'running',
114
- 'unwinding'
115
- ]);
116
- expect(await run(store.findStale(AN_HOUR))).toEqual([]);
117
- });
118
- it('claims a stale instance by counting the attempt', async ()=>{
119
- var _this;
120
- const store = await makeStore();
121
- await run(store.start(instance('s-1')));
122
- const claimed = await run(store.claimForResume('s-1', ANY_AGE));
123
- expect(claimed).toMatchObject({
124
- sagaId: 's-1',
125
- resumeAttempts: 1
126
- });
127
- expect((_this = await run(store.get('s-1'))) == null ? void 0 : _this.resumeAttempts).toBe(1);
128
- });
129
- it('refuses to claim a settled or a fresh instance', async ()=>{
130
- const store = await makeStore();
131
- await run(store.start(instance('done', {
132
- state: 'COMPLETED'
133
- })));
134
- await run(store.start(instance('fresh')));
135
- expect(await run(store.claimForResume('done', ANY_AGE))).toBeUndefined();
136
- expect(await run(store.claimForResume('fresh', AN_HOUR))).toBeUndefined();
137
- expect(await run(store.claimForResume('absent', ANY_AGE))).toBeUndefined();
138
- });
139
- });
140
- };
141
-
142
- //# sourceMappingURL=saga-store.contract.js.map
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../../src/contracts/saga-store.contract.ts"],"sourcesContent":["import type {\n SagaInstance,\n SagaStepOutcome,\n SagaStore,\n} from '@entifix/transactions';\nimport { Effect } from 'effect';\nimport { describe, expect, it } from 'vitest';\n\nconst run = <TValue, TError>(effect: Effect.Effect<TValue, TError>) =>\n Effect.runPromise(effect);\n\n/** A threshold every instance is older than, so no spec waits on a clock. */\nconst ANY_AGE = -60_000;\n/** A threshold no instance just written is older than. */\nconst AN_HOUR = 3_600_000;\n\nconst instance = (\n sagaId: string,\n over: Partial<Omit<SagaInstance, 'updatedAt'>> = {},\n): Omit<SagaInstance, 'updatedAt'> => ({\n sagaId,\n definition: 'contract-flow',\n state: 'RUNNING',\n stepIndex: 0,\n outcomes: [],\n inputs: {},\n resumeAttempts: 0,\n createdAt: new Date().toISOString(),\n ...over,\n});\n\nconst outcome = (stepId: string): SagaStepOutcome => ({ stepId, calls: [] });\n\n/**\n * What every {@link SagaStore} must guarantee to the saga engine: an instance\n * that can be started twice without being overwritten, outcomes that append in\n * arrival order, a compensation flag that lands on one step, and a resume claim\n * that only ever takes an unfinished instance past its deadline.\n *\n * Deliberately not asserted: two concurrent claims producing one winner. That\n * is a property of the conditional write against a real server, and a contract\n * run in one process cannot interleave the two.\n */\nexport const describeSagaStoreContract = (\n name: string,\n makeStore: () => SagaStore | Promise<SagaStore>,\n): void => {\n describe(`SagaStore contract: ${name}`, () => {\n it('starts an instance and reads it back, stamped', async () => {\n const store = await makeStore();\n\n await run(store.start(instance('s-1')));\n const read = await run(store.get('s-1'));\n\n expect(read).toMatchObject({ sagaId: 's-1', state: 'RUNNING' });\n expect(read?.updatedAt).toEqual(expect.any(String));\n });\n\n it('answers undefined for an instance it never started', async () => {\n const store = await makeStore();\n\n expect(await run(store.get('absent'))).toBeUndefined();\n });\n\n // A coordinator restarted mid-flight re-enters `start` with an id it\n // already wrote; what it had recorded must survive that.\n it('does not overwrite an instance started twice', async () => {\n const store = await makeStore();\n await run(store.start(instance('s-1')));\n await run(store.recordOutcome('s-1', outcome('reserve')));\n\n await run(store.start(instance('s-1', { stepIndex: 9 })));\n\n const read = await run(store.get('s-1'));\n expect(read?.stepIndex).toBe(0);\n expect(read?.outcomes.map(entry => entry.stepId)).toEqual(['reserve']);\n });\n\n it('moves the step index and appends outcomes in arrival order', async () => {\n const store = await makeStore();\n await run(store.start(instance('s-1')));\n\n await run(store.beginStep('s-1', 1));\n await run(store.recordOutcome('s-1', outcome('reserve')));\n await run(store.recordOutcome('s-1', outcome('charge')));\n\n const read = await run(store.get('s-1'));\n expect(read?.stepIndex).toBe(1);\n expect(read?.outcomes.map(entry => entry.stepId)).toEqual([\n 'reserve',\n 'charge',\n ]);\n });\n\n it('settles with a state and the error that caused it', async () => {\n const store = await makeStore();\n await run(store.start(instance('s-1')));\n\n await run(store.settle('s-1', 'COMPENSATED', 'charge refused'));\n\n expect(await run(store.get('s-1'))).toMatchObject({\n state: 'COMPENSATED',\n error: 'charge refused',\n });\n });\n\n it('flags only the named step compensated', async () => {\n const store = await makeStore();\n await run(store.start(instance('s-1')));\n await run(store.recordOutcome('s-1', outcome('reserve')));\n await run(store.recordOutcome('s-1', outcome('charge')));\n\n await run(store.markCompensated('s-1', 'reserve'));\n\n const read = await run(store.get('s-1'));\n expect(read?.outcomes).toEqual([\n expect.objectContaining({ stepId: 'reserve', compensated: true }),\n expect.not.objectContaining({ compensated: true }),\n ]);\n });\n\n // `COMPENSATING` is stuck too: a coordinator that died while unwinding is\n // the state that leaves holds in place.\n it('finds unfinished instances past the deadline, and nothing else', async () => {\n const store = await makeStore();\n await run(store.start(instance('running')));\n await run(store.start(instance('unwinding', { state: 'COMPENSATING' })));\n await run(store.start(instance('done', { state: 'COMPLETED' })));\n\n const stale = await run(store.findStale(ANY_AGE));\n expect(stale.map(entry => entry.sagaId).sort()).toEqual([\n 'running',\n 'unwinding',\n ]);\n expect(await run(store.findStale(AN_HOUR))).toEqual([]);\n });\n\n it('claims a stale instance by counting the attempt', async () => {\n const store = await makeStore();\n await run(store.start(instance('s-1')));\n\n const claimed = await run(store.claimForResume('s-1', ANY_AGE));\n\n expect(claimed).toMatchObject({ sagaId: 's-1', resumeAttempts: 1 });\n expect((await run(store.get('s-1')))?.resumeAttempts).toBe(1);\n });\n\n it('refuses to claim a settled or a fresh instance', async () => {\n const store = await makeStore();\n await run(store.start(instance('done', { state: 'COMPLETED' })));\n await run(store.start(instance('fresh')));\n\n expect(await run(store.claimForResume('done', ANY_AGE))).toBeUndefined();\n expect(await run(store.claimForResume('fresh', AN_HOUR))).toBeUndefined();\n expect(\n await run(store.claimForResume('absent', ANY_AGE)),\n ).toBeUndefined();\n });\n });\n};\n"],"names":["Effect","describe","expect","it","run","effect","runPromise","ANY_AGE","AN_HOUR","instance","sagaId","over","definition","state","stepIndex","outcomes","inputs","resumeAttempts","createdAt","Date","toISOString","outcome","stepId","calls","describeSagaStoreContract","name","makeStore","store","start","read","get","toMatchObject","updatedAt","toEqual","any","String","toBeUndefined","recordOutcome","toBe","map","entry","beginStep","settle","error","markCompensated","objectContaining","compensated","not","stale","findStale","sort","claimed","claimForResume"],"mappings":";AAKA,SAASA,MAAM,QAAQ,SAAS;AAChC,SAASC,QAAQ,EAAEC,MAAM,EAAEC,EAAE,QAAQ,SAAS;AAE9C,MAAMC,MAAM,CAAiBC,SAC3BL,OAAOM,UAAU,CAACD;AAEpB,2EAA2E,GAC3E,MAAME,UAAU,CAAC;AACjB,wDAAwD,GACxD,MAAMC,UAAU;AAEhB,MAAMC,WAAW,CACfC,QACAC,OAAiD,CAAC,CAAC,GACd;QACrCD;QACAE,YAAY;QACZC,OAAO;QACPC,WAAW;QACXC,UAAU,EAAE;QACZC,QAAQ,CAAC;QACTC,gBAAgB;QAChBC,WAAW,IAAIC,OAAOC,WAAW;OAC9BT;AAGL,MAAMU,UAAU,CAACC,SAAqC,CAAA;QAAEA;QAAQC,OAAO,EAAE;IAAC,CAAA;AAE1E;;;;;;;;;CASC,GACD,OAAO,MAAMC,4BAA4B,CACvCC,MACAC;IAEAzB,SAAS,CAAC,oBAAoB,EAAEwB,MAAM,EAAE;QACtCtB,GAAG,iDAAiD;YAClD,MAAMwB,QAAQ,MAAMD;YAEpB,MAAMtB,IAAIuB,MAAMC,KAAK,CAACnB,SAAS;YAC/B,MAAMoB,OAAO,MAAMzB,IAAIuB,MAAMG,GAAG,CAAC;YAEjC5B,OAAO2B,MAAME,aAAa,CAAC;gBAAErB,QAAQ;gBAAOG,OAAO;YAAU;YAC7DX,OAAO2B,wBAAAA,KAAMG,SAAS,EAAEC,OAAO,CAAC/B,OAAOgC,GAAG,CAACC;QAC7C;QAEAhC,GAAG,sDAAsD;YACvD,MAAMwB,QAAQ,MAAMD;YAEpBxB,OAAO,MAAME,IAAIuB,MAAMG,GAAG,CAAC,YAAYM,aAAa;QACtD;QAEA,qEAAqE;QACrE,yDAAyD;QACzDjC,GAAG,gDAAgD;YACjD,MAAMwB,QAAQ,MAAMD;YACpB,MAAMtB,IAAIuB,MAAMC,KAAK,CAACnB,SAAS;YAC/B,M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