@event-driven-io/emmett-mongodb 0.43.0-beta.1 → 0.43.0-beta.10

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;
@@ -49,16 +49,18 @@ var ConcurrencyError = class _ConcurrencyError extends EmmettError {
49
49
  // ../emmett/dist/index.js
50
50
  var _uuid = require('uuid');
51
51
 
52
+
52
53
  var _asyncretry = require('async-retry'); var _asyncretry2 = _interopRequireDefault(_asyncretry);
53
54
 
54
55
 
56
+
55
57
  async function tryPublishMessagesAfterCommit(messages, options, context) {
56
- if (_optionalChain([options, 'optionalAccess', _4 => _4.onAfterCommit]) === void 0) return false;
58
+ if (_optionalChain([options, 'optionalAccess', _3 => _3.onAfterCommit]) === void 0) return false;
57
59
  try {
58
- 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)]);
59
61
  return true;
60
- } catch (error2) {
61
- console.error(`Error in on after commit hook`, error2);
62
+ } catch (error) {
63
+ console.error(`Error in on after commit hook`, error);
62
64
  return false;
63
65
  }
64
66
  }
@@ -81,7 +83,7 @@ var assertExpectedVersionMatchesCurrent = (current, expected, defaultVersion) =>
81
83
  };
82
84
  var ExpectedVersionConflictError = class _ExpectedVersionConflictError extends ConcurrencyError {
83
85
  constructor(current, expected) {
84
- 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()]));
85
87
  Object.setPrototypeOf(this, _ExpectedVersionConflictError.prototype);
86
88
  }
87
89
  };
@@ -324,27 +326,109 @@ var deepEquals = (left, right) => {
324
326
  var isEquatable = (left) => {
325
327
  return left !== null && left !== void 0 && typeof left === "object" && "equals" in left && typeof left["equals"] === "function";
326
328
  };
327
- var ParseError = class extends Error {
328
- constructor(text) {
329
- 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
+ }
330
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
+ }
361
+ }
362
+ return value;
331
363
  };
332
- var JSONParser = {
333
- stringify: (value, options) => {
334
- return JSON.stringify(
335
- _optionalChain([options, 'optionalAccess', _11 => _11.map]) ? options.map(value) : value,
336
- //TODO: Consider adding support to DateTime and adding specific format to mark that's a bigint
337
- // eslint-disable-next-line @typescript-eslint/no-unsafe-return
338
- (_, v) => typeof v === "bigint" ? v.toString() : v
339
- );
340
- },
341
- parse: (text, options) => {
342
- const parsed = JSON.parse(text, _optionalChain([options, 'optionalAccess', _12 => _12.reviver]));
343
- if (_optionalChain([options, 'optionalAccess', _13 => _13.typeCheck]) && !_optionalChain([options, 'optionalAccess', _14 => _14.typeCheck, 'call', _15 => _15(parsed)]))
344
- throw new ParseError(text);
345
- 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
+ }
346
370
  }
371
+ return value;
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
+ );
347
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
+ });
348
432
  var textEncoder = new TextEncoder();
349
433
  var AssertionError = class extends Error {
350
434
  constructor(message2) {
@@ -374,7 +458,7 @@ function assertOk(obj, message2) {
374
458
  if (!obj) throw new AssertionError(_nullishCoalesce(message2, () => ( `Condition is not truthy`)));
375
459
  }
376
460
  var downcastRecordedMessage = (recordedMessage, options) => {
377
- if (!_optionalChain([options, 'optionalAccess', _17 => _17.downcast]))
461
+ if (!_optionalChain([options, 'optionalAccess', _23 => _23.downcast]))
378
462
  return recordedMessage;
379
463
  const downcasted = options.downcast(
380
464
  recordedMessage
@@ -392,7 +476,7 @@ var downcastRecordedMessage = (recordedMessage, options) => {
392
476
  };
393
477
  };
394
478
  var upcastRecordedMessage = (recordedMessage, options) => {
395
- if (!_optionalChain([options, 'optionalAccess', _18 => _18.upcast]))
479
+ if (!_optionalChain([options, 'optionalAccess', _24 => _24.upcast]))
396
480
  return recordedMessage;
397
481
  const upcasted = options.upcast(
398
482
  recordedMessage
@@ -410,7 +494,7 @@ var upcastRecordedMessage = (recordedMessage, options) => {
410
494
  };
411
495
  };
412
496
  var upcastRecordedMessages = (recordedMessages, options) => {
413
- if (!_optionalChain([options, 'optionalAccess', _19 => _19.upcast]))
497
+ if (!_optionalChain([options, 'optionalAccess', _25 => _25.upcast]))
414
498
  return recordedMessages;
415
499
  return recordedMessages.map(
416
500
  (recordedMessage) => upcastRecordedMessage(recordedMessage, options)
@@ -425,7 +509,7 @@ var filterProjections = (type, projections2) => {
425
509
  if (duplicateRegistrations.length > 0) {
426
510
  throw new EmmettError(`You cannot register multiple projections with the same name (or without the name).
427
511
  Ensure that:
428
- ${JSONParser.stringify(duplicateRegistrations)}
512
+ ${JSONSerializer.serialize(duplicateRegistrations)}
429
513
  have different names`);
430
514
  }
431
515
  return inlineProjections2;
@@ -553,18 +637,18 @@ var MongoDBInlineProjectionSpec = {
553
637
  if (!isErrorConstructor(args[0])) {
554
638
  assertTrue(
555
639
  args[0](error),
556
- `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()])}`
557
641
  );
558
642
  return;
559
643
  }
560
644
  assertTrue(
561
645
  error instanceof args[0],
562
- `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()])}`
563
647
  );
564
648
  if (args[1]) {
565
649
  assertTrue(
566
650
  args[1](error),
567
- `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()])}`
568
652
  );
569
653
  }
570
654
  } finally {
@@ -734,7 +818,7 @@ var MongoDBEventStoreImplementation = (_class2 = class {
734
818
  }
735
819
  async readStream(streamName, options) {
736
820
  const { streamType } = fromStreamName(streamName);
737
- const expectedStreamVersion = _optionalChain([options, 'optionalAccess', _26 => _26.expectedStreamVersion]);
821
+ const expectedStreamVersion = _optionalChain([options, 'optionalAccess', _32 => _32.expectedStreamVersion]);
738
822
  const collection = await this.storage.collectionFor(streamType);
739
823
  const filter = {
740
824
  streamName: { $eq: streamName }
@@ -770,7 +854,7 @@ var MongoDBEventStoreImplementation = (_class2 = class {
770
854
  );
771
855
  const events = upcastRecordedMessages(
772
856
  stream.messages,
773
- _optionalChain([options, 'optionalAccess', _27 => _27.schema, 'optionalAccess', _28 => _28.versioning])
857
+ _optionalChain([options, 'optionalAccess', _33 => _33.schema, 'optionalAccess', _34 => _34.versioning])
774
858
  );
775
859
  return {
776
860
  events,
@@ -781,7 +865,7 @@ var MongoDBEventStoreImplementation = (_class2 = class {
781
865
  async aggregateStream(streamName, options) {
782
866
  const stream = await this.readStream(
783
867
  streamName,
784
- _optionalChain([options, 'optionalAccess', _29 => _29.read])
868
+ _optionalChain([options, 'optionalAccess', _35 => _35.read])
785
869
  );
786
870
  const { evolve, initialState } = options;
787
871
  const state = stream.events.reduce(evolve, initialState());
@@ -793,7 +877,7 @@ var MongoDBEventStoreImplementation = (_class2 = class {
793
877
  }
794
878
  async appendToStream(streamName, events, options) {
795
879
  const { streamId, streamType } = fromStreamName(streamName);
796
- const expectedStreamVersion = _optionalChain([options, 'optionalAccess', _30 => _30.expectedStreamVersion]);
880
+ const expectedStreamVersion = _optionalChain([options, 'optionalAccess', _36 => _36.expectedStreamVersion]);
797
881
  const collection = await this.storage.collectionFor(streamType);
798
882
  const stream = await collection.findOne(
799
883
  { streamName: { $eq: streamName } },
@@ -805,7 +889,7 @@ var MongoDBEventStoreImplementation = (_class2 = class {
805
889
  }
806
890
  }
807
891
  );
808
- 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));
809
893
  assertExpectedVersionMatchesCurrent(
810
894
  currentStreamVersion,
811
895
  expectedStreamVersion,
@@ -827,7 +911,7 @@ var MongoDBEventStoreImplementation = (_class2 = class {
827
911
  ..."metadata" in event ? _nullishCoalesce(event.metadata, () => ( {})) : {}
828
912
  }
829
913
  },
830
- _optionalChain([options, 'optionalAccess', _33 => _33.schema, 'optionalAccess', _34 => _34.versioning])
914
+ _optionalChain([options, 'optionalAccess', _39 => _39.schema, 'optionalAccess', _40 => _40.versioning])
831
915
  );
832
916
  });
833
917
  const now = /* @__PURE__ */ new Date();
@@ -846,7 +930,7 @@ var MongoDBEventStoreImplementation = (_class2 = class {
846
930
  };
847
931
  if (this.inlineProjections) {
848
932
  await handleInlineProjections({
849
- readModels: _nullishCoalesce(_optionalChain([stream, 'optionalAccess', _35 => _35.projections]), () => ( {})),
933
+ readModels: _nullishCoalesce(_optionalChain([stream, 'optionalAccess', _41 => _41.projections]), () => ( {})),
850
934
  streamId,
851
935
  events: eventsToAppend,
852
936
  projections: this.inlineProjections,
@@ -866,7 +950,7 @@ var MongoDBEventStoreImplementation = (_class2 = class {
866
950
  if (!updatedStream) {
867
951
  throw new ExpectedVersionConflictError(
868
952
  currentStreamVersion,
869
- _nullishCoalesce(_optionalChain([options, 'optionalAccess', _36 => _36.expectedStreamVersion]), () => ( 0n))
953
+ _nullishCoalesce(_optionalChain([options, 'optionalAccess', _42 => _42.expectedStreamVersion]), () => ( 0n))
870
954
  );
871
955
  }
872
956
  await tryPublishMessagesAfterCommit(
@@ -929,7 +1013,7 @@ var MongoDBEventStoreImplementation = (_class2 = class {
929
1013
  projection: { [`projections.${projectionName}`]: 1 }
930
1014
  }
931
1015
  );
932
- 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));
933
1017
  }
934
1018
  async findInlineProjection(streamFilter, projectionQuery, queryOptions) {
935
1019
  const parsedStreamFilter = parseMultiProjectionQueryStreamFilter(streamFilter);
@@ -954,13 +1038,13 @@ var MongoDBEventStoreImplementation = (_class2 = class {
954
1038
  projection: { [`projections.${projectionName}`]: 1 }
955
1039
  }
956
1040
  );
957
- if (_optionalChain([queryOptions, 'optionalAccess', _39 => _39.skip])) {
1041
+ if (_optionalChain([queryOptions, 'optionalAccess', _45 => _45.skip])) {
958
1042
  query = query.skip(queryOptions.skip);
959
1043
  }
960
- if (_optionalChain([queryOptions, 'optionalAccess', _40 => _40.limit])) {
1044
+ if (_optionalChain([queryOptions, 'optionalAccess', _46 => _46.limit])) {
961
1045
  query = query.limit(queryOptions.limit);
962
1046
  }
963
- if (_optionalChain([queryOptions, 'optionalAccess', _41 => _41.sort])) {
1047
+ if (_optionalChain([queryOptions, 'optionalAccess', _47 => _47.sort])) {
964
1048
  const sort = prependMongoFilterWithProjectionPrefix(
965
1049
  queryOptions.sort,
966
1050
  prefix