@entifix/testing-unit 0.1.1 → 0.1.2

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.
@@ -1 +1 @@
1
- {"version":3,"file":"entity-repository.contract.d.ts","sourceRoot":"","sources":["../../src/contracts/entity-repository.contract.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,mBAAmB,CAAC;AAC1D,OAAO,EAAY,KAAK,MAAM,EAAU,KAAK,QAAQ,EAAE,MAAM,eAAe,CAAC;AAM7E;;;;GAIG;AACH,qBACa,cAAe,YAAW,MAAM;;IAK3C,IACI,EAAE,IAAI,QAAQ,CAEjB;IACD,IAAI,EAAE,CAAC,KAAK,EAAE,QAAQ,EAErB;IAED,IACI,IAAI,IAAI,MAAM,GAAG,SAAS,CAE7B;IACD,IAAI,IAAI,CAAC,KAAK,EAAE,MAAM,GAAG,SAAS,EAEjC;IAED,IACI,IAAI,IAAI,MAAM,GAAG,SAAS,CAE7B;IACD,IAAI,IAAI,CAAC,KAAK,EAAE,MAAM,GAAG,SAAS,EAEjC;CACF;AAED,eAAO,MAAM,kBAAkB,GAC7B,IAAI,QAAQ,EACZ,MAAM,MAAM,EACZ,MAAM,MAAM,KACX,cAMF,CAAC;AAEF,MAAM,WAAW,+BAA+B;IAC9C;;;OAGG;IACH,cAAc,CACZ,IAAI,EAAE,cAAc,EAAE,GACrB,gBAAgB,GAAG,OAAO,CAAC,gBAAgB,CAAC,CAAC;CACjD;AAED;;;;;;;;;GASG;AACH,eAAO,MAAM,gCAAgC,GAC3C,MAAM,MAAM,EACZ,oBAAoB,+BAA+B,KAClD,IAsMF,CAAC"}
1
+ {"version":3,"file":"entity-repository.contract.d.ts","sourceRoot":"","sources":["../../src/contracts/entity-repository.contract.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,mBAAmB,CAAC;AAC1D,OAAO,EAAY,KAAK,MAAM,EAAU,KAAK,QAAQ,EAAE,MAAM,eAAe,CAAC;AAM7E;;;;GAIG;AACH,qBACa,cAAe,YAAW,MAAM;;IAK3C,IACI,EAAE,IAAI,QAAQ,CAEjB;IACD,IAAI,EAAE,CAAC,KAAK,EAAE,QAAQ,EAErB;IAED,IACI,IAAI,IAAI,MAAM,GAAG,SAAS,CAE7B;IACD,IAAI,IAAI,CAAC,KAAK,EAAE,MAAM,GAAG,SAAS,EAEjC;IAED,IACI,IAAI,IAAI,MAAM,GAAG,SAAS,CAE7B;IACD,IAAI,IAAI,CAAC,KAAK,EAAE,MAAM,GAAG,SAAS,EAEjC;CACF;AAED,eAAO,MAAM,kBAAkB,GAC7B,IAAI,QAAQ,EACZ,MAAM,MAAM,EACZ,MAAM,MAAM,KACX,cAMF,CAAC;AAEF,MAAM,WAAW,+BAA+B;IAC9C;;;OAGG;IACH,cAAc,CACZ,IAAI,EAAE,cAAc,EAAE,GACrB,gBAAgB,GAAG,OAAO,CAAC,gBAAgB,CAAC,CAAC;CACjD;AAED;;;;;;;;;GASG;AACH,eAAO,MAAM,gCAAgC,GAC3C,MAAM,MAAM,EACZ,oBAAoB,+BAA+B,KAClD,IAwOF,CAAC"}
@@ -98,6 +98,28 @@ export const makeContractWidget = (id, name, size)=>{
98
98
  const withRepository = async (use, seed = seeded())=>{
99
99
  await use(await makeRepository(seed));
100
100
  };
101
+ it('keeps a record unchanged when a read instance is mutated without a save', async ()=>{
102
+ await withRepository(async (repository)=>{
103
+ const read = await runRepository(repository.get('w-1'));
104
+ read.name = 'Mutated';
105
+ const again = await runRepository(repository.get('w-1'));
106
+ expect(again.name).toBe('Alpha');
107
+ const page = await runRepository(repository.load({}));
108
+ page.items[0].name = 'Mutated';
109
+ const reloaded = await runRepository(repository.load({}));
110
+ expect(reloaded.items[0].name).toBe('Alpha');
111
+ });
112
+ });
113
+ it('keeps a saved record unchanged when the saved instance is mutated afterwards', async ()=>{
114
+ await withRepository(async (repository)=>{
115
+ const widget = makeContractWidget('w-9', 'Delta', 40);
116
+ const returned = await runRepository(repository.save(widget));
117
+ widget.name = 'Mutated';
118
+ returned.name = 'Mutated too';
119
+ const stored = await runRepository(repository.get('w-9'));
120
+ expect(stored.name).toBe('Delta');
121
+ });
122
+ });
101
123
  it('loads every stored entity with its total', async ()=>{
102
124
  await withRepository(async (repository)=>{
103
125
  const page = await runRepository(repository.load({}));
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/contracts/entity-repository.contract.ts"],"sourcesContent":["import type { EntityRepository } from '@entifix/business';\nimport { accessor, type Entity, entity, type EntityId } from '@entifix/core';\nimport { Exit } from 'effect';\nimport { describe, expect, it } from 'vitest';\n\nimport { runRepository, runRepositoryExit } from '../effect/run.js';\n\n/**\n * The entity every implementation of the contract is exercised against. It is\n * declared here rather than by each caller so the suite controls exactly which\n * fields exist.\n */\n@entity({ key: 'contract-widget' })\nexport class ContractWidget implements Entity {\n #id?: EntityId;\n #name?: string;\n #size?: number;\n\n @accessor({ type: 'id' })\n get id(): EntityId {\n return this.#id;\n }\n set id(value: EntityId) {\n this.#id = value;\n }\n\n @accessor({ type: 'string' })\n get name(): string | undefined {\n return this.#name;\n }\n set name(value: string | undefined) {\n this.#name = value;\n }\n\n @accessor({ type: 'number' })\n get size(): number | undefined {\n return this.#size;\n }\n set size(value: number | undefined) {\n this.#size = value;\n }\n}\n\nexport const makeContractWidget = (\n id: EntityId,\n name: string,\n size: number,\n): ContractWidget => {\n const widget = new ContractWidget();\n widget.id = id;\n widget.name = name;\n widget.size = size;\n return widget;\n};\n\nexport interface EntityRepositoryContractOptions {\n /**\n * Builds a repository over `seed`. Called fresh for each test, so no state\n * leaks between them.\n */\n makeRepository(\n seed: ContractWidget[],\n ): EntityRepository | Promise<EntityRepository>;\n}\n\n/**\n * The behaviour every {@link EntityRepository} must exhibit, regardless of what\n * backs it.\n *\n * Run it against the in-memory fake *and* against each real adapter. That is\n * what stops a fake from drifting into a more forgiving version of the thing it\n * stands in for — the failure mode where a suite is green and production is\n * not. `entifix-ts-testing-integration` will run this same suite against real\n * infrastructure later.\n */\nexport const describeEntityRepositoryContract = (\n name: string,\n { makeRepository }: EntityRepositoryContractOptions,\n): void => {\n describe(`EntityRepository contract: ${name}`, () => {\n const seeded = () => [\n makeContractWidget('w-1', 'Alpha', 10),\n makeContractWidget('w-2', 'Beta', 20),\n makeContractWidget('w-3', 'Gamma', 30),\n ];\n\n const withRepository = async (\n use: (repository: EntityRepository) => Promise<void>,\n seed: ContractWidget[] = seeded(),\n ) => {\n await use(await makeRepository(seed));\n };\n\n it('loads every stored entity with its total', async () => {\n await withRepository(async repository => {\n const page = await runRepository(repository.load<ContractWidget>({}));\n\n expect(page.total).toBe(3);\n expect(page.items.map(item => item.name)).toEqual([\n 'Alpha',\n 'Beta',\n 'Gamma',\n ]);\n });\n });\n\n it('echoes the request it served on the page', async () => {\n await withRepository(async repository => {\n const request = { page: 1, pageSize: 2 };\n const page = await runRepository(\n repository.load<ContractWidget>(request),\n );\n\n expect(page.request).toEqual(request);\n });\n });\n\n it('pages with a 1-based page number', async () => {\n await withRepository(async repository => {\n const page = await runRepository(\n repository.load<ContractWidget>({ page: 2, pageSize: 2 }),\n );\n\n expect(page.items).toHaveLength(1);\n expect(page.items[0]?.name).toBe('Gamma');\n // The total counts matches, not the page.\n expect(page.total).toBe(3);\n });\n });\n\n it('filters by an equality operator', async () => {\n await withRepository(async repository => {\n const page = await runRepository(\n repository.load<ContractWidget>({\n filtering: [{ property: 'name', operator: 'eq', value: 'Beta' }],\n }),\n );\n\n expect(page.items).toHaveLength(1);\n expect(page.items[0]?.id).toBe('w-2');\n expect(page.total).toBe(1);\n });\n });\n\n it('filters by a range operator', async () => {\n await withRepository(async repository => {\n const page = await runRepository(\n repository.load<ContractWidget>({\n filtering: [\n { property: 'size', operator: 'between', start: 15, end: 35 },\n ],\n }),\n );\n\n expect(page.items.map(item => item.id)).toEqual(['w-2', 'w-3']);\n });\n });\n\n it('matches `like` case-insensitively on a substring', async () => {\n await withRepository(async repository => {\n const page = await runRepository(\n repository.load<ContractWidget>({\n filtering: [{ property: 'name', operator: 'like', value: 'et' }],\n }),\n );\n\n expect(page.items.map(item => item.id)).toEqual(['w-2']);\n });\n });\n\n it('sorts descending when asked to', async () => {\n await withRepository(async repository => {\n const page = await runRepository(\n repository.load<ContractWidget>({\n sorting: [{ 0: { property: 'size', type: 'desc' } }],\n }),\n );\n\n expect(page.items.map(item => item.size)).toEqual([30, 20, 10]);\n });\n });\n\n it('reads a single entity by id', async () => {\n await withRepository(async repository => {\n const found = await runRepository(\n repository.get<ContractWidget>('w-2'),\n );\n\n expect(found.id).toBe('w-2');\n expect(found.name).toBe('Beta');\n });\n });\n\n it('fails rather than resolving undefined for an unknown id', async () => {\n await withRepository(async repository => {\n const exit = await runRepositoryExit(\n repository.get<ContractWidget>('missing'),\n );\n\n expect(Exit.isFailure(exit)).toBe(true);\n });\n });\n\n it('mints an id when saving an entity that has none', async () => {\n await withRepository(async repository => {\n const created = await runRepository(\n repository.save<ContractWidget>(\n makeContractWidget(undefined, 'Delta', 40),\n ),\n );\n\n expect(created.id).toBeDefined();\n\n const page = await runRepository(repository.load<ContractWidget>({}));\n expect(page.total).toBe(4);\n });\n });\n\n it('overwrites in place when saving an entity that already has an id', async () => {\n await withRepository(async repository => {\n await runRepository(\n repository.save<ContractWidget>(\n makeContractWidget('w-2', 'Renamed', 25),\n ),\n );\n\n const found = await runRepository(\n repository.get<ContractWidget>('w-2'),\n );\n expect(found.name).toBe('Renamed');\n\n const page = await runRepository(repository.load<ContractWidget>({}));\n expect(page.total).toBe(3);\n });\n });\n\n it('deletes by id', async () => {\n await withRepository(async repository => {\n await runRepository(repository.delete<ContractWidget>('w-1'));\n\n const page = await runRepository(repository.load<ContractWidget>({}));\n expect(page.items.map(item => item.id)).toEqual(['w-2', 'w-3']);\n });\n });\n\n it('deletes by entity', async () => {\n await withRepository(async repository => {\n await runRepository(\n repository.delete<ContractWidget>(\n makeContractWidget('w-3', 'Gamma', 30),\n ),\n );\n\n const page = await runRepository(repository.load<ContractWidget>({}));\n expect(page.items.map(item => item.id)).toEqual(['w-1', 'w-2']);\n });\n });\n\n it('treats deleting an unknown id as a no-op', async () => {\n await withRepository(async repository => {\n await runRepository(repository.delete<ContractWidget>('missing'));\n\n const page = await runRepository(repository.load<ContractWidget>({}));\n expect(page.total).toBe(3);\n });\n });\n\n it('loads an empty page from an empty store', async () => {\n await withRepository(async repository => {\n const page = await runRepository(repository.load<ContractWidget>({}));\n\n expect(page.items).toEqual([]);\n expect(page.total).toBe(0);\n }, []);\n });\n });\n};\n"],"names":["accessor","entity","Exit","describe","expect","it","runRepository","runRepositoryExit","key","type","ContractWidget","id","value","name","size","makeContractWidget","widget","describeEntityRepositoryContract","makeRepository","seeded","withRepository","use","seed","repository","page","load","total","toBe","items","map","item","toEqual","request","pageSize","toHaveLength","filtering","property","operator","start","end","sorting","found","get","exit","isFailure","created","save","undefined","toBeDefined","delete"],"mappings":";;;;AACA,SAASA,QAAQ,EAAeC,MAAM,QAAuB,gBAAgB;AAC7E,SAASC,IAAI,QAAQ,SAAS;AAC9B,SAASC,QAAQ,EAAEC,MAAM,EAAEC,EAAE,QAAQ,SAAS;AAE9C,SAASC,aAAa,EAAEC,iBAAiB,QAAQ,mBAAmB;OAOnEN,OAAO;IAAEO,KAAK;AAAkB,YAM9BR,SAAS;IAAES,MAAM;AAAK,YAQtBT,SAAS;IAAES,MAAM;AAAS,YAQ1BT,SAAS;IAAES,MAAM;AAAS;;IApB3B,2DACA,+DACA;AAHK,IAAA,AAAMC,iBAAN,MAAMA;IAKX,IACIC,KAAe;QACjB,OAAO,gCAAA,IAAI,EAAC,KAAA;IACd;IACA,IAAIA,GAAGC,KAAe,EAAE;QACtB,gCAAA,IAAI,EAAC,KAAA,OAAMA;IACb;IAEA,IACIC,OAA2B;QAC7B,OAAO,gCAAA,IAAI,EAAC,OAAA;IACd;IACA,IAAIA,KAAKD,KAAyB,EAAE;QAClC,gCAAA,IAAI,EAAC,OAAA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AAWE,IAAI,CAAiB,CAAC;gBAClErB,OAAOoB,KAAKE,KAAK,EAAEC,IAAI,CAAC;YAC1B;QACF;QAEAtB,GAAG,2CAA2C;YAC5C,MAAMe,eAAe,OAAMG;gBACzB,MAAMC,OAAO,MAAMlB,cAAciB,WAAWE,IAAI,CAAiB,CAAC;gBAElErB,OAAOoB,KAAKI,KAAK,EAAEG,OAAO,CAAC,EAAE;gBAC7B3B,OAAOoB,KAAKE,KAAK,EAAEC,IAAI,CAAC;YAC1B,GAAG,EAAE;QACP;IACF;AACF,EAAE;SAvQF,AAAajB,mBAAAA,cA4BZ"}
1
+ {"version":3,"sources":["../../src/contracts/entity-repository.contract.ts"],"sourcesContent":["import type { EntityRepository } from '@entifix/business';\nimport { accessor, type Entity, entity, type EntityId } from '@entifix/core';\nimport { Exit } from 'effect';\nimport { describe, expect, it } from 'vitest';\n\nimport { runRepository, runRepositoryExit } from '../effect/run.js';\n\n/**\n * The entity every implementation of the contract is exercised against. It is\n * declared here rather than by each caller so the suite controls exactly which\n * fields exist.\n */\n@entity({ key: 'contract-widget' })\nexport class ContractWidget implements Entity {\n #id?: EntityId;\n #name?: string;\n #size?: number;\n\n @accessor({ type: 'id' })\n get id(): EntityId {\n return this.#id;\n }\n set id(value: EntityId) {\n this.#id = value;\n }\n\n @accessor({ type: 'string' })\n get name(): string | undefined {\n return this.#name;\n }\n set name(value: string | undefined) {\n this.#name = value;\n }\n\n @accessor({ type: 'number' })\n get size(): number | undefined {\n return this.#size;\n }\n set size(value: number | undefined) {\n this.#size = value;\n }\n}\n\nexport const makeContractWidget = (\n id: EntityId,\n name: string,\n size: number,\n): ContractWidget => {\n const widget = new ContractWidget();\n widget.id = id;\n widget.name = name;\n widget.size = size;\n return widget;\n};\n\nexport interface EntityRepositoryContractOptions {\n /**\n * Builds a repository over `seed`. Called fresh for each test, so no state\n * leaks between them.\n */\n makeRepository(\n seed: ContractWidget[],\n ): EntityRepository | Promise<EntityRepository>;\n}\n\n/**\n * The behaviour every {@link EntityRepository} must exhibit, regardless of what\n * backs it.\n *\n * Run it against the in-memory fake *and* against each real adapter. That is\n * what stops a fake from drifting into a more forgiving version of the thing it\n * stands in for — the failure mode where a suite is green and production is\n * not. `entifix-ts-testing-integration` will run this same suite against real\n * infrastructure later.\n */\nexport const describeEntityRepositoryContract = (\n name: string,\n { makeRepository }: EntityRepositoryContractOptions,\n): void => {\n describe(`EntityRepository contract: ${name}`, () => {\n const seeded = () => [\n makeContractWidget('w-1', 'Alpha', 10),\n makeContractWidget('w-2', 'Beta', 20),\n makeContractWidget('w-3', 'Gamma', 30),\n ];\n\n const withRepository = async (\n use: (repository: EntityRepository) => Promise<void>,\n seed: ContractWidget[] = seeded(),\n ) => {\n await use(await makeRepository(seed));\n };\n\n it('keeps a record unchanged when a read instance is mutated without a save', async () => {\n await withRepository(async repository => {\n const read = await runRepository(repository.get<ContractWidget>('w-1'));\n read.name = 'Mutated';\n\n const again = await runRepository(\n repository.get<ContractWidget>('w-1'),\n );\n expect(again.name).toBe('Alpha');\n\n const page = await runRepository(repository.load<ContractWidget>({}));\n page.items[0]!.name = 'Mutated';\n const reloaded = await runRepository(\n repository.load<ContractWidget>({}),\n );\n expect(reloaded.items[0]!.name).toBe('Alpha');\n });\n });\n\n it('keeps a saved record unchanged when the saved instance is mutated afterwards', async () => {\n await withRepository(async repository => {\n const widget = makeContractWidget('w-9', 'Delta', 40);\n const returned = await runRepository(repository.save(widget));\n\n widget.name = 'Mutated';\n returned.name = 'Mutated too';\n\n const stored = await runRepository(\n repository.get<ContractWidget>('w-9'),\n );\n expect(stored.name).toBe('Delta');\n });\n });\n\n it('loads every stored entity with its total', async () => {\n await withRepository(async repository => {\n const page = await runRepository(repository.load<ContractWidget>({}));\n\n expect(page.total).toBe(3);\n expect(page.items.map(item => item.name)).toEqual([\n 'Alpha',\n 'Beta',\n 'Gamma',\n ]);\n });\n });\n\n it('echoes the request it served on the page', async () => {\n await withRepository(async repository => {\n const request = { page: 1, pageSize: 2 };\n const page = await runRepository(\n repository.load<ContractWidget>(request),\n );\n\n expect(page.request).toEqual(request);\n });\n });\n\n it('pages with a 1-based page number', async () => {\n await withRepository(async repository => {\n const page = await runRepository(\n repository.load<ContractWidget>({ page: 2, pageSize: 2 }),\n );\n\n expect(page.items).toHaveLength(1);\n expect(page.items[0]?.name).toBe('Gamma');\n // The total counts matches, not the page.\n expect(page.total).toBe(3);\n });\n });\n\n it('filters by an equality operator', async () => {\n await withRepository(async repository => {\n const page = await runRepository(\n repository.load<ContractWidget>({\n filtering: [{ property: 'name', operator: 'eq', value: 'Beta' }],\n }),\n );\n\n expect(page.items).toHaveLength(1);\n expect(page.items[0]?.id).toBe('w-2');\n expect(page.total).toBe(1);\n });\n });\n\n it('filters by a range operator', async () => {\n await withRepository(async repository => {\n const page = await runRepository(\n repository.load<ContractWidget>({\n filtering: [\n { property: 'size', operator: 'between', start: 15, end: 35 },\n ],\n }),\n );\n\n expect(page.items.map(item => item.id)).toEqual(['w-2', 'w-3']);\n });\n });\n\n it('matches `like` case-insensitively on a substring', async () => {\n await withRepository(async repository => {\n const page = await runRepository(\n repository.load<ContractWidget>({\n filtering: [{ property: 'name', operator: 'like', value: 'et' }],\n }),\n );\n\n expect(page.items.map(item => item.id)).toEqual(['w-2']);\n });\n });\n\n it('sorts descending when asked to', async () => {\n await withRepository(async repository => {\n const page = await runRepository(\n repository.load<ContractWidget>({\n sorting: [{ 0: { property: 'size', type: 'desc' } }],\n }),\n );\n\n expect(page.items.map(item => item.size)).toEqual([30, 20, 10]);\n });\n });\n\n it('reads a single entity by id', async () => {\n await withRepository(async repository => {\n const found = await runRepository(\n repository.get<ContractWidget>('w-2'),\n );\n\n expect(found.id).toBe('w-2');\n expect(found.name).toBe('Beta');\n });\n });\n\n it('fails rather than resolving undefined for an unknown id', async () => {\n await withRepository(async repository => {\n const exit = await runRepositoryExit(\n repository.get<ContractWidget>('missing'),\n );\n\n expect(Exit.isFailure(exit)).toBe(true);\n });\n });\n\n it('mints an id when saving an entity that has none', async () => {\n await withRepository(async repository => {\n const created = await runRepository(\n repository.save<ContractWidget>(\n makeContractWidget(undefined, 'Delta', 40),\n ),\n );\n\n expect(created.id).toBeDefined();\n\n const page = await runRepository(repository.load<ContractWidget>({}));\n expect(page.total).toBe(4);\n });\n });\n\n it('overwrites in place when saving an entity that already has an id', async () => {\n await withRepository(async repository => {\n await runRepository(\n repository.save<ContractWidget>(\n makeContractWidget('w-2', 'Renamed', 25),\n ),\n );\n\n const found = await runRepository(\n repository.get<ContractWidget>('w-2'),\n );\n expect(found.name).toBe('Renamed');\n\n const page = await runRepository(repository.load<ContractWidget>({}));\n expect(page.total).toBe(3);\n });\n });\n\n it('deletes by id', async () => {\n await withRepository(async repository => {\n await runRepository(repository.delete<ContractWidget>('w-1'));\n\n const page = await runRepository(repository.load<ContractWidget>({}));\n expect(page.items.map(item => item.id)).toEqual(['w-2', 'w-3']);\n });\n });\n\n it('deletes by entity', async () => {\n await withRepository(async repository => {\n await runRepository(\n repository.delete<ContractWidget>(\n makeContractWidget('w-3', 'Gamma', 30),\n ),\n );\n\n const page = await runRepository(repository.load<ContractWidget>({}));\n expect(page.items.map(item => item.id)).toEqual(['w-1', 'w-2']);\n });\n });\n\n it('treats deleting an unknown id as a no-op', async () => {\n await withRepository(async repository => {\n await runRepository(repository.delete<ContractWidget>('missing'));\n\n const page = await runRepository(repository.load<ContractWidget>({}));\n expect(page.total).toBe(3);\n });\n });\n\n it('loads an empty page from an empty store', async () => {\n await withRepository(async repository => {\n const page = await runRepository(repository.load<ContractWidget>({}));\n\n expect(page.items).toEqual([]);\n expect(page.total).toBe(0);\n }, []);\n });\n });\n};\n"],"names":["accessor","entity","Exit","describe","expect","it","runRepository","runRepositoryExit","key","type","ContractWidget","id","value","name","size","makeContractWidget","widget","describeEntityRepositoryContract","makeRepository","seeded","withRepository","use","seed","repository","read","get","again","toBe","page","load","items","reloaded","returned","save","stored","total","map","item","toEqual","request","pageSize","toHaveLength","filtering","property","operator","start","end","sor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WM,IAAI,CAAiB,CAAC;gBAClEzB,OAAOwB,KAAKE,KAAK,CAACM,GAAG,CAACC,CAAAA,OAAQA,KAAK1B,EAAE,GAAG2B,OAAO,CAAC;oBAAC;oBAAO;iBAAM;YAChE;QACF;QAEAjC,GAAG,4CAA4C;YAC7C,MAAMe,eAAe,OAAMG;gBACzB,MAAMjB,cAAciB,WAAW+B,MAAM,CAAiB;gBAEtD,MAAM1B,OAAO,MAAMtB,cAAciB,WAAWM,IAAI,CAAiB,CAAC;gBAClEzB,OAAOwB,KAAKO,KAAK,EAAER,IAAI,CAAC;YAC1B;QACF;QAEAtB,GAAG,2CAA2C;YAC5C,MAAMe,eAAe,OAAMG;gBACzB,MAAMK,OAAO,MAAMtB,cAAciB,WAAWM,IAAI,CAAiB,CAAC;gBAElEzB,OAAOwB,KAAKE,KAAK,EAAEQ,OAAO,CAAC,EAAE;gBAC7BlC,OAAOwB,KAAKO,KAAK,EAAER,IAAI,CAAC;YAC1B,GAAG,EAAE;QACP;IACF;AACF,EAAE;SAzSF,AAAajB,mBAAAA,cA4BZ"}
@@ -1,3 +1,4 @@
1
1
  export * from './entity-repository.contract.js';
2
+ export * from './saga-store.contract.js';
2
3
  export * from './transaction-ports.contract.js';
3
4
  //# sourceMappingURL=index.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/contracts/index.ts"],"names":[],"mappings":"AAAA,cAAc,iCAAiC,CAAC;AAChD,cAAc,iCAAiC,CAAC"}
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/contracts/index.ts"],"names":[],"mappings":"AAAA,cAAc,iCAAiC,CAAC;AAChD,cAAc,0BAA0B,CAAC;AACzC,cAAc,iCAAiC,CAAC"}
@@ -1,4 +1,5 @@
1
1
  export * from './entity-repository.contract.js';
2
+ export * from './saga-store.contract.js';
2
3
  export * from './transaction-ports.contract.js';
3
4
 
4
5
  //# sourceMappingURL=index.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/contracts/index.ts"],"sourcesContent":["export * from './entity-repository.contract.js';\nexport * from './transaction-ports.contract.js';\n"],"names":[],"mappings":"AAAA,cAAc,kCAAkC;AAChD,cAAc,kCAAkC"}
1
+ {"version":3,"sources":["../../src/contracts/index.ts"],"sourcesContent":["export * from './entity-repository.contract.js';\nexport * from './saga-store.contract.js';\nexport * from './transaction-ports.contract.js';\n"],"names":[],"mappings":"AAAA,cAAc,kCAAkC;AAChD,cAAc,2BAA2B;AACzC,cAAc,kCAAkC"}
@@ -0,0 +1,13 @@
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
@@ -0,0 +1 @@
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"}
@@ -0,0 +1,142 @@
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
@@ -0,0 +1 @@
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,MAAM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AOiD,SAASpB,aAAa,CAAC;gBAAErB,QAAQ;gBAAOO,gBAAgB;YAAE;YACjEf,QAAQ,QAAA,MAAME,IAAIuB,MAAMG,GAAG,CAAC,4BAArB,AAAC,MAA8Bb,cAAc,EAAEqB,IAAI,CAAC;QAC7D;QAEAnC,GAAG,kDAAkD;YACnD,MAAMwB,QAAQ,MAAMD;YACpB,MAAMtB,IAAIuB,MAAMC,KAAK,CAACnB,SAAS,QAAQ;gBAAEI,OAAO;YAAY;YAC5D,MAAMT,IAAIuB,MAAMC,KAAK,CAACnB,SAAS;YAE/BP,OAAO,MAAME,IAAIuB,MAAMyB,cAAc,CAAC,QAAQ7C,WAAW6B,aAAa;YACtElC,OAAO,MAAME,IAAIuB,MAAMyB,cAAc,CAAC,SAAS5C,WAAW4B,aAAa;YACvElC,OACE,MAAME,IAAIuB,MAAMyB,cAAc,CAAC,UAAU7C,WACzC6B,aAAa;QACjB;IACF;AACF,EAAE"}
@@ -1 +1 @@
1
- {"version":3,"file":"entity-repository.d.ts","sourceRoot":"","sources":["../../src/doubles/entity-repository.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,mBAAmB,CAAC;AAC1D,OAAO,EAEL,KAAK,YAAY,EACjB,KAAK,MAAM,EAQZ,MAAM,eAAe,CAAC;AAwHvB,MAAM,WAAW,wBAAyB,SAAQ,gBAAgB;IAChE,uDAAuD;IACvD,QAAQ,CAAC,KAAK,EAAE,MAAM,EAAE,CAAC;IACzB,4DAA4D;IAC5D,IAAI,CAAC,KAAK,EAAE,MAAM,EAAE,GAAG,IAAI,CAAC;IAC5B;;;OAGG;IACH,QAAQ,CAAC,KAAK,EAAE,YAAY,GAAG,IAAI,CAAC;CACrC;AAED;;;;;;;;GAQG;AACH,eAAO,MAAM,4BAA4B,GACvC,OAAM,MAAM,EAAO,KAClB,wBAoFF,CAAC"}
1
+ {"version":3,"file":"entity-repository.d.ts","sourceRoot":"","sources":["../../src/doubles/entity-repository.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,mBAAmB,CAAC;AAC1D,OAAO,EAGL,KAAK,YAAY,EACjB,KAAK,MAAM,EAWZ,MAAM,eAAe,CAAC;AAsJvB,MAAM,WAAW,wBAAyB,SAAQ,gBAAgB;IAChE,uDAAuD;IACvD,QAAQ,CAAC,KAAK,EAAE,MAAM,EAAE,CAAC;IACzB,4DAA4D;IAC5D,IAAI,CAAC,KAAK,EAAE,MAAM,EAAE,GAAG,IAAI,CAAC;IAC5B;;;OAGG;IACH,QAAQ,CAAC,KAAK,EAAE,YAAY,GAAG,IAAI,CAAC;CACrC;AAED;;;;;;;;GAQG;AACH,eAAO,MAAM,4BAA4B,GACvC,OAAM,MAAM,EAAO,KAClB,wBAqGF,CAAC"}
@@ -1,5 +1,4 @@
1
- import { randomUUID } from 'node:crypto';
2
- import { EntifixConnError } from '@entifix/core';
1
+ import { deserializeSingleEntity, EntifixConnError, extractMetaAccessors, serializeEntity } from '@entifix/core';
3
2
  import { Effect } from 'effect';
4
3
  /** Escapes a string so `like`/`nlike` match literally, as the Mongo adapter does. */ const escapeRegex = (value)=>value.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
5
4
  const isFilterGroup = (node)=>!('property' in node) && (node.operator === 'and' || node.operator === 'or');
@@ -80,6 +79,24 @@ const applySorting = (items, sorting)=>{
80
79
  return 0;
81
80
  });
82
81
  };
82
+ /**
83
+ * A copy of `entity` that shares no state with it.
84
+ *
85
+ * Through the entity's own mapping — serialize, then deserialize — because that
86
+ * is what a real adapter does to every record on the way in and out: a caller
87
+ * can never hold the instance the store keeps, and a member the mapping drops
88
+ * (`hidden`, `readonly`) does not survive a save here either. A class that
89
+ * declares no accessors has no mapping to go through, so it is copied member by
90
+ * member instead; plain spec fixtures are the case this keeps working.
91
+ */ const copyOf = (entity)=>{
92
+ const entityConstructor = entity.constructor;
93
+ if (extractMetaAccessors(entityConstructor).length === 0) {
94
+ return Effect.succeed(Object.assign(Object.create(Object.getPrototypeOf(entity)), entity));
95
+ }
96
+ // `undefined` only comes back for `null`/`undefined` input, and
97
+ // `serializeEntity` always hands over an object.
98
+ return deserializeSingleEntity(entityConstructor, serializeEntity(entityConstructor, entity));
99
+ };
83
100
  /**
84
101
  * In-memory {@link EntityRepository}: the default double for anything that
85
102
  * depends on persistence.
@@ -107,30 +124,36 @@ const applySorting = (items, sorting)=>{
107
124
  const page = (_request_page = request.page) != null ? _request_page : 1;
108
125
  const pageSize = (_request_pageSize = request.pageSize) != null ? _request_pageSize : 10;
109
126
  const start = (page - 1) * pageSize;
110
- return Effect.succeed({
111
- items: matched.slice(start, start + pageSize),
112
- total: matched.length,
113
- request
114
- });
127
+ return Effect.forEach(matched.slice(start, start + pageSize), copyOf).pipe(Effect.map((copies)=>({
128
+ items: copies,
129
+ total: matched.length,
130
+ request
131
+ })));
115
132
  });
116
133
  const get = (id)=>guard(()=>{
117
134
  const found = items.find((item)=>item.id === id);
118
135
  return found === undefined ? Effect.fail(new EntifixConnError('Entity not found', undefined, {
119
136
  id
120
- })) : Effect.succeed(found);
137
+ })) : copyOf(found);
121
138
  });
122
139
  const save = (entity)=>guard(()=>{
123
140
  var _entity_id;
124
141
  // A create arrives without an id, so the store mints one — same rule the
125
- // Mongo adapter follows.
126
- entity.id = (_entity_id = entity.id) != null ? _entity_id : randomUUID();
127
- const index = items.findIndex((item)=>item.id === entity.id);
128
- if (index === -1) {
129
- items.push(entity);
130
- } else {
131
- items[index] = entity;
132
- }
133
- return Effect.succeed(entity);
142
+ // Mongo adapter follows. The Web Crypto global rather than `node:crypto`,
143
+ // because a browser bundle cannot resolve a `node:` import and an example
144
+ // with no backend runs this repository in the page.
145
+ entity.id = (_entity_id = entity.id) != null ? _entity_id : globalThis.crypto.randomUUID();
146
+ // The store keeps its own copy and hands back another, so neither the
147
+ // caller's instance nor the returned one can change the record without a
148
+ // second save — which a real adapter guarantees by construction.
149
+ return copyOf(entity).pipe(Effect.tap((stored)=>{
150
+ const index = items.findIndex((item)=>item.id === stored.id);
151
+ if (index === -1) {
152
+ items.push(stored);
153
+ } else {
154
+ items[index] = stored;
155
+ }
156
+ }), Effect.flatMap(copyOf));
134
157
  });
135
158
  const remove = (entityOrId)=>guard(()=>{
136
159
  const id = entityOrId != null && typeof entityOrId === 'object' ? entityOrId.id : entityOrId;
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/doubles/entity-repository.ts"],"sourcesContent":["import { randomUUID } from 'node:crypto';\n\nimport type { EntityRepository } from '@entifix/business';\nimport {\n EntifixConnError,\n type EntifixError,\n type Entity,\n type EntityFilter,\n type EntityFiltering,\n type EntityId,\n type EntityLoadRequest,\n type EntityPage,\n type EntitySorting,\n type FilterGroup,\n} from '@entifix/core';\nimport { Effect } from 'effect';\n\n/** Escapes a string so `like`/`nlike` match literally, as the Mongo adapter does. */\nconst escapeRegex = (value: string): string =>\n value.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&');\n\nconst isFilterGroup = <TEntity extends Entity>(\n node: EntityFilter<TEntity> | FilterGroup<TEntity>,\n): node is FilterGroup<TEntity> =>\n !('property' in node) && (node.operator === 'and' || node.operator === 'or');\n\nconst compareValues = (left: unknown, right: unknown): number => {\n if (left === right) return 0;\n // Mongo sorts missing values below present ones.\n if (left == null) return -1;\n if (right == null) return 1;\n if (typeof left === 'number' && typeof right === 'number') {\n return left - right;\n }\n if (left instanceof Date && right instanceof Date) {\n return left.getTime() - right.getTime();\n }\n return String(left).localeCompare(String(right));\n};\n\nconst matchesNode = <TEntity extends Entity>(\n item: TEntity,\n node: EntityFilter<TEntity> | FilterGroup<TEntity>,\n): boolean => {\n if (isFilterGroup(node)) {\n return node.operator === 'or'\n ? node.values.some(child => matchesNode(item, child))\n : node.values.every(child => matchesNode(item, child));\n }\n\n const actual = (item as Record<string, unknown>)[String(node.property)];\n\n switch (node.operator) {\n case 'eq':\n return actual === node.value;\n case 'ne':\n return actual !== node.value;\n case 'gt':\n return compareValues(actual, node.value) > 0;\n case 'gte':\n return compareValues(actual, node.value) >= 0;\n case 'lt':\n return compareValues(actual, node.value) < 0;\n case 'lte':\n return compareValues(actual, node.value) <= 0;\n case 'in':\n return node.values.includes(actual as TEntity[keyof TEntity]);\n case 'nin':\n return !node.values.includes(actual as TEntity[keyof TEntity]);\n case 'between':\n return (\n compareValues(actual, node.start) >= 0 &&\n compareValues(actual, node.end) <= 0\n );\n case 'nbetween':\n return !(\n compareValues(actual, node.start) >= 0 &&\n compareValues(actual, node.end) <= 0\n );\n case 'like':\n return new RegExp(escapeRegex(node.value), 'i').test(String(actual));\n case 'nlike':\n return !new RegExp(escapeRegex(node.value), 'i').test(String(actual));\n case 'isNull':\n return actual == null;\n case 'isNotNull':\n return actual != null;\n default: {\n // Exhaustiveness guard — a new operator must be handled explicitly.\n const never: never = node;\n return never;\n }\n }\n};\n\nconst applyFiltering = <TEntity extends Entity>(\n items: TEntity[],\n filtering?: EntityFiltering<TEntity>[],\n): TEntity[] => {\n if (!filtering || filtering.length === 0) return items;\n // Every top-level entry is combined with `and`, matching `translateFiltering`.\n const nodes = filtering.flatMap(entry =>\n Array.isArray(entry) ? entry : [entry],\n );\n return items.filter(item => nodes.every(node => matchesNode(item, node)));\n};\n\nconst applySorting = <TEntity extends Entity>(\n items: TEntity[],\n sorting?: EntitySorting<TEntity>[],\n): TEntity[] => {\n if (!sorting || sorting.length === 0) return items;\n\n const entries = sorting.flatMap(record =>\n Object.keys(record)\n .map(Number)\n .sort((left, right) => left - right)\n .map(priority => record[priority])\n .filter(entry => entry != null),\n );\n\n return [...items].sort((left, right) => {\n for (const entry of entries) {\n const property = String(entry.property);\n const result = compareValues(\n (left as Record<string, unknown>)[property],\n (right as Record<string, unknown>)[property],\n );\n if (result !== 0) return entry.type === 'desc' ? -result : result;\n }\n return 0;\n });\n};\n\nexport interface InMemoryEntityRepository extends EntityRepository {\n /** Everything currently stored, in insertion order. */\n readonly items: Entity[];\n /** Replaces the contents, discarding whatever was there. */\n seed(items: Entity[]): void;\n /**\n * Makes the next call to any method fail with `error`, so error branches are\n * reachable without reaching for a mocking library.\n */\n failNext(error: EntifixError): void;\n}\n\n/**\n * In-memory {@link EntityRepository}: the default double for anything that\n * depends on persistence.\n *\n * Its semantics deliberately mirror `makeMongoRepository` — same filtering and\n * sorting rules, same 1-based paging with a default page size of 10, same\n * \"entity not found\" failure, same id minting on create — and\n * `describeEntityRepositoryContract` holds both to that shared contract.\n */\nexport const makeInMemoryEntityRepository = (\n seed: Entity[] = [],\n): InMemoryEntityRepository => {\n let items = [...seed];\n let pendingFailure: EntifixError | undefined;\n\n /** Consumes a queued failure, if one was armed. */\n const guard = <TValue>(\n run: () => Effect.Effect<TValue, EntifixError>,\n ): Effect.Effect<TValue, EntifixError> => {\n if (pendingFailure !== undefined) {\n const failure = pendingFailure;\n pendingFailure = undefined;\n return Effect.fail(failure);\n }\n return run();\n };\n\n const load = <TEntity extends Entity>(request: EntityLoadRequest<TEntity>) =>\n guard(() => {\n const matched = applySorting(\n applyFiltering(items as TEntity[], request.filtering),\n request.sorting,\n );\n const page = request.page ?? 1;\n const pageSize = request.pageSize ?? 10;\n const start = (page - 1) * pageSize;\n\n return Effect.succeed({\n items: matched.slice(start, start + pageSize),\n total: matched.length,\n request,\n } satisfies EntityPage<TEntity>);\n });\n\n const get = <TEntity extends Entity>(id: EntityId) =>\n guard(() => {\n const found = items.find(item => item.id === id);\n return found === undefined\n ? Effect.fail(\n new EntifixConnError('Entity not found', undefined, { id }),\n )\n : Effect.succeed(found as TEntity);\n });\n\n const save = <TEntity extends Entity>(entity: TEntity) =>\n guard(() => {\n // A create arrives without an id, so the store mints one — same rule the\n // Mongo adapter follows.\n entity.id = entity.id ?? randomUUID();\n const index = items.findIndex(item => item.id === entity.id);\n if (index === -1) {\n items.push(entity);\n } else {\n items[index] = entity;\n }\n return Effect.succeed(entity);\n });\n\n const remove = <TEntity extends Entity>(entityOrId: EntityId | TEntity) =>\n guard(() => {\n const id =\n entityOrId != null && typeof entityOrId === 'object'\n ? entityOrId.id\n : entityOrId;\n items = items.filter(item => item.id !== id);\n return Effect.succeed(undefined);\n });\n\n return {\n load,\n get,\n save,\n delete: remove,\n get items() {\n return items;\n },\n seed: (next: Entity[]) => {\n items = [...next];\n },\n failNext: (error: EntifixError) => {\n pendingFailure = error;\n },\n // Each method closes over its own state, so nothing is required from the\n // Effect environment; that is assignable to the interface's channel.\n } as unknown as InMemoryEntityRepository;\n};\n"],"names":["randomUUID","EntifixConnError","Effect","escapeRegex","value","replace","isFilterGroup","node","operator","compareValues","left","right","Date","getTime","String","localeCompare","matchesNode","item","values","some","child","every","actual","property","includes","start","end","RegExp","test","never","applyFiltering","items","filtering","length","nodes","flatMap","entry","Array","isArray","filter","applySorting","sorting","entries","record","Object","keys","map","Number","sort","priority","result","type","makeInMemoryEntityRepository","seed","pendingFailure","guard","run","undefined","failure","fail","load","request","matched","page","pageSize","succeed","slice","total","get","id","found","find","save","entity","index","findIndex","push","remove","entityOrId","delete","next","failNext","error"],"mappings":"AAAA,SAASA,UAAU,QAAQ,cAAc;AAGzC,SACEC,gBAAgB,QAUX,gBAAgB;AACvB,SAASC,MAAM,QAAQ,SAAS;AAEhC,mFAAmF,GACnF,MAAMC,cAAc,CAACC,QACnBA,MAAMC,OAAO,CAAC,uBAAuB;AAEvC,MAAMC,gBAAgB,CACpBC,OAEA,CAAE,CAAA,cAAcA,IAAG,KAAOA,CAAAA,KAAKC,QAAQ,KAAK,SAASD,KAAKC,QAAQ,KAAK,IAAG;AAE5E,MAAMC,gBAAgB,CAACC,MAAeC;IACpC,IAAID,SAASC,OAAO,OAAO;IAC3B,iDAAiD;IACjD,IAAID,QAAQ,MAAM,OAAO,CAAC;IAC1B,IAAIC,SAAS,MAAM,OAAO;IAC1B,IAAI,OAAOD,SAAS,YAAY,OAAOC,UAAU,UAAU;QACzD,OAAOD,OAAOC;IAChB;IACA,IAAID,gBAAgBE,QAAQD,iBAAiBC,MAAM;QACjD,OAAOF,KAAKG,OA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AAC2C,MAAM,GAAGD;YACjB;YACA,OAAOvE,OAAO+D,OAAO,CAACQ;QACxB;IAEF,MAAMI,SAAS,CAAyBC,aACtCvB,MAAM;YACJ,MAAMc,KACJS,cAAc,QAAQ,OAAOA,eAAe,WACxCA,WAAWT,EAAE,GACbS;YACN/C,QAAQA,MAAMQ,MAAM,CAACtB,CAAAA,OAAQA,KAAKoD,EAAE,KAAKA;YACzC,OAAOnE,OAAO+D,OAAO,CAACR;QACxB;IAEF,OAAO;QACLG;QACAQ;QACAI;QACAO,QAAQF;QACR,IAAI9C,SAAQ;YACV,OAAOA;QACT;QACAsB,MAAM,CAAC2B;YACLjD,QAAQ;mBAAIiD;aAAK;QACnB;QACAC,UAAU,CAACC;YACT5B,iBAAiB4B;QACnB;IAGF;AACF,EAAE"}
1
+ {"version":3,"sources":["../../src/doubles/entity-repository.ts"],"sourcesContent":["import type { EntityRepository } from '@entifix/business';\nimport {\n deserializeSingleEntity,\n EntifixConnError,\n type EntifixError,\n type Entity,\n type EntityConstructor,\n type EntityFilter,\n type EntityFiltering,\n type EntityId,\n type EntityLoadRequest,\n type EntityPage,\n type EntitySorting,\n extractMetaAccessors,\n type FilterGroup,\n serializeEntity,\n} from '@entifix/core';\nimport { Effect } from 'effect';\n\n/** Escapes a string so `like`/`nlike` match literally, as the Mongo adapter does. */\nconst escapeRegex = (value: string): string =>\n value.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&');\n\nconst isFilterGroup = <TEntity extends Entity>(\n node: EntityFilter<TEntity> | FilterGroup<TEntity>,\n): node is FilterGroup<TEntity> =>\n !('property' in node) && (node.operator === 'and' || node.operator === 'or');\n\nconst compareValues = (left: unknown, right: unknown): number => {\n if (left === right) return 0;\n // Mongo sorts missing values below present ones.\n if (left == null) return -1;\n if (right == null) return 1;\n if (typeof left === 'number' && typeof right === 'number') {\n return left - right;\n }\n if (left instanceof Date && right instanceof Date) {\n return left.getTime() - right.getTime();\n }\n return String(left).localeCompare(String(right));\n};\n\nconst matchesNode = <TEntity extends Entity>(\n item: TEntity,\n node: EntityFilter<TEntity> | FilterGroup<TEntity>,\n): boolean => {\n if (isFilterGroup(node)) {\n return node.operator === 'or'\n ? node.values.some(child => matchesNode(item, child))\n : node.values.every(child => matchesNode(item, child));\n }\n\n const actual = (item as Record<string, unknown>)[String(node.property)];\n\n switch (node.operator) {\n case 'eq':\n return actual === node.value;\n case 'ne':\n return actual !== node.value;\n case 'gt':\n return compareValues(actual, node.value) > 0;\n case 'gte':\n return compareValues(actual, node.value) >= 0;\n case 'lt':\n return compareValues(actual, node.value) < 0;\n case 'lte':\n return compareValues(actual, node.value) <= 0;\n case 'in':\n return node.values.includes(actual as TEntity[keyof TEntity]);\n case 'nin':\n return !node.values.includes(actual as TEntity[keyof TEntity]);\n case 'between':\n return (\n compareValues(actual, node.start) >= 0 &&\n compareValues(actual, node.end) <= 0\n );\n case 'nbetween':\n return !(\n compareValues(actual, node.start) >= 0 &&\n compareValues(actual, node.end) <= 0\n );\n case 'like':\n return new RegExp(escapeRegex(node.value), 'i').test(String(actual));\n case 'nlike':\n return !new RegExp(escapeRegex(node.value), 'i').test(String(actual));\n case 'isNull':\n return actual == null;\n case 'isNotNull':\n return actual != null;\n default: {\n // Exhaustiveness guard — a new operator must be handled explicitly.\n const never: never = node;\n return never;\n }\n }\n};\n\nconst applyFiltering = <TEntity extends Entity>(\n items: TEntity[],\n filtering?: EntityFiltering<TEntity>[],\n): TEntity[] => {\n if (!filtering || filtering.length === 0) return items;\n // Every top-level entry is combined with `and`, matching `translateFiltering`.\n const nodes = filtering.flatMap(entry =>\n Array.isArray(entry) ? entry : [entry],\n );\n return items.filter(item => nodes.every(node => matchesNode(item, node)));\n};\n\nconst applySorting = <TEntity extends Entity>(\n items: TEntity[],\n sorting?: EntitySorting<TEntity>[],\n): TEntity[] => {\n if (!sorting || sorting.length === 0) return items;\n\n const entries = sorting.flatMap(record =>\n Object.keys(record)\n .map(Number)\n .sort((left, right) => left - right)\n .map(priority => record[priority])\n .filter(entry => entry != null),\n );\n\n return [...items].sort((left, right) => {\n for (const entry of entries) {\n const property = String(entry.property);\n const result = compareValues(\n (left as Record<string, unknown>)[property],\n (right as Record<string, unknown>)[property],\n );\n if (result !== 0) return entry.type === 'desc' ? -result : result;\n }\n return 0;\n });\n};\n\n/**\n * A copy of `entity` that shares no state with it.\n *\n * Through the entity's own mapping — serialize, then deserialize — because that\n * is what a real adapter does to every record on the way in and out: a caller\n * can never hold the instance the store keeps, and a member the mapping drops\n * (`hidden`, `readonly`) does not survive a save here either. A class that\n * declares no accessors has no mapping to go through, so it is copied member by\n * member instead; plain spec fixtures are the case this keeps working.\n */\nconst copyOf = <TEntity extends Entity>(\n entity: TEntity,\n): Effect.Effect<TEntity, EntifixError> => {\n const entityConstructor = entity.constructor as EntityConstructor<TEntity>;\n if (extractMetaAccessors(entityConstructor).length === 0) {\n return Effect.succeed(\n Object.assign(\n Object.create(Object.getPrototypeOf(entity) as object) as TEntity,\n entity,\n ),\n );\n }\n // `undefined` only comes back for `null`/`undefined` input, and\n // `serializeEntity` always hands over an object.\n return deserializeSingleEntity(\n entityConstructor,\n serializeEntity(entityConstructor, entity),\n ) as Effect.Effect<TEntity, EntifixError>;\n};\n\nexport interface InMemoryEntityRepository extends EntityRepository {\n /** Everything currently stored, in insertion order. */\n readonly items: Entity[];\n /** Replaces the contents, discarding whatever was there. */\n seed(items: Entity[]): void;\n /**\n * Makes the next call to any method fail with `error`, so error branches are\n * reachable without reaching for a mocking library.\n */\n failNext(error: EntifixError): void;\n}\n\n/**\n * In-memory {@link EntityRepository}: the default double for anything that\n * depends on persistence.\n *\n * Its semantics deliberately mirror `makeMongoRepository` — same filtering and\n * sorting rules, same 1-based paging with a default page size of 10, same\n * \"entity not found\" failure, same id minting on create — and\n * `describeEntityRepositoryContract` holds both to that shared contract.\n */\nexport const makeInMemoryEntityRepository = (\n seed: Entity[] = [],\n): InMemoryEntityRepository => {\n let items = [...seed];\n let pendingFailure: EntifixError | undefined;\n\n /** Consumes a queued failure, if one was armed. */\n const guard = <TValue>(\n run: () => Effect.Effect<TValue, EntifixError>,\n ): Effect.Effect<TValue, EntifixError> => {\n if (pendingFailure !== undefined) {\n const failure = pendingFailure;\n pendingFailure = undefined;\n return Effect.fail(failure);\n }\n return run();\n };\n\n const load = <TEntity extends Entity>(request: EntityLoadRequest<TEntity>) =>\n guard(() => {\n const matched = applySorting(\n applyFiltering(items as TEntity[], request.filtering),\n request.sorting,\n );\n const page = request.page ?? 1;\n const pageSize = request.pageSize ?? 10;\n const start = (page - 1) * pageSize;\n\n return Effect.forEach(\n matched.slice(start, start + pageSize),\n copyOf,\n ).pipe(\n Effect.map(\n copies =>\n ({\n items: copies,\n total: matched.length,\n request,\n }) satisfies EntityPage<TEntity>,\n ),\n );\n });\n\n const get = <TEntity extends Entity>(id: EntityId) =>\n guard(() => {\n const found = items.find(item => item.id === id);\n return found === undefined\n ? Effect.fail(\n new EntifixConnError('Entity not found', undefined, { id }),\n )\n : copyOf(found as TEntity);\n });\n\n const save = <TEntity extends Entity>(entity: TEntity) =>\n guard(() => {\n // A create arrives without an id, so the store mints one — same rule the\n // Mongo adapter follows. The Web Crypto global rather than `node:crypto`,\n // because a browser bundle cannot resolve a `node:` import and an example\n // with no backend runs this repository in the page.\n entity.id = entity.id ?? globalThis.crypto.randomUUID();\n // The store keeps its own copy and hands back another, so neither the\n // caller's instance nor the returned one can change the record without a\n // second save — which a real adapter guarantees by construction.\n return copyOf(entity).pipe(\n Effect.tap(stored => {\n const index = items.findIndex(item => item.id === stored.id);\n if (index === -1) {\n items.push(stored);\n } else {\n items[index] = stored;\n }\n }),\n Effect.flatMap(copyOf),\n );\n });\n\n const remove = <TEntity extends Entity>(entityOrId: EntityId | TEntity) =>\n guard(() => {\n const id =\n entityOrId != null && typeof entityOrId === 'object'\n ? entityOrId.id\n : entityOrId;\n items = items.filter(item => item.id !== id);\n return Effect.succeed(undefined);\n });\n\n return {\n load,\n get,\n save,\n delete: remove,\n get items() {\n return items;\n },\n seed: (next: Entity[]) => {\n items = [...next];\n },\n failNext: (error: EntifixError) => {\n pendingFailure = error;\n },\n // Each method closes over its own state, so nothing is required from the\n // Effect environment; that is assignable to the interface's channel.\n } as unknown as InMemoryEntityRepository;\n};\n"],"names":["deserializeSingleEntity","EntifixConnError","extractMetaAccessors","serializeEntity","Effect","escapeRegex","value","replace","isFilterGroup","node","operator","compareValues","left","right","Date","getTime","String","localeCompare","matchesNode","item","values","some","child","every","actual","property","includes","start","end","RegExp","test","never","applyFiltering","items","filtering","length","nodes","flatMap","entry","Array","isArray","filter","applySorting","sorting","entries","record","Object","keys","map","Number","sort","priority","result","type","copyOf","entity","entityConstructor","succeed","assign","create","getPrototypeOf","makeInMemoryEntityRepository","seed","pendingFailure","guard","run","undefined","failure","fail","load","request","matched","page","pageSize","forEach","slice","pipe","copies","total","get","id","found","find","save","globalThis","crypto","randomUUID","tap","stored","index","findIndex","push","remove","entityOrId","delete","next","failNext","error"],"mappings":"AACA,SACEA,uBAAuB,EACvBC,gBAAgB,EAUhBC,oBAAoB,EAEpBC,eAAe,QACV,gBAAgB;AACvB,SAASC,MAAM,QAAQ,SAAS;AAEhC,mFAAmF,GACnF,MAAMC,cAAc,CAACC,QACnBA,MAAMC,OAAO,CAAC,uBAAuB;AAEvC,MAAMC,gBAAgB,CACpBC,OAEA,CAAE,CAAA,cAAcA,IAAG,KAAOA,CAAAA,KAAKC,QAAQ,KAAK,SAASD,KAAKC,QAAQ,KAAK,IAAG;AAE5E,MAAMC,gBAAgB,CAACC,MAAeC;IACpC,IAAID,SAASC,OAAO,OAAO;IAC3B,iDAAiD;IACjD,IAAID,QAAQ,MAAM,OAAO,CAAC;IAC1B,IAAIC,SAAS,MAAM,OAAO;IAC1B,IAAI,OAAOD,SAAS,YAAY,OAAOC,UAAU,UAAU;QACzD,OAAOD,OAAOC;IAChB;IACA,IAAID,gBAAgBE,QAAQD,iBAAiBC,MAAM;QACjD,OAAOF,KAAKG,OAAO,KAAKF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B,oBAAoBiE,WAAW;gBAAEc;YAAG,MAE3D1B,OAAO2B;QACb;IAEF,MAAME,OAAO,CAAyB5B,SACpCS,MAAM;gBAKQT;YAJZ,yEAAyE;YACzE,0EAA0E;YAC1E,0EAA0E;YAC1E,oDAAoD;YACpDA,OAAOyB,EAAE,IAAGzB,aAAAA,OAAOyB,EAAE,YAATzB,aAAa6B,WAAWC,MAAM,CAACC,UAAU;YACrD,sEAAsE;YACtE,yEAAyE;YACzE,iEAAiE;YACjE,OAAOhC,OAAOC,QAAQqB,IAAI,CACxBxE,OAAOmF,GAAG,CAACC,CAAAA;gBACT,MAAMC,QAAQxD,MAAMyD,SAAS,CAACvE,CAAAA,OAAQA,KAAK6D,EAAE,KAAKQ,OAAOR,EAAE;gBAC3D,IAAIS,UAAU,CAAC,GAAG;oBAChBxD,MAAM0D,IAAI,CAACH;gBACb,OAAO;oBACLvD,KAAK,CAACwD,MAAM,GAAGD;gBACjB;YACF,IACApF,OAAOiC,OAAO,CAACiB;QAEnB;IAEF,MAAMsC,SAAS,CAAyBC,aACtC7B,MAAM;YACJ,MAAMgB,KACJa,cAAc,QAAQ,OAAOA,eAAe,WACxCA,WAAWb,EAAE,GACba;YACN5D,QAAQA,MAAMQ,MAAM,CAACtB,CAAAA,OAAQA,KAAK6D,EAAE,KAAKA;YACzC,OAAO5E,OAAOqD,OAAO,CAACS;QACxB;IAEF,OAAO;QACLG;QACAU;QACAI;QACAW,QAAQF;QACR,IAAI3D,SAAQ;YACV,OAAOA;QACT;QACA6B,MAAM,CAACiC;YACL9D,QAAQ;mBAAI8D;aAAK;QACnB;QACAC,UAAU,CAACC;YACTlC,iBAAiBkC;QACnB;IAGF;AACF,EAAE"}
@@ -1,5 +1,5 @@
1
1
  import { type DomainEvent, type EntifixError } from '@entifix/core';
2
- import type { EventBus, LockService, SequenceService, TransactionInbox } from '@entifix/transactions';
2
+ import type { EventBus, LockService, SagaInstance, SagaStore, SequenceService, TransactionInbox } from '@entifix/transactions';
3
3
  import { Effect } from 'effect';
4
4
  export interface InMemoryLockService extends LockService {
5
5
  /** Keys currently held, in acquisition order. */
@@ -67,4 +67,15 @@ export declare const makeInMemoryInboxes: () => {
67
67
  eventId: string;
68
68
  }[];
69
69
  };
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;
70
81
  //# 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,EACL,KAAK,WAAW,EAEhB,KAAK,YAAY,EAGlB,MAAM,eAAe,CAAC;AACvB,OAAO,KAAK,EACV,QAAQ,EAER,WAAW,EACX,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,mBAsC1C,CAAC;AAEF,MAAM,WAAW,uBAAwB,SAAQ,eAA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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,mBAsC1C,CAAC;AAEF,MAAM,WAAW,uBAAwB,SAAQ,eAAe;IAC9D,6DAA6D;IAC7D,QAAQ,CAAC,MAAM,EAAE,QAAQ,CAAC,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC,CAAC;CACnD;AAED;;;GAGG;AACH,eAAO,MAAM,2BAA2B,QAAO,uBAc9C,CAAC;AAEF,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,YAAY,CAAC,CAAC;IAC/D,wEAAwE;IACxE,eAAe,IAAI,IAAI,CAAC;CACzB;AAED;;;;GAIG;AACH,eAAO,MAAM,qBAAqB,QAAO,iBA4CxC,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;AAEF,MAAM,WAAW,iBAAkB,SAAQ,SAAS;IAClD,4EAA4E;IAC5E,QAAQ,CAAC,SAAS,EAAE,SAAS,YAAY,EAAE,CAAC;CAC7C;AAED;;;;;GAKG;AACH,eAAO,MAAM,qBAAqB,QAAO,iBAwExC,CAAC"}
@@ -1,3 +1,4 @@
1
+ import { _ as _extends } from "@swc/helpers/_/_extends";
1
2
  import { EntifixConnError, EntifixLockError, matchesEventPattern } from '@entifix/core';
2
3
  import { Effect } from 'effect';
3
4
  /**
@@ -141,5 +142,72 @@ import { Effect } from 'effect';
141
142
  }
142
143
  };
143
144
  };
145
+ /**
146
+ * In-memory {@link SagaStore}, with the Mongo adapter's semantics: `start`
147
+ * never overwrites, outcomes append, and a resume claim only takes an
148
+ * unfinished instance whose `updatedAt` is past the deadline — counting the
149
+ * attempt and re-stamping it, so the next sweep does not find it again.
150
+ */ export const makeInMemorySagaStore = ()=>{
151
+ const instances = new Map();
152
+ const stamp = ()=>new Date().toISOString();
153
+ const unfinished = (entry)=>entry.state === 'RUNNING' || entry.state === 'COMPENSATING';
154
+ const pastDeadline = (entry, olderThanMs)=>entry.updatedAt < new Date(Date.now() - olderThanMs).toISOString();
155
+ const update = (sagaId, change)=>Effect.sync(()=>{
156
+ const current = instances.get(sagaId);
157
+ if (current !== undefined) {
158
+ instances.set(sagaId, _extends({}, change(current), {
159
+ updatedAt: stamp()
160
+ }));
161
+ }
162
+ });
163
+ return {
164
+ start: (started)=>Effect.sync(()=>{
165
+ if (!instances.has(started.sagaId)) {
166
+ instances.set(started.sagaId, _extends({}, started, {
167
+ updatedAt: stamp()
168
+ }));
169
+ }
170
+ }),
171
+ beginStep: (sagaId, stepIndex)=>update(sagaId, (entry)=>_extends({}, entry, {
172
+ stepIndex
173
+ })),
174
+ recordOutcome: (sagaId, outcome)=>update(sagaId, (entry)=>_extends({}, entry, {
175
+ outcomes: [
176
+ ...entry.outcomes,
177
+ outcome
178
+ ]
179
+ })),
180
+ settle: (sagaId, state, error)=>update(sagaId, (entry)=>_extends({}, entry, {
181
+ state,
182
+ error
183
+ })),
184
+ markCompensated: (sagaId, stepId)=>update(sagaId, (entry)=>_extends({}, entry, {
185
+ outcomes: entry.outcomes.map((outcome)=>outcome.stepId === stepId ? _extends({}, outcome, {
186
+ compensated: true
187
+ }) : outcome)
188
+ })),
189
+ get: (sagaId)=>Effect.sync(()=>instances.get(sagaId)),
190
+ findStale: (olderThanMs)=>Effect.sync(()=>[
191
+ ...instances.values()
192
+ ].filter((entry)=>unfinished(entry) && pastDeadline(entry, olderThanMs))),
193
+ claimForResume: (sagaId, olderThanMs)=>Effect.sync(()=>{
194
+ const current = instances.get(sagaId);
195
+ if (current === undefined || !unfinished(current) || !pastDeadline(current, olderThanMs)) {
196
+ return undefined;
197
+ }
198
+ const claimed = _extends({}, current, {
199
+ resumeAttempts: current.resumeAttempts + 1,
200
+ updatedAt: stamp()
201
+ });
202
+ instances.set(sagaId, claimed);
203
+ return claimed;
204
+ }),
205
+ get instances () {
206
+ return [
207
+ ...instances.values()
208
+ ];
209
+ }
210
+ };
211
+ };
144
212
 
145
213
  //# sourceMappingURL=transaction-ports.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/doubles/transaction-ports.ts"],"sourcesContent":["import {\n type DomainEvent,\n EntifixConnError,\n type EntifixError,\n EntifixLockError,\n matchesEventPattern,\n} from '@entifix/core';\nimport type {\n EventBus,\n LockHandle,\n LockService,\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 EntifixLockError} — 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(\n new EntifixLockError(`Could not acquire lock \"${key}\"`, undefined, {\n key,\n }),\n );\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, EntifixError>;\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, EntifixError>;\n }> = [];\n let failNext = false;\n\n return {\n publish: event =>\n Effect.suspend(() => {\n if (failNext) {\n failNext = false;\n return Effect.fail(\n new EntifixConnError('Event bus unavailable', undefined, {\n eventId: event.id,\n }),\n );\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":["EntifixConnError","EntifixLockError","matchesEventPattern","Effect","makeInMemoryLockService","tokens","Map","contended","Set","log","counter","acquire","key","suspend","has","fail","undefined","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","eventId","id","void","subscribe","subscription","pattern","deliver","forEach","filter","discard","failNextPublish","makeInMemoryInboxes","claimed","for","consumer","claim","JSON","stringify","claims","map","parse"],"mappings":"AAAA,SAEEA,gBAAgB,EAEhBC,gBAAgB,EAChBC,mBAAmB,Q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MAAMgD,KAAKC,SAAS,CAAC;4BAACH;4BAAUd;yBAAQ;wBAC9C,IAAIY,QAAQ1C,GAAG,CAACF,MAAM,OAAO;wBAC7B4C,QAAQ1B,GAAG,CAAClB;wBACZ,OAAO;oBACT;YACJ,CAAA;QACA,IAAIkD,UAA2D;YAC7D,OAAO;mBAAIN;aAAQ,CAACO,GAAG,CAACnD,CAAAA;gBACtB,MAAM,CAAC8C,UAAUd,QAAQ,GAAGgB,KAAKI,KAAK,CAACpD;gBACvC,OAAO;oBAAE8C;oBAAUd;gBAAQ;YAC7B;QACF;IACF;AACF,EAAE"}
1
+ {"version":3,"sources":["../../src/doubles/transaction-ports.ts"],"sourcesContent":["import {\n type DomainEvent,\n EntifixConnError,\n type EntifixError,\n EntifixLockError,\n matchesEventPattern,\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 EntifixLockError} — 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(\n new EntifixLockError(`Could not acquire lock \"${key}\"`, undefined, {\n key,\n }),\n );\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, EntifixError>;\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, EntifixError>;\n }> = [];\n let failNext = false;\n\n return {\n publish: event =>\n Effect.suspend(() => {\n if (failNext) {\n failNext = false;\n return Effect.fail(\n new EntifixConnError('Event bus unavailable', undefined, {\n eventId: event.id,\n }),\n );\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":["EntifixConnError","EntifixLockError","matchesEventPattern","Effect","makeInMemoryLockService","tokens","Map","contended","Set","log","counter","acquire","key","suspend","has","fail","undefined","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","eventId","id","void","subscribe","subscription","pattern","deliver","forEach","filter","discard","failNextPublish","makeInMemoryInboxes","claimed","for","consumer","claim","JSON","stringify","claims","map","parse","makeInMemorySagaStore","instances","stamp","Date","toISOString","unfinished","entry","state","pastDeadline","olderThanMs","updatedAt","now","update","sagaId","change","current","start","started","beginStep","stepIndex","recordOutcome","outcome","outcomes","settle","error","markCompensated","stepId","compensated","findStale","claimForResume","resumeAttempts"],"mappings":";AAAA,SAEEA,gBAAgB,EAEhBC,gBAAgB,EAChBC,mBAAmB,QACd,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,CAChB,IAAId,iBAAiB,CAAC,wBAAwB,EAAEW,IAAI,CAAC,CAAC,EAAEI,WAAW;wBACjEJ;oBACF;gBAEJ;gBACA,MAAMK,QAAQ,CAAC,MAAM,EAAGP,WAAW,GAAI;gBACvCL,OAAOa,GAAG,CAACN,KAAKK;gBAChBR,IAAIU,IAAI,CAAC;oBAAEC,QAAQ;oBAAWR;gBAAI;gBAClC,OAAOT,OAAOkB,OAAO,CAAC;oBAAET;oBAAKK;gBAAM;YACrC;QACFK,SAAS,CAACC,SACRpB,OAAOqB,IAAI,CAAC;gBACV,IAAInB,OAAOoB,GAAG,CAACF,OAAOX,GAAG,MAAMW,OAAON,KAAK,EAAE;oBAC3CZ,OAAOqB,MAAM,CAACH,OAAOX,GAAG;oBACxBH,IAAIU,IAAI,CAAC;wBAAEC,QAAQ;wBAAWR,KAAKW,OAAOX,GAAG;oBAAC;gBAChD;YACF;QACF,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MAAM,CAAC,MAAM,EAAE,QAAQ,EAAE,CAAM,KACpC,WAohBF,CAAC"}
@@ -358,13 +358,20 @@ const matches = (doc, query)=>Object.entries(query).every(([field, condition])=>
358
358
  * implements is that an absolute-value write loses updates, so a fake that
359
359
  * computed the new total from a value it had already read would model the
360
360
  * bug rather than the fix.
361
+ *
362
+ * `$push` appends, and a `$set` key of the form `field.$[name].member`
363
+ * applies to every element of `field` that `options.arrayFilters` selects —
364
+ * the pair a saga store records an outcome with and later flags one
365
+ * compensated. Both are what keep an array update from being a
366
+ * read-modify-write, which is the point of using them.
361
367
  */ updateOne: (query, update, options)=>record(name, 'updateOne', ()=>{
362
368
  var _update_$setOnInsert;
363
369
  const supported = [
364
370
  '$set',
365
371
  '$addToSet',
366
372
  '$inc',
367
- '$setOnInsert'
373
+ '$setOnInsert',
374
+ '$push'
368
375
  ];
369
376
  const unsupported = Object.keys(update).filter((operator)=>!supported.includes(operator));
370
377
  if (unsupported.length > 0) {
@@ -381,9 +388,35 @@ const matches = (doc, query)=>Object.entries(query).every(([field, condition])=>
381
388
  if (conflicting.length > 0) {
382
389
  throw new Error(`fake-mongo: updateOne has conflicting paths in $setOnInsert and $inc/$set: ${conflicting.join(', ')}`);
383
390
  }
384
- /** `$set`, `$addToSet` and `$inc`, which apply on both branches. */ const applyOperators = (base)=>{
385
- var _update_$set, _update_$addToSet, _update_$inc;
386
- const updated = _extends({}, base, (_update_$set = update.$set) != null ? _update_$set : {});
391
+ /** `$set`, `$addToSet`, `$inc` and `$push`, which apply on both branches. */ const applyOperators = (base)=>{
392
+ var _update_$set, _update_$set1, _update_$push, _update_$addToSet, _update_$inc;
393
+ const plain = Object.entries((_update_$set = update.$set) != null ? _update_$set : {}).filter(([field])=>!field.includes('.$['));
394
+ const updated = _extends({}, base, Object.fromEntries(plain));
395
+ for (const [path, value] of Object.entries((_update_$set1 = update.$set) != null ? _update_$set1 : {})){
396
+ var _ref;
397
+ const filtered = /^([^.]+)\.\$\[([^\]]+)\]\.(.+)$/.exec(path);
398
+ if (filtered === null) continue;
399
+ const [, field, identifier, member] = filtered;
400
+ // The server refuses a filtered position with no filter naming it.
401
+ const conditions = ((_ref = options == null ? void 0 : options.arrayFilters) != null ? _ref : []).flatMap((filter)=>Object.entries(filter).filter(([key])=>key.startsWith(`${identifier}.`)).map(([key, condition])=>[
402
+ key.slice(identifier.length + 1),
403
+ condition
404
+ ]));
405
+ if (conditions.length === 0) {
406
+ throw new Error(`fake-mongo: no array filter found for identifier ${identifier}`);
407
+ }
408
+ const current = updated[field];
409
+ updated[field] = (Array.isArray(current) ? current : []).map((element)=>isPlainObject(element) && conditions.every(([key, condition])=>matchesCondition(element[key], condition)) ? _extends({}, element, {
410
+ [member]: value
411
+ }) : element);
412
+ }
413
+ for (const [field, value] of Object.entries((_update_$push = update.$push) != null ? _update_$push : {})){
414
+ const current = updated[field];
415
+ updated[field] = [
416
+ ...Array.isArray(current) ? current : [],
417
+ value
418
+ ];
419
+ }
387
420
  for (const [field, value] of Object.entries((_update_$addToSet = update.$addToSet) != null ? _update_$addToSet : {})){
388
421
  const current = updated[field];
389
422
  const array = Array.isArray(current) ? current : [];
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/drivers/fake-mongo.ts"],"sourcesContent":["/**\n * A fake of the mongodb driver, not of the repository port.\n *\n * It sits one level *below* `makeMongoRepository`, so the adapter's own code —\n * the filter translation, the projection, the upsert rule, the error mapping —\n * actually runs and is measured by coverage. A fake at the port level would\n * skip all of it.\n *\n * Only the surface the adapter uses is implemented; anything else is a\n * deliberate `TypeError` rather than a silent no-op.\n */\n\n/** The subset of a Mongo query document the adapter produces. */\ntype QueryDocument = Record<string, unknown>;\ntype Document = Record<string, unknown>;\n\nconst isPlainObject = (value: unknown): value is Document =>\n typeof value === 'object' && value !== null && !Array.isArray(value);\n\nconst compare = (left: unknown, right: unknown): number => {\n if (left == null && right == null) return 0;\n if (left == null) return -1;\n if (right == null) return 1;\n if (typeof left === 'number' && typeof right === 'number')\n return left - right;\n if (left instanceof Date && right instanceof Date) {\n return left.getTime() - right.getTime();\n }\n return String(left).localeCompare(String(right));\n};\n\n/** Evaluates one `{ $op: value }` condition against a document field. */\nconst matchesCondition = (actual: unknown, condition: unknown): boolean => {\n if (!isPlainObject(condition)) {\n return actual === condition;\n }\n\n return Object.entries(condition).every(([operator, operand]) => {\n switch (operator) {\n case '$eq':\n return actual === operand;\n case '$ne':\n return actual !== operand;\n case '$gt':\n return compare(actual, operand) > 0;\n case '$gte':\n return compare(actual, operand) >= 0;\n case '$lt':\n return compare(actual, operand) < 0;\n case '$lte':\n return compare(actual, operand) <= 0;\n case '$in':\n return (operand as unknown[]).includes(actual);\n // Absence, not falsiness. A settlement ledger keys \"unpaid\" on a `runId`\n // that is not there at all, and `undefined` is what a document without\n // the field reads as — so `{ $exists: false }` must be a different test\n // from `{ $eq: undefined }` would be if the serializer ever wrote one.\n case '$exists':\n return (actual !== undefined) === (operand as boolean);\n case '$nin':\n return !(operand as unknown[]).includes(actual);\n case '$not':\n return !matchesCondition(actual, operand);\n case '$regex':\n return new RegExp(\n operand as string,\n (condition['$options'] as string) ?? '',\n ).test(String(actual));\n case '$options':\n // Handled together with `$regex`.\n return true;\n default:\n throw new TypeError(`fake mongo: unsupported operator \"${operator}\"`);\n }\n });\n};\n\n/**\n * Evaluates one node of an aggregation expression — the `$expr` half of a\n * query, which is a different language from the operators above: it compares\n * two *fields of the same document* rather than a field against a constant.\n *\n * Only the shape a conditional stock write sends is implemented — a\n * `$subtract` of two field paths compared with `$gte` — and anything else is a\n * `TypeError`. That is the same rule the rest of this file follows: a fake that\n * quietly evaluated an expression it does not understand would answer `true`\n * for a document the real server would have refused, which turns an\n * oversell-prevention test into a test that asserts nothing.\n */\nconst evaluateExpression = (doc: Document, node: unknown): unknown => {\n if (typeof node === 'string' && node.startsWith('$')) {\n return doc[node.slice(1)];\n }\n if (!isPlainObject(node)) {\n return node;\n }\n\n const entries = Object.entries(node);\n if (entries.length !== 1) {\n throw new TypeError(\n `fake mongo: $expr node must have exactly one operator, got ${entries.length}`,\n );\n }\n const [operator, operand] = entries[0];\n const operands = (operand as unknown[]).map(child =>\n evaluateExpression(doc, child),\n );\n\n switch (operator) {\n case '$subtract':\n return (operands[0] as number) - (operands[1] as number);\n case '$add':\n return (operands[0] as number) + (operands[1] as number);\n case '$gte':\n return compare(operands[0], operands[1]) >= 0;\n case '$gt':\n return compare(operands[0], operands[1]) > 0;\n case '$lte':\n return compare(operands[0], operands[1]) <= 0;\n case '$lt':\n return compare(operands[0], operands[1]) < 0;\n case '$eq':\n return operands[0] === operands[1];\n default:\n throw new TypeError(\n `fake mongo: unsupported $expr operator \"${operator}\"`,\n );\n }\n};\n\n/**\n * Every value a field path names, the way the server reads one.\n *\n * A dotted path descends, and **an array on the way down is walked\n * element-wise** — which is what makes `{'items.vendorId': x}` match an order\n * with a line for that vendor rather than nothing at all. Without it a query\n * into an embedded collection silently answers empty here while working against\n * a real server, which is worse than an unsupported-operator throw: the spec\n * passes and asserts the opposite of what it claims.\n *\n * The array itself is kept as a candidate beside its elements, because the\n * server matches both — `{ tags: 'a' }` matches `{ tags: ['a'] }` and\n * `{ tags: 'a' }` alike.\n */\nconst valuesAt = (doc: Document, field: string): unknown[] => {\n let current: unknown[] = [doc];\n for (const segment of field.split('.')) {\n const next: unknown[] = [];\n for (const value of current) {\n const container = Array.isArray(value) ? value : [value];\n for (const element of container) {\n if (isPlainObject(element)) {\n next.push(element[segment]);\n }\n }\n }\n current = next;\n }\n return current.flatMap(value =>\n Array.isArray(value) ? [value, ...value] : [value],\n );\n};\n\n/** Operators that exclude a document when a single value matches them. */\nconst NEGATIVE_OPERATORS = new Set(['$ne', '$nin', '$not']);\n\nconst isNegativeCondition = (condition: unknown): boolean =>\n isPlainObject(condition) &&\n Object.keys(condition).some(operator => NEGATIVE_OPERATORS.has(operator));\n\nconst matches = (doc: Document, query: QueryDocument): boolean =>\n Object.entries(query).every(([field, condition]) => {\n if (field === '$and') {\n return (condition as QueryDocument[]).every(child => matches(doc, child));\n }\n if (field === '$or') {\n return (condition as QueryDocument[]).some(child => matches(doc, child));\n }\n if (field === '$expr') {\n return evaluateExpression(doc, condition) === true;\n }\n const candidates = valuesAt(doc, field);\n if (candidates.length === 0) {\n return matchesCondition(undefined, condition);\n }\n // A positive condition matches when **any** value at the path satisfies it;\n // a negative one only when **every** value does. That asymmetry is the\n // server's: `{ 'items.vendorId': { $ne: 'a' } }` must exclude an order that\n // has a line for `a`, not include it because some other line differs.\n return isNegativeCondition(condition)\n ? candidates.every(value => matchesCondition(value, condition))\n : candidates.some(value => matchesCondition(value, condition));\n });\n\n/**\n * The error a real server raises when a write violates a unique index.\n *\n * The `code` matters and the message does not: callers recognise a duplicate\n * key by `error.code === 11000` (or the same code inside `writeErrors`), and a\n * fake that threw a plain `Error` would send a retry path that exists precisely\n * for this case down the \"unexpected failure\" branch instead.\n */\nclass FakeDuplicateKeyError extends Error {\n readonly code = 11000;\n\n constructor(collection: string, key: Document) {\n super(\n `fake mongo: E11000 duplicate key error collection: ${collection} dup key: ${JSON.stringify(key)}`,\n );\n this.name = 'MongoServerError';\n }\n}\n\nexport interface FakeMongoCollection {\n /** The documents currently stored, as the driver would return them. */\n readonly documents: Document[];\n}\n\nexport interface FakeMongoDb {\n /** Replaces a collection's contents. */\n seed(collection: string, documents: Document[]): void;\n /** Reads a collection's current contents. */\n read(collection: string): Document[];\n /**\n * Makes every subsequent driver call reject with `error`, so the adapter's\n * `EntifixConnError` mapping is reachable. Pass `undefined` to restore.\n */\n failWith(error: unknown): void;\n /**\n * Makes only `operation` reject, leaving the rest working — the way a read\n * that succeeds and a count that then fails reaches a distinct error branch.\n */\n failOn(operation: string, error: unknown): void;\n /** Every operation performed, for assertions about what the adapter did. */\n readonly operations: ReadonlyArray<{ collection: string; op: string }>;\n /**\n * Opens a session whose `withTransaction` rolls the whole store back when its\n * body throws. What a service hands to `client.startSession()`; see the\n * implementation for why it is atomicity and not isolation.\n */\n startSession(): {\n withTransaction(body: () => Promise<unknown>): Promise<unknown>;\n endSession(): Promise<void>;\n readonly hasEnded: boolean;\n };\n /** The object to hand to `makeMongoRepository` in place of a real `Db`. */\n readonly db: unknown;\n}\n\n/**\n * Builds an in-memory stand-in for a mongodb `Db`.\n *\n * `db` is typed `unknown` on purpose: casting it at the call site keeps this\n * package free of a hard dependency on the `mongodb` types while remaining\n * honest that it is not a real driver.\n */\nexport const makeFakeMongoDb = (\n seed: Record<string, Document[]> = {},\n): FakeMongoDb => {\n const collections = new Map<string, Document[]>(\n Object.entries(seed).map(([name, docs]) => [\n name,\n docs.map(d => ({ ...d })),\n ]),\n );\n const operations: Array<{ collection: string; op: string }> = [];\n let failure: unknown;\n const failuresByOperation = new Map<string, unknown>();\n\n const documentsOf = (name: string): Document[] => {\n if (!collections.has(name)) collections.set(name, []);\n return collections.get(name) as Document[];\n };\n\n /**\n * The unique indexes `createIndex` has been asked for, per collection, as the\n * field lists they key on.\n *\n * Recording them is not bookkeeping: `updateOne` with `upsert` is atomic per\n * *document*, so two concurrent upserts for the same key each fail to see the\n * other's uncommitted insert and each create a row. The index is what makes\n * the fold singular, and a fake that accepted `createIndex` as a no-op would\n * report a service as covered while the property the index exists for went\n * untested (ADR 0010).\n */\n const uniqueIndexes = new Map<string, string[][]>();\n\n const uniqueIndexesOf = (name: string): string[][] =>\n uniqueIndexes.get(name) ?? [];\n\n /**\n * Refuses `candidate` if it would duplicate an existing document under one of\n * the collection's unique indexes.\n *\n * `ignored` is the document being replaced by an update, which must not count\n * as its own duplicate. A key whose value is `undefined` on the candidate is\n * skipped: a real index treats a missing field as `null` and would collide,\n * but nothing in this repo indexes an optional member, and guessing wrong\n * here would fail writes the server accepts.\n */\n const assertUnique = (\n name: string,\n candidate: Document,\n ignored?: Document,\n ): void => {\n for (const fields of uniqueIndexesOf(name)) {\n if (fields.some(field => candidate[field] === undefined)) continue;\n const clash = documentsOf(name).find(\n doc =>\n doc !== ignored &&\n fields.every(field => doc[field] === candidate[field]),\n );\n if (clash !== undefined) {\n throw new FakeDuplicateKeyError(\n name,\n Object.fromEntries(fields.map(field => [field, candidate[field]])),\n );\n }\n }\n };\n\n const record = <TValue>(name: string, op: string, produce: () => TValue) => {\n operations.push({ collection: name, op });\n const scoped = failuresByOperation.get(op);\n if (scoped !== undefined) return Promise.reject(scoped);\n if (failure !== undefined) return Promise.reject(failure);\n // `try`/`catch` rather than `Promise.resolve(produce())`: a real driver\n // returns a promise and *rejects*, so a fake that threw synchronously would\n // need different handling at every call site than the thing it stands in for.\n try {\n return Promise.resolve(produce());\n } catch (error) {\n return Promise.reject(error);\n }\n };\n\n /** Applies `{ projection: { _id: 0 } }`, the only projection the adapter uses. */\n const project = (doc: Document, options?: { projection?: Document }) => {\n const copy = { ...doc };\n if (options?.projection && options.projection['_id'] === 0) {\n delete copy['_id'];\n }\n return copy;\n };\n\n const collection = (name: string) => ({\n find: (query: QueryDocument = {}, options?: { projection?: Document }) => {\n let sortSpec: Record<string, 1 | -1> = {};\n let skipCount = 0;\n let limitCount = Infinity;\n\n const cursor = {\n sort(spec: Record<string, 1 | -1>) {\n sortSpec = spec;\n return cursor;\n },\n skip(count: number) {\n skipCount = count;\n return cursor;\n },\n limit(count: number) {\n limitCount = count;\n return cursor;\n },\n toArray: () =>\n record(name, 'find', () => {\n const matched = documentsOf(name).filter(doc =>\n matches(doc, query),\n );\n const sorted = Object.entries(sortSpec).reduceRight(\n (items, [field, direction]) =>\n [...items].sort(\n (left, right) =>\n compare(left[field], right[field]) * direction,\n ),\n matched,\n );\n return sorted\n .slice(skipCount, skipCount + limitCount)\n .map(doc => project(doc, options));\n }),\n };\n return cursor;\n },\n\n findOne: (query: QueryDocument, options?: { projection?: Document }) =>\n record(name, 'findOne', () => {\n const found = documentsOf(name).find(doc => matches(doc, query));\n return found === undefined ? null : project(found, options);\n }),\n\n countDocuments: (query: QueryDocument = {}) =>\n record(\n name,\n 'countDocuments',\n () => documentsOf(name).filter(doc => matches(doc, query)).length,\n ),\n\n // Used by the services' own seeding, which the e2e `mock` profile runs for\n // real so both profiles serve the same catalog.\n insertMany: (documents: Document[]) =>\n record(name, 'insertMany', () => {\n const stored = documentsOf(name);\n for (const document of documents) {\n assertUnique(name, document);\n stored.push({ ...document });\n }\n return { insertedCount: documents.length };\n }),\n\n /**\n * A single insert — how an append-only ledger grows, and how a hold is\n * written beside the counter it moved.\n *\n * The options argument is accepted and ignored except for its `session`,\n * which the transaction wrapper already handles: a caller that passes one\n * is inside `withTransaction`, and this fake's rollback is a snapshot of\n * the whole store rather than anything per-operation.\n */\n insertOne: (document: Document) =>\n record(name, 'insertOne', () => {\n assertUnique(name, document);\n documentsOf(name).push({ ...document });\n return { acknowledged: true, insertedId: document['id'] ?? null };\n }),\n\n replaceOne: (\n query: QueryDocument,\n replacement: Document,\n options?: { upsert?: boolean },\n ) =>\n record(name, 'replaceOne', () => {\n const documents = documentsOf(name);\n const index = documents.findIndex(doc => matches(doc, query));\n if (index === -1) {\n if (!options?.upsert) return { matchedCount: 0, upsertedCount: 0 };\n documents.push({ ...replacement });\n return { matchedCount: 0, upsertedCount: 1 };\n }\n documents[index] = { ...replacement };\n return { matchedCount: 1, upsertedCount: 0 };\n }),\n\n /**\n * Partial update. `$set`, `$addToSet`, `$inc` and `$setOnInsert` are\n * implemented — the operators the adapters and the stock ledger use — and\n * **anything else throws**, because a fake that silently accepted `$unset`\n * without applying it would let a spec pass on an update that never\n * happened.\n *\n * `$addToSet` is what links an identifier onto `user-identity.identifiers`\n * without duplicating it on a repair run; supporting it here rather than\n * ignoring it is the difference between the e2e proving the link and merely\n * not noticing its absence.\n *\n * `$inc` with `upsert` is how a quantity moves. It matters that it is a\n * real increment and not a read-modify-write even here: the whole rule it\n * implements is that an absolute-value write loses updates, so a fake that\n * computed the new total from a value it had already read would model the\n * bug rather than the fix.\n */\n updateOne: (\n query: QueryDocument,\n update: {\n $set?: Document;\n $addToSet?: Document;\n $inc?: Document;\n $setOnInsert?: Document;\n },\n options?: { upsert?: boolean },\n ) =>\n record(name, 'updateOne', () => {\n const supported = ['$set', '$addToSet', '$inc', '$setOnInsert'];\n const unsupported = Object.keys(update).filter(\n operator => !supported.includes(operator),\n );\n if (unsupported.length > 0) {\n throw new Error(\n `fake-mongo: updateOne does not implement ${unsupported.join(', ')}`,\n );\n }\n\n // A real server rejects an update whose operators both name one field,\n // and the message is the one this repro'd against: `$setOnInsert` that\n // also named a field `$inc` touches. Reproducing the refusal is what\n // keeps the fake from blessing an update Mongo would refuse.\n const conflicting = Object.keys(update.$setOnInsert ?? {}).filter(\n field => field in (update.$inc ?? {}) || field in (update.$set ?? {}),\n );\n if (conflicting.length > 0) {\n throw new Error(\n `fake-mongo: updateOne has conflicting paths in $setOnInsert and $inc/$set: ${conflicting.join(', ')}`,\n );\n }\n\n /** `$set`, `$addToSet` and `$inc`, which apply on both branches. */\n const applyOperators = (base: Document): Document => {\n const updated = { ...base, ...(update.$set ?? {}) };\n for (const [field, value] of Object.entries(update.$addToSet ?? {})) {\n const current = updated[field];\n const array = Array.isArray(current) ? current : [];\n if (!array.includes(value)) {\n updated[field] = [...array, value];\n }\n }\n for (const [field, delta] of Object.entries(update.$inc ?? {})) {\n // An absent field is created at the increment's value, which is\n // exactly why `$setOnInsert` must not also name it.\n const current = updated[field];\n updated[field] =\n (typeof current === 'number' ? current : 0) + (delta as number);\n }\n return updated;\n };\n\n const documents = documentsOf(name);\n const index = documents.findIndex(doc => matches(doc, query));\n\n if (index === -1) {\n if (options?.upsert !== true) {\n return { matchedCount: 0, modifiedCount: 0, upsertedCount: 0 };\n }\n // The upserted document starts from the query's *equality* fields,\n // the way a real server seeds one — an operator condition contributes\n // nothing, which is why a `$expr`-guarded upsert would insert a row\n // missing the very field it filtered on.\n const seedFields = Object.fromEntries(\n Object.entries(query).filter(\n ([field, condition]) =>\n !field.startsWith('$') && !isPlainObject(condition),\n ),\n );\n const inserted = applyOperators({\n ...seedFields,\n ...(update.$setOnInsert ?? {}),\n });\n assertUnique(name, inserted);\n documents.push(inserted);\n return { matchedCount: 0, modifiedCount: 0, upsertedCount: 1 };\n }\n\n const updated = applyOperators(documents[index]);\n assertUnique(name, updated, documents[index]);\n documents[index] = updated;\n return { matchedCount: 1, modifiedCount: 1, upsertedCount: 0 };\n }),\n\n /**\n * `$set` across every matching document, and the count of what changed.\n *\n * ⚠️ **The count is what a caller branches on.** A settlement run claims its\n * ledger lines with this and reads `modifiedCount === 0` as \"another replica\n * took them all\" — so a fake returning a fixed `1`, or the match count\n * rather than the modified count, would make the losing replica behave like\n * the winning one and the conditional claim would test nothing.\n *\n * `$set` only. Anything else throws, for the reason `updateOne` gives:\n * silently accepting an operator it does not apply lets a spec pass on an\n * update that never happened.\n */\n updateMany: (query: QueryDocument, update: { $set?: Document }) =>\n record(name, 'updateMany', () => {\n const unsupported = Object.keys(update).filter(\n operator => operator !== '$set',\n );\n if (unsupported.length > 0) {\n throw new Error(\n `fake-mongo: updateMany does not implement ${unsupported.join(', ')}`,\n );\n }\n\n const documents = documentsOf(name);\n let modifiedCount = 0;\n documents.forEach((doc, index) => {\n if (!matches(doc, query)) return;\n const updated = { ...doc, ...(update.$set ?? {}) };\n assertUnique(name, updated, doc);\n documents[index] = updated;\n modifiedCount += 1;\n });\n return { matchedCount: modifiedCount, modifiedCount };\n }),\n\n /**\n * Update one document and hand back the result, upserting when asked.\n *\n * ⚠️ **`returnDocument: 'after'` is the only mode implemented, and the\n * default here is `'after'` rather than the driver's `'before'`** — because\n * the callers that need this primitive at all need the merged document. A\n * two-message join upserts its own half and then asks \"is the pair complete\n * now?\", which is a question only the *after* state answers. `'before'`\n * throws rather than quietly returning the wrong half.\n *\n * Implemented over {@link updateOne} so the upsert seeding rule, the\n * conflicting-path refusal and the unique-index enforcement are the same\n * ones, rather than a second copy that could drift from them.\n */\n findOneAndUpdate: (\n query: QueryDocument,\n update: {\n $set?: Document;\n $addToSet?: Document;\n $inc?: Document;\n $setOnInsert?: Document;\n },\n options?: { upsert?: boolean; returnDocument?: 'before' | 'after' },\n ) =>\n record(name, 'findOneAndUpdate', async () => {\n if (options?.returnDocument === 'before') {\n throw new Error(\n 'fake-mongo: findOneAndUpdate only implements returnDocument: \"after\"',\n );\n }\n // Where the document is *before* the write, because afterwards the\n // query may no longer find it: an upsert's operator conditions need not\n // hold of the row it just inserted — `{ folded: { $exists: false } }`\n // matches nothing once `folded` has been set. `documentsOf` hands back\n // the live array, which `updateOne` mutates in place or pushes onto, so\n // the position is enough to identify it either way.\n const documents = documentsOf(name);\n const index = documents.findIndex(doc => matches(doc, query));\n\n const result = await collection(name).updateOne(query, update, {\n upsert: options?.upsert === true,\n });\n if (result.matchedCount === 0 && result.upsertedCount === 0) {\n return null;\n }\n\n return index === -1\n ? documents[documents.length - 1]\n : documents[index];\n }),\n\n deleteOne: (query: QueryDocument) =>\n record(name, 'deleteOne', () => {\n const documents = documentsOf(name);\n const index = documents.findIndex(doc => matches(doc, query));\n if (index === -1) return { deletedCount: 0 };\n documents.splice(index, 1);\n return { deletedCount: 1 };\n }),\n\n /**\n * Declares an index, and **enforces it when it is unique**.\n *\n * Idempotent, like the real one: a service that ensures its index per\n * request rather than at boot — because a tenant database only appears on\n * first write — calls this on every write.\n */\n createIndex: (spec: Document, options?: Document) =>\n record(name, 'createIndex', () => {\n if (options?.['unique'] === true) {\n const fields = Object.keys(spec);\n const existing = uniqueIndexes.get(name) ?? [];\n const already = existing.some(\n candidate =>\n candidate.length === fields.length &&\n candidate.every((field, at) => field === fields[at]),\n );\n if (!already) {\n uniqueIndexes.set(name, [...existing, fields]);\n }\n }\n return { spec, options };\n }),\n });\n\n /**\n * A session whose `withTransaction` really rolls back.\n *\n * ⚠️ **It is atomicity, not isolation, and the difference decides where a\n * test may live.** The store is a single-threaded object graph, so nothing\n * runs concurrently with the body and a \"race\" here resolves in the order it\n * was written: a concurrency property — two writers contending for the last\n * unit — is green under this fake no matter what the code does, and belongs\n * in a `*.live.spec.ts` against real Mongo (ADR 0010).\n *\n * What it *does* model is the abort path, which is worth having: a body that\n * throws leaves the store exactly as it found it, so a conditional write that\n * moves a counter and then fails to write its row cannot leave the counter\n * moved. That is a real bug shape, and one a fake without rollback would hide\n * by committing half of it.\n */\n const startSession = () => {\n let open = true;\n return {\n withTransaction: async (body: () => Promise<unknown>) => {\n const snapshot = new Map(\n [...collections].map(([name, docs]) => [\n name,\n docs.map(doc => ({ ...doc })),\n ]),\n );\n try {\n return await body();\n } catch (error) {\n collections.clear();\n for (const [name, docs] of snapshot) collections.set(name, docs);\n throw error;\n }\n },\n endSession: () => {\n open = false;\n return Promise.resolve();\n },\n get hasEnded() {\n return !open;\n },\n };\n };\n\n return {\n seed: (name, documents) => {\n collections.set(\n name,\n documents.map(doc => ({ ...doc })),\n );\n },\n read: name => documentsOf(name).map(doc => ({ ...doc })),\n failWith: error => {\n failure = error;\n },\n failOn: (operation, error) => {\n failuresByOperation.set(operation, error);\n },\n get operations() {\n return operations;\n },\n startSession,\n db: { collection },\n };\n};\n"],"names":["isPlainObject","value","Array","isArray","compare","left","right","Date","getTime","String","localeCompare","matchesCondition","actual","condition","Object","entries","every","operator","operand","includes","undefined","RegExp","test","TypeError","evaluateExpression","doc","node","startsWith","slice","length","operands","map","child","valuesAt","field","current","segment","split","next","container","element","push","flatMap","NEGATIVE_OPERATORS","Set","isNegativeCondition","keys","some","has","matches","query","candidates","FakeDuplicateKeyError","Error","collection","key","JSON","stringify","code","name","makeFakeMongoDb","seed","collections","Map","docs","d","operations","failure","failuresByOperation","documentsOf","set","get","uniqueIndexes","uniqueIndexesOf","assertUnique","candidate","ignored","fields","clash","find","fromEntries","record","op","produce","scoped","Promise","reject","resolve","error","project","options","copy","projection","sortSpec","skipCount","limitCount","Infinity","cursor","sort","spec","skip","count","limit","toArray","matched","filter","sorted","reduceRight","items","direction","findOne","found","countDocuments","insertMany","documents","stored","document","insertedCount","insertOne","acknowledged","insertedId","replaceOne","replacement","index","findIndex","upsert","matchedCount","upsertedCount","updateOne","update","supported","unsupported","join","conflicting","$setOnInsert","$inc","$set","applyOperators","base","updated","$addToSet","array","delta","modifiedCount","seedFields","inserted","updateMany","forEach","findOneAndUpdate","returnDocument","result","deleteOne","deletedCount","splice","createIndex","existing","already","at","startSession","open","withTransaction","body","snapshot","clear","endSession","hasEnded","read","failWith","failOn","operation","db"],"mappings":"AAAA;;;;;;;;;;CAUC,GAED,+DAA+D;AAI/D,MAAMA,gBAAgB,CAACC,QACrB,OAAOA,UAAU,YAAYA,UAAU,QAAQ,CAACC,MAAMC,OAAO,CAACF;AAEhE,MAAMG,UAAU,CAACC,MAAeC;IAC9B,IAAID,QAAQ,QAAQC,SAAS,MAAM,OAAO;IAC1C,IAAID,QAAQ,MAAM,OAAO,CAAC;IAC1B,IAAIC,SAAS,MAAM,OAAO;IAC1B,IAAI,OAAOD,SAAS,YAAY,OAAOC,UAAU,UAC/C,OAAOD,OAAOC;IAChB,IAAID,gBAAgBE,QAAQD,iBAAiBC,MAAM;QACjD,OAAOF,KAAKG,OAAO,KAAKF,MAAME,OAAO;IACvC;IACA,OAAOC,OAAOJ,MAAMK,aAAa,CAACD,OAAOH;AAC3C;AAEA,uEAAuE,GACvE,MAAMK,mBAAmB,CAACC,QAAiBC;IACzC,IAAI,CAACb,cAAca,YAAY;QAC7B,OAAOD,WAAWC;IACpB;IAEA,OAAOC,OAAOC,OAAO,CAACF,WAAWG,KAAK,CAAC,CAAC,CAACC,UAAUC,QAAQ;QACzD,OAAQD;YACN,KAAK;gBACH,OAAOL,WAAWM;YACpB,KAAK;gBACH,OAAON,WAAWM;YACpB,KAAK;gBACH,OAAOd,QAAQQ,QAAQM,WAAW;YACpC,KAAK;gBACH,OAAOd,QAAQQ,QAAQM,YAAY;YACrC,KAAK;gBACH,OAAOd,QAAQQ,QAAQM,WAAW;YACpC,KAAK;gBACH,OAAOd,QAAQQ,QAAQM,YAAY;YACrC,KAAK;gBACH,OAAO,AAACA,QAAsBC,QAAQ,CAACP;YACzC,yEAAyE;YACzE,uEAAuE;YACvE,wEAAwE;YACxE,uEAAuE;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AAW,IAAInG,IACnB;uBAAID;iBAAY,CAAC/B,GAAG,CAAC,CAAC,CAAC4B,MAAMK,KAAK,GAAK;wBACrCL;wBACAK,KAAKjC,GAAG,CAACN,CAAAA,MAAQ,aAAKA;qBACvB;gBAEH,IAAI;oBACF,OAAO,MAAMwI;gBACf,EAAE,OAAOzE,OAAO;oBACd1B,YAAYqG,KAAK;oBACjB,KAAK,MAAM,CAACxG,MAAMK,KAAK,IAAIkG,SAAUpG,YAAYQ,GAAG,CAACX,MAAMK;oBAC3D,MAAMwB;gBACR;YACF;YACA4E,YAAY;gBACVL,OAAO;gBACP,OAAO1E,QAAQE,OAAO;YACxB;YACA,IAAI8E,YAAW;gBACb,OAAO,CAACN;YACV;QACF;IACF;IAEA,OAAO;QACLlG,MAAM,CAACF,MAAMuD;YACXpD,YAAYQ,GAAG,CACbX,MACAuD,UAAUnF,GAAG,CAACN,CAAAA,MAAQ,aAAKA;QAE/B;QACA6I,MAAM3G,CAAAA,OAAQU,YAAYV,MAAM5B,GAAG,CAACN,CAAAA,MAAQ,aAAKA;QACjD8I,UAAU/E,CAAAA;YACRrB,UAAUqB;QACZ;QACAgF,QAAQ,CAACC,WAAWjF;YAClBpB,oBAAoBE,GAAG,CAACmG,WAAWjF;QACrC;QACA,IAAItB,cAAa;YACf,OAAOA;QACT;QACA4F;QACAY,IAAI;YAAEpH;QAAW;IACnB;AACF,EAAE"}
1
+ {"version":3,"sources":["../../src/drivers/fake-mongo.ts"],"sourcesContent":["/**\n * A fake of the mongodb driver, not of the repository port.\n *\n * It sits one level *below* `makeMongoRepository`, so the adapter's own code —\n * the filter translation, the projection, the upsert rule, the error mapping —\n * actually runs and is measured by coverage. A fake at the port level would\n * skip all of it.\n *\n * Only the surface the adapter uses is implemented; anything else is a\n * deliberate `TypeError` rather than a silent no-op.\n */\n\n/** The subset of a Mongo query document the adapter produces. */\ntype QueryDocument = Record<string, unknown>;\ntype Document = Record<string, unknown>;\n\nconst isPlainObject = (value: unknown): value is Document =>\n typeof value === 'object' && value !== null && !Array.isArray(value);\n\nconst compare = (left: unknown, right: unknown): number => {\n if (left == null && right == null) return 0;\n if (left == null) return -1;\n if (right == null) return 1;\n if (typeof left === 'number' && typeof right === 'number')\n return left - right;\n if (left instanceof Date && right instanceof Date) {\n return left.getTime() - right.getTime();\n }\n return String(left).localeCompare(String(right));\n};\n\n/** Evaluates one `{ $op: value }` condition against a document field. */\nconst matchesCondition = (actual: unknown, condition: unknown): boolean => {\n if (!isPlainObject(condition)) {\n return actual === condition;\n }\n\n return Object.entries(condition).every(([operator, operand]) => {\n switch (operator) {\n case '$eq':\n return actual === operand;\n case '$ne':\n return actual !== operand;\n case '$gt':\n return compare(actual, operand) > 0;\n case '$gte':\n return compare(actual, operand) >= 0;\n case '$lt':\n return compare(actual, operand) < 0;\n case '$lte':\n return compare(actual, operand) <= 0;\n case '$in':\n return (operand as unknown[]).includes(actual);\n // Absence, not falsiness. A settlement ledger keys \"unpaid\" on a `runId`\n // that is not there at all, and `undefined` is what a document without\n // the field reads as — so `{ $exists: false }` must be a different test\n // from `{ $eq: undefined }` would be if the serializer ever wrote one.\n case '$exists':\n return (actual !== undefined) === (operand as boolean);\n case '$nin':\n return !(operand as unknown[]).includes(actual);\n case '$not':\n return !matchesCondition(actual, operand);\n case '$regex':\n return new RegExp(\n operand as string,\n (condition['$options'] as string) ?? '',\n ).test(String(actual));\n case '$options':\n // Handled together with `$regex`.\n return true;\n default:\n throw new TypeError(`fake mongo: unsupported operator \"${operator}\"`);\n }\n });\n};\n\n/**\n * Evaluates one node of an aggregation expression — the `$expr` half of a\n * query, which is a different language from the operators above: it compares\n * two *fields of the same document* rather than a field against a constant.\n *\n * Only the shape a conditional stock write sends is implemented — a\n * `$subtract` of two field paths compared with `$gte` — and anything else is a\n * `TypeError`. That is the same rule the rest of this file follows: a fake that\n * quietly evaluated an expression it does not understand would answer `true`\n * for a document the real server would have refused, which turns an\n * oversell-prevention test into a test that asserts nothing.\n */\nconst evaluateExpression = (doc: Document, node: unknown): unknown => {\n if (typeof node === 'string' && node.startsWith('$')) {\n return doc[node.slice(1)];\n }\n if (!isPlainObject(node)) {\n return node;\n }\n\n const entries = Object.entries(node);\n if (entries.length !== 1) {\n throw new TypeError(\n `fake mongo: $expr node must have exactly one operator, got ${entries.length}`,\n );\n }\n const [operator, operand] = entries[0];\n const operands = (operand as unknown[]).map(child =>\n evaluateExpression(doc, child),\n );\n\n switch (operator) {\n case '$subtract':\n return (operands[0] as number) - (operands[1] as number);\n case '$add':\n return (operands[0] as number) + (operands[1] as number);\n case '$gte':\n return compare(operands[0], operands[1]) >= 0;\n case '$gt':\n return compare(operands[0], operands[1]) > 0;\n case '$lte':\n return compare(operands[0], operands[1]) <= 0;\n case '$lt':\n return compare(operands[0], operands[1]) < 0;\n case '$eq':\n return operands[0] === operands[1];\n default:\n throw new TypeError(\n `fake mongo: unsupported $expr operator \"${operator}\"`,\n );\n }\n};\n\n/**\n * Every value a field path names, the way the server reads one.\n *\n * A dotted path descends, and **an array on the way down is walked\n * element-wise** — which is what makes `{'items.vendorId': x}` match an order\n * with a line for that vendor rather than nothing at all. Without it a query\n * into an embedded collection silently answers empty here while working against\n * a real server, which is worse than an unsupported-operator throw: the spec\n * passes and asserts the opposite of what it claims.\n *\n * The array itself is kept as a candidate beside its elements, because the\n * server matches both — `{ tags: 'a' }` matches `{ tags: ['a'] }` and\n * `{ tags: 'a' }` alike.\n */\nconst valuesAt = (doc: Document, field: string): unknown[] => {\n let current: unknown[] = [doc];\n for (const segment of field.split('.')) {\n const next: unknown[] = [];\n for (const value of current) {\n const container = Array.isArray(value) ? value : [value];\n for (const element of container) {\n if (isPlainObject(element)) {\n next.push(element[segment]);\n }\n }\n }\n current = next;\n }\n return current.flatMap(value =>\n Array.isArray(value) ? [value, ...value] : [value],\n );\n};\n\n/** Operators that exclude a document when a single value matches them. */\nconst NEGATIVE_OPERATORS = new Set(['$ne', '$nin', '$not']);\n\nconst isNegativeCondition = (condition: unknown): boolean =>\n isPlainObject(condition) &&\n Object.keys(condition).some(operator => NEGATIVE_OPERATORS.has(operator));\n\nconst matches = (doc: Document, query: QueryDocument): boolean =>\n Object.entries(query).every(([field, condition]) => {\n if (field === '$and') {\n return (condition as QueryDocument[]).every(child => matches(doc, child));\n }\n if (field === '$or') {\n return (condition as QueryDocument[]).some(child => matches(doc, child));\n }\n if (field === '$expr') {\n return evaluateExpression(doc, condition) === true;\n }\n const candidates = valuesAt(doc, field);\n if (candidates.length === 0) {\n return matchesCondition(undefined, condition);\n }\n // A positive condition matches when **any** value at the path satisfies it;\n // a negative one only when **every** value does. That asymmetry is the\n // server's: `{ 'items.vendorId': { $ne: 'a' } }` must exclude an order that\n // has a line for `a`, not include it because some other line differs.\n return isNegativeCondition(condition)\n ? candidates.every(value => matchesCondition(value, condition))\n : candidates.some(value => matchesCondition(value, condition));\n });\n\n/**\n * The error a real server raises when a write violates a unique index.\n *\n * The `code` matters and the message does not: callers recognise a duplicate\n * key by `error.code === 11000` (or the same code inside `writeErrors`), and a\n * fake that threw a plain `Error` would send a retry path that exists precisely\n * for this case down the \"unexpected failure\" branch instead.\n */\nclass FakeDuplicateKeyError extends Error {\n readonly code = 11000;\n\n constructor(collection: string, key: Document) {\n super(\n `fake mongo: E11000 duplicate key error collection: ${collection} dup key: ${JSON.stringify(key)}`,\n );\n this.name = 'MongoServerError';\n }\n}\n\nexport interface FakeMongoCollection {\n /** The documents currently stored, as the driver would return them. */\n readonly documents: Document[];\n}\n\nexport interface FakeMongoDb {\n /** Replaces a collection's contents. */\n seed(collection: string, documents: Document[]): void;\n /** Reads a collection's current contents. */\n read(collection: string): Document[];\n /**\n * Makes every subsequent driver call reject with `error`, so the adapter's\n * `EntifixConnError` mapping is reachable. Pass `undefined` to restore.\n */\n failWith(error: unknown): void;\n /**\n * Makes only `operation` reject, leaving the rest working — the way a read\n * that succeeds and a count that then fails reaches a distinct error branch.\n */\n failOn(operation: string, error: unknown): void;\n /** Every operation performed, for assertions about what the adapter did. */\n readonly operations: ReadonlyArray<{ collection: string; op: string }>;\n /**\n * Opens a session whose `withTransaction` rolls the whole store back when its\n * body throws. What a service hands to `client.startSession()`; see the\n * implementation for why it is atomicity and not isolation.\n */\n startSession(): {\n withTransaction(body: () => Promise<unknown>): Promise<unknown>;\n endSession(): Promise<void>;\n readonly hasEnded: boolean;\n };\n /** The object to hand to `makeMongoRepository` in place of a real `Db`. */\n readonly db: unknown;\n}\n\n/**\n * Builds an in-memory stand-in for a mongodb `Db`.\n *\n * `db` is typed `unknown` on purpose: casting it at the call site keeps this\n * package free of a hard dependency on the `mongodb` types while remaining\n * honest that it is not a real driver.\n */\nexport const makeFakeMongoDb = (\n seed: Record<string, Document[]> = {},\n): FakeMongoDb => {\n const collections = new Map<string, Document[]>(\n Object.entries(seed).map(([name, docs]) => [\n name,\n docs.map(d => ({ ...d })),\n ]),\n );\n const operations: Array<{ collection: string; op: string }> = [];\n let failure: unknown;\n const failuresByOperation = new Map<string, unknown>();\n\n const documentsOf = (name: string): Document[] => {\n if (!collections.has(name)) collections.set(name, []);\n return collections.get(name) as Document[];\n };\n\n /**\n * The unique indexes `createIndex` has been asked for, per collection, as the\n * field lists they key on.\n *\n * Recording them is not bookkeeping: `updateOne` with `upsert` is atomic per\n * *document*, so two concurrent upserts for the same key each fail to see the\n * other's uncommitted insert and each create a row. The index is what makes\n * the fold singular, and a fake that accepted `createIndex` as a no-op would\n * report a service as covered while the property the index exists for went\n * untested (ADR 0010).\n */\n const uniqueIndexes = new Map<string, string[][]>();\n\n const uniqueIndexesOf = (name: string): string[][] =>\n uniqueIndexes.get(name) ?? [];\n\n /**\n * Refuses `candidate` if it would duplicate an existing document under one of\n * the collection's unique indexes.\n *\n * `ignored` is the document being replaced by an update, which must not count\n * as its own duplicate. A key whose value is `undefined` on the candidate is\n * skipped: a real index treats a missing field as `null` and would collide,\n * but nothing in this repo indexes an optional member, and guessing wrong\n * here would fail writes the server accepts.\n */\n const assertUnique = (\n name: string,\n candidate: Document,\n ignored?: Document,\n ): void => {\n for (const fields of uniqueIndexesOf(name)) {\n if (fields.some(field => candidate[field] === undefined)) continue;\n const clash = documentsOf(name).find(\n doc =>\n doc !== ignored &&\n fields.every(field => doc[field] === candidate[field]),\n );\n if (clash !== undefined) {\n throw new FakeDuplicateKeyError(\n name,\n Object.fromEntries(fields.map(field => [field, candidate[field]])),\n );\n }\n }\n };\n\n const record = <TValue>(name: string, op: string, produce: () => TValue) => {\n operations.push({ collection: name, op });\n const scoped = failuresByOperation.get(op);\n if (scoped !== undefined) return Promise.reject(scoped);\n if (failure !== undefined) return Promise.reject(failure);\n // `try`/`catch` rather than `Promise.resolve(produce())`: a real driver\n // returns a promise and *rejects*, so a fake that threw synchronously would\n // need different handling at every call site than the thing it stands in for.\n try {\n return Promise.resolve(produce());\n } catch (error) {\n return Promise.reject(error);\n }\n };\n\n /** Applies `{ projection: { _id: 0 } }`, the only projection the adapter uses. */\n const project = (doc: Document, options?: { projection?: Document }) => {\n const copy = { ...doc };\n if (options?.projection && options.projection['_id'] === 0) {\n delete copy['_id'];\n }\n return copy;\n };\n\n const collection = (name: string) => ({\n find: (query: QueryDocument = {}, options?: { projection?: Document }) => {\n let sortSpec: Record<string, 1 | -1> = {};\n let skipCount = 0;\n let limitCount = Infinity;\n\n const cursor = {\n sort(spec: Record<string, 1 | -1>) {\n sortSpec = spec;\n return cursor;\n },\n skip(count: number) {\n skipCount = count;\n return cursor;\n },\n limit(count: number) {\n limitCount = count;\n return cursor;\n },\n toArray: () =>\n record(name, 'find', () => {\n const matched = documentsOf(name).filter(doc =>\n matches(doc, query),\n );\n const sorted = Object.entries(sortSpec).reduceRight(\n (items, [field, direction]) =>\n [...items].sort(\n (left, right) =>\n compare(left[field], right[field]) * direction,\n ),\n matched,\n );\n return sorted\n .slice(skipCount, skipCount + limitCount)\n .map(doc => project(doc, options));\n }),\n };\n return cursor;\n },\n\n findOne: (query: QueryDocument, options?: { projection?: Document }) =>\n record(name, 'findOne', () => {\n const found = documentsOf(name).find(doc => matches(doc, query));\n return found === undefined ? null : project(found, options);\n }),\n\n countDocuments: (query: QueryDocument = {}) =>\n record(\n name,\n 'countDocuments',\n () => documentsOf(name).filter(doc => matches(doc, query)).length,\n ),\n\n // Used by the services' own seeding, which the e2e `mock` profile runs for\n // real so both profiles serve the same catalog.\n insertMany: (documents: Document[]) =>\n record(name, 'insertMany', () => {\n const stored = documentsOf(name);\n for (const document of documents) {\n assertUnique(name, document);\n stored.push({ ...document });\n }\n return { insertedCount: documents.length };\n }),\n\n /**\n * A single insert — how an append-only ledger grows, and how a hold is\n * written beside the counter it moved.\n *\n * The options argument is accepted and ignored except for its `session`,\n * which the transaction wrapper already handles: a caller that passes one\n * is inside `withTransaction`, and this fake's rollback is a snapshot of\n * the whole store rather than anything per-operation.\n */\n insertOne: (document: Document) =>\n record(name, 'insertOne', () => {\n assertUnique(name, document);\n documentsOf(name).push({ ...document });\n return { acknowledged: true, insertedId: document['id'] ?? null };\n }),\n\n replaceOne: (\n query: QueryDocument,\n replacement: Document,\n options?: { upsert?: boolean },\n ) =>\n record(name, 'replaceOne', () => {\n const documents = documentsOf(name);\n const index = documents.findIndex(doc => matches(doc, query));\n if (index === -1) {\n if (!options?.upsert) return { matchedCount: 0, upsertedCount: 0 };\n documents.push({ ...replacement });\n return { matchedCount: 0, upsertedCount: 1 };\n }\n documents[index] = { ...replacement };\n return { matchedCount: 1, upsertedCount: 0 };\n }),\n\n /**\n * Partial update. `$set`, `$addToSet`, `$inc` and `$setOnInsert` are\n * implemented — the operators the adapters and the stock ledger use — and\n * **anything else throws**, because a fake that silently accepted `$unset`\n * without applying it would let a spec pass on an update that never\n * happened.\n *\n * `$addToSet` is what links an identifier onto `user-identity.identifiers`\n * without duplicating it on a repair run; supporting it here rather than\n * ignoring it is the difference between the e2e proving the link and merely\n * not noticing its absence.\n *\n * `$inc` with `upsert` is how a quantity moves. It matters that it is a\n * real increment and not a read-modify-write even here: the whole rule it\n * implements is that an absolute-value write loses updates, so a fake that\n * computed the new total from a value it had already read would model the\n * bug rather than the fix.\n *\n * `$push` appends, and a `$set` key of the form `field.$[name].member`\n * applies to every element of `field` that `options.arrayFilters` selects —\n * the pair a saga store records an outcome with and later flags one\n * compensated. Both are what keep an array update from being a\n * read-modify-write, which is the point of using them.\n */\n updateOne: (\n query: QueryDocument,\n update: {\n $set?: Document;\n $addToSet?: Document;\n $inc?: Document;\n $setOnInsert?: Document;\n $push?: Document;\n },\n options?: { upsert?: boolean; arrayFilters?: readonly Document[] },\n ) =>\n record(name, 'updateOne', () => {\n const supported = [\n '$set',\n '$addToSet',\n '$inc',\n '$setOnInsert',\n '$push',\n ];\n const unsupported = Object.keys(update).filter(\n operator => !supported.includes(operator),\n );\n if (unsupported.length > 0) {\n throw new Error(\n `fake-mongo: updateOne does not implement ${unsupported.join(', ')}`,\n );\n }\n\n // A real server rejects an update whose operators both name one field,\n // and the message is the one this repro'd against: `$setOnInsert` that\n // also named a field `$inc` touches. Reproducing the refusal is what\n // keeps the fake from blessing an update Mongo would refuse.\n const conflicting = Object.keys(update.$setOnInsert ?? {}).filter(\n field => field in (update.$inc ?? {}) || field in (update.$set ?? {}),\n );\n if (conflicting.length > 0) {\n throw new Error(\n `fake-mongo: updateOne has conflicting paths in $setOnInsert and $inc/$set: ${conflicting.join(', ')}`,\n );\n }\n\n /** `$set`, `$addToSet`, `$inc` and `$push`, which apply on both branches. */\n const applyOperators = (base: Document): Document => {\n const plain = Object.entries(update.$set ?? {}).filter(\n ([field]) => !field.includes('.$['),\n );\n const updated = { ...base, ...Object.fromEntries(plain) };\n for (const [path, value] of Object.entries(update.$set ?? {})) {\n const filtered = /^([^.]+)\\.\\$\\[([^\\]]+)\\]\\.(.+)$/.exec(path);\n if (filtered === null) continue;\n const [, field, identifier, member] = filtered as unknown as [\n string,\n string,\n string,\n string,\n ];\n // The server refuses a filtered position with no filter naming it.\n const conditions = (options?.arrayFilters ?? []).flatMap(filter =>\n Object.entries(filter)\n .filter(([key]) => key.startsWith(`${identifier}.`))\n .map(\n ([key, condition]) =>\n [key.slice(identifier.length + 1), condition] as const,\n ),\n );\n if (conditions.length === 0) {\n throw new Error(\n `fake-mongo: no array filter found for identifier ${identifier}`,\n );\n }\n const current = updated[field];\n updated[field] = (Array.isArray(current) ? current : []).map(\n element =>\n isPlainObject(element) &&\n conditions.every(([key, condition]) =>\n matchesCondition(element[key], condition),\n )\n ? { ...element, [member]: value }\n : element,\n );\n }\n for (const [field, value] of Object.entries(update.$push ?? {})) {\n const current = updated[field];\n updated[field] = [\n ...(Array.isArray(current) ? current : []),\n value,\n ];\n }\n for (const [field, value] of Object.entries(update.$addToSet ?? {})) {\n const current = updated[field];\n const array = Array.isArray(current) ? current : [];\n if (!array.includes(value)) {\n updated[field] = [...array, value];\n }\n }\n for (const [field, delta] of Object.entries(update.$inc ?? {})) {\n // An absent field is created at the increment's value, which is\n // exactly why `$setOnInsert` must not also name it.\n const current = updated[field];\n updated[field] =\n (typeof current === 'number' ? current : 0) + (delta as number);\n }\n return updated;\n };\n\n const documents = documentsOf(name);\n const index = documents.findIndex(doc => matches(doc, query));\n\n if (index === -1) {\n if (options?.upsert !== true) {\n return { matchedCount: 0, modifiedCount: 0, upsertedCount: 0 };\n }\n // The upserted document starts from the query's *equality* fields,\n // the way a real server seeds one — an operator condition contributes\n // nothing, which is why a `$expr`-guarded upsert would insert a row\n // missing the very field it filtered on.\n const seedFields = Object.fromEntries(\n Object.entries(query).filter(\n ([field, condition]) =>\n !field.startsWith('$') && !isPlainObject(condition),\n ),\n );\n const inserted = applyOperators({\n ...seedFields,\n ...(update.$setOnInsert ?? {}),\n });\n assertUnique(name, inserted);\n documents.push(inserted);\n return { matchedCount: 0, modifiedCount: 0, upsertedCount: 1 };\n }\n\n const updated = applyOperators(documents[index]);\n assertUnique(name, updated, documents[index]);\n documents[index] = updated;\n return { matchedCount: 1, modifiedCount: 1, upsertedCount: 0 };\n }),\n\n /**\n * `$set` across every matching document, and the count of what changed.\n *\n * ⚠️ **The count is what a caller branches on.** A settlement run claims its\n * ledger lines with this and reads `modifiedCount === 0` as \"another replica\n * took them all\" — so a fake returning a fixed `1`, or the match count\n * rather than the modified count, would make the losing replica behave like\n * the winning one and the conditional claim would test nothing.\n *\n * `$set` only. Anything else throws, for the reason `updateOne` gives:\n * silently accepting an operator it does not apply lets a spec pass on an\n * update that never happened.\n */\n updateMany: (query: QueryDocument, update: { $set?: Document }) =>\n record(name, 'updateMany', () => {\n const unsupported = Object.keys(update).filter(\n operator => operator !== '$set',\n );\n if (unsupported.length > 0) {\n throw new Error(\n `fake-mongo: updateMany does not implement ${unsupported.join(', ')}`,\n );\n }\n\n const documents = documentsOf(name);\n let modifiedCount = 0;\n documents.forEach((doc, index) => {\n if (!matches(doc, query)) return;\n const updated = { ...doc, ...(update.$set ?? {}) };\n assertUnique(name, updated, doc);\n documents[index] = updated;\n modifiedCount += 1;\n });\n return { matchedCount: modifiedCount, modifiedCount };\n }),\n\n /**\n * Update one document and hand back the result, upserting when asked.\n *\n * ⚠️ **`returnDocument: 'after'` is the only mode implemented, and the\n * default here is `'after'` rather than the driver's `'before'`** — because\n * the callers that need this primitive at all need the merged document. A\n * two-message join upserts its own half and then asks \"is the pair complete\n * now?\", which is a question only the *after* state answers. `'before'`\n * throws rather than quietly returning the wrong half.\n *\n * Implemented over {@link updateOne} so the upsert seeding rule, the\n * conflicting-path refusal and the unique-index enforcement are the same\n * ones, rather than a second copy that could drift from them.\n */\n findOneAndUpdate: (\n query: QueryDocument,\n update: {\n $set?: Document;\n $addToSet?: Document;\n $inc?: Document;\n $setOnInsert?: Document;\n $push?: Document;\n },\n options?: { upsert?: boolean; returnDocument?: 'before' | 'after' },\n ) =>\n record(name, 'findOneAndUpdate', async () => {\n if (options?.returnDocument === 'before') {\n throw new Error(\n 'fake-mongo: findOneAndUpdate only implements returnDocument: \"after\"',\n );\n }\n // Where the document is *before* the write, because afterwards the\n // query may no longer find it: an upsert's operator conditions need not\n // hold of the row it just inserted — `{ folded: { $exists: false } }`\n // matches nothing once `folded` has been set. `documentsOf` hands back\n // the live array, which `updateOne` mutates in place or pushes onto, so\n // the position is enough to identify it either way.\n const documents = documentsOf(name);\n const index = documents.findIndex(doc => matches(doc, query));\n\n const result = await collection(name).updateOne(query, update, {\n upsert: options?.upsert === true,\n });\n if (result.matchedCount === 0 && result.upsertedCount === 0) {\n return null;\n }\n\n return index === -1\n ? documents[documents.length - 1]\n : documents[index];\n }),\n\n deleteOne: (query: QueryDocument) =>\n record(name, 'deleteOne', () => {\n const documents = documentsOf(name);\n const index = documents.findIndex(doc => matches(doc, query));\n if (index === -1) return { deletedCount: 0 };\n documents.splice(index, 1);\n return { deletedCount: 1 };\n }),\n\n /**\n * Declares an index, and **enforces it when it is unique**.\n *\n * Idempotent, like the real one: a service that ensures its index per\n * request rather than at boot — because a tenant database only appears on\n * first write — calls this on every write.\n */\n createIndex: (spec: Document, options?: Document) =>\n record(name, 'createIndex', () => {\n if (options?.['unique'] === true) {\n const fields = Object.keys(spec);\n const existing = uniqueIndexes.get(name) ?? [];\n const already = existing.some(\n candidate =>\n candidate.length === fields.length &&\n candidate.every((field, at) => field === fields[at]),\n );\n if (!already) {\n uniqueIndexes.set(name, [...existing, fields]);\n }\n }\n return { spec, options };\n }),\n });\n\n /**\n * A session whose `withTransaction` really rolls back.\n *\n * ⚠️ **It is atomicity, not isolation, and the difference decides where a\n * test may live.** The store is a single-threaded object graph, so nothing\n * runs concurrently with the body and a \"race\" here resolves in the order it\n * was written: a concurrency property — two writers contending for the last\n * unit — is green under this fake no matter what the code does, and belongs\n * in a `*.live.spec.ts` against real Mongo (ADR 0010).\n *\n * What it *does* model is the abort path, which is worth having: a body that\n * throws leaves the store exactly as it found it, so a conditional write that\n * moves a counter and then fails to write its row cannot leave the counter\n * moved. That is a real bug shape, and one a fake without rollback would hide\n * by committing half of it.\n */\n const startSession = () => {\n let open = true;\n return {\n withTransaction: async (body: () => Promise<unknown>) => {\n const snapshot = new Map(\n [...collections].map(([name, docs]) => [\n name,\n docs.map(doc => ({ ...doc })),\n ]),\n );\n try {\n return await body();\n } catch (error) {\n collections.clear();\n for (const [name, docs] of snapshot) collections.set(name, docs);\n throw error;\n }\n },\n endSession: () => {\n open = false;\n return Promise.resolve();\n },\n get hasEnded() {\n return !open;\n },\n };\n };\n\n return {\n seed: (name, documents) => {\n collections.set(\n name,\n documents.map(doc => ({ ...doc })),\n );\n },\n read: name => documentsOf(name).map(doc => ({ ...doc })),\n failWith: error => {\n failure = error;\n },\n failOn: (operation, error) => {\n failuresByOperation.set(operation, error);\n },\n get operations() {\n return operations;\n },\n startSession,\n db: { collection },\n };\n};\n"],"names":["isPlainObject","value","Array","isArray","compare","left","right","Date","getTime","String","localeCompare","matchesCondition","actual","condition","Object","entries","every","operator","operand","includes","undefined","RegExp","test","TypeError","evaluateExpression","doc","node","startsWith","slice","length","operands","map","child","valuesAt","field","current","segment","split","next","container","element","push","flatMap","NEGATIVE_OPERATORS","Set","isNegativeCondition","keys","some","has","matches","query","candidates","FakeDuplicateKeyError","Error","collection","key","JSON","stringify","code","name","makeFakeMongoDb","seed","collections","Map","docs","d","operations","failure","failuresByOperation","documentsOf","set","get","uniqueIndexes","uniqueIndexesOf","assertUnique","candidate","ignored","fields","clash","find","fromEntries","record","op","produce","scoped","Promise","reject","resolve","error","project","options","copy","projection","sortSpec","skipCount","limitCount","Infinity","cursor","sort","spec","skip","count","limit","toArray","matched","filter","sorted","reduceRight","items","direction","findOne","found","countDocuments","insertMany","documents","stored","document","insertedCount","insertOne","acknowledged","insertedId","replaceOne","replacement","index","findIndex","upsert","matchedCount","upsertedCount","updateOne","update","supported","unsupported","join","conflicting","$setOnInsert","$inc","$set","applyOperators","base","plain","updated","path","filtered","exec","identifier","member","conditions","arrayFilters","$push","$addToSet","array","delta","modifiedCount","seedFields","inserted","updateMany","forEach","findOneAndUpdate","returnDocument","result","deleteOne","deletedCount","splice","createIndex","existing","already","at","startSession","open","withTransaction","body","snapshot","clear","endSession","hasEnded","read","failWith","failOn","oper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;;;GAeC,GACD,MAAM6E,eAAe;QACnB,IAAIC,OAAO;QACX,OAAO;YACLC,iBAAiB,OAAOC;gBACtB,MAAMC,WAAW,IAAI5G,IACnB;uBAAID;iBAAY,CAAC/B,GAAG,CAAC,CAAC,CAAC4B,MAAMK,KAAK,GAAK;wBACrCL;wBACAK,KAAKjC,GAAG,CAACN,CAAAA,MAAQ,aAAKA;qBACvB;gBAEH,IAAI;oBACF,OAAO,MAAMiJ;gBACf,EAAE,OAAOlF,OAAO;oBACd1B,YAAY8G,KAAK;oBACjB,KAAK,MAAM,CAACjH,MAAMK,KAAK,IAAI2G,SAAU7G,YAAYQ,GAAG,CAACX,MAAMK;oBAC3D,MAAMwB;gBACR;YACF;YACAqF,YAAY;gBACVL,OAAO;gBACP,OAAOnF,QAAQE,OAAO;YACxB;YACA,IAAIuF,YAAW;gBACb,OAAO,CAACN;YACV;QACF;IACF;IAEA,OAAO;QACL3G,MAAM,CAACF,MAAMuD;YACXpD,YAAYQ,GAAG,CACbX,MACAuD,UAAUnF,GAAG,CAACN,CAAAA,MAAQ,aAAKA;QAE/B;QACAsJ,MAAMpH,CAAAA,OAAQU,YAAYV,MAAM5B,GAAG,CAACN,CAAAA,MAAQ,aAAKA;QACjDuJ,UAAUxF,CAAAA;YACRrB,UAAUqB;QACZ;QACAyF,QAAQ,CAACC,WAAW1F;YAClBpB,oBAAoBE,GAAG,CAAC4G,WAAW1F;QACrC;QACA,IAAItB,cAAa;YACf,OAAOA;QACT;QACAqG;QACAY,IAAI;YAAE7H;QAAW;IACnB;AACF,EAAE"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@entifix/testing-unit",
3
- "version": "0.1.1",
3
+ "version": "0.1.2",
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": {
@@ -55,8 +55,6 @@
55
55
  },
56
56
  "nx": {
57
57
  "tags": [
58
- "layer:entifix",
59
- "scope:shared",
60
58
  "type:testing",
61
59
  "tier:5"
62
60
  ],
@@ -80,9 +78,9 @@
80
78
  "dependencies": {
81
79
  "@effect/sql": "0.52.1",
82
80
  "@swc/helpers": "0.5.23",
83
- "@entifix/transactions": "0.1.1",
84
- "@entifix/business": "0.1.1",
85
- "@entifix/core": "0.1.1"
81
+ "@entifix/business": "0.1.2",
82
+ "@entifix/transactions": "0.1.2",
83
+ "@entifix/core": "0.1.2"
86
84
  },
87
85
  "peerDependencies": {
88
86
  "@effect/vitest": ">=0.30 <1",
@@ -91,7 +89,7 @@
91
89
  "msw": "*",
92
90
  "react": "*",
93
91
  "vitest": "*",
94
- "@entifix/react-controls": "0.1.1"
92
+ "@entifix/react-controls": "0.1.2"
95
93
  },
96
94
  "peerDependenciesMeta": {
97
95
  "@effect/vitest": {