@entifix/testing-unit 0.3.0 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,6 +1,6 @@
1
+ import { _ as _apply_decs_2203_r } from "@swc/helpers/_/_apply_decs_2203_r";
1
2
  import { _ as _class_private_field_loose_base } from "@swc/helpers/_/_class_private_field_loose_base";
2
3
  import { _ as _class_private_field_loose_key } from "@swc/helpers/_/_class_private_field_loose_key";
3
- import { _ as _apply_decs_2203_r } from "@swc/helpers/_/_apply_decs_2203_r";
4
4
  var _dec, _initClass, _dec1, _dec2, _dec3, _dec4, _dec5, _initProto;
5
5
  import { accessor, entity } from '@entifix/core';
6
6
  import { Exit } from 'effect';
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/doubles/entity-repository.ts"],"sourcesContent":["import type { EntityRepository } from '@entifix/business';\nimport {\n applyFiltering,\n applySorting,\n deserializeSingleEntity,\n EntifixConnError,\n type EntifixError,\n type Entity,\n type EntityConstructor,\n type EntityId,\n type EntityLoadRequest,\n type EntityPage,\n extractMetaAccessors,\n serializeEntity,\n} from '@entifix/core';\nimport { Effect } from 'effect';\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` — the same filtering\n * and sorting rules, which it takes from core's in-memory query evaluation\n * rather than keeping a copy of its own, 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 Effect.sync(() => {\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 ),\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":["applyFiltering","applySorting","deserializeSingleEntity","EntifixConnError","extractMetaAccessors","serializeEntity","Effect","copyOf","entity","entityConstructor","length","succeed","Object","assign","create","getPrototypeOf","makeInMemoryEntityRepository","seed","items","pendingFailure","guard","run","undefined","failure","fail","load","request","matched","filtering","sorting","page","pageSize","start","forEach","slice","pipe","map","copies","total","get","id","found","find","item","save","globalThis","crypto","randomUUID","tap","stored","sync","index","findIndex","push","flatMap","remove","entityOrId","filter","delete","next","failNext","error"],"mappings":"AACA,SACEA,cAAc,EACdC,YAAY,EACZC,uBAAuB,EACvBC,gBAAgB,EAOhBC,oBAAoB,EACpBC,eAAe,QACV,gBAAgB;AACvB,SAASC,MAAM,QAAQ,SAAS;AAEhC;;;;;;;;;CASC,GACD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AAOC,UAAUnB,YACbhB,OAAOkB,IAAI,CACT,IAAIrB,iBAAiB,oBAAoBmB,WAAW;gBAAEkB;YAAG,MAE3DjC,OAAOkC;QACb;IAEF,MAAMG,OAAO,CAAyBpC,SACpCY,MAAM;gBAKQZ;YAJZ,yEAAyE;YACzE,0EAA0E;YAC1E,0EAA0E;YAC1E,oDAAoD;YACpDA,OAAOgC,EAAE,IAAGhC,aAAAA,OAAOgC,EAAE,YAAThC,aAAaqC,WAAWC,MAAM,CAACC,UAAU;YACrD,sEAAsE;YACtE,yEAAyE;YACzE,iEAAiE;YACjE,OAAOxC,OAAOC,QAAQ2B,IAAI,CACxB7B,OAAO0C,GAAG,CAACC,CAAAA,SACT3C,OAAO4C,IAAI,CAAC;oBACV,MAAMC,QAAQjC,MAAMkC,SAAS,CAACT,CAAAA,OAAQA,KAAKH,EAAE,KAAKS,OAAOT,EAAE;oBAC3D,IAAIW,UAAU,CAAC,GAAG;wBAChBjC,MAAMmC,IAAI,CAACJ;oBACb,OAAO;wBACL/B,KAAK,CAACiC,MAAM,GAAGF;oBACjB;gBACF,KAEF3C,OAAOgD,OAAO,CAAC/C;QAEnB;IAEF,MAAMgD,SAAS,CAAyBC,aACtCpC,MAAM;YACJ,MAAMoB,KACJgB,cAAc,QAAQ,OAAOA,eAAe,WACxCA,WAAWhB,EAAE,GACbgB;YACNtC,QAAQA,MAAMuC,MAAM,CAACd,CAAAA,OAAQA,KAAKH,EAAE,KAAKA;YACzC,OAAOlC,OAAOK,OAAO,CAACW;QACxB;IAEF,OAAO;QACLG;QACAc;QACAK;QACAc,QAAQH;QACR,IAAIrC,SAAQ;YACV,OAAOA;QACT;QACAD,MAAM,CAAC0C;YACLzC,QAAQ;mBAAIyC;aAAK;QACnB;QACAC,UAAU,CAACC;YACT1C,iBAAiB0C;QACnB;IAGF;AACF,EAAE"}
1
+ {"version":3,"sources":["../../src/doubles/entity-repository.ts"],"sourcesContent":["import type { EntityRepository } from '@entifix/business';\nimport {\n applyFiltering,\n applySorting,\n deserializeSingleEntity,\n EntifixConnError,\n type EntifixError,\n type Entity,\n type EntityConstructor,\n type EntityId,\n type EntityLoadRequest,\n type EntityPage,\n extractMetaAccessors,\n serializeEntity,\n} from '@entifix/core';\nimport { Effect } from 'effect';\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` — the same filtering\n * and sorting rules, which it takes from core's in-memory query evaluation\n * rather than keeping a copy of its own, 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 Effect.sync(() => {\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 ),\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":["applyFiltering","applySorting","deserializeSingleEntity","EntifixConnError","extractMetaAccessors","serializeEntity","Effect","copyOf","entity","entityConstructor","length","succeed","Object","assign","create","getPrototypeOf","makeInMemoryEntityRepository","seed","items","pendingFailure","guard","run","undefined","failure","fail","load","request","matched","filtering","sorting","page","pageSize","start","forEach","slice","pipe","map","copies","total","get","id","found","find","item","save","globalThis","crypto","randomUUID","tap","stored","sync","index","findIndex","push","flatMap","remove","entityOrId","filter","delete","next","failNext","error"],"mappings":"AACA,SACEA,cAAc,EACdC,YAAY,EACZC,uBAAuB,EACvBC,gBAAgB,EAOhBC,oBAAoB,EACpBC,eAAe,QACV,gBAAgB;AACvB,SAASC,MAAM,QAAQ,SAAS;AAEhC;;;;;;;;;CASC,GACD,MAAMC,SAAS,CACbC;IAEA,MAAMC,oBAAoBD,OAAO,WAAW;IAC5C,IAAIJ,qBAAqBK,mBAAmBC,MAAM,KAAK,GAAG;QACxD,OAAOJ,OAAOK,OAAO,CACnBC,OAAOC,MAAM,CACXD,OAAOE,MAAM,CAACF,OAAOG,cAAc,CAACP,UACpCA;IAGN;IACA,gEAAgE;IAChE,iDAAiD;IACjD,OAAON,wBACLO,mBACAJ,gBAAgBI,mBAAmBD;AAEvC;AAcA;;;;;;;;;CASC,GACD,OAAO,MAAMQ,+BAA+B,CAC1CC,OAAiB,EAAE;IAEnB,IAAIC,QAAQ;WAAID;KAAK;IACrB,IAAIE;IAEJ,iDAAiD,GACjD,MAAMC,QAAQ,CACZC;QAEA,IAAIF,mBAAmBG,WAAW;YAChC,MAAMC,UAAUJ;YAChBA,iBAAiBG;YACjB,OAAOhB,OAAOkB,IAAI,CAACD;QACr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,IAAIW,UAAU,CAAC,GAAG;wBAChBjC,MAAMmC,IAAI,CAACJ;oBACb,OAAO;wBACL/B,KAAK,CAACiC,MAAM,GAAGF;oBACjB;gBACF,KAEF3C,OAAOgD,OAAO,CAAC/C;QAEnB;IAEF,MAAMgD,SAAS,CAAyBC,aACtCpC,MAAM;YACJ,MAAMoB,KACJgB,cAAc,QAAQ,OAAOA,eAAe,WACxCA,WAAWhB,EAAE,GACbgB;YACNtC,QAAQA,MAAMuC,MAAM,CAACd,CAAAA,OAAQA,KAAKH,EAAE,KAAKA;YACzC,OAAOlC,OAAOK,OAAO,CAACW;QACxB;IAEF,OAAO;QACLG;QACAc;QACAK;QACAc,QAAQH;QACR,IAAIrC;YACF,OAAOA;QACT;QACAD,MAAM,CAAC0C;YACLzC,QAAQ;mBAAIyC;aAAK;QACnB;QACAC,UAAU,CAACC;YACT1C,iBAAiB0C;QACnB;IAGF;AACF,EAAE"}
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/doubles/link-resolver.ts"],"sourcesContent":["import {\n EntifixConnError,\n type Entity,\n type EntityConstructor,\n type EntityId,\n type EntityLinkResolver,\n} from '@entifix/core';\nimport { Effect } from 'effect';\n\nexport interface InMemoryEntityLinkResolver extends EntityLinkResolver {\n /** Every (constructor, id) pair the resolver was asked for, in order. */\n readonly requested: ReadonlyArray<{ entity: string; id: EntityId }>;\n}\n\n/**\n * In-memory {@link EntityLinkResolver} over a per-constructor table of targets.\n *\n * A use-case that follows links yields `EntityLinkResolverTag`, so this is the\n * double that lets link-following be tested without any adapter at all — and\n * `requested` shows whether an already-embedded link was needlessly refetched.\n */\nexport const makeInMemoryEntityLinkResolver = (\n entries: ReadonlyArray<readonly [EntityConstructor<Entity>, Entity[]]>,\n): InMemoryEntityLinkResolver => {\n const tables = new Map<unknown, Entity[]>(\n entries.map(([constructor, items]) => [constructor, items]),\n );\n const requested: Array<{ entity: string; id: EntityId }> = [];\n\n return {\n resolve: <TEntity extends Entity>(\n entityConstructor: EntityConstructor<TEntity>,\n id: EntityId,\n ) =>\n Effect.suspend(() => {\n requested.push({ entity: entityConstructor.name, id });\n const found = tables\n .get(entityConstructor)\n ?.find(item => item.id === id);\n return found === undefined\n ? Effect.fail(\n new EntifixConnError('Link target not found', undefined, {\n entity: entityConstructor.name,\n id,\n }),\n )\n : Effect.succeed(found as TEntity);\n }),\n get requested() {\n return requested;\n },\n };\n};\n"],"names":["EntifixConnError","Effect","makeInMemoryEntityLinkResolver","entries","tables","Map","map","constructor","items","requested","resolve","entityConstructor","id","suspend","push","entity","name","found","get","find","item","undefined","fail","succeed"],"mappings":"AAAA,SACEA,gBAAgB,QAKX,gBAAgB;AACvB,SAASC,MAAM,QAAQ,SAAS;AAOhC;;;;;;CAMC,GACD,OAAO,MAAMC,iCAAiC,CAC5CC;IAEA,MAAMC,SAAS,IAAIC,IACjBF,QAAQG,GAAG,CAAC,CAAC,CAACC,aAAaC,MAAM,GAAK;YAACD;YAAaC;SAAM;IAE5D,MAAMC,YAAqD,EAAE;IAE7D,OAAO;QACLC,SAAS,CACPC,mBACAC,KAEAX,OAAOY,OAAO,CAAC;oBAECT;gBADdK,UAAUK,IAAI,CAAC;oBAAEC,QAAQJ,kBAAkBK,IAAI;oBAAEJ;gBAAG;gBACpD,MAAMK,SAAQb,cAAAA,OACXc,GAAG,CAACP,uCADOP,YAEVe,IAAI,CAACC,CAAAA,OAAQA,KAAKR,EAAE,KAAKA;gBAC7B,OAAOK,UAAUI,YACbpB,OAAOqB,IAAI,CACT,IAAItB,iBAAiB,yBAAyBqB,WAAW;oBACvDN,QAAQJ,kBAAkBK,IAAI;oBAC9BJ;gBACF,MAEFX,OAAOsB,OAAO,CAACN;YACrB;QACF,IAAIR,aAAY;YACd,OAAOA;QACT;IACF;AACF,EAAE"}
1
+ {"version":3,"sources":["../../src/doubles/link-resolver.ts"],"sourcesContent":["import {\n EntifixConnError,\n type Entity,\n type EntityConstructor,\n type EntityId,\n type EntityLinkResolver,\n} from '@entifix/core';\nimport { Effect } from 'effect';\n\nexport interface InMemoryEntityLinkResolver extends EntityLinkResolver {\n /** Every (constructor, id) pair the resolver was asked for, in order. */\n readonly requested: ReadonlyArray<{ entity: string; id: EntityId }>;\n}\n\n/**\n * In-memory {@link EntityLinkResolver} over a per-constructor table of targets.\n *\n * A use-case that follows links yields `EntityLinkResolverTag`, so this is the\n * double that lets link-following be tested without any adapter at all — and\n * `requested` shows whether an already-embedded link was needlessly refetched.\n */\nexport const makeInMemoryEntityLinkResolver = (\n entries: ReadonlyArray<readonly [EntityConstructor<Entity>, Entity[]]>,\n): InMemoryEntityLinkResolver => {\n const tables = new Map<unknown, Entity[]>(\n entries.map(([constructor, items]) => [constructor, items]),\n );\n const requested: Array<{ entity: string; id: EntityId }> = [];\n\n return {\n resolve: <TEntity extends Entity>(\n entityConstructor: EntityConstructor<TEntity>,\n id: EntityId,\n ) =>\n Effect.suspend(() => {\n requested.push({ entity: entityConstructor.name, id });\n const found = tables\n .get(entityConstructor)\n ?.find(item => item.id === id);\n return found === undefined\n ? Effect.fail(\n new EntifixConnError('Link target not found', undefined, {\n entity: entityConstructor.name,\n id,\n }),\n )\n : Effect.succeed(found as TEntity);\n }),\n get requested() {\n return requested;\n },\n };\n};\n"],"names":["EntifixConnError","Effect","makeInMemoryEntityLinkResolver","entries","tables","Map","map","constructor","items","requested","resolve","entityConstructor","id","suspend","push","entity","name","found","get","find","item","undefined","fail","succeed"],"mappings":"AAAA,SACEA,gBAAgB,QAKX,gBAAgB;AACvB,SAASC,MAAM,QAAQ,SAAS;AAOhC;;;;;;CAMC,GACD,OAAO,MAAMC,iCAAiC,CAC5CC;IAEA,MAAMC,SAAS,IAAIC,IACjBF,QAAQG,GAAG,CAAC,CAAC,CAACC,aAAaC,MAAM,GAAK;YAACD;YAAaC;SAAM;IAE5D,MAAMC,YAAqD,EAAE;IAE7D,OAAO;QACLC,SAAS,CACPC,mBACAC,KAEAX,OAAOY,OAAO,CAAC;oBAECT;gBADdK,UAAUK,IAAI,CAAC;oBAAEC,QAAQJ,kBAAkBK,IAAI;oBAAEJ;gBAAG;gBACpD,MAAMK,SAAQb,cAAAA,OACXc,GAAG,CAACP,uCADOP,YAEVe,IAAI,CAACC,CAAAA,OAAQA,KAAKR,EAAE,KAAKA;gBAC7B,OAAOK,UAAUI,YACbpB,OAAOqB,IAAI,CACT,IAAItB,iBAAiB,yBAAyBqB,WAAW;oBACvDN,QAAQJ,kBAAkBK,IAAI;oBAC9BJ;gBACF,MAEFX,OAAOsB,OAAO,CAACN;YACrB;QACF,IAAIR;YACF,OAAOA;QACT;IACF;AACF,EAAE"}
@@ -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 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;gBACh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,WAAWR;;gBAEbD,UAAUhD,GAAG,CAAC4D,QAAQtB;gBACtB,OAAOA;YACT;QACF,IAAIU,aAAY;YACd,OAAO;mBAAIA,UAAU/B,MAAM;aAAG;QAChC;IACF;AACF,EAAE"}
1
+ {"version":3,"sources":["../../src/doubles/transaction-ports.ts"],"sourcesContent":["import {\n type DomainEvent,\n 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,IAAIe;YACF,OAAO;mBAAItB,OAAOuB,IAAI;aAAG;QAC3B;QACA,IAAInB;YACF,OAAOA;QACT;QACAoB,WAAWjB,CAAAA;YACTL,UAAUuB,GAAG,CAAClB;QAChB;IACF;AACF,EAAE;AAOF;;;CAGC,GACD,OAAO,MAAMmB,8BAA8B;IACzC,MAAMC,YAAY,IAAI1B;I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A,QAAU,aAAKA;oBAAOa;;QACvCC,eAAe,CAACP,QAAQQ,UACtBT,OAAOC,QAAQP,CAAAA,QAAU,aACpBA;oBACHgB,UAAU;2BAAIhB,MAAMgB,QAAQ;wBAAED;qBAAQ;;QAE1CE,QAAQ,CAACV,QAAQN,OAAOiB,QACtBZ,OAAOC,QAAQP,CAAAA,QAAU,aAAKA;oBAAOC;oBAAOiB;;QAC9CC,iBAAiB,CAACZ,QAAQa,SACxBd,OAAOC,QAAQP,CAAAA,QAAU,aACpBA;oBACHgB,UAAUhB,MAAMgB,QAAQ,CAACxB,GAAG,CAACuB,CAAAA,UAC3BA,QAAQK,MAAM,KAAKA,SACf,aAAKL;4BAASM,aAAa;6BAC3BN;;QAGV7D,KAAKqD,CAAAA,SAAU3E,OAAOqB,IAAI,CAAC,IAAM0C,UAAUzC,GAAG,CAACqD;QAC/Ce,WAAWnB,CAAAA,cACTvE,OAAOqB,IAAI,CAAC,IACV;uBAAI0C,UAAU/B,MAAM;iBAAG,CAACiB,MAAM,CAC5BmB,CAAAA,QAASD,WAAWC,UAAUE,aAAaF,OAAOG;QAGxDoB,gBAAgB,CAAChB,QAAQJ,cACvBvE,OAAOqB,IAAI,CAAC;gBACV,MAAMwD,UAAUd,UAAUzC,GAAG,CAACqD;gBAC9B,IACEE,YAAYhE,aACZ,CAACsD,WAAWU,YACZ,CAACP,aAAaO,SAASN,cACvB;oBACA,OAAO1D;gBACT;gBACA,MAAMwC,UAAU,aACXwB;oBACHe,gBAAgBf,QAAQe,cAAc,GAAG;oBACzCpB,WAAWR;;gBAEbD,UAAUhD,GAAG,CAAC4D,QAAQtB;gBACtB,OAAOA;YACT;QACF,IAAIU;YACF,OAAO;mBAAIA,UAAU/B,MAAM;aAAG;QAChC;IACF;AACF,EAAE"}
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/drivers/fake-amqp.ts"],"sourcesContent":["import { matchesEventPattern } from '@entifix/core';\n\n/**\n * A fake of the amqplib channel, not of the {@link EventBus} port.\n *\n * `makeAmqpEventBus` runs on top of it, so the envelope framing, the\n * `prefetch(1)` the saga tracker depends on, and the ack/nack policy are\n * all exercised for real.\n */\n\nexport interface FakeAmqpMessage {\n content: Buffer;\n}\n\nexport interface FakeAmqpChannel {\n /** Everything published, decoded from the wire. */\n readonly published: ReadonlyArray<{\n exchange: string;\n routingKey: string;\n body: unknown;\n }>;\n /**\n * Every queue binding the adapter asked for. Recorded because the exchange is\n * a topic now: the pattern a subscriber binds is the whole of its routing, so\n * a fake that swallowed it would let a wrong binding pass every test.\n */\n readonly bindings: ReadonlyArray<{\n queue: string;\n exchange: string;\n pattern: string;\n }>;\n /**\n * Every exchange the adapter declared, with its type. Recorded because the\n * dead-letter exchange is `direct` while the event exchange is `topic`, and a\n * broker will not retype an existing exchange — declaring the wrong type is a\n * failure that only appears against a real broker.\n */\n readonly exchanges: ReadonlyArray<{\n exchange: string;\n type: string;\n options: Record<string, unknown> | undefined;\n }>;\n /**\n * Every queue the adapter declared, with the arguments it declared it with.\n * The arguments *are* the delivery policy — `x-queue-type`,\n * `x-delivery-limit`, `x-dead-letter-exchange` — so a fake that swallowed\n * them would let a queue with no retry ceiling and no dead-letter path pass\n * every test, which is the exact defect ADR 0030 exists to close.\n */\n readonly queues: ReadonlyArray<{\n queue: string;\n options: Record<string, unknown> | undefined;\n }>;\n /** Messages acked, so the success policy can be asserted. */\n readonly acked: FakeAmqpMessage[];\n /**\n * Messages nacked, **with their flags**. `requeue` is the whole distinction\n * between a transient failure the broker should retry and a poison message it\n * should quarantine at once, so recording only that a nack happened is how\n * \"dead-letters a failed message\" stayed a passing test for a bus that\n * discarded it.\n */\n readonly nacked: ReadonlyArray<{\n message: FakeAmqpMessage;\n allUpTo: boolean;\n requeue: boolean;\n }>;\n /** The prefetch the adapter asked for — 1, or the fold races. */\n readonly prefetchCount: number | undefined;\n /**\n * The consumer tags cancelled, in order.\n *\n * Recorded rather than merely accepted because a graceful shutdown's first\n * phase *is* the cancel (ADR 0030): a connector that dropped the tag on the\n * floor would pass every test while leaving the broker delivering into a\n * process that is closing its connection.\n */\n readonly cancelled: readonly string[];\n /**\n * Pushes a message to the consumers whose binding matches it, as the broker\n * would. The routing key defaults to the envelope's own `meta.event.name`,\n * which is what the adapter publishes with.\n */\n deliver(body: unknown, routingKey?: string): Promise<void>;\n /** Pushes a raw payload, for malformed-message paths. */\n deliverRaw(payload: string): Promise<void>;\n /** Simulates the broker cancelling the consumer (amqplib delivers `null`). */\n deliverCancellation(): Promise<void>;\n /** Makes every subsequent channel call throw/reject with `error`. */\n failWith(error: unknown): void;\n /** The object to pass where an amqplib `Channel` is expected. */\n readonly channel: unknown;\n}\n\n/** The routing key a body would have been published with. */\nconst routingKeyOf = (body: unknown): string => {\n const event = (body as { meta?: { event?: { name?: unknown } } })?.meta\n ?.event;\n return typeof event?.name === 'string' ? event.name : '';\n};\n\nexport const makeFakeAmqpChannel = (): FakeAmqpChannel => {\n const published: Array<{\n exchange: string;\n routingKey: string;\n body: unknown;\n }> = [];\n const bindings: Array<{ queue: string; exchange: string; pattern: string }> =\n [];\n const exchanges: Array<{\n exchange: string;\n type: string;\n options: Record<string, unknown> | undefined;\n }> = [];\n const queues: Array<{\n queue: string;\n options: Record<string, unknown> | undefined;\n }> = [];\n const acked: FakeAmqpMessage[] = [];\n const nacked: Array<{\n message: FakeAmqpMessage;\n allUpTo: boolean;\n requeue: boolean;\n }> = [];\n let consumer: ((message: FakeAmqpMessage | null) => void) | undefined;\n const cancelled: string[] = [];\n let consumerTags = 0;\n let boundQueue: string | undefined;\n let prefetchCount: number | undefined;\n let failure: unknown;\n\n const guard = () => {\n if (failure !== undefined) throw failure;\n };\n\n const channel = {\n publish: (exchange: string, routingKey: string, content: Buffer) => {\n guard();\n published.push({\n exchange,\n routingKey,\n body: JSON.parse(content.toString()) as unknown,\n });\n return true;\n },\n prefetch: async (count: number) => {\n guard();\n prefetchCount = count;\n },\n assertExchange: async (\n exchange: string,\n type: string,\n options?: Record<string, unknown>,\n ) => {\n guard();\n exchanges.push({ exchange, type, options });\n return { exchange };\n },\n assertQueue: async (queue: string, options?: Record<string, unknown>) => {\n guard();\n const name = queue === '' ? 'amq.gen-fake' : queue;\n queues.push({ queue: name, options });\n return { queue: name };\n },\n bindQueue: async (queue: string, exchange: string, pattern: string) => {\n guard();\n bindings.push({ queue, exchange, pattern });\n },\n consume: async (\n queue: string,\n handler: (message: FakeAmqpMessage | null) => void,\n ) => {\n guard();\n consumer = handler;\n boundQueue = queue;\n // A fresh tag per `consume`, so a reconnect's re-bind is distinguishable\n // from the binding it replaced — the connector cancels what it currently\n // holds, and a constant tag would hide it cancelling a stale one.\n consumerTags += 1;\n return { consumerTag: `fake-consumer-${consumerTags}` };\n },\n cancel: async (consumerTag: string) => {\n guard();\n cancelled.push(consumerTag);\n consumer = undefined;\n },\n ack: (message: FakeAmqpMessage) => {\n acked.push(message);\n },\n nack: (message: FakeAmqpMessage, allUpTo: boolean, requeue: boolean) => {\n nacked.push({ message, allUpTo, requeue });\n },\n close: async () => {\n guard();\n },\n };\n\n /**\n * The adapter acks/nacks from inside a floating promise chain, so a delivery\n * is only settled once the microtask queue drains.\n */\n const settle = () => new Promise<void>(resolve => setTimeout(resolve, 0));\n\n /**\n * Whether the consumer's queue is bound to a pattern matching `routingKey`.\n * The broker decides this in production, so the fake has to as well — without\n * it every subscriber sees every message and the topic exchange is untested.\n */\n const routes = (routingKey: string) =>\n bindings.some(\n binding =>\n binding.queue === boundQueue &&\n matchesEventPattern(binding.pattern, routingKey),\n );\n\n /**\n * `routingKey === undefined` means \"the broker already routed this\" — used by\n * the malformed-payload path, where the message reached the queue and it is\n * the *content* that is wrong.\n */\n const push = async (payload: string, routingKey: string | undefined) => {\n if (consumer === undefined) {\n throw new Error('fake amqp: nothing subscribed yet');\n }\n if (routingKey !== undefined && !routes(routingKey)) {\n return;\n }\n consumer({ content: Buffer.from(payload) });\n await settle();\n };\n\n return {\n get published() {\n return published;\n },\n get bindings() {\n return bindings;\n },\n get exchanges() {\n return exchanges;\n },\n get queues() {\n return queues;\n },\n get acked() {\n return acked;\n },\n get nacked() {\n return nacked;\n },\n get prefetchCount() {\n return prefetchCount;\n },\n get cancelled() {\n return cancelled;\n },\n deliver: (body, routingKey) =>\n push(JSON.stringify(body), routingKey ?? routingKeyOf(body)),\n deliverRaw: payload => push(payload, undefined),\n deliverCancellation: async () => {\n if (consumer === undefined) {\n throw new Error('fake amqp: nothing subscribed yet');\n }\n consumer(null);\n await settle();\n },\n failWith: error => {\n failure = error;\n },\n channel,\n };\n};\n"],"names":["matchesEventPattern","routingKeyOf","body","event","meta","name","makeFakeAmqpChannel","published","bindings","exchanges","queues","acked","nacked","consumer","cancelled","consumerTags","boundQueue","prefetchCount","failure","guard","undefined","channel","publish","exchange","routingKey","content","push","JSON","parse","toString","prefetch","count","assertExchange","type","options","assertQueue","queue","bindQueue","pattern","consume","handler","consumerTag","cancel","ack","message","nack","allUpTo","requeue","close","settle","Promise","resolve","setTimeout","routes","some","binding","payload","Error","Buffer","from","deliver","stringify","deliverRaw","deliverCancellation","failWith","error"],"mappings":"AAAA,SAASA,mBAAmB,QAAQ,gBAAgB;AA8FpD,2DAA2D,GAC3D,MAAMC,eAAe,CAACC;QACN;IAAd,MAAMC,QAASD,yBAAD,aAAA,AAACA,KAAoDE,IAAI,qBAAzD,WACVD,KAAK;IACT,OAAO,QAAOA,yBAAAA,MAAOE,IAAI,MAAK,WAAWF,MAAME,IAAI,GAAG;AACxD;AAEA,OAAO,MAAMC,sBAAsB;IACjC,MAAMC,YAID,EAAE;IACP,MAAMC,WACJ,EAAE;IACJ,MAAMC,YAID,EAAE;IACP,MAAMC,SAGD,EAAE;IACP,MAAMC,QAA2B,EAAE;IACnC,MAAMC,SAID,EAAE;IACP,IAAIC;IACJ,MAAMC,YAAsB,EAAE;IAC9B,IAAIC,eAAe;IACnB,IAAIC;IACJ,IAAIC;IACJ,IAAIC;IAEJ,MAAMC,QAAQ;QACZ,IAAID,YAAYE,WAAW,MAAMF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,IAAI,CACXC,CAAAA,UACEA,QAAQnB,KAAK,KAAKpB,cAClBhB,oBAAoBuD,QAAQjB,OAAO,EAAEd;IAG3C;;;;GAIC,GACD,MAAME,OAAO,OAAO8B,SAAiBhC;QACnC,IAAIX,aAAaO,WAAW;YAC1B,MAAM,IAAIqC,MAAM;QAClB;QACA,IAAIjC,eAAeJ,aAAa,CAACiC,OAAO7B,aAAa;YACnD;QACF;QACAX,SAAS;YAAEY,SAASiC,OAAOC,IAAI,CAACH;QAAS;QACzC,MAAMP;IACR;IAEA,OAAO;QACL,IAAI1C,aAAY;YACd,OAAOA;QACT;QACA,IAAIC,YAAW;YACb,OAAOA;QACT;QACA,IAAIC,aAAY;YACd,OAAOA;QACT;QACA,IAAIC,UAAS;YACX,OAAOA;QACT;QACA,IAAIC,SAAQ;YACV,OAAOA;QACT;QACA,IAAIC,UAAS;YACX,OAAOA;QACT;QACA,IAAIK,iBAAgB;YAClB,OAAOA;QACT;QACA,IAAIH,aAAY;YACd,OAAOA;QACT;QACA8C,SAAS,CAAC1D,MAAMsB,aACdE,KAAKC,KAAKkC,SAAS,CAAC3D,OAAOsB,qBAAAA,aAAcvB,aAAaC;QACxD4D,YAAYN,CAAAA,UAAW9B,KAAK8B,SAASpC;QACrC2C,qBAAqB;YACnB,IAAIlD,aAAaO,WAAW;gBAC1B,MAAM,IAAIqC,MAAM;YAClB;YACA5C,SAAS;YACT,MAAMoC;QACR;QACAe,UAAUC,CAAAA;YACR/C,UAAU+C;QACZ;QACA5C;IACF;AACF,EAAE"}
1
+ {"version":3,"sources":["../../src/drivers/fake-amqp.ts"],"sourcesContent":["import { matchesEventPattern } from '@entifix/core';\n\n/**\n * A fake of the amqplib channel, not of the {@link EventBus} port.\n *\n * `makeAmqpEventBus` runs on top of it, so the envelope framing, the\n * `prefetch(1)` the saga tracker depends on, and the ack/nack policy are\n * all exercised for real.\n */\n\nexport interface FakeAmqpMessage {\n content: Buffer;\n}\n\nexport interface FakeAmqpChannel {\n /** Everything published, decoded from the wire. */\n readonly published: ReadonlyArray<{\n exchange: string;\n routingKey: string;\n body: unknown;\n }>;\n /**\n * Every queue binding the adapter asked for. Recorded because the exchange is\n * a topic now: the pattern a subscriber binds is the whole of its routing, so\n * a fake that swallowed it would let a wrong binding pass every test.\n */\n readonly bindings: ReadonlyArray<{\n queue: string;\n exchange: string;\n pattern: string;\n }>;\n /**\n * Every exchange the adapter declared, with its type. Recorded because the\n * dead-letter exchange is `direct` while the event exchange is `topic`, and a\n * broker will not retype an existing exchange — declaring the wrong type is a\n * failure that only appears against a real broker.\n */\n readonly exchanges: ReadonlyArray<{\n exchange: string;\n type: string;\n options: Record<string, unknown> | undefined;\n }>;\n /**\n * Every queue the adapter declared, with the arguments it declared it with.\n * The arguments *are* the delivery policy — `x-queue-type`,\n * `x-delivery-limit`, `x-dead-letter-exchange` — so a fake that swallowed\n * them would let a queue with no retry ceiling and no dead-letter path pass\n * every test, which is the exact defect ADR 0030 exists to close.\n */\n readonly queues: ReadonlyArray<{\n queue: string;\n options: Record<string, unknown> | undefined;\n }>;\n /** Messages acked, so the success policy can be asserted. */\n readonly acked: FakeAmqpMessage[];\n /**\n * Messages nacked, **with their flags**. `requeue` is the whole distinction\n * between a transient failure the broker should retry and a poison message it\n * should quarantine at once, so recording only that a nack happened is how\n * \"dead-letters a failed message\" stayed a passing test for a bus that\n * discarded it.\n */\n readonly nacked: ReadonlyArray<{\n message: FakeAmqpMessage;\n allUpTo: boolean;\n requeue: boolean;\n }>;\n /** The prefetch the adapter asked for — 1, or the fold races. */\n readonly prefetchCount: number | undefined;\n /**\n * The consumer tags cancelled, in order.\n *\n * Recorded rather than merely accepted because a graceful shutdown's first\n * phase *is* the cancel (ADR 0030): a connector that dropped the tag on the\n * floor would pass every test while leaving the broker delivering into a\n * process that is closing its connection.\n */\n readonly cancelled: readonly string[];\n /**\n * Pushes a message to the consumers whose binding matches it, as the broker\n * would. The routing key defaults to the envelope's own `meta.event.name`,\n * which is what the adapter publishes with.\n */\n deliver(body: unknown, routingKey?: string): Promise<void>;\n /** Pushes a raw payload, for malformed-message paths. */\n deliverRaw(payload: string): Promise<void>;\n /** Simulates the broker cancelling the consumer (amqplib delivers `null`). */\n deliverCancellation(): Promise<void>;\n /** Makes every subsequent channel call throw/reject with `error`. */\n failWith(error: unknown): void;\n /** The object to pass where an amqplib `Channel` is expected. */\n readonly channel: unknown;\n}\n\n/** The routing key a body would have been published with. */\nconst routingKeyOf = (body: unknown): string => {\n const event = (body as { meta?: { event?: { name?: unknown } } })?.meta\n ?.event;\n return typeof event?.name === 'string' ? event.name : '';\n};\n\nexport const makeFakeAmqpChannel = (): FakeAmqpChannel => {\n const published: Array<{\n exchange: string;\n routingKey: string;\n body: unknown;\n }> = [];\n const bindings: Array<{ queue: string; exchange: string; pattern: string }> =\n [];\n const exchanges: Array<{\n exchange: string;\n type: string;\n options: Record<string, unknown> | undefined;\n }> = [];\n const queues: Array<{\n queue: string;\n options: Record<string, unknown> | undefined;\n }> = [];\n const acked: FakeAmqpMessage[] = [];\n const nacked: Array<{\n message: FakeAmqpMessage;\n allUpTo: boolean;\n requeue: boolean;\n }> = [];\n let consumer: ((message: FakeAmqpMessage | null) => void) | undefined;\n const cancelled: string[] = [];\n let consumerTags = 0;\n let boundQueue: string | undefined;\n let prefetchCount: number | undefined;\n let failure: unknown;\n\n const guard = () => {\n if (failure !== undefined) throw failure;\n };\n\n const channel = {\n publish: (exchange: string, routingKey: string, content: Buffer) => {\n guard();\n published.push({\n exchange,\n routingKey,\n body: JSON.parse(content.toString()) as unknown,\n });\n return true;\n },\n prefetch: async (count: number) => {\n guard();\n prefetchCount = count;\n },\n assertExchange: async (\n exchange: string,\n type: string,\n options?: Record<string, unknown>,\n ) => {\n guard();\n exchanges.push({ exchange, type, options });\n return { exchange };\n },\n assertQueue: async (queue: string, options?: Record<string, unknown>) => {\n guard();\n const name = queue === '' ? 'amq.gen-fake' : queue;\n queues.push({ queue: name, options });\n return { queue: name };\n },\n bindQueue: async (queue: string, exchange: string, pattern: string) => {\n guard();\n bindings.push({ queue, exchange, pattern });\n },\n consume: async (\n queue: string,\n handler: (message: FakeAmqpMessage | null) => void,\n ) => {\n guard();\n consumer = handler;\n boundQueue = queue;\n // A fresh tag per `consume`, so a reconnect's re-bind is distinguishable\n // from the binding it replaced — the connector cancels what it currently\n // holds, and a constant tag would hide it cancelling a stale one.\n consumerTags += 1;\n return { consumerTag: `fake-consumer-${consumerTags}` };\n },\n cancel: async (consumerTag: string) => {\n guard();\n cancelled.push(consumerTag);\n consumer = undefined;\n },\n ack: (message: FakeAmqpMessage) => {\n acked.push(message);\n },\n nack: (message: FakeAmqpMessage, allUpTo: boolean, requeue: boolean) => {\n nacked.push({ message, allUpTo, requeue });\n },\n close: async () => {\n guard();\n },\n };\n\n /**\n * The adapter acks/nacks from inside a floating promise chain, so a delivery\n * is only settled once the microtask queue drains.\n */\n const settle = () => new Promise<void>(resolve => setTimeout(resolve, 0));\n\n /**\n * Whether the consumer's queue is bound to a pattern matching `routingKey`.\n * The broker decides this in production, so the fake has to as well — without\n * it every subscriber sees every message and the topic exchange is untested.\n */\n const routes = (routingKey: string) =>\n bindings.some(\n binding =>\n binding.queue === boundQueue &&\n matchesEventPattern(binding.pattern, routingKey),\n );\n\n /**\n * `routingKey === undefined` means \"the broker already routed this\" — used by\n * the malformed-payload path, where the message reached the queue and it is\n * the *content* that is wrong.\n */\n const push = async (payload: string, routingKey: string | undefined) => {\n if (consumer === undefined) {\n throw new Error('fake amqp: nothing subscribed yet');\n }\n if (routingKey !== undefined && !routes(routingKey)) {\n return;\n }\n consumer({ content: Buffer.from(payload) });\n await settle();\n };\n\n return {\n get published() {\n return published;\n },\n get bindings() {\n return bindings;\n },\n get exchanges() {\n return exchanges;\n },\n get queues() {\n return queues;\n },\n get acked() {\n return acked;\n },\n get nacked() {\n return nacked;\n },\n get prefetchCount() {\n return prefetchCount;\n },\n get cancelled() {\n return cancelled;\n },\n deliver: (body, routingKey) =>\n push(JSON.stringify(body), routingKey ?? routingKeyOf(body)),\n deliverRaw: payload => push(payload, undefined),\n deliverCancellation: async () => {\n if (consumer === undefined) {\n throw new Error('fake amqp: nothing subscribed yet');\n }\n consumer(null);\n await settle();\n },\n failWith: error => {\n failure = error;\n },\n channel,\n };\n};\n"],"names":["matchesEventPattern","routingKeyOf","body","event","meta","name","makeFakeAmqpChannel","published","bindings","exchanges","queues","acked","nacked","consumer","cancelled","consumerTags","boundQueue","prefetchCount","failure","guard","undefined","channel","publish","exchange","routingKey","content","push","JSON","parse","toString","prefetch","count","assertExchange","type","options","assertQueue","queue","bindQueue","pattern","consume","handler","consumerTag","cancel","ack","message","nack","allUpTo","requeue","close","settle","Promise","resolve","setTimeout","routes","some","binding","payload","Error","Buffer","from","deliver","stringify","deliverRaw","deliverCancellation","failWith","error"],"mappings":"AAAA,SAASA,mBAAmB,QAAQ,gBAAgB;AA8FpD,2DAA2D,GAC3D,MAAMC,eAAe,CAACC;QACN;IAAd,MAAMC,QAASD,yBAAD,aAAA,AAACA,KAAoDE,IAAI,qBAAzD,WACVD,KAAK;IACT,OAAO,QAAOA,yBAAAA,MAAOE,IAAI,MAAK,WAAWF,MAAME,IAAI,GAAG;AACxD;AAEA,OAAO,MAAMC,sBAAsB;IACjC,MAAMC,YAID,EAAE;IACP,MAAMC,WACJ,EAAE;IACJ,MAAMC,YAID,EAAE;IACP,MAAMC,SAGD,EAAE;IACP,MAAMC,QAA2B,EAAE;IACnC,MAAMC,SAID,EAAE;IACP,IAAIC;IACJ,MAAMC,YAAsB,EAAE;IAC9B,IAAIC,eAAe;IACnB,IAAIC;IACJ,IAAIC;IACJ,IAAIC;IAEJ,MAAMC,QAAQ;QACZ,IAAID,YAAYE,WAAW,MAAMF;IACnC;IAEA,MAAMG,UAAU;QACdC,SAAS,CAACC,UAAkBC,YAAoBC;YAC9CN;YACAZ,UAAUmB,IAAI,CAAC;gBACbH;gBACAC;gBACAtB,MAAMyB,KAAKC,KAAK,CAACH,QAAQI,QAAQ;YAC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AW;YAC1B,MAAM,IAAIqC,MAAM;QAClB;QACA,IAAIjC,eAAeJ,aAAa,CAACiC,OAAO7B,aAAa;YACnD;QACF;QACAX,SAAS;YAAEY,SAASiC,OAAOC,IAAI,CAACH;QAAS;QACzC,MAAMP;IACR;IAEA,OAAO;QACL,IAAI1C;YACF,OAAOA;QACT;QACA,IAAIC;YACF,OAAOA;QACT;QACA,IAAIC;YACF,OAAOA;QACT;QACA,IAAIC;YACF,OAAOA;QACT;QACA,IAAIC;YACF,OAAOA;QACT;QACA,IAAIC;YACF,OAAOA;QACT;QACA,IAAIK;YACF,OAAOA;QACT;QACA,IAAIH;YACF,OAAOA;QACT;QACA8C,SAAS,CAAC1D,MAAMsB,aACdE,KAAKC,KAAKkC,SAAS,CAAC3D,OAAOsB,qBAAAA,aAAcvB,aAAaC;QACxD4D,YAAYN,CAAAA,UAAW9B,KAAK8B,SAASpC;QACrC2C,qBAAqB;YACnB,IAAIlD,aAAaO,WAAW;gBAC1B,MAAM,IAAIqC,MAAM;YAClB;YACA5C,SAAS;YACT,MAAMoC;QACR;QACAe,UAAUC,CAAAA;YACR/C,UAAU+C;QACZ;QACA5C;IACF;AACF,EAAE"}
@@ -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 // A dotted field sorts by the value it names, as the\n // server does — one locale of a localized member, say.\n compare(\n valuesAt(left, field)[0],\n valuesAt(right, field)[0],\n ) * 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","operation","db"],"mappings":"AAAA;;;;;;;;;;CAUC,GAED,+DAA+D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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"}
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 // A dotted field sorts by the value it names, as the\n // server does — one locale of a localized member, say.\n compare(\n valuesAt(left, field)[0],\n valuesAt(right, field)[0],\n ) * 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","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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":["../../src/drivers/fake-redis.ts"],"sourcesContent":["/**\n * A fake of the ioredis client, not of the lock/sequence ports.\n *\n * `makeRedisLockService`, `makeRedisSequenceService`, the session store, the\n * one-time token store and the attempt limiter all run unchanged on top of it,\n * so their real behaviour — `SET NX PX`, the bounded retry loop, the\n * compare-and-delete release script, `INCR`, `GETDEL` — is what the specs\n * exercise.\n *\n * Time does not pass: `EX`/`EXPIRE` are remembered so `TTL` can report them, but\n * nothing here expires on its own. Adapters that must be tested across an expiry\n * drive the clock themselves.\n */\n\nexport interface FakeRedis {\n /** Current keys and values, for assertions about what the adapter wrote. */\n read(key: string): string | undefined;\n /** Pre-set a key so the next `SET NX` finds it taken — i.e. lock contention. */\n hold(key: string, token?: string): void;\n /** Drop a key, releasing contention. */\n free(key: string): void;\n /** Makes every subsequent command reject with `error`. */\n failWith(error: unknown): void;\n /** Every command issued, in order. */\n readonly commands: ReadonlyArray<{ command: string; args: unknown[] }>;\n /** The object to pass where an ioredis `Redis` is expected. */\n readonly redis: unknown;\n}\n\nexport const makeFakeRedis = (): FakeRedis => {\n const store = new Map<string, string>();\n const sets = new Map<string, Set<string>>();\n /** Seconds last requested per key, so `TTL` can answer something plausible. */\n const ttls = new Map<string, number>();\n const commands: Array<{ command: string; args: unknown[] }> = [];\n let failure: unknown;\n\n const record = <TValue>(\n command: string,\n args: unknown[],\n produce: () => TValue,\n ): Promise<TValue> => {\n commands.push({ command, args });\n return failure !== undefined\n ? Promise.reject(failure)\n : Promise.resolve(produce());\n };\n\n const redis = {\n /**\n * Supports the one form the lock adapter issues:\n * `set(key, token, 'PX', ttl, 'NX')`. `NX` is what makes acquisition\n * atomic, so honouring it is the whole point of this fake.\n */\n set: (key: string, value: string, ...rest: unknown[]) =>\n record('set', [key, value, ...rest], () => {\n const nx = rest.some(\n argument => String(argument).toUpperCase() === 'NX',\n );\n if (nx && store.has(key)) return null;\n store.set(key, value);\n // Remember an `EX <seconds>` so a later `TTL` is not a lie.\n const exIndex = rest.findIndex(\n argument => String(argument).toUpperCase() === 'EX',\n );\n if (exIndex !== -1) ttls.set(key, Number(rest[exIndex + 1]));\n return 'OK';\n }),\n\n get: (key: string) => record('get', [key], () => store.get(key) ?? null),\n\n /**\n * `TTL`: seconds remaining, `-2` when the key is gone and `-1` when it has\n * no expiry. Time does not actually pass here, so this reports whatever TTL\n * was last set — enough for adapters that branch on \"is it still alive\".\n */\n ttl: (key: string) =>\n record('ttl', [key], () => {\n if (!store.has(key) && !sets.has(key)) return -2;\n return ttls.get(key) ?? -1;\n }),\n\n /** `GETDEL`: read and remove atomically — a single-use token redemption. */\n getdel: (key: string) =>\n record('getdel', [key], () => {\n const value = store.get(key) ?? null;\n store.delete(key);\n ttls.delete(key);\n return value;\n }),\n\n /** `SCARD`: how many members a set holds. */\n scard: (key: string) =>\n record('scard', [key], () => sets.get(key)?.size ?? 0),\n\n del: (key: string) =>\n record('del', [key], () => {\n // A key can hold a string or a set; drop whichever is there so the\n // session store's `del` frees both record keys and index-set keys.\n const hadString = store.delete(key);\n const hadSet = sets.delete(key);\n return hadString || hadSet ? 1 : 0;\n }),\n\n /** `SADD`: add a member to a set, returning how many were newly added (0/1). */\n sadd: (key: string, member: string) =>\n record('sadd', [key, member], () => {\n const set = sets.get(key) ?? new Set<string>();\n const isNew = !set.has(member);\n set.add(member);\n sets.set(key, set);\n return isNew ? 1 : 0;\n }),\n\n /** `SREM`: remove a member, returning how many were removed (0/1). */\n srem: (key: string, member: string) =>\n record('srem', [key, member], () =>\n sets.get(key)?.delete(member) ? 1 : 0,\n ),\n\n /** `SMEMBERS`: the set's members, or an empty array for a missing set. */\n smembers: (key: string) =>\n record('smembers', [key], () => [...(sets.get(key) ?? [])]),\n\n /**\n * `EXPIRE`: TTL is not enforced by this fake, so it only reports whether the\n * key exists (1) or not (0) — which is the branch the session adapter reads\n * to detect a vanished session on `touch`.\n */\n expire: (key: string, seconds: number) =>\n record('expire', [key, seconds], () => {\n if (!store.has(key) && !sets.has(key)) return 0;\n ttls.set(key, seconds);\n return 1;\n }),\n\n incr: (key: string) =>\n record('incr', [key], () => {\n const next = Number(store.get(key) ?? '0') + 1;\n store.set(key, String(next));\n return next;\n }),\n\n /**\n * The release script is a compare-and-delete: free the key only when it\n * still holds our own token. Rather than interpreting Lua, this reproduces\n * that one script's semantics.\n */\n eval: (_script: string, _numKeys: number, key: string, token: string) =>\n record('eval', [key, token], () => {\n if (store.get(key) !== token) return 0;\n store.delete(key);\n return 1;\n }),\n\n quit: () => record('quit', [], () => 'OK'),\n };\n\n return {\n read: key => store.get(key),\n hold: (key, token = 'someone-else') => {\n store.set(key, token);\n },\n free: key => {\n store.delete(key);\n },\n failWith: error => {\n failure = error;\n },\n get commands() {\n return commands;\n },\n redis,\n };\n};\n"],"names":["makeFakeRedis","store","Map","sets","ttls","commands","failure","record","command","args","produce","push","undefined","Promise","reject","resolve","redis","set","key","value","rest","nx","some","argument","String","toUpperCase","has","exIndex","findIndex","Number","get","ttl","getdel","delete","scard","size","del","hadString","hadSet","sadd","member","Set","isNew","add","srem","smembers","expire","seconds","incr","next","eval","_script","_numKeys","token","quit","read","hold","free","failWith","error"],"mappings":"AAAA;;;;;;;;;;;;CAYC,GAiBD,OAAO,MAAMA,gBAAgB;IAC3B,MAAMC,QAAQ,IAAIC;IAClB,MAAMC,OAAO,IAAID;IACjB,6EAA6E,GAC7E,MAAME,OAAO,IAAIF;IACjB,MAAMG,WAAwD,EAAE;IAChE,IAAIC;IAEJ,MAAMC,SAAS,CACbC,SACAC,MACAC;QAEAL,SAASM,IAAI,CAAC;YAAEH;YAASC;QAAK;QAC9B,OAAOH,YAAYM,YACfC,QAAQC,MAAM,CAACR,WACfO,QAAQE,OAAO,CAACL;IACtB;IAEA,MAAMM,QAAQ;QACZ;;;;KAIC,GACDC,KAAK,CAACC,KAAaC,OAAe,GAAGC,OACnCb,OAAO,OAAO;gBAACW;gBAAKC;mBAAUC;aAAK,EAAE;gBACnC,MAAMC,KAAKD,KAAKE,IAAI,CAClBC,CAAA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GACDC,MAAM,CAACC,SAAiBC,UAAkBlC,KAAamC,QACrD9C,OAAO,QAAQ;gBAACW;gBAAKmC;aAAM,EAAE;gBAC3B,IAAIpD,MAAM6B,GAAG,CAACZ,SAASmC,OAAO,OAAO;gBACrCpD,MAAMgC,MAAM,CAACf;gBACb,OAAO;YACT;QAEFoC,MAAM,IAAM/C,OAAO,QAAQ,EAAE,EAAE,IAAM;IACvC;IAEA,OAAO;QACLgD,MAAMrC,CAAAA,MAAOjB,MAAM6B,GAAG,CAACZ;QACvBsC,MAAM,CAACtC,KAAKmC,QAAQ,cAAc;YAChCpD,MAAMgB,GAAG,CAACC,KAAKmC;QACjB;QACAI,MAAMvC,CAAAA;YACJjB,MAAMgC,MAAM,CAACf;QACf;QACAwC,UAAUC,CAAAA;YACRrD,UAAUqD;QACZ;QACA,IAAItD,YAAW;YACb,OAAOA;QACT;QACAW;IACF;AACF,EAAE"}
1
+ {"version":3,"sources":["../../src/drivers/fake-redis.ts"],"sourcesContent":["/**\n * A fake of the ioredis client, not of the lock/sequence ports.\n *\n * `makeRedisLockService`, `makeRedisSequenceService`, the session store, the\n * one-time token store and the attempt limiter all run unchanged on top of it,\n * so their real behaviour — `SET NX PX`, the bounded retry loop, the\n * compare-and-delete release script, `INCR`, `GETDEL` — is what the specs\n * exercise.\n *\n * Time does not pass: `EX`/`EXPIRE` are remembered so `TTL` can report them, but\n * nothing here expires on its own. Adapters that must be tested across an expiry\n * drive the clock themselves.\n */\n\nexport interface FakeRedis {\n /** Current keys and values, for assertions about what the adapter wrote. */\n read(key: string): string | undefined;\n /** Pre-set a key so the next `SET NX` finds it taken — i.e. lock contention. */\n hold(key: string, token?: string): void;\n /** Drop a key, releasing contention. */\n free(key: string): void;\n /** Makes every subsequent command reject with `error`. */\n failWith(error: unknown): void;\n /** Every command issued, in order. */\n readonly commands: ReadonlyArray<{ command: string; args: unknown[] }>;\n /** The object to pass where an ioredis `Redis` is expected. */\n readonly redis: unknown;\n}\n\nexport const makeFakeRedis = (): FakeRedis => {\n const store = new Map<string, string>();\n const sets = new Map<string, Set<string>>();\n /** Seconds last requested per key, so `TTL` can answer something plausible. */\n const ttls = new Map<string, number>();\n const commands: Array<{ command: string; args: unknown[] }> = [];\n let failure: unknown;\n\n const record = <TValue>(\n command: string,\n args: unknown[],\n produce: () => TValue,\n ): Promise<TValue> => {\n commands.push({ command, args });\n return failure !== undefined\n ? Promise.reject(failure)\n : Promise.resolve(produce());\n };\n\n const redis = {\n /**\n * Supports the one form the lock adapter issues:\n * `set(key, token, 'PX', ttl, 'NX')`. `NX` is what makes acquisition\n * atomic, so honouring it is the whole point of this fake.\n */\n set: (key: string, value: string, ...rest: unknown[]) =>\n record('set', [key, value, ...rest], () => {\n const nx = rest.some(\n argument => String(argument).toUpperCase() === 'NX',\n );\n if (nx && store.has(key)) return null;\n store.set(key, value);\n // Remember an `EX <seconds>` so a later `TTL` is not a lie.\n const exIndex = rest.findIndex(\n argument => String(argument).toUpperCase() === 'EX',\n );\n if (exIndex !== -1) ttls.set(key, Number(rest[exIndex + 1]));\n return 'OK';\n }),\n\n get: (key: string) => record('get', [key], () => store.get(key) ?? null),\n\n /**\n * `TTL`: seconds remaining, `-2` when the key is gone and `-1` when it has\n * no expiry. Time does not actually pass here, so this reports whatever TTL\n * was last set — enough for adapters that branch on \"is it still alive\".\n */\n ttl: (key: string) =>\n record('ttl', [key], () => {\n if (!store.has(key) && !sets.has(key)) return -2;\n return ttls.get(key) ?? -1;\n }),\n\n /** `GETDEL`: read and remove atomically — a single-use token redemption. */\n getdel: (key: string) =>\n record('getdel', [key], () => {\n const value = store.get(key) ?? null;\n store.delete(key);\n ttls.delete(key);\n return value;\n }),\n\n /** `SCARD`: how many members a set holds. */\n scard: (key: string) =>\n record('scard', [key], () => sets.get(key)?.size ?? 0),\n\n del: (key: string) =>\n record('del', [key], () => {\n // A key can hold a string or a set; drop whichever is there so the\n // session store's `del` frees both record keys and index-set keys.\n const hadString = store.delete(key);\n const hadSet = sets.delete(key);\n return hadString || hadSet ? 1 : 0;\n }),\n\n /** `SADD`: add a member to a set, returning how many were newly added (0/1). */\n sadd: (key: string, member: string) =>\n record('sadd', [key, member], () => {\n const set = sets.get(key) ?? new Set<string>();\n const isNew = !set.has(member);\n set.add(member);\n sets.set(key, set);\n return isNew ? 1 : 0;\n }),\n\n /** `SREM`: remove a member, returning how many were removed (0/1). */\n srem: (key: string, member: string) =>\n record('srem', [key, member], () =>\n sets.get(key)?.delete(member) ? 1 : 0,\n ),\n\n /** `SMEMBERS`: the set's members, or an empty array for a missing set. */\n smembers: (key: string) =>\n record('smembers', [key], () => [...(sets.get(key) ?? [])]),\n\n /**\n * `EXPIRE`: TTL is not enforced by this fake, so it only reports whether the\n * key exists (1) or not (0) — which is the branch the session adapter reads\n * to detect a vanished session on `touch`.\n */\n expire: (key: string, seconds: number) =>\n record('expire', [key, seconds], () => {\n if (!store.has(key) && !sets.has(key)) return 0;\n ttls.set(key, seconds);\n return 1;\n }),\n\n incr: (key: string) =>\n record('incr', [key], () => {\n const next = Number(store.get(key) ?? '0') + 1;\n store.set(key, String(next));\n return next;\n }),\n\n /**\n * The release script is a compare-and-delete: free the key only when it\n * still holds our own token. Rather than interpreting Lua, this reproduces\n * that one script's semantics.\n */\n eval: (_script: string, _numKeys: number, key: string, token: string) =>\n record('eval', [key, token], () => {\n if (store.get(key) !== token) return 0;\n store.delete(key);\n return 1;\n }),\n\n quit: () => record('quit', [], () => 'OK'),\n };\n\n return {\n read: key => store.get(key),\n hold: (key, token = 'someone-else') => {\n store.set(key, token);\n },\n free: key => {\n store.delete(key);\n },\n failWith: error => {\n failure = error;\n },\n get commands() {\n return commands;\n },\n redis,\n };\n};\n"],"names":["makeFakeRedis","store","Map","sets","ttls","commands","failure","record","command","args","produce","push","undefined","Promise","reject","resolve","redis","set","key","value","rest","nx","some","argument","String","toUpperCase","has","exIndex","findIndex","Number","get","ttl","getdel","delete","scard","size","del","hadString","hadSet","sadd","member","Set","isNew","add","srem","smembers","expire","seconds","incr","next","eval","_script","_numKeys","token","quit","read","hold","free","failWith","error"],"mappings":"AAAA;;;;;;;;;;;;CAYC,GAiBD,OAAO,MAAMA,gBAAgB;IAC3B,MAAMC,QAAQ,IAAIC;IAClB,MAAMC,OAAO,IAAID;IACjB,6EAA6E,GAC7E,MAAME,OAAO,IAAIF;IACjB,MAAMG,WAAwD,EAAE;IAChE,IAAIC;IAEJ,MAAMC,SAAS,CACbC,SACAC,MACAC;QAEAL,SAASM,IAAI,CAAC;YAAEH;YAASC;QAAK;QAC9B,OAAOH,YAAYM,YACfC,QAAQC,MAAM,CAACR,WACfO,QAAQE,OAAO,CAACL;IACtB;IAEA,MAAMM,QAAQ;QACZ;;;;KAIC,GACDC,KAAK,CAACC,KAAaC,OAAe,GAAGC,OACnCb,OAAO,OAAO;gBAACW;gBAAKC;mBAAUC;aAAK,EAAE;gBACnC,MAAMC,KAAKD,KAAKE,IAAI,CAClBC,CAAAA,WAAYC,OAAOD,UAAUE,WAAW,OAAO;gBAEjD,IAAIJ,MAAMpB,MAAMyB,GAAG,CAACR,MAAM,OAAO;gBACjCjB,MAAMgB,GAAG,CAACC,KAAKC;gBACf,4DAA4D;gBAC5D,MAAMQ,UAAUP,KAAKQ,SAAS,CAC5BL,CAAAA,WAAYC,OAAOD,UAAUE,WAAW,OAAO;gBAEjD,IAAIE,YAAY,CAAC,GAAGvB,KAAKa,GAAG,CAACC,KAAKW,OAAOT,IAAI,CAACO,UAAU,EAAE;gBAC1D,OAAO;YACT;QAEFG,KAAK,CAACZ,MAAgBX,OAAO,OAAO;gBAACW;aAAI,EAAE;oBAAMjB;wBAAAA,aAAAA,MAAM6B,GAAG,CAACZ,gBAAVjB,aAAkB;;QAEnE;;;;KAIC,GACD8B,KAAK,CAACb,MACJX,OAAO,OAAO;gBAACW;aAAI,EAAE;oBAEZd;gBADP,IAAI,CAACH,MAAMyB,GAAG,CAACR,QAAQ,CAACf,KAAKuB,GAAG,CAACR,MAAM,OAAO,CAAC;gBAC/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not of the repository port.\n *\n * It sits one level *below* `makeSqlRepository`, so the adapter's own code — the\n * filter translation, the clause assembly, the upsert rule, the error mapping —\n * actually runs and is measured by coverage. A fake at the port level would skip\n * all of it. Same reasoning as {@link makeFakeMongoDb}.\n *\n * What it does **not** do is execute SQL: it hands back canned rows and records\n * the statement each call compiled to, so a spec asserts on the SQL and\n * parameters the adapter produced. Running the shared\n * `describeEntityRepositoryContract` needs a real engine and belongs against real\n * Postgres, the way the driver connection Layers are covered.\n */\n\nimport { Effect } from 'effect';\nimport { SqlError } from 'effect/sql';\nimport { Statement } from 'effect/sql';\n\n/** One statement the adapter executed, already compiled. */\nexport interface FakeSqlExecution {\n /** The compiled SQL text, parameters replaced by `$1`, `$2`, … */\n readonly sql: string;\n readonly params: ReadonlyArray<unknown>;\n}\n\n/** Rows to answer with when a statement's SQL contains `match`. */\nexport interface FakeSqlResponse {\n readonly match: string;\n readonly rows: ReadonlyArray<Record<string, unknown>>;\n}\n\nexport interface FakeSqlClient {\n /**\n * Answers `rows` for any statement whose compiled SQL contains `match`. Later\n * registrations win, so a spec can override a default set up by a helper.\n */\n respondTo(match: string, rows: ReadonlyArray<Record<string, unknown>>): void;\n /**\n * Makes every subsequent execution fail, so the adapter's `EntifixConnError`\n * mapping is reachable.\n */\n failWith(message: string): void;\n /**\n * Makes only the statements containing `match` fail, leaving the rest working\n * — the way a select that succeeds and a count that then fails reaches a\n * distinct error branch.\n */\n failOn(match: string, message: string): void;\n /** Every statement executed, in order, for assertions about what ran. */\n readonly executions: ReadonlyArray<FakeSqlExecution>;\n /** The most recently executed statement. */\n readonly lastExecution: FakeSqlExecution | undefined;\n /**\n * The object to hand to `makeSqlRepository` in place of a real `SqlClient`.\n *\n * Typed `unknown` on purpose — casting at the call site keeps this fake honest\n * that it implements only the constructor surface the adapters use, not the\n * whole `SqlClient` (no transactions, no reactivity, no streaming).\n */\n readonly client: unknown;\n}\n\nconst unsupported = (name: string): never => {\n throw new TypeError(`fake sql: ${name} is not implemented`);\n};\n\n/**\n * The Postgres compiler's configuration, mirrored from `@effect/sql-pg` so the\n * fake emits exactly the dialect production does — `$n` placeholders and\n * double-quoted identifiers — without this package depending on the `pg` driver.\n *\n * `sql.updateValues` and the `PgJson` custom segment are deliberate `TypeError`s\n * rather than approximations: no adapter uses either, and a compiler that\n * half-emitted them would let a spec pass on SQL that real Postgres rejects.\n */\nconst pgCompiler = Statement.makeCompiler({\n dialect: 'pg',\n placeholder: index => `$${index}`,\n onIdentifier: Statement.defaultEscape('\"'),\n onRecordUpdate: () => unsupported('updateValues'),\n onCustom: () => unsupported('custom segments'),\n});\n\n/** Builds an in-memory stand-in for an `@effect/sql` client. */\nexport const makeFakeSqlClient = (\n seed: ReadonlyArray<FakeSqlResponse> = [],\n): FakeSqlClient => {\n const responses: FakeSqlResponse[] = [...seed];\n const executions: FakeSqlExecution[] = [];\n const failuresByMatch: Array<{ match: string; message: string }> = [];\n let failure: string | undefined;\n\n const answer = (sql: string) => {\n // Last registration wins, so an override does not have to remove the\n // default it replaces.\n for (let index = responses.length - 1; index >= 0; index -= 1) {\n const response = responses[index];\n if (response !== undefined && sql.includes(response.match)) {\n return response.rows;\n }\n }\n return [];\n };\n\n const execute = (sql: string, params: ReadonlyArray<unknown>) => {\n executions.push({ sql, params });\n\n const scoped = failuresByMatch.find(entry => sql.includes(entry.match));\n const message = scoped?.message ?? failure;\n if (message !== undefined) {\n return Effect.fail(\n new SqlError.SqlError({\n reason: new SqlError.UnknownError({\n cause: new Error(message),\n message,\n }),\n }),\n );\n }\n return Effect.succeed(answer(sql));\n };\n\n const connection = {\n execute: (sql: string, params: ReadonlyArray<unknown>) =>\n execute(sql, params),\n executeUnprepared: (sql: string, params: ReadonlyArray<unknown>) =>\n execute(sql, params),\n executeRaw: (sql: string, params: ReadonlyArray<unknown>) =>\n execute(sql, params),\n executeValues: () => unsupported('executeValues'),\n executeStream: () => unsupported('executeStream'),\n };\n\n return {\n respondTo: (match, rows) => {\n responses.push({ match, rows });\n },\n failWith: message => {\n failure = message;\n },\n failOn: (match, message) => {\n failuresByMatch.push({ match, message });\n },\n get executions() {\n return executions;\n },\n get lastExecution() {\n return executions[executions.length - 1];\n },\n client: Statement.make(\n Effect.succeed(connection) as never,\n pgCompiler,\n [],\n undefined,\n ),\n };\n};\n"],"names":["Effect","SqlError","Statement","unsupported","name","TypeError","pgCompiler","makeCompiler","dialect","placeholder","index","onIdentifier","defaultEscape","onRecordUpdate","onCustom","makeFakeSqlClient","seed","responses","executions","failuresByMatch","failure","answer","sql","length","response","undefined","includes","match","rows","execute","params","push","scoped","find","entry","message","fail","reason","UnknownError","cause","Error","succeed","connection","executeUnprepared","executeRaw","executeValues","executeStream","respondTo","failWith","failOn","lastExecution","client","make"],"mappings":"AAAA;;;;;;;;;;;;;CAaC,GAED,SAASA,MAAM,QAAQ,SAAS;AAChC,SAASC,QAAQ,QAAQ,aAAa;AACtC,SAASC,SAAS,QAAQ,aAAa;AA8CvC,MAAMC,cAAc,CAACC;IACnB,MAAM,IAAIC,UAAU,CAAC,UAAU,EAAED,KAAK,mBAAmB,CAAC;AAC5D;AAEA;;;;;;;;CAQC,GACD,MAAME,aAAaJ,UAAUK,YAAY,CAAC;IACxCC,SAAS;IACTC,aAAaC,CAAAA,QAAS,CAAC,CAAC,EAAEA,OAAO;IACjCC,cAAcT,UAAUU,aAAa,CAAC;IACtCC,gBAAgB,IAAMV,YAAY;IAClCW,UAAU,IAAMX,YAAY;AAC9B;AAEA,8DAA8D,GAC9D,OAAO,MAAMY,oBAAoB,CAC/BC,OAAuC,EAAE;IAEzC,MAAMC,YAA+B;WAAID;KAAK;IAC9C,MAAME,aAAiC,EAAE;IACzC,MAAMC,kBAA6D,EAAE;IACrE,IAAIC;IAEJ,MAAMC,SAAS,CAACC;QACd,qEAAqE;QACrE,uBAAuB;QACvB,IAAK,IAAIZ,QAAQO,UAAUM,MAAM,GAAG,GAAGb,SAAS,GAAGA,SAAS,EAAG;YAC7D,MAAMc,WAAWP,SAAS,CAAC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AACC,aACfpC,YACA,EAAE,EACFmB;IAEJ;AACF,EAAE"}
1
+ {"version":3,"sources":["../../src/drivers/fake-sql.ts"],"sourcesContent":["/**\n * A fake of the `@effect/sql` driver, not of the repository port.\n *\n * It sits one level *below* `makeSqlRepository`, so the adapter's own code — the\n * filter translation, the clause assembly, the upsert rule, the error mapping —\n * actually runs and is measured by coverage. A fake at the port level would skip\n * all of it. Same reasoning as {@link makeFakeMongoDb}.\n *\n * What it does **not** do is execute SQL: it hands back canned rows and records\n * the statement each call compiled to, so a spec asserts on the SQL and\n * parameters the adapter produced. Running the shared\n * `describeEntityRepositoryContract` needs a real engine and belongs against real\n * Postgres, the way the driver connection Layers are covered.\n */\n\nimport { Effect } from 'effect';\nimport { SqlError } from 'effect/sql';\nimport { Statement } from 'effect/sql';\n\n/** One statement the adapter executed, already compiled. */\nexport interface FakeSqlExecution {\n /** The compiled SQL text, parameters replaced by `$1`, `$2`, … */\n readonly sql: string;\n readonly params: ReadonlyArray<unknown>;\n}\n\n/** Rows to answer with when a statement's SQL contains `match`. */\nexport interface FakeSqlResponse {\n readonly match: string;\n readonly rows: ReadonlyArray<Record<string, unknown>>;\n}\n\nexport interface FakeSqlClient {\n /**\n * Answers `rows` for any statement whose compiled SQL contains `match`. Later\n * registrations win, so a spec can override a default set up by a helper.\n */\n respondTo(match: string, rows: ReadonlyArray<Record<string, unknown>>): void;\n /**\n * Makes every subsequent execution fail, so the adapter's `EntifixConnError`\n * mapping is reachable.\n */\n failWith(message: string): void;\n /**\n * Makes only the statements containing `match` fail, leaving the rest working\n * — the way a select that succeeds and a count that then fails reaches a\n * distinct error branch.\n */\n failOn(match: string, message: string): void;\n /** Every statement executed, in order, for assertions about what ran. */\n readonly executions: ReadonlyArray<FakeSqlExecution>;\n /** The most recently executed statement. */\n readonly lastExecution: FakeSqlExecution | undefined;\n /**\n * The object to hand to `makeSqlRepository` in place of a real `SqlClient`.\n *\n * Typed `unknown` on purpose — casting at the call site keeps this fake honest\n * that it implements only the constructor surface the adapters use, not the\n * whole `SqlClient` (no transactions, no reactivity, no streaming).\n */\n readonly client: unknown;\n}\n\nconst unsupported = (name: string): never => {\n throw new TypeError(`fake sql: ${name} is not implemented`);\n};\n\n/**\n * The Postgres compiler's configuration, mirrored from `@effect/sql-pg` so the\n * fake emits exactly the dialect production does — `$n` placeholders and\n * double-quoted identifiers — without this package depending on the `pg` driver.\n *\n * `sql.updateValues` and the `PgJson` custom segment are deliberate `TypeError`s\n * rather than approximations: no adapter uses either, and a compiler that\n * half-emitted them would let a spec pass on SQL that real Postgres rejects.\n */\nconst pgCompiler = Statement.makeCompiler({\n dialect: 'pg',\n placeholder: index => `$${index}`,\n onIdentifier: Statement.defaultEscape('\"'),\n onRecordUpdate: () => unsupported('updateValues'),\n onCustom: () => unsupported('custom segments'),\n});\n\n/** Builds an in-memory stand-in for an `@effect/sql` client. */\nexport const makeFakeSqlClient = (\n seed: ReadonlyArray<FakeSqlResponse> = [],\n): FakeSqlClient => {\n const responses: FakeSqlResponse[] = [...seed];\n const executions: FakeSqlExecution[] = [];\n const failuresByMatch: Array<{ match: string; message: string }> = [];\n let failure: string | undefined;\n\n const answer = (sql: string) => {\n // Last registration wins, so an override does not have to remove the\n // default it replaces.\n for (let index = responses.length - 1; index >= 0; index -= 1) {\n const response = responses[index];\n if (response !== undefined && sql.includes(response.match)) {\n return response.rows;\n }\n }\n return [];\n };\n\n const execute = (sql: string, params: ReadonlyArray<unknown>) => {\n executions.push({ sql, params });\n\n const scoped = failuresByMatch.find(entry => sql.includes(entry.match));\n const message = scoped?.message ?? failure;\n if (message !== undefined) {\n return Effect.fail(\n new SqlError.SqlError({\n reason: new SqlError.UnknownError({\n cause: new Error(message),\n message,\n }),\n }),\n );\n }\n return Effect.succeed(answer(sql));\n };\n\n const connection = {\n execute: (sql: string, params: ReadonlyArray<unknown>) =>\n execute(sql, params),\n executeUnprepared: (sql: string, params: ReadonlyArray<unknown>) =>\n execute(sql, params),\n executeRaw: (sql: string, params: ReadonlyArray<unknown>) =>\n execute(sql, params),\n executeValues: () => unsupported('executeValues'),\n executeStream: () => unsupported('executeStream'),\n };\n\n return {\n respondTo: (match, rows) => {\n responses.push({ match, rows });\n },\n failWith: message => {\n failure = message;\n },\n failOn: (match, message) => {\n failuresByMatch.push({ match, message });\n },\n get executions() {\n return executions;\n },\n get lastExecution() {\n return executions[executions.length - 1];\n },\n client: Statement.make(\n Effect.succeed(connection) as never,\n pgCompiler,\n [],\n undefined,\n ),\n };\n};\n"],"names":["Effect","SqlError","Statement","unsupported","name","TypeError","pgCompiler","makeCompiler","dialect","placeholder","index","onIdentifier","defaultEscape","onRecordUpdate","onCustom","makeFakeSqlClient","seed","responses","executions","failuresByMatch","failure","answer","sql","length","response","undefined","includes","match","rows","execute","params","push","scoped","find","entry","message","fail","reason","UnknownError","cause","Error","succeed","connection","executeUnprepared","executeRaw","executeValues","executeStream","respondTo","failWith","failOn","lastExecution","client","make"],"mappings":"AAAA;;;;;;;;;;;;;CAaC,GAED,SAASA,MAAM,QAAQ,SAAS;AAChC,SAASC,QAAQ,QAAQ,aAAa;AACtC,SAASC,SAAS,QAAQ,aAAa;AA8CvC,MAAMC,cAAc,CAACC;IACnB,MAAM,IAAIC,UAAU,CAAC,UAAU,EAAED,KAAK,mBAAmB,CAAC;AAC5D;AAEA;;;;;;;;CAQC,GACD,MAAME,aAAaJ,UAAUK,YAAY,CAAC;IACxCC,SAAS;IACTC,aAAaC,CAAAA,QAAS,CAAC,CAAC,EAAEA,OAAO;IACjCC,cAAcT,UAAUU,aAAa,CAAC;IACtCC,gBAAgB,IAAMV,YAAY;IAClCW,UAAU,IAAMX,YAAY;AAC9B;AAEA,8DAA8D,GAC9D,OAAO,MAAMY,oBAAoB,CAC/BC,OAAuC,EAAE;IAEzC,MAAMC,YAA+B;WAAID;KAAK;IAC9C,MAAME,aAAiC,EAAE;IACzC,MAAMC,kBAA6D,EAAE;IACrE,IAAIC;IAEJ,MAAMC,SAAS,CAACC;QACd,qEAAqE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ACF,OAAOhC,UAAU,CAACA,WAAWK,MAAM,GAAG,EAAE;QAC1C;QACA4B,QAAQjD,UAAUkD,IAAI,CACpBpD,OAAOyC,OAAO,CAACC,aACfpC,YACA,EAAE,EACFmB;IAEJ;AACF,EAAE"}
@@ -5,7 +5,7 @@ export type EntifixMockServer = ReturnType<typeof setupServer>;
5
5
  /**
6
6
  * Starts an MSW server for the current test file and wires its lifecycle.
7
7
  *
8
- * `onUnhandledRequest: 'error'` is the important part: a request nobody stubbed
8
+ * `onUnhandledFrame: 'error'` is the important part: a request nobody stubbed
9
9
  * fails the test instead of quietly escaping to the network. A test that passes
10
10
  * because it silently talked to nothing is worse than one that fails.
11
11
  *
@@ -1 +1 @@
1
- {"version":3,"file":"server.d.ts","sourceRoot":"","sources":["../../src/http/server.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,KAAK,cAAc,EAAE,MAAM,KAAK,CAAC;AAC1C,OAAO,EAAE,WAAW,EAAE,MAAM,UAAU,CAAC;AAGvC,8EAA8E;AAC9E,MAAM,MAAM,iBAAiB,GAAG,UAAU,CAAC,OAAO,WAAW,CAAC,CAAC;AAE/D;;;;;;;;;;;;GAYG;AACH,eAAO,MAAM,kBAAkB,GAC7B,GAAG,UAAU,cAAc,EAAE,KAC5B,iBAcF,CAAC"}
1
+ {"version":3,"file":"server.d.ts","sourceRoot":"","sources":["../../src/http/server.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,KAAK,cAAc,EAAE,MAAM,KAAK,CAAC;AAC1C,OAAO,EAAE,WAAW,EAAE,MAAM,UAAU,CAAC;AAGvC,8EAA8E;AAC9E,MAAM,MAAM,iBAAiB,GAAG,UAAU,CAAC,OAAO,WAAW,CAAC,CAAC;AAE/D;;;;;;;;;;;;GAYG;AACH,eAAO,MAAM,kBAAkB,GAC7B,GAAG,UAAU,cAAc,EAAE,KAC5B,iBAgBF,CAAC"}
@@ -3,7 +3,7 @@ import { afterAll, afterEach, beforeAll } from 'vitest';
3
3
  /**
4
4
  * Starts an MSW server for the current test file and wires its lifecycle.
5
5
  *
6
- * `onUnhandledRequest: 'error'` is the important part: a request nobody stubbed
6
+ * `onUnhandledFrame: 'error'` is the important part: a request nobody stubbed
7
7
  * fails the test instead of quietly escaping to the network. A test that passes
8
8
  * because it silently talked to nothing is worse than one that fails.
9
9
  *
@@ -15,8 +15,10 @@ import { afterAll, afterEach, beforeAll } from 'vitest';
15
15
  */ export const setupEntifixServer = (...handlers)=>{
16
16
  const server = setupServer(...handlers);
17
17
  beforeAll(()=>{
18
+ // msw 3 renamed `onUnhandledRequest`. The old name is ignored, not
19
+ // rejected, so keeping it would let unmocked requests through silently.
18
20
  server.listen({
19
- onUnhandledRequest: 'error'
21
+ onUnhandledFrame: 'error'
20
22
  });
21
23
  });
22
24
  afterEach(()=>{
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/http/server.ts"],"sourcesContent":["import { type RequestHandler } from 'msw';\nimport { setupServer } from 'msw/node';\nimport { afterAll, afterEach, beforeAll } from 'vitest';\n\n/** What `setupServer` actually returns, so the type cannot drift from msw. */\nexport type EntifixMockServer = ReturnType<typeof setupServer>;\n\n/**\n * Starts an MSW server for the current test file and wires its lifecycle.\n *\n * `onUnhandledRequest: 'error'` is the important part: a request nobody stubbed\n * fails the test instead of quietly escaping to the network. A test that passes\n * because it silently talked to nothing is worse than one that fails.\n *\n * ```ts\n * const server = setupEntifixServer(...entityRestHandlers(Product, { … }));\n * // inside a test, to override for one case:\n * server.use(respondWith500('http://service/api/product'));\n * ```\n */\nexport const setupEntifixServer = (\n ...handlers: RequestHandler[]\n): EntifixMockServer => {\n const server = setupServer(...handlers);\n\n beforeAll(() => {\n server.listen({ onUnhandledRequest: 'error' });\n });\n afterEach(() => {\n server.resetHandlers();\n });\n afterAll(() => {\n server.close();\n });\n\n return server;\n};\n"],"names":["setupServer","afterAll","afterEach","beforeAll","setupEntifixServer","handlers","server","listen","onUnhandledRequest","resetHandlers","close"],"mappings":"AACA,SAASA,WAAW,QAAQ,WAAW;AACvC,SAASC,QAAQ,EAAEC,SAAS,EAAEC,SAAS,QAAQ,SAAS;AAKxD;;;;;;;;;;;;CAYC,GACD,OAAO,MAAMC,qBAAqB,CAChC,GAAGC;IAEH,MAAMC,SAASN,eAAeK;IAE9BF,UAAU;QACRG,OAAOC,MAAM,CAAC;YAAEC,oBAAoB;QAAQ;IAC9C;IACAN,UAAU;QACRI,OAAOG,aAAa;IACtB;IACAR,SAAS;QACPK,OAAOI,KAAK;IACd;IAEA,OAAOJ;AACT,EAAE"}
1
+ {"version":3,"sources":["../../src/http/server.ts"],"sourcesContent":["import { type RequestHandler } from 'msw';\nimport { setupServer } from 'msw/node';\nimport { afterAll, afterEach, beforeAll } from 'vitest';\n\n/** What `setupServer` actually returns, so the type cannot drift from msw. */\nexport type EntifixMockServer = ReturnType<typeof setupServer>;\n\n/**\n * Starts an MSW server for the current test file and wires its lifecycle.\n *\n * `onUnhandledFrame: 'error'` is the important part: a request nobody stubbed\n * fails the test instead of quietly escaping to the network. A test that passes\n * because it silently talked to nothing is worse than one that fails.\n *\n * ```ts\n * const server = setupEntifixServer(...entityRestHandlers(Product, { … }));\n * // inside a test, to override for one case:\n * server.use(respondWith500('http://service/api/product'));\n * ```\n */\nexport const setupEntifixServer = (\n ...handlers: RequestHandler[]\n): EntifixMockServer => {\n const server = setupServer(...handlers);\n\n beforeAll(() => {\n // msw 3 renamed `onUnhandledRequest`. The old name is ignored, not\n // rejected, so keeping it would let unmocked requests through silently.\n server.listen({ onUnhandledFrame: 'error' });\n });\n afterEach(() => {\n server.resetHandlers();\n });\n afterAll(() => {\n server.close();\n });\n\n return server;\n};\n"],"names":["setupServer","afterAll","afterEach","beforeAll","setupEntifixServer","handlers","server","listen","onUnhandledFrame","resetHandlers","close"],"mappings":"AACA,SAASA,WAAW,QAAQ,WAAW;AACvC,SAASC,QAAQ,EAAEC,SAAS,EAAEC,SAAS,QAAQ,SAAS;AAKxD;;;;;;;;;;;;CAYC,GACD,OAAO,MAAMC,qBAAqB,CAChC,GAAGC;IAEH,MAAMC,SAASN,eAAeK;IAE9BF,UAAU;QACR,mEAAmE;QACnE,wEAAwE;QACxEG,OAAOC,MAAM,CAAC;YAAEC,kBAAkB;QAAQ;IAC5C;IACAN,UAAU;QACRI,OAAOG,aAAa;IACtB;IACAR,SAAS;QACPK,OAAOI,KAAK;IACd;IAEA,OAAOJ;AACT,EAAE"}
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/react/ui-preferences.ts"],"sourcesContent":["import type { UiPreferencesState } from '@entifix/react-controls';\nimport { Effect } from 'effect';\n\nexport interface InMemoryUiPreferencesState extends UiPreferencesState {\n /** Everything currently stored, keyed exactly as the controls wrote it. */\n readonly entries: Readonly<Record<string, unknown>>;\n /** Pre-populates the store, e.g. to render a table already personalized. */\n seed(entries: Record<string, unknown>): void;\n}\n\n/**\n * In-memory {@link UiPreferencesState}.\n *\n * The port is Effect-returning precisely so an asynchronous, server-backed\n * store can replace `localStorage` without touching a component; this double\n * exists so specs can assert on personalization without depending on jsdom\n * storage behaviour at all.\n */\nexport const makeInMemoryUiPreferencesState = (\n seed: Record<string, unknown> = {},\n): InMemoryUiPreferencesState => {\n let entries: Record<string, unknown> = { ...seed };\n\n return {\n read: <TValue>(key: string) =>\n Effect.sync(() => entries[key] as TValue | undefined),\n write: <TValue>(key: string, value: TValue) =>\n Effect.sync(() => {\n entries[key] = value;\n }),\n remove: (key: string) =>\n Effect.sync(() => {\n delete entries[key];\n }),\n get entries() {\n return entries;\n },\n seed: next => {\n entries = { ...next };\n },\n };\n};\n"],"names":["Effect","makeInMemoryUiPreferencesState","seed","entries","read","key","sync","write","value","remove","next"],"mappings":";AACA,SAASA,MAAM,QAAQ,SAAS;AAShC;;;;;;;CAOC,GACD,OAAO,MAAMC,iCAAiC,CAC5CC,OAAgC,CAAC,CAAC;IAElC,IAAIC,UAAmC,aAAKD;IAE5C,OAAO;QACLE,MAAM,CAASC,MACbL,OAAOM,IAAI,CAAC,IAAMH,OAAO,CAACE,IAAI;QAChCE,OAAO,CAASF,KAAaG,QAC3BR,OAAOM,IAAI,CAAC;gBACVH,OAAO,CAACE,IAAI,GAAGG;YACjB;QACFC,QAAQ,CAACJ,MACPL,OAAOM,IAAI,CAAC;gBACV,OAAOH,OAAO,CAACE,IAAI;YACrB;QACF,IAAIF,WAAU;YACZ,OAAOA;QACT;QACAD,MAAMQ,CAAAA;YACJP,UAAU,aAAKO;QACjB;IACF;AACF,EAAE"}
1
+ {"version":3,"sources":["../../src/react/ui-preferences.ts"],"sourcesContent":["import type { UiPreferencesState } from '@entifix/react-controls';\nimport { Effect } from 'effect';\n\nexport interface InMemoryUiPreferencesState extends UiPreferencesState {\n /** Everything currently stored, keyed exactly as the controls wrote it. */\n readonly entries: Readonly<Record<string, unknown>>;\n /** Pre-populates the store, e.g. to render a table already personalized. */\n seed(entries: Record<string, unknown>): void;\n}\n\n/**\n * In-memory {@link UiPreferencesState}.\n *\n * The port is Effect-returning precisely so an asynchronous, server-backed\n * store can replace `localStorage` without touching a component; this double\n * exists so specs can assert on personalization without depending on jsdom\n * storage behaviour at all.\n */\nexport const makeInMemoryUiPreferencesState = (\n seed: Record<string, unknown> = {},\n): InMemoryUiPreferencesState => {\n let entries: Record<string, unknown> = { ...seed };\n\n return {\n read: <TValue>(key: string) =>\n Effect.sync(() => entries[key] as TValue | undefined),\n write: <TValue>(key: string, value: TValue) =>\n Effect.sync(() => {\n entries[key] = value;\n }),\n remove: (key: string) =>\n Effect.sync(() => {\n delete entries[key];\n }),\n get entries() {\n return entries;\n },\n seed: next => {\n entries = { ...next };\n },\n };\n};\n"],"names":["Effect","makeInMemoryUiPreferencesState","seed","entries","read","key","sync","write","value","remove","next"],"mappings":";AACA,SAASA,MAAM,QAAQ,SAAS;AAShC;;;;;;;CAOC,GACD,OAAO,MAAMC,iCAAiC,CAC5CC,OAAgC,CAAC,CAAC;IAElC,IAAIC,UAAmC,aAAKD;IAE5C,OAAO;QACLE,MAAM,CAASC,MACbL,OAAOM,IAAI,CAAC,IAAMH,OAAO,CAACE,IAAI;QAChCE,OAAO,CAASF,KAAaG,QAC3BR,OAAOM,IAAI,CAAC;gBACVH,OAAO,CAACE,IAAI,GAAGG;YACjB;QACFC,QAAQ,CAACJ,MACPL,OAAOM,IAAI,CAAC;gBACV,OAAOH,OAAO,CAACE,IAAI;YACrB;QACF,IAAIF;YACF,OAAOA;QACT;QACAD,MAAMQ,CAAAA;YACJP,UAAU,aAAKO;QACjB;IACF;AACF,EAAE"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@entifix/testing-unit",
3
- "version": "0.3.0",
3
+ "version": "0.4.0",
4
4
  "description": "Test doubles for entifix: in-memory ports, driver fakes for Mongo, Redis, RabbitMQ and SQL, MSW handlers and port contract suites.",
5
5
  "license": "MIT",
6
6
  "repository": {
@@ -72,17 +72,17 @@
72
72
  },
73
73
  "dependencies": {
74
74
  "@swc/helpers": "0.5.23",
75
- "@entifix/transactions": "0.3.0",
76
- "@entifix/business": "0.3.0",
77
- "@entifix/core": "0.3.0"
75
+ "@entifix/business": "0.4.0",
76
+ "@entifix/core": "0.4.0",
77
+ "@entifix/transactions": "0.4.0"
78
78
  },
79
79
  "peerDependencies": {
80
80
  "@testing-library/react": "*",
81
81
  "effect": "^4.0.5",
82
- "msw": "*",
82
+ "msw": ">=3",
83
83
  "react": "*",
84
84
  "vitest": "*",
85
- "@entifix/react-controls": "0.3.0"
85
+ "@entifix/react-controls": "0.4.0"
86
86
  },
87
87
  "peerDependenciesMeta": {
88
88
  "@entifix/react-controls": {