@event-driven-io/emmett-mongodb 0.43.0-beta.7 → 0.43.0-beta.9

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -38,7 +38,7 @@ var ConcurrencyError = class _ConcurrencyError extends EmmettError {
38
38
  constructor(current, expected, message) {
39
39
  super({
40
40
  errorCode: EmmettError.Codes.ConcurrencyError,
41
- message: _nullishCoalesce(message, () => ( `Expected version ${expected.toString()} does not match current ${_optionalChain([current, 'optionalAccess', _2 => _2.toString, 'call', _3 => _3()])}`))
41
+ message: _nullishCoalesce(message, () => ( `Expected version ${expected.toString()} does not match current ${_optionalChain([current, 'optionalAccess', _ => _.toString, 'call', _2 => _2()])}`))
42
42
  });
43
43
  this.current = current;
44
44
  this.expected = expected;
@@ -55,9 +55,9 @@ var _asyncretry = require('async-retry'); var _asyncretry2 = _interopRequireDefa
55
55
 
56
56
 
57
57
  async function tryPublishMessagesAfterCommit(messages, options, context) {
58
- if (_optionalChain([options, 'optionalAccess', _4 => _4.onAfterCommit]) === void 0) return false;
58
+ if (_optionalChain([options, 'optionalAccess', _3 => _3.onAfterCommit]) === void 0) return false;
59
59
  try {
60
- await _optionalChain([options, 'optionalAccess', _5 => _5.onAfterCommit, 'call', _6 => _6(messages, context)]);
60
+ await _optionalChain([options, 'optionalAccess', _4 => _4.onAfterCommit, 'call', _5 => _5(messages, context)]);
61
61
  return true;
62
62
  } catch (error) {
63
63
  console.error(`Error in on after commit hook`, error);
@@ -83,7 +83,7 @@ var assertExpectedVersionMatchesCurrent = (current, expected, defaultVersion) =>
83
83
  };
84
84
  var ExpectedVersionConflictError = class _ExpectedVersionConflictError extends ConcurrencyError {
85
85
  constructor(current, expected) {
86
- super(_optionalChain([current, 'optionalAccess', _7 => _7.toString, 'call', _8 => _8()]), _optionalChain([expected, 'optionalAccess', _9 => _9.toString, 'call', _10 => _10()]));
86
+ super(_optionalChain([current, 'optionalAccess', _6 => _6.toString, 'call', _7 => _7()]), _optionalChain([expected, 'optionalAccess', _8 => _8.toString, 'call', _9 => _9()]));
87
87
  Object.setPrototypeOf(this, _ExpectedVersionConflictError.prototype);
88
88
  }
89
89
  };
@@ -326,27 +326,109 @@ var deepEquals = (left, right) => {
326
326
  var isEquatable = (left) => {
327
327
  return left !== null && left !== void 0 && typeof left === "object" && "equals" in left && typeof left["equals"] === "function";
328
328
  };
329
- var ParseError = class extends Error {
330
- constructor(text) {
331
- super(`Cannot parse! ${text}`);
329
+ var bigIntReplacer = (_key, value) => {
330
+ return typeof value === "bigint" ? value.toString() : value;
331
+ };
332
+ var dateReplacer = (_key, value) => {
333
+ return value instanceof Date ? value.toISOString() : value;
334
+ };
335
+ var isFirstLetterNumeric = (str) => {
336
+ const c = str.charCodeAt(0);
337
+ return c >= 48 && c <= 57;
338
+ };
339
+ var isFirstLetterNumericOrMinus = (str) => {
340
+ const c = str.charCodeAt(0);
341
+ return c >= 48 && c <= 57 || c === 45;
342
+ };
343
+ var bigIntReviver = (_key, value, context) => {
344
+ if (typeof value === "number" && Number.isInteger(value) && !Number.isSafeInteger(value)) {
345
+ try {
346
+ return BigInt(_nullishCoalesce(_optionalChain([context, 'optionalAccess', _10 => _10.source]), () => ( value.toString())));
347
+ } catch (e2) {
348
+ return value;
349
+ }
350
+ }
351
+ if (typeof value === "string" && value.length > 15) {
352
+ if (isFirstLetterNumericOrMinus(value)) {
353
+ const num = Number(value);
354
+ if (Number.isFinite(num) && !Number.isSafeInteger(num)) {
355
+ try {
356
+ return BigInt(value);
357
+ } catch (e3) {
358
+ }
359
+ }
360
+ }
332
361
  }
362
+ return value;
333
363
  };
334
- var JSONParser = {
335
- stringify: (value, options) => {
336
- return JSON.stringify(
337
- _optionalChain([options, 'optionalAccess', _11 => _11.map]) ? options.map(value) : value,
338
- //TODO: Consider adding support to DateTime and adding specific format to mark that's a bigint
339
- // eslint-disable-next-line @typescript-eslint/no-unsafe-return
340
- (_, v) => typeof v === "bigint" ? v.toString() : v
341
- );
342
- },
343
- parse: (text, options) => {
344
- const parsed = JSON.parse(text, _optionalChain([options, 'optionalAccess', _12 => _12.reviver]));
345
- if (_optionalChain([options, 'optionalAccess', _13 => _13.typeCheck]) && !_optionalChain([options, 'optionalAccess', _14 => _14.typeCheck, 'call', _15 => _15(parsed)]))
346
- throw new ParseError(text);
347
- return _optionalChain([options, 'optionalAccess', _16 => _16.map]) ? options.map(parsed) : parsed;
364
+ var dateReviver = (_key, value) => {
365
+ if (typeof value === "string" && value.length === 24 && isFirstLetterNumeric(value) && value[10] === "T" && value[23] === "Z") {
366
+ const date = new Date(value);
367
+ if (!isNaN(date.getTime())) {
368
+ return date;
369
+ }
348
370
  }
371
+ return value;
349
372
  };
373
+ var composeJSONReplacers = (...replacers) => {
374
+ const filteredReplacers = replacers.filter((r) => r !== void 0);
375
+ if (filteredReplacers.length === 0) return void 0;
376
+ return (key, value) => (
377
+ // eslint-disable-next-line @typescript-eslint/no-unsafe-return
378
+ filteredReplacers.reduce(
379
+ // eslint-disable-next-line @typescript-eslint/no-unsafe-return
380
+ (accValue, replacer) => replacer(key, accValue),
381
+ value
382
+ )
383
+ );
384
+ };
385
+ var composeJSONRevivers = (...revivers) => {
386
+ const filteredRevivers = revivers.filter((r) => r !== void 0);
387
+ if (filteredRevivers.length === 0) return void 0;
388
+ return (key, value, context) => (
389
+ // eslint-disable-next-line @typescript-eslint/no-unsafe-return
390
+ filteredRevivers.reduce(
391
+ // eslint-disable-next-line @typescript-eslint/no-unsafe-return
392
+ (accValue, reviver) => reviver(key, accValue, context),
393
+ value
394
+ )
395
+ );
396
+ };
397
+ var JSONReplacer = (opts) => composeJSONReplacers(
398
+ _optionalChain([opts, 'optionalAccess', _11 => _11.replacer]),
399
+ _optionalChain([opts, 'optionalAccess', _12 => _12.failOnBigIntSerialization]) !== true ? JSONReplacers.bigInt : void 0,
400
+ _optionalChain([opts, 'optionalAccess', _13 => _13.useDefaultDateSerialization]) !== true ? JSONReplacers.date : void 0
401
+ );
402
+ var JSONReviver = (opts) => composeJSONRevivers(
403
+ _optionalChain([opts, 'optionalAccess', _14 => _14.reviver]),
404
+ _optionalChain([opts, 'optionalAccess', _15 => _15.parseBigInts]) === true ? JSONRevivers.bigInt : void 0,
405
+ _optionalChain([opts, 'optionalAccess', _16 => _16.parseDates]) === true ? JSONRevivers.date : void 0
406
+ );
407
+ var JSONReplacers = {
408
+ bigInt: bigIntReplacer,
409
+ date: dateReplacer
410
+ };
411
+ var JSONRevivers = {
412
+ bigInt: bigIntReviver,
413
+ date: dateReviver
414
+ };
415
+ var jsonSerializer = (options) => {
416
+ const defaultReplacer = JSONReplacer(options);
417
+ const defaultReviver = JSONReviver(options);
418
+ return {
419
+ serialize: (object, serializerOptions) => JSON.stringify(
420
+ object,
421
+ serializerOptions ? JSONReplacer(serializerOptions) : defaultReplacer
422
+ ),
423
+ deserialize: (payload, deserializerOptions) => JSON.parse(
424
+ payload,
425
+ deserializerOptions ? JSONReviver(deserializerOptions) : defaultReviver
426
+ )
427
+ };
428
+ };
429
+ var JSONSerializer = Object.assign(jsonSerializer(), {
430
+ from: (options) => _nullishCoalesce(_optionalChain([options, 'optionalAccess', _17 => _17.serialization, 'optionalAccess', _18 => _18.serializer]), () => ( (_optionalChain([options, 'optionalAccess', _19 => _19.serialization, 'optionalAccess', _20 => _20.options]) ? jsonSerializer(_optionalChain([options, 'optionalAccess', _21 => _21.serialization, 'optionalAccess', _22 => _22.options])) : JSONSerializer)))
431
+ });
350
432
  var textEncoder = new TextEncoder();
351
433
  var AssertionError = class extends Error {
352
434
  constructor(message2) {
@@ -376,7 +458,7 @@ function assertOk(obj, message2) {
376
458
  if (!obj) throw new AssertionError(_nullishCoalesce(message2, () => ( `Condition is not truthy`)));
377
459
  }
378
460
  var downcastRecordedMessage = (recordedMessage, options) => {
379
- if (!_optionalChain([options, 'optionalAccess', _17 => _17.downcast]))
461
+ if (!_optionalChain([options, 'optionalAccess', _23 => _23.downcast]))
380
462
  return recordedMessage;
381
463
  const downcasted = options.downcast(
382
464
  recordedMessage
@@ -394,7 +476,7 @@ var downcastRecordedMessage = (recordedMessage, options) => {
394
476
  };
395
477
  };
396
478
  var upcastRecordedMessage = (recordedMessage, options) => {
397
- if (!_optionalChain([options, 'optionalAccess', _18 => _18.upcast]))
479
+ if (!_optionalChain([options, 'optionalAccess', _24 => _24.upcast]))
398
480
  return recordedMessage;
399
481
  const upcasted = options.upcast(
400
482
  recordedMessage
@@ -412,7 +494,7 @@ var upcastRecordedMessage = (recordedMessage, options) => {
412
494
  };
413
495
  };
414
496
  var upcastRecordedMessages = (recordedMessages, options) => {
415
- if (!_optionalChain([options, 'optionalAccess', _19 => _19.upcast]))
497
+ if (!_optionalChain([options, 'optionalAccess', _25 => _25.upcast]))
416
498
  return recordedMessages;
417
499
  return recordedMessages.map(
418
500
  (recordedMessage) => upcastRecordedMessage(recordedMessage, options)
@@ -427,7 +509,7 @@ var filterProjections = (type, projections2) => {
427
509
  if (duplicateRegistrations.length > 0) {
428
510
  throw new EmmettError(`You cannot register multiple projections with the same name (or without the name).
429
511
  Ensure that:
430
- ${JSONParser.stringify(duplicateRegistrations)}
512
+ ${JSONSerializer.serialize(duplicateRegistrations)}
431
513
  have different names`);
432
514
  }
433
515
  return inlineProjections2;
@@ -555,18 +637,18 @@ var MongoDBInlineProjectionSpec = {
555
637
  if (!isErrorConstructor(args[0])) {
556
638
  assertTrue(
557
639
  args[0](error),
558
- `Error didn't match the error condition: ${_optionalChain([error, 'optionalAccess', _20 => _20.toString, 'call', _21 => _21()])}`
640
+ `Error didn't match the error condition: ${_optionalChain([error, 'optionalAccess', _26 => _26.toString, 'call', _27 => _27()])}`
559
641
  );
560
642
  return;
561
643
  }
562
644
  assertTrue(
563
645
  error instanceof args[0],
564
- `Caught error is not an instance of the expected type: ${_optionalChain([error, 'optionalAccess', _22 => _22.toString, 'call', _23 => _23()])}`
646
+ `Caught error is not an instance of the expected type: ${_optionalChain([error, 'optionalAccess', _28 => _28.toString, 'call', _29 => _29()])}`
565
647
  );
566
648
  if (args[1]) {
567
649
  assertTrue(
568
650
  args[1](error),
569
- `Error didn't match the error condition: ${_optionalChain([error, 'optionalAccess', _24 => _24.toString, 'call', _25 => _25()])}`
651
+ `Error didn't match the error condition: ${_optionalChain([error, 'optionalAccess', _30 => _30.toString, 'call', _31 => _31()])}`
570
652
  );
571
653
  }
572
654
  } finally {
@@ -736,7 +818,7 @@ var MongoDBEventStoreImplementation = (_class2 = class {
736
818
  }
737
819
  async readStream(streamName, options) {
738
820
  const { streamType } = fromStreamName(streamName);
739
- const expectedStreamVersion = _optionalChain([options, 'optionalAccess', _26 => _26.expectedStreamVersion]);
821
+ const expectedStreamVersion = _optionalChain([options, 'optionalAccess', _32 => _32.expectedStreamVersion]);
740
822
  const collection = await this.storage.collectionFor(streamType);
741
823
  const filter = {
742
824
  streamName: { $eq: streamName }
@@ -772,7 +854,7 @@ var MongoDBEventStoreImplementation = (_class2 = class {
772
854
  );
773
855
  const events = upcastRecordedMessages(
774
856
  stream.messages,
775
- _optionalChain([options, 'optionalAccess', _27 => _27.schema, 'optionalAccess', _28 => _28.versioning])
857
+ _optionalChain([options, 'optionalAccess', _33 => _33.schema, 'optionalAccess', _34 => _34.versioning])
776
858
  );
777
859
  return {
778
860
  events,
@@ -783,7 +865,7 @@ var MongoDBEventStoreImplementation = (_class2 = class {
783
865
  async aggregateStream(streamName, options) {
784
866
  const stream = await this.readStream(
785
867
  streamName,
786
- _optionalChain([options, 'optionalAccess', _29 => _29.read])
868
+ _optionalChain([options, 'optionalAccess', _35 => _35.read])
787
869
  );
788
870
  const { evolve, initialState } = options;
789
871
  const state = stream.events.reduce(evolve, initialState());
@@ -795,7 +877,7 @@ var MongoDBEventStoreImplementation = (_class2 = class {
795
877
  }
796
878
  async appendToStream(streamName, events, options) {
797
879
  const { streamId, streamType } = fromStreamName(streamName);
798
- const expectedStreamVersion = _optionalChain([options, 'optionalAccess', _30 => _30.expectedStreamVersion]);
880
+ const expectedStreamVersion = _optionalChain([options, 'optionalAccess', _36 => _36.expectedStreamVersion]);
799
881
  const collection = await this.storage.collectionFor(streamType);
800
882
  const stream = await collection.findOne(
801
883
  { streamName: { $eq: streamName } },
@@ -807,7 +889,7 @@ var MongoDBEventStoreImplementation = (_class2 = class {
807
889
  }
808
890
  }
809
891
  );
810
- const currentStreamVersion = _nullishCoalesce(_optionalChain([stream, 'optionalAccess', _31 => _31.metadata, 'access', _32 => _32.streamPosition]), () => ( MongoDBEventStoreDefaultStreamVersion));
892
+ const currentStreamVersion = _nullishCoalesce(_optionalChain([stream, 'optionalAccess', _37 => _37.metadata, 'access', _38 => _38.streamPosition]), () => ( MongoDBEventStoreDefaultStreamVersion));
811
893
  assertExpectedVersionMatchesCurrent(
812
894
  currentStreamVersion,
813
895
  expectedStreamVersion,
@@ -829,7 +911,7 @@ var MongoDBEventStoreImplementation = (_class2 = class {
829
911
  ..."metadata" in event ? _nullishCoalesce(event.metadata, () => ( {})) : {}
830
912
  }
831
913
  },
832
- _optionalChain([options, 'optionalAccess', _33 => _33.schema, 'optionalAccess', _34 => _34.versioning])
914
+ _optionalChain([options, 'optionalAccess', _39 => _39.schema, 'optionalAccess', _40 => _40.versioning])
833
915
  );
834
916
  });
835
917
  const now = /* @__PURE__ */ new Date();
@@ -848,7 +930,7 @@ var MongoDBEventStoreImplementation = (_class2 = class {
848
930
  };
849
931
  if (this.inlineProjections) {
850
932
  await handleInlineProjections({
851
- readModels: _nullishCoalesce(_optionalChain([stream, 'optionalAccess', _35 => _35.projections]), () => ( {})),
933
+ readModels: _nullishCoalesce(_optionalChain([stream, 'optionalAccess', _41 => _41.projections]), () => ( {})),
852
934
  streamId,
853
935
  events: eventsToAppend,
854
936
  projections: this.inlineProjections,
@@ -868,7 +950,7 @@ var MongoDBEventStoreImplementation = (_class2 = class {
868
950
  if (!updatedStream) {
869
951
  throw new ExpectedVersionConflictError(
870
952
  currentStreamVersion,
871
- _nullishCoalesce(_optionalChain([options, 'optionalAccess', _36 => _36.expectedStreamVersion]), () => ( 0n))
953
+ _nullishCoalesce(_optionalChain([options, 'optionalAccess', _42 => _42.expectedStreamVersion]), () => ( 0n))
872
954
  );
873
955
  }
874
956
  await tryPublishMessagesAfterCommit(
@@ -931,7 +1013,7 @@ var MongoDBEventStoreImplementation = (_class2 = class {
931
1013
  projection: { [`projections.${projectionName}`]: 1 }
932
1014
  }
933
1015
  );
934
- return _nullishCoalesce(_optionalChain([result, 'optionalAccess', _37 => _37.projections, 'optionalAccess', _38 => _38[projectionName]]), () => ( null));
1016
+ return _nullishCoalesce(_optionalChain([result, 'optionalAccess', _43 => _43.projections, 'optionalAccess', _44 => _44[projectionName]]), () => ( null));
935
1017
  }
936
1018
  async findInlineProjection(streamFilter, projectionQuery, queryOptions) {
937
1019
  const parsedStreamFilter = parseMultiProjectionQueryStreamFilter(streamFilter);
@@ -956,13 +1038,13 @@ var MongoDBEventStoreImplementation = (_class2 = class {
956
1038
  projection: { [`projections.${projectionName}`]: 1 }
957
1039
  }
958
1040
  );
959
- if (_optionalChain([queryOptions, 'optionalAccess', _39 => _39.skip])) {
1041
+ if (_optionalChain([queryOptions, 'optionalAccess', _45 => _45.skip])) {
960
1042
  query = query.skip(queryOptions.skip);
961
1043
  }
962
- if (_optionalChain([queryOptions, 'optionalAccess', _40 => _40.limit])) {
1044
+ if (_optionalChain([queryOptions, 'optionalAccess', _46 => _46.limit])) {
963
1045
  query = query.limit(queryOptions.limit);
964
1046
  }
965
- if (_optionalChain([queryOptions, 'optionalAccess', _41 => _41.sort])) {
1047
+ if (_optionalChain([queryOptions, 'optionalAccess', _47 => _47.sort])) {
966
1048
  const sort = prependMongoFilterWithProjectionPrefix(
967
1049
  queryOptions.sort,
968
1050
  prefix