@entifix/testing-unit 0.14.0 → 0.16.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.
@@ -2,6 +2,10 @@ import { _ as _extends } from "@swc/helpers/_/_extends";
2
2
  import { slipSteps } from '@entifix/business/flow';
3
3
  import { flowEvent, FlowNotFound, FlowSignalRejected } from '@entifix/transactions';
4
4
  import { Effect } from 'effect';
5
+ /** The outcome named on a signal's value or a timeout's, when a string. */ const outcomeOf = (value)=>{
6
+ const named = typeof value === 'object' && value !== null ? value.outcome : undefined;
7
+ return typeof named === 'string' ? named : undefined;
8
+ };
5
9
  const failureOf = (error)=>({
6
10
  code: error.code,
7
11
  category: error.category
@@ -11,8 +15,11 @@ const failureOf = (error)=>({
11
15
  * ([ADR 0016](../../../../../docs/adr/0016-a-flow-engine-port-and-a-durable-workflow-adapter.md)):
12
16
  * a failure before the commit point — the pivot's own included — compensates
13
17
  * the steps that succeeded, in reverse; a failure after it suspends the flow;
14
- * a `wait` parks it until a signal names that step. It runs synchronously and
15
- * durably remembers nothing, which is what makes it a fake.
18
+ * a `wait` parks it until a signal names that step, or until its `timeoutMs`
19
+ * runs out and its `onTimeout` answers an outcome or strands the flow; a step
20
+ * guarded on a wait's answer runs only on the outcomes it names. It runs
21
+ * synchronously but for a timeout, and durably remembers nothing, which is
22
+ * what makes it a fake.
16
23
  */ export const makeFakeFlowEngine = (catalog, participant)=>{
17
24
  const runs = new Map();
18
25
  const byKey = new Map();
@@ -49,9 +56,18 @@ const failureOf = (error)=>({
49
56
  const commitAt = steps.findIndex((step)=>kindOf(step) === 'pivot');
50
57
  while(run.next < steps.length){
51
58
  const step = steps[run.next];
59
+ if (step.guard !== undefined) {
60
+ const outcome = run.answered.get(step.guard.wait);
61
+ if (run.skipped.has(step.guard.wait) || outcome === undefined || !step.guard.outcomes.includes(outcome)) {
62
+ run.skipped.add(step.step);
63
+ run.next += 1;
64
+ continue;
65
+ }
66
+ }
52
67
  run.step = step.step;
53
68
  if (kindOf(step) === 'wait') {
54
69
  run.state = 'waiting';
70
+ armTimeout(run, step);
55
71
  return;
56
72
  }
57
73
  const result = yield* Effect.result(participant(step));
@@ -81,6 +97,38 @@ const failureOf = (error)=>({
81
97
  run.step = undefined;
82
98
  announce(run, 'flow.completed', 'completed');
83
99
  });
100
+ /**
101
+ * Answers a parked wait when its `timeoutMs` runs out, unless a signal came
102
+ * first: with the outcome its `onTimeout` names, or by stranding the flow.
103
+ * Named neither, a timeout is a failure past the commit point — suspended.
104
+ */ function armTimeout(run, step) {
105
+ var _step_parameters, _step_parameters1;
106
+ const timeoutMs = (_step_parameters = step.parameters) == null ? void 0 : _step_parameters['timeoutMs'];
107
+ if (typeof timeoutMs !== 'number') return;
108
+ const onTimeout = (_step_parameters1 = step.parameters) == null ? void 0 : _step_parameters1['onTimeout'];
109
+ Effect.runFork(Effect.sleep(timeoutMs).pipe(Effect.andThen(Effect.suspend(()=>{
110
+ if (run.state !== 'waiting' || run.step !== step.step) return Effect.void;
111
+ if (onTimeout === 'strand') {
112
+ run.state = 'stranded';
113
+ announce(run, 'flow.stranded', step.step);
114
+ return Effect.void;
115
+ }
116
+ const outcome = outcomeOf(onTimeout);
117
+ if (outcome === undefined) {
118
+ run.state = 'suspended';
119
+ announce(run, 'flow.suspended', step.step, {
120
+ failure: {
121
+ code: 'flowWaitTimedOut',
122
+ category: 'timeout'
123
+ }
124
+ });
125
+ return Effect.void;
126
+ }
127
+ return resume(run, step.step, {
128
+ outcome
129
+ });
130
+ }))));
131
+ }
84
132
  /** What a parked run's wait is correlated with, per its step's parameters. */ const correlationOf = (run)=>{
85
133
  if (run.state !== 'waiting') return undefined;
86
134
  // A waiting run is parked on the step at `next`.
@@ -88,15 +136,16 @@ const failureOf = (error)=>({
88
136
  const correlation = parameters == null ? void 0 : parameters['correlation'];
89
137
  return typeof correlation === 'string' ? correlation : undefined;
90
138
  };
91
- const signal = (token)=>(run)=>{
92
- if (run.state !== 'waiting' || run.step !== token) return Effect.fail(new FlowSignalRejected({
139
+ function resume(run, token, value) {
140
+ run.answered.set(token, outcomeOf(value));
141
+ run.state = 'running';
142
+ run.next += 1;
143
+ return walk(run);
144
+ }
145
+ const signal = (token, value)=>(run)=>run.state !== 'waiting' || run.step !== token ? Effect.fail(new FlowSignalRejected({
93
146
  flowId: run.slip.flowId,
94
147
  token
95
- }));
96
- run.state = 'running';
97
- run.next += 1;
98
- return walk(run);
99
- };
148
+ })) : resume(run, token, value);
100
149
  const find = (flowId)=>{
101
150
  const run = runs.get(flowId);
102
151
  return run === undefined ? Effect.fail(new FlowNotFound({
@@ -115,7 +164,9 @@ const failureOf = (error)=>({
115
164
  slip,
116
165
  state: 'running',
117
166
  next: 0,
118
- done: []
167
+ done: [],
168
+ answered: new Map(),
169
+ skipped: new Set()
119
170
  };
120
171
  runs.set(slip.flowId, run);
121
172
  byKey.set(idempotencyKey, slip.flowId);
@@ -131,14 +182,22 @@ const failureOf = (error)=>({
131
182
  }, run.step === undefined ? {} : {
132
183
  step: run.step
133
184
  })),
134
- signal: (flowId, token)=>Effect.flatMap(find(flowId), signal(token)),
135
- signalCorrelated: (correlation, token)=>{
136
- var _ref;
137
- var _find;
138
- return Effect.flatMap(find((_ref = (_find = [
139
- ...runs.entries()
140
- ].find(([, run])=>correlationOf(run) === correlation)) == null ? void 0 : _find[0]) != null ? _ref : correlation), signal(token));
141
- },
185
+ signal: (flowId, token, outcome)=>Effect.flatMap(find(flowId), signal(token, outcome)),
186
+ signalCorrelated: (correlation, value)=>Effect.suspend(()=>{
187
+ var _catalog_get;
188
+ const run = [
189
+ ...runs.values()
190
+ ].find((candidate)=>correlationOf(candidate) === correlation);
191
+ if (run === undefined) return Effect.fail(new FlowNotFound({
192
+ flowId: correlation
193
+ }));
194
+ const token = run.step;
195
+ const accepts = (_catalog_get = catalog.get(slipSteps(run.slip)[run.next].ref)) == null ? void 0 : _catalog_get.outcomes;
196
+ return accepts !== undefined && !accepts.includes(value.outcome) ? Effect.fail(new FlowSignalRejected({
197
+ flowId: run.slip.flowId,
198
+ token
199
+ })) : signal(token, value)(run);
200
+ }),
142
201
  interrupt: (flowId)=>Effect.map(find(flowId), (run)=>{
143
202
  if (run.state === 'running' || run.state === 'waiting') run.state = 'interrupted';
144
203
  })
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/doubles/flow-engine.ts"],"sourcesContent":["import type { FragmentCatalog, Slip, SlipStep } from '@entifix/business/flow';\nimport { slipSteps } from '@entifix/business/flow';\nimport { type DomainEvent, type EntifixFailure } from '@entifix/core';\nimport {\n type FlowEngine,\n flowEvent,\n type FlowEventData,\n FlowNotFound,\n FlowSignalRejected,\n type FlowState,\n} from '@entifix/transactions';\nimport { Effect } from 'effect';\n\n/** What a fake participant does for one step: succeed with an outcome, or fail. */\nexport type FakeParticipant = (\n step: SlipStep,\n) => Effect.Effect<unknown, EntifixFailure>;\n\nexport interface FakeFlowEngine extends FlowEngine {\n /** Every `flow.*` event the engine announced, in order. */\n readonly events: readonly DomainEvent<FlowEventData>[];\n /** Every compensation it ran, as `compensate:<step>`, in order. */\n readonly compensations: readonly string[];\n}\n\ninterface Run {\n readonly slip: Slip;\n state: FlowState;\n step?: string;\n /** The next step to run. */\n next: number;\n readonly done: SlipStep[];\n}\n\nconst failureOf = (error: EntifixFailure) => ({\n code: error.code,\n category: error.category,\n});\n\n/**\n * An in-memory {@link FlowEngine} with the semantics a durable one must have\n * ([ADR 0016](../../../../../docs/adr/0016-a-flow-engine-port-and-a-durable-workflow-adapter.md)):\n * a failure before the commit point — the pivot's own included — compensates\n * the steps that succeeded, in reverse; a failure after it suspends the flow;\n * a `wait` parks it until a signal names that step. It runs synchronously and\n * durably remembers nothing, which is what makes it a fake.\n */\nexport const makeFakeFlowEngine = (\n catalog: FragmentCatalog,\n participant: FakeParticipant,\n): FakeFlowEngine => {\n const runs = new Map<string, Run>();\n const byKey = new Map<string, string>();\n const events: DomainEvent<FlowEventData>[] = [];\n const compensations: string[] = [];\n\n const kindOf = (step: SlipStep) => catalog.get(step.ref)?.kind ?? 'retriable';\n\n const announce = (\n run: Run,\n name: DomainEvent['name'] & `flow.${string}`,\n step: string,\n extra: Partial<FlowEventData> = {},\n ) => {\n events.push(\n flowEvent({\n name: name as 'flow.started',\n source: 'fake-flow-engine',\n at: new Date(0).toISOString(),\n step,\n ordinal: events.length,\n audience: [{ kind: 'flow', id: run.slip.flowId }],\n data: {\n flowId: run.slip.flowId,\n definition: run.slip.recipe,\n slipVersion: run.slip.slipVersion,\n step,\n ...extra,\n },\n }),\n );\n };\n\n const walk = (run: Run): Effect.Effect<void> =>\n Effect.gen(function* () {\n const steps = slipSteps(run.slip);\n const commitAt = steps.findIndex(step => kindOf(step) === 'pivot');\n while (run.next < steps.length) {\n const step = steps[run.next] as SlipStep;\n run.step = step.step;\n if (kindOf(step) === 'wait') {\n run.state = 'waiting';\n return;\n }\n const result = yield* Effect.result(participant(step));\n if (result._tag === 'Failure') {\n const error = result.failure;\n const preCommit = commitAt === -1 || run.next <= commitAt;\n if (preCommit) {\n for (const done of [...run.done].reverse())\n if (kindOf(done) === 'compensatable')\n compensations.push(`compensate:${done.step}`);\n run.state = 'compensated';\n announce(run, 'flow.failed', step.step, {\n failure: failureOf(error),\n });\n } else {\n run.state = 'suspended';\n announce(run, 'flow.suspended', step.step, {\n failure: failureOf(error),\n });\n }\n return;\n }\n run.done.push(step);\n run.next += 1;\n }\n run.state = 'completed';\n run.step = undefined;\n announce(run, 'flow.completed', 'completed');\n });\n\n /** What a parked run's wait is correlated with, per its step's parameters. */\n const correlationOf = (run: Run) => {\n if (run.state !== 'waiting') return undefined;\n // A waiting run is parked on the step at `next`.\n const { parameters } = slipSteps(run.slip)[run.next] as SlipStep;\n const correlation = parameters?.['correlation'];\n return typeof correlation === 'string' ? correlation : undefined;\n };\n\n const signal = (token: string) => (run: Run) => {\n if (run.state !== 'waiting' || run.step !== token)\n return Effect.fail(\n new FlowSignalRejected({ flowId: run.slip.flowId, token }),\n );\n run.state = 'running';\n run.next += 1;\n return walk(run);\n };\n\n const find = (flowId: string) => {\n const run = runs.get(flowId);\n return run === undefined\n ? Effect.fail(new FlowNotFound({ flowId }))\n : Effect.succeed(run);\n };\n\n return {\n events,\n compensations,\n start: (slip, idempotencyKey) =>\n Effect.gen(function* () {\n const known = byKey.get(idempotencyKey);\n if (known !== undefined) return { flowId: known };\n const run: Run = { slip, state: 'running', next: 0, done: [] };\n runs.set(slip.flowId, run);\n byKey.set(idempotencyKey, slip.flowId);\n announce(run, 'flow.started', 'started');\n yield* walk(run);\n return { flowId: slip.flowId };\n }),\n status: flowId =>\n Effect.map(find(flowId), run => ({\n flowId,\n state: run.state,\n ...(run.step === undefined ? {} : { step: run.step }),\n })),\n signal: (flowId, token) => Effect.flatMap(find(flowId), signal(token)),\n signalCorrelated: (correlation, token) =>\n Effect.flatMap(\n find(\n [...runs.entries()].find(\n ([, run]) => correlationOf(run) === correlation,\n )?.[0] ?? correlation,\n ),\n signal(token),\n ),\n interrupt: flowId =>\n Effect.map(find(flowId), run => {\n if (run.state === 'running' || run.state === 'waiting')\n run.state = 'interrupted';\n }),\n };\n};\n"],"names":["slipSteps","flowEvent","FlowNotFound","FlowSignalRejected","Effect","failureOf","error","code","category","makeFakeFlowEngine","catalog","participant","runs","Map","byKey","events","compensations","kindOf","step","get","ref","kind","announce","run","name","extra","push","source","at","Date","toISOString","ordinal","length","audience","id","slip","flowId","data","definition","recipe","slipVersion","walk","gen","steps","commitAt","findIndex","next","state","result","_tag","failure","preCommit","done","reverse","undefined","correlationOf","parameters","correlation","signal","token","fail","find","succeed","start","idempotencyKey","known","set","status","map","flatMap","signalCorrelated","entries","interrupt"],"mappings":";AACA,SAASA,SAAS,QAAQ,yBAAyB;AAEnD,SAEEC,SAAS,EAETC,YAAY,EACZC,kBAAkB,QAEb,wBAAwB;AAC/B,SAASC,MAAM,QAAQ,SAAS;AAuBhC,MAAMC,YAAY,CAACC,QAA2B,CAAA;QAC5CC,MAAMD,MAAMC,IA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AI,GAAKgC,cAAchC,SAASkC,iCADtC,KAEG,CAAC,EAAE,mBAAIA,cAEZC,OAAOC;;QAEXa,WAAWpC,CAAAA,SACThC,OAAOgE,GAAG,CAACP,KAAKzB,SAASb,CAAAA;gBACvB,IAAIA,IAAIwB,KAAK,KAAK,aAAaxB,IAAIwB,KAAK,KAAK,WAC3CxB,IAAIwB,KAAK,GAAG;YAChB;IACJ;AACF,EAAE"}
1
+ {"version":3,"sources":["../../src/doubles/flow-engine.ts"],"sourcesContent":["import type { FragmentCatalog, Slip, SlipStep } from '@entifix/business/flow';\nimport { slipSteps } from '@entifix/business/flow';\nimport { type DomainEvent, type EntifixFailure } from '@entifix/core';\nimport {\n type FlowEngine,\n flowEvent,\n type FlowEventData,\n FlowNotFound,\n FlowSignalRejected,\n type FlowState,\n} from '@entifix/transactions';\nimport { Effect } from 'effect';\n\n/** What a fake participant does for one step: succeed with an outcome, or fail. */\nexport type FakeParticipant = (\n step: SlipStep,\n) => Effect.Effect<unknown, EntifixFailure>;\n\nexport interface FakeFlowEngine extends FlowEngine {\n /** Every `flow.*` event the engine announced, in order. */\n readonly events: readonly DomainEvent<FlowEventData>[];\n /** Every compensation it ran, as `compensate:<step>`, in order. */\n readonly compensations: readonly string[];\n}\n\ninterface Run {\n readonly slip: Slip;\n state: FlowState;\n step?: string;\n /** The next step to run. */\n next: number;\n readonly done: SlipStep[];\n /** What each wait was answered with, by step name. */\n readonly answered: Map<string, string | undefined>;\n /** Steps a guard passed over. */\n readonly skipped: Set<string>;\n}\n\n/** The outcome named on a signal's value or a timeout's, when a string. */\nconst outcomeOf = (value: unknown): string | undefined => {\n const named =\n typeof value === 'object' && value !== null\n ? (value as { readonly outcome?: unknown }).outcome\n : undefined;\n return typeof named === 'string' ? named : undefined;\n};\n\nconst failureOf = (error: EntifixFailure) => ({\n code: error.code,\n category: error.category,\n});\n\n/**\n * An in-memory {@link FlowEngine} with the semantics a durable one must have\n * ([ADR 0016](../../../../../docs/adr/0016-a-flow-engine-port-and-a-durable-workflow-adapter.md)):\n * a failure before the commit point — the pivot's own included — compensates\n * the steps that succeeded, in reverse; a failure after it suspends the flow;\n * a `wait` parks it until a signal names that step, or until its `timeoutMs`\n * runs out and its `onTimeout` answers an outcome or strands the flow; a step\n * guarded on a wait's answer runs only on the outcomes it names. It runs\n * synchronously but for a timeout, and durably remembers nothing, which is\n * what makes it a fake.\n */\nexport const makeFakeFlowEngine = (\n catalog: FragmentCatalog,\n participant: FakeParticipant,\n): FakeFlowEngine => {\n const runs = new Map<string, Run>();\n const byKey = new Map<string, string>();\n const events: DomainEvent<FlowEventData>[] = [];\n const compensations: string[] = [];\n\n const kindOf = (step: SlipStep) => catalog.get(step.ref)?.kind ?? 'retriable';\n\n const announce = (\n run: Run,\n name: DomainEvent['name'] & `flow.${string}`,\n step: string,\n extra: Partial<FlowEventData> = {},\n ) => {\n events.push(\n flowEvent({\n name: name as 'flow.started',\n source: 'fake-flow-engine',\n at: new Date(0).toISOString(),\n step,\n ordinal: events.length,\n audience: [{ kind: 'flow', id: run.slip.flowId }],\n data: {\n flowId: run.slip.flowId,\n definition: run.slip.recipe,\n slipVersion: run.slip.slipVersion,\n step,\n ...extra,\n },\n }),\n );\n };\n\n const walk = (run: Run): Effect.Effect<void> =>\n Effect.gen(function* () {\n const steps = slipSteps(run.slip);\n const commitAt = steps.findIndex(step => kindOf(step) === 'pivot');\n while (run.next < steps.length) {\n const step = steps[run.next] as SlipStep;\n if (step.guard !== undefined) {\n const outcome = run.answered.get(step.guard.wait);\n if (\n run.skipped.has(step.guard.wait) ||\n outcome === undefined ||\n !step.guard.outcomes.includes(outcome)\n ) {\n run.skipped.add(step.step);\n run.next += 1;\n continue;\n }\n }\n run.step = step.step;\n if (kindOf(step) === 'wait') {\n run.state = 'waiting';\n armTimeout(run, step);\n return;\n }\n const result = yield* Effect.result(participant(step));\n if (result._tag === 'Failure') {\n const error = result.failure;\n const preCommit = commitAt === -1 || run.next <= commitAt;\n if (preCommit) {\n for (const done of [...run.done].reverse())\n if (kindOf(done) === 'compensatable')\n compensations.push(`compensate:${done.step}`);\n run.state = 'compensated';\n announce(run, 'flow.failed', step.step, {\n failure: failureOf(error),\n });\n } else {\n run.state = 'suspended';\n announce(run, 'flow.suspended', step.step, {\n failure: failureOf(error),\n });\n }\n return;\n }\n run.done.push(step);\n run.next += 1;\n }\n run.state = 'completed';\n run.step = undefined;\n announce(run, 'flow.completed', 'completed');\n });\n\n /**\n * Answers a parked wait when its `timeoutMs` runs out, unless a signal came\n * first: with the outcome its `onTimeout` names, or by stranding the flow.\n * Named neither, a timeout is a failure past the commit point — suspended.\n */\n function armTimeout(run: Run, step: SlipStep): void {\n const timeoutMs = step.parameters?.['timeoutMs'];\n if (typeof timeoutMs !== 'number') return;\n const onTimeout = step.parameters?.['onTimeout'];\n Effect.runFork(\n Effect.sleep(timeoutMs).pipe(\n Effect.andThen(\n Effect.suspend(() => {\n if (run.state !== 'waiting' || run.step !== step.step)\n return Effect.void;\n if (onTimeout === 'strand') {\n run.state = 'stranded';\n announce(run, 'flow.stranded', step.step);\n return Effect.void;\n }\n const outcome = outcomeOf(onTimeout);\n if (outcome === undefined) {\n run.state = 'suspended';\n announce(run, 'flow.suspended', step.step, {\n failure: { code: 'flowWaitTimedOut', category: 'timeout' },\n });\n return Effect.void;\n }\n return resume(run, step.step, { outcome });\n }),\n ),\n ),\n );\n }\n\n /** What a parked run's wait is correlated with, per its step's parameters. */\n const correlationOf = (run: Run) => {\n if (run.state !== 'waiting') return undefined;\n // A waiting run is parked on the step at `next`.\n const { parameters } = slipSteps(run.slip)[run.next] as SlipStep;\n const correlation = parameters?.['correlation'];\n return typeof correlation === 'string' ? correlation : undefined;\n };\n\n function resume(run: Run, token: string, value: unknown) {\n run.answered.set(token, outcomeOf(value));\n run.state = 'running';\n run.next += 1;\n return walk(run);\n }\n\n const signal = (token: string, value: unknown) => (run: Run) =>\n run.state !== 'waiting' || run.step !== token\n ? Effect.fail(new FlowSignalRejected({ flowId: run.slip.flowId, token }))\n : resume(run, token, value);\n\n const find = (flowId: string) => {\n const run = runs.get(flowId);\n return run === undefined\n ? Effect.fail(new FlowNotFound({ flowId }))\n : Effect.succeed(run);\n };\n\n return {\n events,\n compensations,\n start: (slip, idempotencyKey) =>\n Effect.gen(function* () {\n const known = byKey.get(idempotencyKey);\n if (known !== undefined) return { flowId: known };\n const run: Run = {\n slip,\n state: 'running',\n next: 0,\n done: [],\n answered: new Map(),\n skipped: new Set(),\n };\n runs.set(slip.flowId, run);\n byKey.set(idempotencyKey, slip.flowId);\n announce(run, 'flow.started', 'started');\n yield* walk(run);\n return { flowId: slip.flowId };\n }),\n status: flowId =>\n Effect.map(find(flowId), run => ({\n flowId,\n state: run.state,\n ...(run.step === undefined ? {} : { step: run.step }),\n })),\n signal: (flowId, token, outcome) =>\n Effect.flatMap(find(flowId), signal(token, outcome)),\n signalCorrelated: (correlation, value) =>\n Effect.suspend(\n (): Effect.Effect<void, FlowNotFound | FlowSignalRejected> => {\n const run = [...runs.values()].find(\n candidate => correlationOf(candidate) === correlation,\n );\n if (run === undefined)\n return Effect.fail(new FlowNotFound({ flowId: correlation }));\n const token = run.step as string;\n const accepts = catalog.get(\n (slipSteps(run.slip)[run.next] as SlipStep).ref,\n )?.outcomes;\n return accepts !== undefined && !accepts.includes(value.outcome)\n ? Effect.fail(\n new FlowSignalRejected({ flowId: run.slip.flowId, token }),\n )\n : signal(token, value)(run);\n },\n ),\n interrupt: flowId =>\n Effect.map(find(flowId), run => {\n if (run.state === 'running' || run.state === 'waiting')\n run.state = 'interrupted';\n }),\n };\n};\n"],"names":["slipSteps","flowEvent","FlowNotFound","FlowSignalRejected","Effect","outcomeOf","value","named","outcome","undefined","failureOf","error","code","category","makeFakeFlowEngine","catalog","participant","runs","Map","byKey","events","compensations","kindOf","step","get","ref","kind","announce","run","name","extra","push","source","at","Date","toISOString","ordinal","length","audience","id","slip","flowId","data","definition","recipe","slipVersion","walk","gen","steps","commitAt","findIndex","next","guard","answered","wait","skipped","has","outcomes","includes","add","state","armTimeout","result","_tag","failure","preCommit","done","reverse","timeoutMs","parameters","onTimeout","runFork","sleep","pipe","andThen","suspend","void","resume","correlationOf","correlation","token","set","signal","fail","find","succeed","start","idempotencyKey","known","Set","status","map","flatMap","signalCorrelated","values","candidate","accepts","interrupt"],"mappings":";AACA,SAASA,SAAS,QAAQ,yBAAyB;AAEnD,SAEEC,SAAS,EAETC,YAAY,EACZC,kBAAkB,QAEb,wBAAwB;AAC/B,SAASC,MAAM,QAAQ,SAAS;AA2BhC,yEAAyE,GACzE,MAAMC,YAAY,CAACC;IACjB,MAAMC,QACJ,OAAOD,UAAU,YAAYA,UAAU,OACnC,AAACA,MAAyCE,OAAO,GACjDC;IACN,OAAO,OAAOF,UAAU,WAAWA,QAAQE;AAC7C;AAEA,MAAMC,YAAY,CAACC,QAA2B,CAAA;QAC5CC,MAAMD,MAAMC,IAAI;QAChBC,UAAUF,MAAME,QAAQ;IAC1B,CAAA;AAEA;;;;;;;;;;CAUC,GACD,OAAO,MAAMC,qBAAqB,CAChCC,SACAC;IAEA,MAAMC,OAAO,IAAIC;IACjB,MAAMC,QAAQ,IAAID;IAClB,MAAME,SAAuC,EAAE;IAC/C,MAAMC,gBAA0B,EAAE;IAElC,MAAMC,SAAS,CAACC;;YAAmBR;wBAAAA,eAAAA,QAAQS,GAAG,CAACD,KAAKE,GAAG,sBAApBV,aAAuBW,IAAI,mBAAI;;IAElE,MAAMC,WAAW,CACfC,KACAC,MACAN,MACAO,QAAgC,CAAC,CAAC;QAElCV,OAAOW,IAAI,CACT9B,UAAU;YACR4B,MAAMA;YACNG,QAAQ;YACRC,IAAI,IAAIC,KAAK,GAAGC,WAAW;YAC3BZ;YACAa,SAAShB,OAAOiB,MAAM;YACtBC,UAAU;gBAAC;oBAAEZ,MAAM;oBAAQa,IAAIX,IAAIY,IAAI,CAACC,MAAM;gBAAC;aAAE;YACjDC,MAAM;gBACJD,QAAQb,IAAIY,IAAI,CAACC,MAAM;gBAC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,OAAO,IAC3DJ,OAAO+E,IAAI,CACT,IAAIhF,mBAAmB;oBAAEsC,QAAQb,IAAIY,IAAI,CAACC,MAAM;oBAAEuC;gBAAM,MAE1DE,OAAOF,OAAO1E,OAAOsB;YAC3B;QAEJqE,WAAWxD,CAAAA,SACTrC,OAAOuF,GAAG,CAACP,KAAK3C,SAASb,CAAAA;gBACvB,IAAIA,IAAIgC,KAAK,KAAK,aAAahC,IAAIgC,KAAK,KAAK,WAC3ChC,IAAIgC,KAAK,GAAG;YAChB;IACJ;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;IAC5E;;;OAGG;IACH,SAAS,CAAC,GAAG,EAAE,MAAM,GAAG,IAAI,CAAC;CAC9B;AAED;;;;;GAKG;AACH,eAAO,MAAM,uBAAuB,QAAO,mBAkC1C,CAAC;AAEF,MAAM,WAAW,uBAAwB,SAAQ,eAAe;IAC9D,6DAA6D;IAC7D,QA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;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,OAAOY,GAAG,CAACL,KAAKI;gBAChBP,IAAIS,IAAI,CAAC;oBAAEC,QAAQ;oBAAWP;gBAAI;gBAClC,OAAOT,OAAOiB,OAAO,CAAC;oBAAER;oBAAKI;gBAAM;YACrC;QACFK,SAAS,CAACC,SACRnB,OAAOoB,IAAI,CAAC;gBACV,I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,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,IAAIC,WAAW;IAEf,OAAO;QACLC,SAASC,CAAAA,QACPN,OAAOO,OAAO,CAAC;gBACb,IAAIH,UAAU;oBACZA,WAAW;oBACX,OAAOJ,OAAOQ,IAAI,CAAC,IAAIT,YAAY;wBAAEU,YAAY;oBAAM;gBACzD;gBACAP,UAAUQ,IAAI,CAACJ;gBACf,OAAON,OAAOW,IAAI;YACpB;QACFC,WAAW,CAACC,cAAcC,SACxBd,OAAOe,IAAI,CAAC;gBACV,kEAAkE;gBAClE,uEAAuE;gBACvE,gEAAgE;gBAChEZ,SAASO,IAAI,CAAC;oBAAEM,SAASH,aAAaG,OAAO;oBAAEF;gBAAO;YACxD;QACFG,SAASX,CAAAA,QACPN,OAAOkB,OAAO,CACZf,SAASgB,MAAM,CAAC,CAAC,EAAEH,OAAO,EAAE,GAC1BlB,oBAAoBkB,SAASV,MAAMc,IAAI,IAEzC,CAAC,EAAEN,MAAM,EAAE,GAAKA,OAAOR,QACvB;gBAAEe,SAAS;YAAK;QAEpB,IAAInB;YACF,OAAOA;QACT;QACAoB,iBAAiB;YACflB,WAAW;QACb;IACF;AACF,EAAE;AAEF;;;;;;;;CAQC,GACD,OAAO,MAAMmB,sBAAsB;IACjC,MAAMC,UAAU,IAAIC;IAEpB,OAAO;QACL,wDAAwD,GACxDC,KAAK,CAACC,WAAwC,CAAA;gBAC5CC,OAAOC,CAAAA,UACL7B,OAAOe,IAAI,CAAC;wBACV,MAAMe,MAAMC,KAAKC,SAAS,CAAC;4BAACL;4BAAUE;yBAAQ;wBAC9C,IAAIL,QAAQS,GAAG,CAACH,MAAM,OAAO;wBAC7BN,QAAQU,GAAG,CAACJ;wBACZ,OAAO;oBACT;YACJ,CAAA;QACA,IAAIK;YACF,OAAO;mBAAIX;aAAQ,CAACY,GAAG,CAACN,CAAAA;gBACtB,MAAM,CAACH,UAAUE,QAAQ,GAAGE,KAAKM,KAAK,CAACP;gBACvC,OAAO;oBAAEH;oBAAUE;gBAAQ;YAC7B;QACF;IACF;AACF,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;gBAEjD,IAAIJ,MAAMpB,MAAMyB,GAAG,CAACR,MAAM,OAAO;gBACjCjB,MAAMgB,GAAG,CAACC,KAAKC;gBACf,4DAA4D;gBAC5D,MAAMQ,UAAUP,KAAKQ,SAAS,CAC5BL,CAAAA,WAAYC,OAAOD,UAAUE,WAAW,OAAO;gBAEjD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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,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,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d,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.16.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.16.0",
76
+ "@entifix/transactions": "0.16.0",
77
+ "@entifix/core": "0.16.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.16.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"}