@event-driven-io/emmett-sqlite 0.43.0-beta.1 → 0.43.0-beta.11

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
@@ -1,4 +1,131 @@
1
- "use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _nullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } } async function _asyncNullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return await rhsFn(); } } function _optionalChain(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; } var _class;// ../emmett/dist/chunk-AZDDB5SF.js
1
+ "use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _nullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } } async function _asyncNullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return await rhsFn(); } } function _optionalChain(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; } var _class;// src/eventStore/projections/pongo/pongoProjections.ts
2
+
3
+
4
+ var _pongo = require('@event-driven-io/pongo');
5
+ var pongoProjection = ({
6
+ name,
7
+ kind,
8
+ version,
9
+ truncate,
10
+ handle,
11
+ canHandle,
12
+ eventsOptions
13
+ }) => sqliteProjection({
14
+ name,
15
+ version,
16
+ kind: _nullishCoalesce(kind, () => ( "emt:projections:postgresql:pongo:generic")),
17
+ canHandle,
18
+ eventsOptions,
19
+ handle: async (events, context) => {
20
+ const { connection } = context;
21
+ const driver = await pongoDriverRegistry.tryResolve(
22
+ context.driverType
23
+ );
24
+ const pongo = _pongo.pongoClient.call(void 0, {
25
+ driver,
26
+ connectionOptions: { connection }
27
+ });
28
+ try {
29
+ await handle(events, {
30
+ ...context,
31
+ pongo
32
+ });
33
+ } finally {
34
+ await pongo.close();
35
+ }
36
+ },
37
+ truncate: truncate ? async (context) => {
38
+ const { connection } = context;
39
+ const driver = await pongoDriverRegistry.tryResolve(
40
+ context.driverType
41
+ );
42
+ const pongo = _pongo.pongoClient.call(void 0, {
43
+ driver,
44
+ connectionOptions: { connection }
45
+ });
46
+ try {
47
+ await truncate({
48
+ ...context,
49
+ pongo
50
+ });
51
+ } finally {
52
+ await pongo.close();
53
+ }
54
+ } : void 0
55
+ });
56
+ var pongoMultiStreamProjection = (options) => {
57
+ const { collectionName, getDocumentId, canHandle } = options;
58
+ const collectionNameWithVersion = options.version && options.version > 0 ? `${collectionName}_v${options.version}` : collectionName;
59
+ return pongoProjection({
60
+ name: collectionNameWithVersion,
61
+ version: options.version,
62
+ kind: _nullishCoalesce(options.kind, () => ( "emt:projections:postgresql:pongo:multi_stream")),
63
+ eventsOptions: options.eventsOptions,
64
+ handle: async (events, { pongo }) => {
65
+ const collection = pongo.db().collection(
66
+ collectionNameWithVersion,
67
+ options.collectionOptions
68
+ );
69
+ for (const event of events) {
70
+ await collection.handle(getDocumentId(event), async (document) => {
71
+ return "initialState" in options ? await options.evolve(
72
+ _nullishCoalesce(document, () => ( options.initialState())),
73
+ event
74
+ ) : await options.evolve(
75
+ document,
76
+ event
77
+ );
78
+ });
79
+ }
80
+ },
81
+ canHandle,
82
+ truncate: async (context) => {
83
+ const { connection } = context;
84
+ const driver = await pongoDriverRegistry.tryResolve(
85
+ context.driverType
86
+ );
87
+ const pongo = _pongo.pongoClient.call(void 0, {
88
+ driver,
89
+ connectionOptions: { connection }
90
+ });
91
+ try {
92
+ await pongo.db().collection(
93
+ collectionNameWithVersion,
94
+ options.collectionOptions
95
+ ).deleteMany();
96
+ } finally {
97
+ await pongo.close();
98
+ }
99
+ },
100
+ init: async (context) => {
101
+ const { connection } = context;
102
+ const driver = await pongoDriverRegistry.tryResolve(
103
+ context.driverType
104
+ );
105
+ const pongo = _pongo.pongoClient.call(void 0, {
106
+ connectionOptions: { connection },
107
+ driver
108
+ });
109
+ try {
110
+ await pongo.db().collection(
111
+ collectionNameWithVersion,
112
+ options.collectionOptions
113
+ ).schema.migrate();
114
+ } finally {
115
+ await pongo.close();
116
+ }
117
+ }
118
+ });
119
+ };
120
+ var pongoSingleStreamProjection = (options) => {
121
+ return pongoMultiStreamProjection({
122
+ ...options,
123
+ kind: "emt:projections:postgresql:pongo:single_stream",
124
+ getDocumentId: _nullishCoalesce(options.getDocumentId, () => ( ((event) => event.metadata.streamName)))
125
+ });
126
+ };
127
+
128
+ // ../emmett/dist/chunk-AZDDB5SF.js
2
129
  var isNumber = (val) => typeof val === "number" && val === val;
3
130
  var isString = (val) => typeof val === "string";
4
131
  var isErrorConstructor = (expect) => {
@@ -38,7 +165,7 @@ var ConcurrencyError = class _ConcurrencyError extends EmmettError {
38
165
  constructor(current, expected, message) {
39
166
  super({
40
167
  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()])}`))
168
+ message: _nullishCoalesce(message, () => ( `Expected version ${expected.toString()} does not match current ${_optionalChain([current, 'optionalAccess', _ => _.toString, 'call', _2 => _2()])}`))
42
169
  });
43
170
  this.current = current;
44
171
  this.expected = expected;
@@ -49,12 +176,24 @@ var ConcurrencyError = class _ConcurrencyError extends EmmettError {
49
176
  // ../emmett/dist/index.js
50
177
  var _uuid = require('uuid');
51
178
 
179
+
52
180
  var _asyncretry = require('async-retry'); var _asyncretry2 = _interopRequireDefault(_asyncretry);
53
181
 
54
182
 
183
+
55
184
  var emmettPrefix = "emt";
56
185
  var defaultTag = `${emmettPrefix}:default`;
57
186
  var unknownTag = `${emmettPrefix}:unknown`;
187
+ var canCreateEventStoreSession = (eventStore) => "withSession" in eventStore;
188
+ var nulloSessionFactory = (eventStore) => ({
189
+ withSession: (callback) => {
190
+ const nulloSession = {
191
+ eventStore,
192
+ close: () => Promise.resolve()
193
+ };
194
+ return callback(nulloSession);
195
+ }
196
+ });
58
197
  var STREAM_EXISTS = "STREAM_EXISTS";
59
198
  var STREAM_DOES_NOT_EXIST = "STREAM_DOES_NOT_EXIST";
60
199
  var NO_CONCURRENCY_CHECK = "NO_CONCURRENCY_CHECK";
@@ -71,12 +210,12 @@ var assertExpectedVersionMatchesCurrent = (current, expected, defaultVersion) =>
71
210
  };
72
211
  var ExpectedVersionConflictError = class _ExpectedVersionConflictError extends ConcurrencyError {
73
212
  constructor(current, expected) {
74
- super(_optionalChain([current, 'optionalAccess', _4 => _4.toString, 'call', _5 => _5()]), _optionalChain([expected, 'optionalAccess', _6 => _6.toString, 'call', _7 => _7()]));
213
+ super(_optionalChain([current, 'optionalAccess', _3 => _3.toString, 'call', _4 => _4()]), _optionalChain([expected, 'optionalAccess', _5 => _5.toString, 'call', _6 => _6()]));
75
214
  Object.setPrototypeOf(this, _ExpectedVersionConflictError.prototype);
76
215
  }
77
216
  };
78
- var isExpectedVersionConflictError = (error2) => error2 instanceof ExpectedVersionConflictError || EmmettError.isInstanceOf(
79
- error2,
217
+ var isExpectedVersionConflictError = (error) => error instanceof ExpectedVersionConflictError || EmmettError.isInstanceOf(
218
+ error,
80
219
  ExpectedVersionConflictError.Codes.ConcurrencyError
81
220
  );
82
221
  var isPrimitive = (value) => {
@@ -284,26 +423,132 @@ var toNormalizedString = (value) => value.toString().padStart(19, "0");
284
423
  var bigInt = {
285
424
  toNormalizedString
286
425
  };
287
- var ParseError = class extends Error {
288
- constructor(text) {
289
- super(`Cannot parse! ${text}`);
426
+ var bigIntReplacer = (_key, value) => {
427
+ return typeof value === "bigint" ? value.toString() : value;
428
+ };
429
+ var dateReplacer = (_key, value) => {
430
+ return value instanceof Date ? value.toISOString() : value;
431
+ };
432
+ var isFirstLetterNumeric = (str) => {
433
+ const c = str.charCodeAt(0);
434
+ return c >= 48 && c <= 57;
435
+ };
436
+ var isFirstLetterNumericOrMinus = (str) => {
437
+ const c = str.charCodeAt(0);
438
+ return c >= 48 && c <= 57 || c === 45;
439
+ };
440
+ var bigIntReviver = (_key, value, context) => {
441
+ if (typeof value === "number" && Number.isInteger(value) && !Number.isSafeInteger(value)) {
442
+ try {
443
+ return BigInt(_nullishCoalesce(_optionalChain([context, 'optionalAccess', _7 => _7.source]), () => ( value.toString())));
444
+ } catch (e2) {
445
+ return value;
446
+ }
447
+ }
448
+ if (typeof value === "string" && value.length > 15) {
449
+ if (isFirstLetterNumericOrMinus(value)) {
450
+ const num = Number(value);
451
+ if (Number.isFinite(num) && !Number.isSafeInteger(num)) {
452
+ try {
453
+ return BigInt(value);
454
+ } catch (e3) {
455
+ }
456
+ }
457
+ }
458
+ }
459
+ return value;
460
+ };
461
+ var dateReviver = (_key, value) => {
462
+ if (typeof value === "string" && value.length === 24 && isFirstLetterNumeric(value) && value[10] === "T" && value[23] === "Z") {
463
+ const date = new Date(value);
464
+ if (!isNaN(date.getTime())) {
465
+ return date;
466
+ }
290
467
  }
468
+ return value;
469
+ };
470
+ var composeJSONReplacers = (...replacers) => {
471
+ const filteredReplacers = replacers.filter((r) => r !== void 0);
472
+ if (filteredReplacers.length === 0) return void 0;
473
+ return (key, value) => (
474
+ // eslint-disable-next-line @typescript-eslint/no-unsafe-return
475
+ filteredReplacers.reduce(
476
+ // eslint-disable-next-line @typescript-eslint/no-unsafe-return
477
+ (accValue, replacer) => replacer(key, accValue),
478
+ value
479
+ )
480
+ );
291
481
  };
292
- var JSONParser = {
293
- stringify: (value, options) => {
294
- return JSON.stringify(
295
- _optionalChain([options, 'optionalAccess', _8 => _8.map]) ? options.map(value) : value,
296
- //TODO: Consider adding support to DateTime and adding specific format to mark that's a bigint
482
+ var composeJSONRevivers = (...revivers) => {
483
+ const filteredRevivers = revivers.filter((r) => r !== void 0);
484
+ if (filteredRevivers.length === 0) return void 0;
485
+ return (key, value, context) => (
486
+ // eslint-disable-next-line @typescript-eslint/no-unsafe-return
487
+ filteredRevivers.reduce(
297
488
  // eslint-disable-next-line @typescript-eslint/no-unsafe-return
298
- (_, v) => typeof v === "bigint" ? v.toString() : v
299
- );
300
- },
301
- parse: (text, options) => {
302
- const parsed = JSON.parse(text, _optionalChain([options, 'optionalAccess', _9 => _9.reviver]));
303
- if (_optionalChain([options, 'optionalAccess', _10 => _10.typeCheck]) && !_optionalChain([options, 'optionalAccess', _11 => _11.typeCheck, 'call', _12 => _12(parsed)]))
304
- throw new ParseError(text);
305
- return _optionalChain([options, 'optionalAccess', _13 => _13.map]) ? options.map(parsed) : parsed;
306
- }
489
+ (accValue, reviver) => reviver(key, accValue, context),
490
+ value
491
+ )
492
+ );
493
+ };
494
+ var JSONReplacer = (opts) => composeJSONReplacers(
495
+ _optionalChain([opts, 'optionalAccess', _8 => _8.replacer]),
496
+ _optionalChain([opts, 'optionalAccess', _9 => _9.failOnBigIntSerialization]) !== true ? JSONReplacers.bigInt : void 0,
497
+ _optionalChain([opts, 'optionalAccess', _10 => _10.useDefaultDateSerialization]) !== true ? JSONReplacers.date : void 0
498
+ );
499
+ var JSONReviver = (opts) => composeJSONRevivers(
500
+ _optionalChain([opts, 'optionalAccess', _11 => _11.reviver]),
501
+ _optionalChain([opts, 'optionalAccess', _12 => _12.parseBigInts]) === true ? JSONRevivers.bigInt : void 0,
502
+ _optionalChain([opts, 'optionalAccess', _13 => _13.parseDates]) === true ? JSONRevivers.date : void 0
503
+ );
504
+ var JSONReplacers = {
505
+ bigInt: bigIntReplacer,
506
+ date: dateReplacer
507
+ };
508
+ var JSONRevivers = {
509
+ bigInt: bigIntReviver,
510
+ date: dateReviver
511
+ };
512
+ var jsonSerializer = (options) => {
513
+ const defaultReplacer = JSONReplacer(options);
514
+ const defaultReviver = JSONReviver(options);
515
+ return {
516
+ serialize: (object, serializerOptions) => JSON.stringify(
517
+ object,
518
+ serializerOptions ? JSONReplacer(serializerOptions) : defaultReplacer
519
+ ),
520
+ deserialize: (payload, deserializerOptions) => JSON.parse(
521
+ payload,
522
+ deserializerOptions ? JSONReviver(deserializerOptions) : defaultReviver
523
+ )
524
+ };
525
+ };
526
+ var JSONSerializer = Object.assign(jsonSerializer(), {
527
+ from: (options) => _nullishCoalesce(_optionalChain([options, 'optionalAccess', _14 => _14.serialization, 'optionalAccess', _15 => _15.serializer]), () => ( (_optionalChain([options, 'optionalAccess', _16 => _16.serialization, 'optionalAccess', _17 => _17.options]) ? jsonSerializer(_optionalChain([options, 'optionalAccess', _18 => _18.serialization, 'optionalAccess', _19 => _19.options])) : JSONSerializer)))
528
+ });
529
+ var NoRetries = { retries: 0 };
530
+ var asyncRetry = async (fn, opts) => {
531
+ if (opts === void 0 || opts.retries === 0) return fn();
532
+ return _asyncretry2.default.call(void 0,
533
+ async (bail) => {
534
+ try {
535
+ const result = await fn();
536
+ if (_optionalChain([opts, 'optionalAccess', _20 => _20.shouldRetryResult]) && opts.shouldRetryResult(result)) {
537
+ throw new EmmettError(
538
+ `Retrying because of result: ${JSONSerializer.serialize(result)}`
539
+ );
540
+ }
541
+ return result;
542
+ } catch (error) {
543
+ if (_optionalChain([opts, 'optionalAccess', _21 => _21.shouldRetryError]) && !opts.shouldRetryError(error)) {
544
+ bail(error);
545
+ return void 0;
546
+ }
547
+ throw error;
548
+ }
549
+ },
550
+ _nullishCoalesce(opts, () => ( { retries: 0 }))
551
+ );
307
552
  };
308
553
  var onShutdown = (handler) => {
309
554
  const signals = ["SIGTERM", "SIGINT"];
@@ -395,12 +640,13 @@ var reactor = (options) => {
395
640
  id: processorId,
396
641
  instanceId,
397
642
  type,
643
+ canHandle,
398
644
  init,
399
645
  start: async (startOptions) => {
400
646
  if (isActive) return;
401
647
  await init(startOptions);
402
648
  isActive = true;
403
- closeSignal = onShutdown(() => close({}));
649
+ closeSignal = onShutdown(() => close(startOptions));
404
650
  if (lastCheckpoint !== null)
405
651
  return {
406
652
  lastCheckpoint
@@ -411,7 +657,7 @@ var reactor = (options) => {
411
657
  }
412
658
  if (startFrom && startFrom !== "CURRENT") return startFrom;
413
659
  if (checkpoints) {
414
- const readResult = await _optionalChain([checkpoints, 'optionalAccess', _14 => _14.read, 'call', _15 => _15(
660
+ const readResult = await _optionalChain([checkpoints, 'optionalAccess', _22 => _22.read, 'call', _23 => _23(
415
661
  {
416
662
  processorId,
417
663
  partition
@@ -439,7 +685,7 @@ var reactor = (options) => {
439
685
  const upcasted = upcastRecordedMessage(
440
686
  // TODO: Make it smarter
441
687
  message2,
442
- _optionalChain([options, 'access', _16 => _16.messageOptions, 'optionalAccess', _17 => _17.schema, 'optionalAccess', _18 => _18.versioning])
688
+ _optionalChain([options, 'access', _24 => _24.messageOptions, 'optionalAccess', _25 => _25.schema, 'optionalAccess', _26 => _26.versioning])
443
689
  );
444
690
  if (canHandle !== void 0 && !canHandle.includes(upcasted.type))
445
691
  continue;
@@ -492,13 +738,13 @@ var projector = (options) => {
492
738
  processorId,
493
739
  messageOptions: options.projection.eventsOptions,
494
740
  hooks: {
495
- onInit: _optionalChain([options, 'access', _19 => _19.hooks, 'optionalAccess', _20 => _20.onInit]),
496
- onStart: options.truncateOnStart && options.projection.truncate || _optionalChain([options, 'access', _21 => _21.hooks, 'optionalAccess', _22 => _22.onStart]) ? async (context) => {
741
+ onInit: _optionalChain([options, 'access', _27 => _27.hooks, 'optionalAccess', _28 => _28.onInit]),
742
+ onStart: options.truncateOnStart && options.projection.truncate || _optionalChain([options, 'access', _29 => _29.hooks, 'optionalAccess', _30 => _30.onStart]) ? async (context) => {
497
743
  if (options.truncateOnStart && options.projection.truncate)
498
744
  await options.projection.truncate(context);
499
- if (_optionalChain([options, 'access', _23 => _23.hooks, 'optionalAccess', _24 => _24.onStart])) await _optionalChain([options, 'access', _25 => _25.hooks, 'optionalAccess', _26 => _26.onStart, 'call', _27 => _27(context)]);
745
+ if (_optionalChain([options, 'access', _31 => _31.hooks, 'optionalAccess', _32 => _32.onStart])) await _optionalChain([options, 'access', _33 => _33.hooks, 'optionalAccess', _34 => _34.onStart, 'call', _35 => _35(context)]);
500
746
  } : void 0,
501
- onClose: _optionalChain([options, 'access', _28 => _28.hooks, 'optionalAccess', _29 => _29.onClose])
747
+ onClose: _optionalChain([options, 'access', _36 => _36.hooks, 'optionalAccess', _37 => _37.onClose])
502
748
  },
503
749
  eachMessage: async (event2, context) => projection2.handle([event2], context)
504
750
  });
@@ -523,6 +769,15 @@ var isSubset = (superObj, subObj) => {
523
769
  var assertFails = (message2) => {
524
770
  throw new AssertionError(_nullishCoalesce(message2, () => ( "That should not ever happened, right?")));
525
771
  };
772
+ var assertDeepEqual = (actual, expected, message2) => {
773
+ if (!deepEquals(actual, expected))
774
+ throw new AssertionError(
775
+ _nullishCoalesce(message2, () => ( `subObj:
776
+ ${JSONSerializer.serialize(expected)}
777
+ is not equal to
778
+ ${JSONSerializer.serialize(actual)}`))
779
+ );
780
+ };
526
781
  function assertTrue(condition, message2) {
527
782
  if (condition !== true)
528
783
  throw new AssertionError(_nullishCoalesce(message2, () => ( `Condition is false`)));
@@ -534,22 +789,29 @@ function assertEqual(expected, actual, message2) {
534
789
  if (expected !== actual)
535
790
  throw new AssertionError(
536
791
  `${_nullishCoalesce(message2, () => ( "Objects are not equal"))}:
537
- Expected: ${JSONParser.stringify(expected)}
538
- Actual: ${JSONParser.stringify(actual)}`
792
+ Expected: ${JSONSerializer.serialize(expected)}
793
+ Actual: ${JSONSerializer.serialize(actual)}`
539
794
  );
540
795
  }
541
796
  function assertNotEqual(obj, other, message2) {
542
797
  if (obj === other)
543
798
  throw new AssertionError(
544
- _nullishCoalesce(message2, () => ( `Objects are equal: ${JSONParser.stringify(obj)}`))
799
+ _nullishCoalesce(message2, () => ( `Objects are equal: ${JSONSerializer.serialize(obj)}`))
545
800
  );
546
801
  }
802
+ function assertIsNotNull(result) {
803
+ assertNotEqual(result, null);
804
+ assertOk(result);
805
+ }
806
+ function assertIsNull(result) {
807
+ assertEqual(result, null);
808
+ }
547
809
  var assertThatArray = (array) => {
548
810
  return {
549
811
  isEmpty: () => assertEqual(
550
812
  array.length,
551
813
  0,
552
- `Array is not empty ${JSONParser.stringify(array)}`
814
+ `Array is not empty ${JSONSerializer.serialize(array)}`
553
815
  ),
554
816
  isNotEmpty: () => assertNotEqual(array.length, 0, `Array is empty`),
555
817
  hasSize: (length) => assertEqual(array.length, length),
@@ -606,7 +868,7 @@ var assertThatArray = (array) => {
606
868
  };
607
869
  };
608
870
  var downcastRecordedMessage = (recordedMessage, options) => {
609
- if (!_optionalChain([options, 'optionalAccess', _30 => _30.downcast]))
871
+ if (!_optionalChain([options, 'optionalAccess', _38 => _38.downcast]))
610
872
  return recordedMessage;
611
873
  const downcasted = options.downcast(
612
874
  recordedMessage
@@ -624,14 +886,14 @@ var downcastRecordedMessage = (recordedMessage, options) => {
624
886
  };
625
887
  };
626
888
  var downcastRecordedMessages = (recordedMessages, options) => {
627
- if (!_optionalChain([options, 'optionalAccess', _31 => _31.downcast]))
889
+ if (!_optionalChain([options, 'optionalAccess', _39 => _39.downcast]))
628
890
  return recordedMessages;
629
891
  return recordedMessages.map(
630
892
  (recordedMessage) => downcastRecordedMessage(recordedMessage, options)
631
893
  );
632
894
  };
633
895
  var upcastRecordedMessage = (recordedMessage, options) => {
634
- if (!_optionalChain([options, 'optionalAccess', _32 => _32.upcast]))
896
+ if (!_optionalChain([options, 'optionalAccess', _40 => _40.upcast]))
635
897
  return recordedMessage;
636
898
  const upcasted = options.upcast(
637
899
  recordedMessage
@@ -649,6 +911,418 @@ var upcastRecordedMessage = (recordedMessage, options) => {
649
911
  };
650
912
  };
651
913
  var projection = (definition) => definition;
914
+ var WorkflowHandlerStreamVersionConflictRetryOptions = {
915
+ retries: 3,
916
+ minTimeout: 100,
917
+ factor: 1.5,
918
+ shouldRetryError: isExpectedVersionConflictError
919
+ };
920
+ var fromWorkflowHandlerRetryOptions = (retryOptions) => {
921
+ if (retryOptions === void 0) return NoRetries;
922
+ if ("onVersionConflict" in retryOptions) {
923
+ if (typeof retryOptions.onVersionConflict === "boolean")
924
+ return WorkflowHandlerStreamVersionConflictRetryOptions;
925
+ else if (typeof retryOptions.onVersionConflict === "number")
926
+ return {
927
+ ...WorkflowHandlerStreamVersionConflictRetryOptions,
928
+ retries: retryOptions.onVersionConflict
929
+ };
930
+ else return retryOptions.onVersionConflict;
931
+ }
932
+ return retryOptions;
933
+ };
934
+ var emptyHandlerResult = (nextExpectedStreamVersion = 0n) => ({
935
+ newMessages: [],
936
+ createdNewStream: false,
937
+ nextExpectedStreamVersion
938
+ });
939
+ var createInputMetadata = (originalMessageId, action) => ({
940
+ originalMessageId,
941
+ input: true,
942
+ action
943
+ });
944
+ var tagOutputMessage = (msg, action) => {
945
+ const existingMetadata = "metadata" in msg && msg.metadata ? msg.metadata : {};
946
+ return {
947
+ ...msg,
948
+ metadata: {
949
+ ...existingMetadata,
950
+ action
951
+ }
952
+ };
953
+ };
954
+ var createWrappedInitialState = (initialState) => {
955
+ return () => ({
956
+ userState: initialState(),
957
+ processedInputIds: /* @__PURE__ */ new Set()
958
+ });
959
+ };
960
+ var createWrappedEvolve = (evolve, workflowName, separateInputInboxFromProcessing) => {
961
+ return (state, event2) => {
962
+ const metadata = event2.metadata;
963
+ let processedInputIds = state.processedInputIds;
964
+ if (_optionalChain([metadata, 'optionalAccess', _41 => _41.input]) === true && typeof _optionalChain([metadata, 'optionalAccess', _42 => _42.originalMessageId]) === "string") {
965
+ processedInputIds = new Set(state.processedInputIds);
966
+ processedInputIds.add(metadata.originalMessageId);
967
+ }
968
+ if (separateInputInboxFromProcessing && _optionalChain([metadata, 'optionalAccess', _43 => _43.input]) === true) {
969
+ return {
970
+ userState: state.userState,
971
+ processedInputIds
972
+ };
973
+ }
974
+ const eventType = event2.type;
975
+ const eventForEvolve = eventType.startsWith(`${workflowName}:`) ? {
976
+ ...event2,
977
+ type: eventType.replace(`${workflowName}:`, "")
978
+ } : event2;
979
+ return {
980
+ userState: evolve(state.userState, eventForEvolve),
981
+ processedInputIds
982
+ };
983
+ };
984
+ };
985
+ var workflowStreamName = ({
986
+ workflowName,
987
+ workflowId
988
+ }) => `emt:workflow:${workflowName}:${workflowId}`;
989
+ var WorkflowHandler = (options) => async (store, message2, handleOptions) => asyncRetry(
990
+ async () => {
991
+ const result = await withSession2(store, async ({ eventStore }) => {
992
+ const {
993
+ workflow: { evolve, initialState, decide, name: workflowName },
994
+ getWorkflowId: getWorkflowId2
995
+ } = options;
996
+ const inputMessageId = (
997
+ // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
998
+ _nullishCoalesce(("metadata" in message2 && _optionalChain([message2, 'access', _44 => _44.metadata, 'optionalAccess', _45 => _45.messageId]) ? (
999
+ // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
1000
+ message2.metadata.messageId
1001
+ ) : void 0), () => ( _uuid.v7.call(void 0, )))
1002
+ );
1003
+ const messageWithMetadata = {
1004
+ ...message2,
1005
+ // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
1006
+ metadata: {
1007
+ messageId: inputMessageId,
1008
+ ...message2.metadata
1009
+ }
1010
+ };
1011
+ const workflowId = getWorkflowId2(messageWithMetadata);
1012
+ if (!workflowId) {
1013
+ return emptyHandlerResult();
1014
+ }
1015
+ const streamName = options.mapWorkflowId ? options.mapWorkflowId(workflowId) : workflowStreamName({ workflowName, workflowId });
1016
+ const messageType = messageWithMetadata.type;
1017
+ const hasWorkflowPrefix = messageType.startsWith(`${workflowName}:`);
1018
+ if (options.separateInputInboxFromProcessing && !hasWorkflowPrefix) {
1019
+ const inputMetadata2 = createInputMetadata(
1020
+ inputMessageId,
1021
+ "InitiatedBy"
1022
+ );
1023
+ const inputToStore2 = {
1024
+ type: `${workflowName}:${messageWithMetadata.type}`,
1025
+ data: messageWithMetadata.data,
1026
+ kind: messageWithMetadata.kind,
1027
+ metadata: inputMetadata2
1028
+ };
1029
+ const appendResult2 = await eventStore.appendToStream(
1030
+ streamName,
1031
+ [inputToStore2],
1032
+ {
1033
+ ...handleOptions,
1034
+ expectedStreamVersion: _nullishCoalesce(_optionalChain([handleOptions, 'optionalAccess', _46 => _46.expectedStreamVersion]), () => ( NO_CONCURRENCY_CHECK))
1035
+ }
1036
+ );
1037
+ return {
1038
+ ...appendResult2,
1039
+ newMessages: []
1040
+ };
1041
+ }
1042
+ const wrappedInitialState = createWrappedInitialState(initialState);
1043
+ const wrappedEvolve = createWrappedEvolve(
1044
+ evolve,
1045
+ workflowName,
1046
+ _nullishCoalesce(options.separateInputInboxFromProcessing, () => ( false))
1047
+ );
1048
+ const aggregationResult = await eventStore.aggregateStream(streamName, {
1049
+ evolve: wrappedEvolve,
1050
+ initialState: wrappedInitialState,
1051
+ read: {
1052
+ ...handleOptions,
1053
+ // expected stream version is passed to fail fast
1054
+ // if stream is in the wrong state
1055
+ expectedStreamVersion: _nullishCoalesce(_optionalChain([handleOptions, 'optionalAccess', _47 => _47.expectedStreamVersion]), () => ( NO_CONCURRENCY_CHECK))
1056
+ }
1057
+ });
1058
+ const { currentStreamVersion } = aggregationResult;
1059
+ const { userState: state, processedInputIds } = aggregationResult.state;
1060
+ if (processedInputIds.has(inputMessageId)) {
1061
+ return emptyHandlerResult(currentStreamVersion);
1062
+ }
1063
+ const messageForDecide = hasWorkflowPrefix ? {
1064
+ ...messageWithMetadata,
1065
+ type: messageType.replace(`${workflowName}:`, "")
1066
+ } : messageWithMetadata;
1067
+ const result2 = decide(messageForDecide, state);
1068
+ const inputMetadata = createInputMetadata(
1069
+ inputMessageId,
1070
+ aggregationResult.streamExists ? "Received" : "InitiatedBy"
1071
+ );
1072
+ const inputToStore = {
1073
+ type: `${workflowName}:${messageWithMetadata.type}`,
1074
+ data: messageWithMetadata.data,
1075
+ kind: messageWithMetadata.kind,
1076
+ metadata: inputMetadata
1077
+ };
1078
+ const outputMessages = (Array.isArray(result2) ? result2 : [result2]).filter((msg) => msg !== void 0 && msg !== null);
1079
+ const outputCommandTypes = _nullishCoalesce(_optionalChain([options, 'access', _48 => _48.outputs, 'optionalAccess', _49 => _49.commands]), () => ( []));
1080
+ const taggedOutputMessages = outputMessages.map((msg) => {
1081
+ const action = outputCommandTypes.includes(
1082
+ msg.type
1083
+ ) ? "Sent" : "Published";
1084
+ return tagOutputMessage(msg, action);
1085
+ });
1086
+ const messagesToAppend = options.separateInputInboxFromProcessing && hasWorkflowPrefix ? [...taggedOutputMessages] : [inputToStore, ...taggedOutputMessages];
1087
+ if (messagesToAppend.length === 0) {
1088
+ return emptyHandlerResult(currentStreamVersion);
1089
+ }
1090
+ const expectedStreamVersion = _nullishCoalesce(_optionalChain([handleOptions, 'optionalAccess', _50 => _50.expectedStreamVersion]), () => ( (aggregationResult.streamExists ? currentStreamVersion : STREAM_DOES_NOT_EXIST)));
1091
+ const appendResult = await eventStore.appendToStream(
1092
+ streamName,
1093
+ // TODO: Fix this cast
1094
+ messagesToAppend,
1095
+ {
1096
+ ...handleOptions,
1097
+ expectedStreamVersion
1098
+ }
1099
+ );
1100
+ return {
1101
+ ...appendResult,
1102
+ newMessages: outputMessages
1103
+ };
1104
+ });
1105
+ return result;
1106
+ },
1107
+ fromWorkflowHandlerRetryOptions(
1108
+ handleOptions && "retry" in handleOptions ? handleOptions.retry : options.retry
1109
+ )
1110
+ );
1111
+ var withSession2 = (eventStore, callback) => {
1112
+ const sessionFactory = canCreateEventStoreSession(eventStore) ? eventStore : nulloSessionFactory(eventStore);
1113
+ return sessionFactory.withSession(callback);
1114
+ };
1115
+ var getWorkflowId = (options) => `emt:processor:workflow:${options.workflowName}`;
1116
+ var workflowProcessor = (options) => {
1117
+ const { workflow, ...rest } = options;
1118
+ const inputs = [...options.inputs.commands, ...options.inputs.events];
1119
+ let canHandle = inputs;
1120
+ if (options.separateInputInboxFromProcessing)
1121
+ canHandle = [
1122
+ ...canHandle,
1123
+ ...options.inputs.commands.map((t) => `${workflow.name}:${t}`),
1124
+ ...options.inputs.events.map((t) => `${workflow.name}:${t}`)
1125
+ ];
1126
+ if (options.outputHandler)
1127
+ canHandle = [...canHandle, ...options.outputHandler.canHandle];
1128
+ const handle = WorkflowHandler(options);
1129
+ return reactor({
1130
+ ...rest,
1131
+ processorId: _nullishCoalesce(options.processorId, () => ( getWorkflowId({ workflowName: workflow.name }))),
1132
+ canHandle,
1133
+ type: MessageProcessorType.PROJECTOR,
1134
+ eachMessage: async (message2, context) => {
1135
+ const messageType = message2.type;
1136
+ const metadata = message2.metadata;
1137
+ const isInput = _optionalChain([metadata, 'optionalAccess', _51 => _51.input]) === true;
1138
+ if (isInput || inputs.includes(messageType)) {
1139
+ const result = await handle(
1140
+ context.connection.messageStore,
1141
+ message2,
1142
+ context
1143
+ );
1144
+ if (options.stopAfter && result.newMessages.length > 0) {
1145
+ for (const outputMessage of result.newMessages) {
1146
+ if (options.stopAfter(
1147
+ outputMessage
1148
+ )) {
1149
+ return { type: "STOP", reason: "Stop condition reached" };
1150
+ }
1151
+ }
1152
+ }
1153
+ return;
1154
+ }
1155
+ if (_optionalChain([options, 'access', _52 => _52.outputHandler, 'optionalAccess', _53 => _53.canHandle, 'access', _54 => _54.includes, 'call', _55 => _55(messageType)]) === true) {
1156
+ const handledOutputMessages = await options.outputHandler.handle(
1157
+ message2,
1158
+ context
1159
+ );
1160
+ if (handledOutputMessages instanceof EmmettError) {
1161
+ return {
1162
+ type: "STOP",
1163
+ reason: "Routing error",
1164
+ error: handledOutputMessages
1165
+ };
1166
+ }
1167
+ const messagesToAppend = Array.isArray(handledOutputMessages) ? handledOutputMessages : handledOutputMessages ? [handledOutputMessages] : [];
1168
+ if (messagesToAppend.length === 0) {
1169
+ return;
1170
+ }
1171
+ const workflowId = options.getWorkflowId(
1172
+ message2
1173
+ );
1174
+ if (!workflowId) return;
1175
+ const streamName = options.mapWorkflowId ? options.mapWorkflowId(workflowId) : workflowStreamName({
1176
+ workflowName: workflow.name,
1177
+ workflowId
1178
+ });
1179
+ await context.connection.messageStore.appendToStream(
1180
+ streamName,
1181
+ messagesToAppend
1182
+ );
1183
+ return;
1184
+ }
1185
+ return;
1186
+ }
1187
+ });
1188
+ };
1189
+
1190
+ // src/eventStore/projections/pongo/pongoProjectionSpec.ts
1191
+
1192
+
1193
+
1194
+ var withCollection = async (handle, options) => {
1195
+ const { connection, inDatabase, inCollection } = options;
1196
+ const driver = await pongoDriverRegistry.tryResolve(
1197
+ connection.driverType
1198
+ );
1199
+ const pongo = _pongo.pongoClient.call(void 0, {
1200
+ connectionOptions: { connection },
1201
+ driver
1202
+ });
1203
+ try {
1204
+ const collection = pongo.db(inDatabase).collection(inCollection);
1205
+ return handle(collection);
1206
+ } finally {
1207
+ await pongo.close();
1208
+ }
1209
+ };
1210
+ var withoutIdAndVersion = (doc) => {
1211
+ const { _id, _version, ...without } = doc;
1212
+ return without;
1213
+ };
1214
+ var assertDocumentsEqual = (actual, expected) => {
1215
+ if ("_id" in expected)
1216
+ assertEqual(
1217
+ expected._id,
1218
+ actual._id,
1219
+ // eslint-disable-next-line @typescript-eslint/restrict-template-expressions
1220
+ `Document ids are not matching! Expected: ${expected._id}, Actual: ${actual._id}`
1221
+ );
1222
+ return assertDeepEqual(
1223
+ withoutIdAndVersion(actual),
1224
+ withoutIdAndVersion(expected)
1225
+ );
1226
+ };
1227
+ var documentExists = (document, options) => (assertOptions) => withCollection(
1228
+ async (collection) => {
1229
+ const result = await collection.findOne(
1230
+ "withId" in options ? { _id: options.withId } : options.matchingFilter
1231
+ );
1232
+ assertIsNotNull(result);
1233
+ assertDocumentsEqual(result, document);
1234
+ },
1235
+ { ...options, ...assertOptions }
1236
+ );
1237
+ var documentsAreTheSame = (documents, options) => (assertOptions) => withCollection(
1238
+ async (collection) => {
1239
+ const result = await collection.find(
1240
+ "withId" in options ? { _id: options.withId } : options.matchingFilter
1241
+ );
1242
+ assertEqual(
1243
+ documents.length,
1244
+ result.length,
1245
+ "Different Documents Count than expected"
1246
+ );
1247
+ for (let i = 0; i < documents.length; i++) {
1248
+ assertThatArray(result).contains(documents[i]);
1249
+ }
1250
+ },
1251
+ { ...options, ...assertOptions }
1252
+ );
1253
+ var documentsMatchingHaveCount = (expectedCount, options) => (assertOptions) => withCollection(
1254
+ async (collection) => {
1255
+ const result = await collection.find(
1256
+ "withId" in options ? { _id: options.withId } : options.matchingFilter
1257
+ );
1258
+ assertEqual(
1259
+ expectedCount,
1260
+ result.length,
1261
+ "Different Documents Count than expected"
1262
+ );
1263
+ },
1264
+ { ...options, ...assertOptions }
1265
+ );
1266
+ var documentMatchingExists = (options) => (assertOptions) => withCollection(
1267
+ async (collection) => {
1268
+ const result = await collection.find(
1269
+ "withId" in options ? { _id: options.withId } : options.matchingFilter
1270
+ );
1271
+ assertThatArray(result).isNotEmpty();
1272
+ },
1273
+ { ...options, ...assertOptions }
1274
+ );
1275
+ var documentDoesNotExist = (options) => (assertOptions) => withCollection(
1276
+ async (collection) => {
1277
+ const result = await collection.findOne(
1278
+ "withId" in options ? { _id: options.withId } : options.matchingFilter
1279
+ );
1280
+ assertIsNull(result);
1281
+ },
1282
+ { ...options, ...assertOptions }
1283
+ );
1284
+ var expectPongoDocuments = {
1285
+ fromCollection: (collectionName) => {
1286
+ return {
1287
+ withId: (id) => {
1288
+ return {
1289
+ toBeEqual: (document) => documentExists(document, {
1290
+ withId: id,
1291
+ inCollection: collectionName
1292
+ }),
1293
+ toExist: () => documentMatchingExists({
1294
+ withId: id,
1295
+ inCollection: collectionName
1296
+ }),
1297
+ notToExist: () => documentDoesNotExist({
1298
+ withId: id,
1299
+ inCollection: collectionName
1300
+ })
1301
+ };
1302
+ },
1303
+ matching: (filter) => {
1304
+ return {
1305
+ toBeTheSame: (documents) => documentsAreTheSame(documents, {
1306
+ matchingFilter: filter,
1307
+ inCollection: collectionName
1308
+ }),
1309
+ toHaveCount: (expectedCount) => documentsMatchingHaveCount(expectedCount, {
1310
+ matchingFilter: filter,
1311
+ inCollection: collectionName
1312
+ }),
1313
+ toExist: () => documentMatchingExists({
1314
+ matchingFilter: filter,
1315
+ inCollection: collectionName
1316
+ }),
1317
+ notToExist: () => documentDoesNotExist({
1318
+ matchingFilter: filter,
1319
+ inCollection: collectionName
1320
+ })
1321
+ };
1322
+ }
1323
+ };
1324
+ }
1325
+ };
652
1326
 
653
1327
  // src/eventStore/projections/sqliteProjection.ts
654
1328
  var handleProjections = async (options) => {
@@ -721,6 +1395,11 @@ var SQLiteProjectionSpec = {
721
1395
  {
722
1396
  const driverType = options.driver.driverType;
723
1397
  const pool = _nullishCoalesce(options.pool, () => ( _dumbo.dumbo.call(void 0, {
1398
+ serialization: options.serialization,
1399
+ transactionOptions: {
1400
+ allowNestedTransactions: true,
1401
+ mode: "session_based"
1402
+ },
724
1403
  ...options.driver.mapToDumboOptions(options)
725
1404
  })));
726
1405
  const projection2 = options.projection;
@@ -731,7 +1410,7 @@ var SQLiteProjectionSpec = {
731
1410
  const allEvents = [];
732
1411
  const run = async (connection) => {
733
1412
  let globalPosition = 0n;
734
- const numberOfTimes = _nullishCoalesce(_optionalChain([options2, 'optionalAccess', _33 => _33.numberOfTimes]), () => ( 1));
1413
+ const numberOfTimes = _nullishCoalesce(_optionalChain([options2, 'optionalAccess', _56 => _56.numberOfTimes]), () => ( 1));
735
1414
  for (const event of [
736
1415
  ...givenEvents,
737
1416
  ...Array.from({ length: numberOfTimes }).flatMap(() => events)
@@ -798,18 +1477,18 @@ var SQLiteProjectionSpec = {
798
1477
  if (!isErrorConstructor(args[0])) {
799
1478
  assertTrue(
800
1479
  args[0](error),
801
- `Error didn't match the error condition: ${_optionalChain([error, 'optionalAccess', _34 => _34.toString, 'call', _35 => _35()])}`
1480
+ `Error didn't match the error condition: ${_optionalChain([error, 'optionalAccess', _57 => _57.toString, 'call', _58 => _58()])}`
802
1481
  );
803
1482
  return;
804
1483
  }
805
1484
  assertTrue(
806
1485
  error instanceof args[0],
807
- `Caught error is not an instance of the expected type: ${_optionalChain([error, 'optionalAccess', _36 => _36.toString, 'call', _37 => _37()])}`
1486
+ `Caught error is not an instance of the expected type: ${_optionalChain([error, 'optionalAccess', _59 => _59.toString, 'call', _60 => _60()])}`
808
1487
  );
809
1488
  if (args[1]) {
810
1489
  assertTrue(
811
1490
  args[1](error),
812
- `Error didn't match the error condition: ${_optionalChain([error, 'optionalAccess', _38 => _38.toString, 'call', _39 => _39()])}`
1491
+ `Error didn't match the error condition: ${_optionalChain([error, 'optionalAccess', _61 => _61.toString, 'call', _62 => _62()])}`
813
1492
  );
814
1493
  }
815
1494
  }
@@ -826,7 +1505,7 @@ var eventInStream = (streamName, event) => {
826
1505
  ...event,
827
1506
  metadata: {
828
1507
  ..._nullishCoalesce(event.metadata, () => ( {})),
829
- streamName: _nullishCoalesce(_optionalChain([event, 'access', _40 => _40.metadata, 'optionalAccess', _41 => _41.streamName]), () => ( streamName))
1508
+ streamName: _nullishCoalesce(_optionalChain([event, 'access', _63 => _63.metadata, 'optionalAccess', _64 => _64.streamName]), () => ( streamName))
830
1509
  }
831
1510
  };
832
1511
  };
@@ -898,7 +1577,7 @@ var { identifier, merge } = _dumbo.SQL;
898
1577
  var appendToStream = async (connection, streamName, streamType, messages, options) => {
899
1578
  if (messages.length === 0) return { success: false };
900
1579
  const expectedStreamVersion = toExpectedVersion(
901
- _optionalChain([options, 'optionalAccess', _42 => _42.expectedStreamVersion])
1580
+ _optionalChain([options, 'optionalAccess', _65 => _65.expectedStreamVersion])
902
1581
  );
903
1582
  const messagesToAppend = messages.map(
904
1583
  (m, i) => ({
@@ -921,13 +1600,13 @@ var appendToStream = async (connection, streamName, streamType, messages, option
921
1600
  streamType,
922
1601
  downcastRecordedMessages(
923
1602
  messagesToAppend,
924
- _optionalChain([options, 'optionalAccess', _43 => _43.schema, 'optionalAccess', _44 => _44.versioning])
1603
+ _optionalChain([options, 'optionalAccess', _66 => _66.schema, 'optionalAccess', _67 => _67.versioning])
925
1604
  ),
926
1605
  {
927
1606
  expectedStreamVersion
928
1607
  }
929
1608
  );
930
- if (_optionalChain([options, 'optionalAccess', _45 => _45.onBeforeCommit]))
1609
+ if (_optionalChain([options, 'optionalAccess', _68 => _68.onBeforeCommit]))
931
1610
  await options.onBeforeCommit(messagesToAppend, { connection });
932
1611
  return { success: true, result };
933
1612
  }
@@ -951,7 +1630,7 @@ var toExpectedVersion = (expected) => {
951
1630
  return expected;
952
1631
  };
953
1632
  var appendToStreamRaw = async (execute, streamId, streamType, messages, options) => {
954
- let expectedStreamVersion = _nullishCoalesce(_optionalChain([options, 'optionalAccess', _46 => _46.expectedStreamVersion]), () => ( null));
1633
+ let expectedStreamVersion = _nullishCoalesce(_optionalChain([options, 'optionalAccess', _69 => _69.expectedStreamVersion]), () => ( null));
955
1634
  const currentStreamVersion = await getLastStreamPosition(
956
1635
  execute,
957
1636
  streamId,
@@ -969,7 +1648,7 @@ var appendToStreamRaw = async (execute, streamId, streamType, messages, options)
969
1648
  VALUES (
970
1649
  ${streamId},
971
1650
  ${messages.length},
972
- ${_nullishCoalesce(_optionalChain([options, 'optionalAccess', _47 => _47.partition]), () => ( streamsTable.columns.partition))},
1651
+ ${_nullishCoalesce(_optionalChain([options, 'optionalAccess', _70 => _70.partition]), () => ( streamsTable.columns.partition))},
973
1652
  ${streamType},
974
1653
  '[]',
975
1654
  false
@@ -979,7 +1658,7 @@ var appendToStreamRaw = async (execute, streamId, streamType, messages, options)
979
1658
  SET stream_position = stream_position + ${messages.length}
980
1659
  WHERE stream_id = ${streamId}
981
1660
  AND stream_position = ${expectedStreamVersion}
982
- AND partition = ${_nullishCoalesce(_optionalChain([options, 'optionalAccess', _48 => _48.partition]), () => ( streamsTable.columns.partition))}
1661
+ AND partition = ${_nullishCoalesce(_optionalChain([options, 'optionalAccess', _71 => _71.partition]), () => ( streamsTable.columns.partition))}
983
1662
  AND is_archived = false
984
1663
  RETURNING stream_position;
985
1664
  `;
@@ -987,12 +1666,12 @@ var appendToStreamRaw = async (execute, streamId, streamType, messages, options)
987
1666
  messages,
988
1667
  expectedStreamVersion,
989
1668
  streamId,
990
- _nullishCoalesce(_optionalChain([options, 'optionalAccess', _49 => _49.partition, 'optionalAccess', _50 => _50.toString, 'call', _51 => _51()]), () => ( defaultTag2))
1669
+ _nullishCoalesce(_optionalChain([options, 'optionalAccess', _72 => _72.partition, 'optionalAccess', _73 => _73.toString, 'call', _74 => _74()]), () => ( defaultTag2))
991
1670
  );
992
1671
  const results = await execute.batchCommand([streamSQL, insertSQL], { assertChanges: true });
993
1672
  const [streamResult, messagesResult] = results;
994
- const streamPosition = _optionalChain([streamResult, 'optionalAccess', _52 => _52.rows, 'access', _53 => _53[0], 'optionalAccess', _54 => _54.stream_position]);
995
- const globalPosition = _optionalChain([messagesResult, 'optionalAccess', _55 => _55.rows, 'access', _56 => _56.at, 'call', _57 => _57(-1), 'optionalAccess', _58 => _58.global_position]);
1673
+ const streamPosition = _optionalChain([streamResult, 'optionalAccess', _75 => _75.rows, 'access', _76 => _76[0], 'optionalAccess', _77 => _77.stream_position]);
1674
+ const globalPosition = _optionalChain([messagesResult, 'optionalAccess', _78 => _78.rows, 'access', _79 => _79.at, 'call', _80 => _80(-1), 'optionalAccess', _81 => _81.global_position]);
996
1675
  if (!streamPosition)
997
1676
  throw new ExpectedVersionConflictError(0n, _nullishCoalesce(expectedStreamVersion, () => ( 0n)));
998
1677
  if (!globalPosition) throw new Error("Could not find global position");
@@ -1008,7 +1687,7 @@ async function getLastStreamPosition(execute, streamId, expectedStreamVersion) {
1008
1687
  _dumbo.SQL`SELECT CAST(stream_position AS VARCHAR) AS stream_position FROM ${identifier(streamsTable.name)} WHERE stream_id = ${streamId}`
1009
1688
  )
1010
1689
  );
1011
- if (_optionalChain([result, 'optionalAccess', _59 => _59.stream_position]) == null) {
1690
+ if (_optionalChain([result, 'optionalAccess', _82 => _82.stream_position]) == null) {
1012
1691
  expectedStreamVersion = 0n;
1013
1692
  } else {
1014
1693
  expectedStreamVersion = BigInt(result.stream_position);
@@ -1017,7 +1696,7 @@ async function getLastStreamPosition(execute, streamId, expectedStreamVersion) {
1017
1696
  }
1018
1697
  var buildMessageInsertQuery = (messages, expectedStreamVersion, streamId, partition) => {
1019
1698
  const values = messages.map((message) => {
1020
- if (_optionalChain([message, 'access', _60 => _60.metadata, 'optionalAccess', _61 => _61.streamPosition]) == null || typeof message.metadata.streamPosition !== "bigint") {
1699
+ if (_optionalChain([message, 'access', _83 => _83.metadata, 'optionalAccess', _84 => _84.streamPosition]) == null || typeof message.metadata.streamPosition !== "bigint") {
1021
1700
  throw new Error("Stream position is required");
1022
1701
  }
1023
1702
  const streamPosition = BigInt(message.metadata.streamPosition) + BigInt(expectedStreamVersion);
@@ -1184,7 +1863,7 @@ var readLastMessageGlobalPosition = async (execute, options) => {
1184
1863
  _dumbo.SQL`
1185
1864
  SELECT global_position
1186
1865
  FROM ${identifier3(messagesTable.name)}
1187
- WHERE partition = ${_nullishCoalesce(_optionalChain([options, 'optionalAccess', _62 => _62.partition]), () => ( defaultTag2))} AND is_archived = FALSE
1866
+ WHERE partition = ${_nullishCoalesce(_optionalChain([options, 'optionalAccess', _85 => _85.partition]), () => ( defaultTag2))} AND is_archived = FALSE
1188
1867
  ORDER BY global_position
1189
1868
  LIMIT 1`
1190
1869
  )
@@ -1198,6 +1877,7 @@ var readLastMessageGlobalPosition = async (execute, options) => {
1198
1877
 
1199
1878
  var { identifier: identifier4 } = _dumbo.SQL;
1200
1879
  var readMessagesBatch = async (execute, options) => {
1880
+ const { serializer } = options;
1201
1881
  const from = "from" in options ? options.from : void 0;
1202
1882
  const after = "after" in options ? options.after : void 0;
1203
1883
  const batchSize = "batchSize" in options ? options.batchSize : options.to - options.from;
@@ -1208,15 +1888,15 @@ var readMessagesBatch = async (execute, options) => {
1208
1888
  execute.query(
1209
1889
  _dumbo.SQL`SELECT stream_id, stream_position, global_position, message_data, message_metadata, message_schema_version, message_type, message_id
1210
1890
  FROM ${identifier4(messagesTable.name)}
1211
- WHERE partition = ${_nullishCoalesce(_optionalChain([options, 'optionalAccess', _63 => _63.partition]), () => ( defaultTag2))} AND is_archived = FALSE ${fromCondition} ${toCondition}
1891
+ WHERE partition = ${_nullishCoalesce(_optionalChain([options, 'optionalAccess', _86 => _86.partition]), () => ( defaultTag2))} AND is_archived = FALSE ${fromCondition} ${toCondition}
1212
1892
  ORDER BY global_position
1213
1893
  ${limitCondition}`
1214
1894
  ),
1215
1895
  (row) => {
1216
1896
  const rawEvent = {
1217
1897
  type: row.message_type,
1218
- data: JSONParser.parse(row.message_data),
1219
- metadata: JSONParser.parse(row.message_metadata)
1898
+ data: serializer.deserialize(row.message_data),
1899
+ metadata: serializer.deserialize(row.message_metadata)
1220
1900
  };
1221
1901
  const metadata = {
1222
1902
  ..."metadata" in rawEvent ? _nullishCoalesce(rawEvent.metadata, () => ( {})) : {},
@@ -1252,7 +1932,7 @@ var readProcessorCheckpoint = async (execute, options) => {
1252
1932
  execute.query(
1253
1933
  _dumbo.SQL`SELECT last_processed_checkpoint
1254
1934
  FROM ${identifier5(processorsTable.name)}
1255
- WHERE partition = ${_nullishCoalesce(_optionalChain([options, 'optionalAccess', _64 => _64.partition]), () => ( defaultTag2))} AND processor_id = ${options.processorId}
1935
+ WHERE partition = ${_nullishCoalesce(_optionalChain([options, 'optionalAccess', _87 => _87.partition]), () => ( defaultTag2))} AND processor_id = ${options.processorId}
1256
1936
  LIMIT 1`
1257
1937
  )
1258
1938
  );
@@ -1276,18 +1956,21 @@ var sqliteEventStoreMessageBatchPuller = ({
1276
1956
  eachBatch,
1277
1957
  pullingFrequencyInMs,
1278
1958
  stopWhen,
1279
- signal
1959
+ signal,
1960
+ serialization
1280
1961
  }) => {
1281
1962
  let isRunning = false;
1282
1963
  let start;
1964
+ const serializer = JSONSerializer.from({ serialization });
1283
1965
  const pullMessages = async (options) => {
1284
1966
  const after = options.startFrom === "BEGINNING" ? 0n : options.startFrom === "END" ? await _asyncNullishCoalesce((await readLastMessageGlobalPosition(executor)).currentGlobalPosition, async () => ( 0n)) : parseBigIntProcessorCheckpoint(options.startFrom.lastCheckpoint);
1285
1967
  const readMessagesOptions = {
1286
1968
  after,
1287
- batchSize
1969
+ batchSize,
1970
+ serializer
1288
1971
  };
1289
1972
  let waitTime = 100;
1290
- while (isRunning && !_optionalChain([signal, 'optionalAccess', _65 => _65.aborted])) {
1973
+ while (isRunning && !_optionalChain([signal, 'optionalAccess', _88 => _88.aborted])) {
1291
1974
  const { messages, currentGlobalPosition, areMessagesLeft } = await readMessagesBatch(executor, readMessagesOptions);
1292
1975
  if (messages.length > 0) {
1293
1976
  const result = await eachBatch(messages);
@@ -1298,7 +1981,7 @@ var sqliteEventStoreMessageBatchPuller = ({
1298
1981
  }
1299
1982
  readMessagesOptions.after = currentGlobalPosition;
1300
1983
  await new Promise((resolve) => setTimeout(resolve, waitTime));
1301
- if (_optionalChain([stopWhen, 'optionalAccess', _66 => _66.noMessagesLeft]) === true && !areMessagesLeft) {
1984
+ if (_optionalChain([stopWhen, 'optionalAccess', _89 => _89.noMessagesLeft]) === true && !areMessagesLeft) {
1302
1985
  isRunning = false;
1303
1986
  break;
1304
1987
  }
@@ -1343,7 +2026,7 @@ var zipSQLiteEventStoreMessageBatchPullerStartFrom = (options) => {
1343
2026
  var sqliteCheckpointer = () => ({
1344
2027
  read: async (options, context) => {
1345
2028
  const result = await readProcessorCheckpoint(context.execute, options);
1346
- return { lastCheckpoint: _optionalChain([result, 'optionalAccess', _67 => _67.lastProcessedCheckpoint]) };
2029
+ return { lastCheckpoint: _optionalChain([result, 'optionalAccess', _90 => _90.lastProcessedCheckpoint]) };
1347
2030
  },
1348
2031
  store: async (options, context) => {
1349
2032
  const newCheckpoint = getCheckpoint(options.message);
@@ -1361,7 +2044,7 @@ var sqliteCheckpointer = () => ({
1361
2044
  // src/eventStore/consumers/sqliteProcessor.ts
1362
2045
  var sqliteProcessingScope = () => {
1363
2046
  const processingScope = async (handler, partialContext) => {
1364
- const connection = _optionalChain([partialContext, 'optionalAccess', _68 => _68.connection]);
2047
+ const connection = _optionalChain([partialContext, 'optionalAccess', _91 => _91.connection]);
1365
2048
  if (!connection)
1366
2049
  throw new EmmettError("Connection is required in context or options");
1367
2050
  return connection.withTransaction(
@@ -1376,6 +2059,49 @@ var sqliteProcessingScope = () => {
1376
2059
  };
1377
2060
  return processingScope;
1378
2061
  };
2062
+ var sqliteWorkflowProcessingScope = (messageStore) => {
2063
+ const processingScope = async (handler, partialContext) => {
2064
+ const connection = _optionalChain([partialContext, 'optionalAccess', _92 => _92.connection]);
2065
+ if (!connection)
2066
+ throw new EmmettError("Connection is required in context or options");
2067
+ return connection.withTransaction(
2068
+ async (transaction) => {
2069
+ return handler({
2070
+ ...partialContext,
2071
+ connection: Object.assign(connection, { messageStore }),
2072
+ execute: transaction.execute
2073
+ });
2074
+ }
2075
+ );
2076
+ };
2077
+ return processingScope;
2078
+ };
2079
+ var sqliteWorkflowProcessor = (options) => {
2080
+ const {
2081
+ processorId = _nullishCoalesce(options.processorId, () => ( getWorkflowId({
2082
+ workflowName: _nullishCoalesce(options.workflow.name, () => ( "unknown"))
2083
+ }))),
2084
+ processorInstanceId = getProcessorInstanceId(processorId),
2085
+ version = defaultProcessorVersion,
2086
+ partition = defaultProcessorPartition
2087
+ } = options;
2088
+ const hooks = {
2089
+ ..._nullishCoalesce(options.hooks, () => ( {})),
2090
+ onClose: _optionalChain([options, 'access', _93 => _93.hooks, 'optionalAccess', _94 => _94.onClose])
2091
+ };
2092
+ return workflowProcessor({
2093
+ ...options,
2094
+ processorId,
2095
+ processorInstanceId,
2096
+ version,
2097
+ partition,
2098
+ hooks,
2099
+ processingScope: sqliteWorkflowProcessingScope(
2100
+ options.messageStore
2101
+ ),
2102
+ checkpoints: sqliteCheckpointer()
2103
+ });
2104
+ };
1379
2105
  var sqliteReactor = (options) => {
1380
2106
  const {
1381
2107
  processorId = options.processorId,
@@ -1406,7 +2132,7 @@ var sqliteProjector = (options) => {
1406
2132
  } = options;
1407
2133
  const hooks = {
1408
2134
  ..._nullishCoalesce(options.hooks, () => ( {})),
1409
- onInit: options.projection.init !== void 0 || _optionalChain([options, 'access', _69 => _69.hooks, 'optionalAccess', _70 => _70.onInit]) ? async (context) => {
2135
+ onInit: options.projection.init !== void 0 || _optionalChain([options, 'access', _95 => _95.hooks, 'optionalAccess', _96 => _96.onInit]) ? async (context) => {
1410
2136
  if (options.projection.init)
1411
2137
  await options.projection.init({
1412
2138
  version: _nullishCoalesce(options.projection.version, () => ( version)),
@@ -1417,13 +2143,13 @@ var sqliteProjector = (options) => {
1417
2143
  migrationOptions: options.migrationOptions
1418
2144
  }
1419
2145
  });
1420
- if (_optionalChain([options, 'access', _71 => _71.hooks, 'optionalAccess', _72 => _72.onInit]))
2146
+ if (_optionalChain([options, 'access', _97 => _97.hooks, 'optionalAccess', _98 => _98.onInit]))
1421
2147
  await options.hooks.onInit({
1422
2148
  ...context,
1423
2149
  migrationOptions: options.migrationOptions
1424
2150
  });
1425
- } : _optionalChain([options, 'access', _73 => _73.hooks, 'optionalAccess', _74 => _74.onInit]),
1426
- onClose: _optionalChain([options, 'access', _75 => _75.hooks, 'optionalAccess', _76 => _76.onClose])
2151
+ } : _optionalChain([options, 'access', _99 => _99.hooks, 'optionalAccess', _100 => _100.onInit]),
2152
+ onClose: _optionalChain([options, 'access', _101 => _101.hooks, 'optionalAccess', _102 => _102.onClose])
1427
2153
  };
1428
2154
  const processor = projector({
1429
2155
  ...options,
@@ -1448,11 +2174,12 @@ var sqliteEventStoreConsumer = (options) => {
1448
2174
  let start;
1449
2175
  let messagePuller;
1450
2176
  const pool = _nullishCoalesce(options.pool, () => ( _dumbo.dumbo.call(void 0, {
1451
- ...options.driver.mapToDumboOptions(options),
2177
+ serialization: options.serialization,
1452
2178
  transactionOptions: {
1453
2179
  allowNestedTransactions: true,
1454
2180
  mode: "session_based"
1455
- }
2181
+ },
2182
+ ...options.driver.mapToDumboOptions(options)
1456
2183
  })));
1457
2184
  const eachBatch = (messagesBatch) => pool.withConnection(async (connection) => {
1458
2185
  const activeProcessors = processors.filter((s) => s.isActive);
@@ -1470,7 +2197,7 @@ var sqliteEventStoreConsumer = (options) => {
1470
2197
  })
1471
2198
  );
1472
2199
  return result.some(
1473
- (r) => r.status === "fulfilled" && _optionalChain([r, 'access', _77 => _77.value, 'optionalAccess', _78 => _78.type]) !== "STOP"
2200
+ (r) => r.status === "fulfilled" && _optionalChain([r, 'access', _103 => _103.value, 'optionalAccess', _104 => _104.type]) !== "STOP"
1474
2201
  ) ? void 0 : {
1475
2202
  type: "STOP"
1476
2203
  };
@@ -1484,12 +2211,12 @@ var sqliteEventStoreConsumer = (options) => {
1484
2211
  if (!isRunning) return;
1485
2212
  isRunning = false;
1486
2213
  if (messagePuller) {
1487
- _optionalChain([abortController, 'optionalAccess', _79 => _79.abort, 'call', _80 => _80()]);
2214
+ _optionalChain([abortController, 'optionalAccess', _105 => _105.abort, 'call', _106 => _106()]);
1488
2215
  await messagePuller.stop();
1489
- messagePuller = void 0;
1490
- abortController = null;
1491
2216
  }
1492
2217
  await start;
2218
+ messagePuller = void 0;
2219
+ abortController = null;
1493
2220
  await stopProcessors();
1494
2221
  };
1495
2222
  const init = async () => {
@@ -1531,6 +2258,22 @@ var sqliteEventStoreConsumer = (options) => {
1531
2258
  );
1532
2259
  return processor;
1533
2260
  },
2261
+ workflowProcessor: (processorOptions) => {
2262
+ const messageStore = getSQLiteEventStore({
2263
+ ...options,
2264
+ pool,
2265
+ schema: { autoMigration: "None" }
2266
+ });
2267
+ const processor = sqliteWorkflowProcessor({
2268
+ ...processorOptions,
2269
+ messageStore
2270
+ });
2271
+ processors.push(
2272
+ // TODO: change that
2273
+ processor
2274
+ );
2275
+ return processor;
2276
+ },
1534
2277
  start: () => {
1535
2278
  if (isRunning) return start;
1536
2279
  if (processors.length === 0)
@@ -1543,8 +2286,8 @@ var sqliteEventStoreConsumer = (options) => {
1543
2286
  stopWhen: options.stopWhen,
1544
2287
  executor: pool.execute,
1545
2288
  eachBatch,
1546
- batchSize: _nullishCoalesce(_optionalChain([pulling, 'optionalAccess', _81 => _81.batchSize]), () => ( DefaultSQLiteEventStoreProcessorBatchSize)),
1547
- pullingFrequencyInMs: _nullishCoalesce(_optionalChain([pulling, 'optionalAccess', _82 => _82.pullingFrequencyInMs]), () => ( DefaultSQLiteEventStoreProcessorPullingFrequencyInMs)),
2289
+ batchSize: _nullishCoalesce(_optionalChain([pulling, 'optionalAccess', _107 => _107.batchSize]), () => ( DefaultSQLiteEventStoreProcessorBatchSize)),
2290
+ pullingFrequencyInMs: _nullishCoalesce(_optionalChain([pulling, 'optionalAccess', _108 => _108.pullingFrequencyInMs]), () => ( DefaultSQLiteEventStoreProcessorPullingFrequencyInMs)),
1548
2291
  signal: abortController.signal
1549
2292
  });
1550
2293
  start = (async () => {
@@ -1583,22 +2326,20 @@ var sqliteEventStoreConsumer = (options) => {
1583
2326
  var SQLiteEventStoreDefaultStreamVersion = 0n;
1584
2327
  var getSQLiteEventStore = (options) => {
1585
2328
  let autoGenerateSchema = false;
2329
+ const serializer = JSONSerializer.from(options);
1586
2330
  const pool = _nullishCoalesce(options.pool, () => ( _dumbo.dumbo.call(void 0, {
1587
- ...options.driver.mapToDumboOptions(options),
2331
+ serialization: options.serialization,
1588
2332
  transactionOptions: {
1589
2333
  allowNestedTransactions: true,
1590
2334
  mode: "session_based"
1591
- }
2335
+ },
2336
+ ...options.driver.mapToDumboOptions(options)
1592
2337
  })));
1593
2338
  let migrateSchema = void 0;
1594
2339
  const inlineProjections = (_nullishCoalesce(options.projections, () => ( []))).filter(({ type }) => type === "inline").map(({ projection: projection2 }) => projection2);
1595
- const onBeforeCommitHook = _optionalChain([options, 'access', _83 => _83.hooks, 'optionalAccess', _84 => _84.onBeforeCommit]);
1596
- const withConnection = async (handler) => pool.withConnection(async (connection) => {
1597
- await ensureSchemaExists(connection);
1598
- return await handler(connection);
1599
- });
2340
+ const onBeforeCommitHook = _optionalChain([options, 'access', _109 => _109.hooks, 'optionalAccess', _110 => _110.onBeforeCommit]);
1600
2341
  if (options) {
1601
- autoGenerateSchema = _optionalChain([options, 'access', _85 => _85.schema, 'optionalAccess', _86 => _86.autoMigration]) === void 0 || _optionalChain([options, 'access', _87 => _87.schema, 'optionalAccess', _88 => _88.autoMigration]) !== "None";
2342
+ autoGenerateSchema = _optionalChain([options, 'access', _111 => _111.schema, 'optionalAccess', _112 => _112.autoMigration]) === void 0 || _optionalChain([options, 'access', _113 => _113.schema, 'optionalAccess', _114 => _114.autoMigration]) !== "None";
1602
2343
  }
1603
2344
  const migrate = (connection) => {
1604
2345
  if (!migrateSchema) {
@@ -1618,29 +2359,32 @@ var getSQLiteEventStore = (options) => {
1618
2359
  });
1619
2360
  }
1620
2361
  }
1621
- if (_optionalChain([options, 'access', _89 => _89.hooks, 'optionalAccess', _90 => _90.onBeforeSchemaCreated])) {
2362
+ if (_optionalChain([options, 'access', _115 => _115.hooks, 'optionalAccess', _116 => _116.onBeforeSchemaCreated])) {
1622
2363
  await options.hooks.onBeforeSchemaCreated(context);
1623
2364
  }
1624
2365
  },
1625
- onAfterSchemaCreated: _optionalChain([options, 'access', _91 => _91.hooks, 'optionalAccess', _92 => _92.onAfterSchemaCreated])
2366
+ onAfterSchemaCreated: _optionalChain([options, 'access', _117 => _117.hooks, 'optionalAccess', _118 => _118.onAfterSchemaCreated])
1626
2367
  });
1627
2368
  }
1628
2369
  return migrateSchema;
1629
2370
  };
1630
- const ensureSchemaExists = (connection) => {
2371
+ const ensureSchemaExists = () => {
1631
2372
  if (!autoGenerateSchema) return Promise.resolve();
1632
- return migrate(connection);
2373
+ return pool.withConnection((connection) => migrate(connection));
1633
2374
  };
1634
2375
  return {
1635
2376
  async aggregateStream(streamName, options2) {
2377
+ await ensureSchemaExists();
1636
2378
  const { evolve, initialState, read } = options2;
1637
- const expectedStreamVersion = _optionalChain([read, 'optionalAccess', _93 => _93.expectedStreamVersion]);
2379
+ const expectedStreamVersion = _optionalChain([read, 'optionalAccess', _119 => _119.expectedStreamVersion]);
1638
2380
  let state = initialState();
1639
2381
  if (typeof streamName !== "string") {
1640
2382
  throw new Error("Stream name is not string");
1641
2383
  }
1642
- const result = await withConnection(
1643
- ({ execute }) => readStream(execute, streamName, read)
2384
+ const result = await readStream(
2385
+ pool.execute,
2386
+ streamName,
2387
+ { ...read, serializer: _nullishCoalesce(_optionalChain([read, 'optionalAccess', _120 => _120.serialization, 'optionalAccess', _121 => _121.serializer]), () => ( serializer)) }
1644
2388
  );
1645
2389
  const currentStreamVersion = result.currentStreamVersion;
1646
2390
  assertExpectedVersionMatchesCurrent(
@@ -1658,13 +2402,18 @@ var getSQLiteEventStore = (options) => {
1658
2402
  streamExists: result.streamExists
1659
2403
  };
1660
2404
  },
1661
- readStream: async (streamName, options2) => withConnection(
1662
- ({ execute }) => readStream(execute, streamName, options2)
1663
- ),
2405
+ readStream: async (streamName, readOptions) => {
2406
+ await ensureSchemaExists();
2407
+ return readStream(pool.execute, streamName, {
2408
+ ...readOptions,
2409
+ serializer: _nullishCoalesce(_optionalChain([options, 'access', _122 => _122.serialization, 'optionalAccess', _123 => _123.serializer]), () => ( serializer))
2410
+ });
2411
+ },
1664
2412
  appendToStream: async (streamName, events, appendOptions) => {
2413
+ await ensureSchemaExists();
1665
2414
  const [firstPart, ...rest] = streamName.split("-");
1666
2415
  const streamType = firstPart && rest.length > 0 ? firstPart : unknownTag2;
1667
- const appendResult = await withConnection(
2416
+ const appendResult = await pool.withConnection(
1668
2417
  (connection) => appendToStream(connection, streamName, streamType, events, {
1669
2418
  ...appendOptions,
1670
2419
  onBeforeCommit: async (messages, context) => {
@@ -1676,15 +2425,17 @@ var getSQLiteEventStore = (options) => {
1676
2425
  connection: context.connection,
1677
2426
  driverType: options.driver.driverType
1678
2427
  });
1679
- if (onBeforeCommitHook) await onBeforeCommitHook(messages, context);
2428
+ if (onBeforeCommitHook)
2429
+ await onBeforeCommitHook(messages, context);
1680
2430
  }
1681
- })
2431
+ }),
2432
+ { readonly: false }
1682
2433
  );
1683
2434
  if (!appendResult.success)
1684
2435
  throw new ExpectedVersionConflictError(
1685
2436
  -1n,
1686
2437
  //TODO: Return actual version in case of error
1687
- _nullishCoalesce(_optionalChain([appendOptions, 'optionalAccess', _94 => _94.expectedStreamVersion]), () => ( NO_CONCURRENCY_CHECK))
2438
+ _nullishCoalesce(_optionalChain([appendOptions, 'optionalAccess', _124 => _124.expectedStreamVersion]), () => ( NO_CONCURRENCY_CHECK))
1688
2439
  );
1689
2440
  return {
1690
2441
  nextExpectedStreamVersion: appendResult.nextStreamPosition,
@@ -1692,16 +2443,41 @@ var getSQLiteEventStore = (options) => {
1692
2443
  createdNewStream: appendResult.nextStreamPosition >= BigInt(events.length)
1693
2444
  };
1694
2445
  },
1695
- streamExists(streamName, options2) {
1696
- return withConnection(
1697
- ({ execute }) => streamExists(execute, streamName, options2)
1698
- );
2446
+ async streamExists(streamName, options2) {
2447
+ await ensureSchemaExists();
2448
+ return streamExists(pool.execute, streamName, options2);
1699
2449
  },
1700
2450
  consumer: (consumerOptions) => sqliteEventStoreConsumer({
1701
2451
  ..._nullishCoalesce(options, () => ( {})),
1702
2452
  ..._nullishCoalesce(consumerOptions, () => ( {})),
1703
2453
  pool
1704
2454
  }),
2455
+ async withSession(callback) {
2456
+ return await pool.withConnection(async (connection) => {
2457
+ const sessionStore = getSQLiteEventStore({
2458
+ ...options,
2459
+ pool: _dumbo.dumbo.call(void 0, {
2460
+ ...options.driver.mapToDumboOptions(options),
2461
+ connection,
2462
+ serialization: options.serialization
2463
+ }),
2464
+ transactionOptions: {
2465
+ allowNestedTransactions: true,
2466
+ mode: "session_based"
2467
+ },
2468
+ schema: {
2469
+ ...options.schema,
2470
+ autoMigration: "None"
2471
+ },
2472
+ serialization: options.serialization
2473
+ });
2474
+ await ensureSchemaExists();
2475
+ return callback({
2476
+ eventStore: sessionStore,
2477
+ close: () => Promise.resolve()
2478
+ });
2479
+ });
2480
+ },
1705
2481
  close: () => pool.close(),
1706
2482
  schema: {
1707
2483
  sql: () => schemaSQL.join(""),
@@ -1714,22 +2490,23 @@ var getSQLiteEventStore = (options) => {
1714
2490
  // src/eventStore/schema/readStream.ts
1715
2491
  var { identifier: identifier6 } = _dumbo.SQL;
1716
2492
  var readStream = async (execute, streamId, options) => {
1717
- const fromCondition = _optionalChain([options, 'optionalAccess', _95 => _95.from]) ? _dumbo.SQL`AND stream_position >= ${options.from}` : _dumbo.SQL.EMPTY;
2493
+ const { serializer } = options;
2494
+ const fromCondition = options.from ? _dumbo.SQL`AND stream_position >= ${options.from}` : _dumbo.SQL.EMPTY;
1718
2495
  const to = Number(
1719
- _nullishCoalesce(_optionalChain([options, 'optionalAccess', _96 => _96.to]), () => ( (_optionalChain([options, 'optionalAccess', _97 => _97.maxCount]) ? (_nullishCoalesce(options.from, () => ( 0n))) + options.maxCount : NaN)))
2496
+ _nullishCoalesce(_optionalChain([options, 'optionalAccess', _125 => _125.to]), () => ( (_optionalChain([options, 'optionalAccess', _126 => _126.maxCount]) ? (_nullishCoalesce(options.from, () => ( 0n))) + options.maxCount : NaN)))
1720
2497
  );
1721
2498
  const toCondition = !isNaN(to) ? _dumbo.SQL`AND stream_position <= ${to}` : _dumbo.SQL.EMPTY;
1722
2499
  const { rows: results } = await execute.query(
1723
2500
  _dumbo.SQL`SELECT stream_id, stream_position, global_position, message_data, message_metadata, message_schema_version, message_type, message_id
1724
2501
  FROM ${identifier6(messagesTable.name)}
1725
- WHERE stream_id = ${streamId} AND partition = ${_nullishCoalesce(_optionalChain([options, 'optionalAccess', _98 => _98.partition]), () => ( defaultTag2))} AND is_archived = FALSE ${fromCondition} ${toCondition}
2502
+ WHERE stream_id = ${streamId} AND partition = ${_nullishCoalesce(_optionalChain([options, 'optionalAccess', _127 => _127.partition]), () => ( defaultTag2))} AND is_archived = FALSE ${fromCondition} ${toCondition}
1726
2503
  ORDER BY stream_position ASC`
1727
2504
  );
1728
2505
  const messages = results.map((row) => {
1729
2506
  const rawEvent = {
1730
2507
  type: row.message_type,
1731
- data: JSONParser.parse(row.message_data),
1732
- metadata: JSONParser.parse(row.message_metadata)
2508
+ data: serializer.deserialize(row.message_data),
2509
+ metadata: serializer.deserialize(row.message_metadata)
1733
2510
  };
1734
2511
  const metadata = {
1735
2512
  ..."metadata" in rawEvent ? _nullishCoalesce(rawEvent.metadata, () => ( {})) : {},
@@ -1744,7 +2521,7 @@ var readStream = async (execute, streamId, options) => {
1744
2521
  kind: "Event",
1745
2522
  metadata
1746
2523
  };
1747
- return upcastRecordedMessage(event, _optionalChain([options, 'optionalAccess', _99 => _99.schema, 'optionalAccess', _100 => _100.versioning]));
2524
+ return upcastRecordedMessage(event, _optionalChain([options, 'optionalAccess', _128 => _128.schema, 'optionalAccess', _129 => _129.versioning]));
1748
2525
  });
1749
2526
  return messages.length > 0 ? {
1750
2527
  currentStreamVersion: messages[messages.length - 1].metadata.streamPosition,
@@ -1789,7 +2566,7 @@ async function storeSubscriptionCheckpointSQLite(execute, processorId, version,
1789
2566
  WHERE processor_id = ${processorId} AND partition = ${partition}`
1790
2567
  )
1791
2568
  );
1792
- const currentPosition = current_position && _optionalChain([current_position, 'optionalAccess', _101 => _101.last_processed_checkpoint]) !== null ? current_position.last_processed_checkpoint : null;
2569
+ const currentPosition = current_position && _optionalChain([current_position, 'optionalAccess', _130 => _130.last_processed_checkpoint]) !== null ? current_position.last_processed_checkpoint : null;
1793
2570
  if (currentPosition === position) {
1794
2571
  return 0;
1795
2572
  } else if (position !== null && currentPosition !== null && currentPosition > position) {
@@ -1817,7 +2594,7 @@ async function storeSubscriptionCheckpointSQLite(execute, processorId, version,
1817
2594
  WHERE processor_id = ${processorId} AND partition = ${partition}`
1818
2595
  )
1819
2596
  );
1820
- const currentPosition = current && _optionalChain([current, 'optionalAccess', _102 => _102.last_processed_checkpoint]) !== null ? BigInt(current.last_processed_checkpoint) : null;
2597
+ const currentPosition = current && _optionalChain([current, 'optionalAccess', _131 => _131.last_processed_checkpoint]) !== null ? BigInt(current.last_processed_checkpoint) : null;
1821
2598
  if (currentPosition === position) {
1822
2599
  return 0;
1823
2600
  } else {
@@ -1850,7 +2627,7 @@ var streamExists = (execute, streamId, options) => _dumbo.exists.call(void 0,
1850
2627
  _dumbo.SQL`SELECT EXISTS (
1851
2628
  SELECT 1
1852
2629
  from ${_dumbo.SQL.identifier(streamsTable.name)}
1853
- WHERE stream_id = ${streamId} AND partition = ${_nullishCoalesce(_optionalChain([options, 'optionalAccess', _103 => _103.partition]), () => ( defaultTag2))} AND is_archived = FALSE) as exists
2630
+ WHERE stream_id = ${streamId} AND partition = ${_nullishCoalesce(_optionalChain([options, 'optionalAccess', _132 => _132.partition]), () => ( defaultTag2))} AND is_archived = FALSE) as exists
1854
2631
  `
1855
2632
  )
1856
2633
  );
@@ -1916,13 +2693,13 @@ var schemaSQL = [
1916
2693
  var createEventStoreSchema = async (pool, hooks) => {
1917
2694
  await pool.withTransaction(async (tx) => {
1918
2695
  await migration_0_42_0_FromSubscriptionsToProcessors(tx.execute);
1919
- if (_optionalChain([hooks, 'optionalAccess', _104 => _104.onBeforeSchemaCreated])) {
2696
+ if (_optionalChain([hooks, 'optionalAccess', _133 => _133.onBeforeSchemaCreated])) {
1920
2697
  await hooks.onBeforeSchemaCreated({
1921
2698
  connection: tx.connection
1922
2699
  });
1923
2700
  }
1924
2701
  await tx.execute.batchCommand(schemaSQL);
1925
- if (_optionalChain([hooks, 'optionalAccess', _105 => _105.onAfterSchemaCreated])) {
2702
+ if (_optionalChain([hooks, 'optionalAccess', _134 => _134.onAfterSchemaCreated])) {
1926
2703
  await hooks.onAfterSchemaCreated();
1927
2704
  }
1928
2705
  });
@@ -1966,5 +2743,14 @@ var createEventStoreSchema = async (pool, hooks) => {
1966
2743
 
1967
2744
 
1968
2745
 
1969
- exports.SQLiteEventStoreDefaultStreamVersion = SQLiteEventStoreDefaultStreamVersion; exports.SQLiteProjectionSpec = SQLiteProjectionSpec; exports.appendToStream = appendToStream; exports.assertSQLQueryResultMatches = assertSQLQueryResultMatches; exports.createEventStoreSchema = createEventStoreSchema; exports.defaultTag = defaultTag2; exports.emmettPrefix = emmettPrefix2; exports.eventInStream = eventInStream; exports.eventsInStream = eventsInStream; exports.expectSQL = expectSQL; exports.getSQLiteEventStore = getSQLiteEventStore; exports.globalNames = globalNames; exports.globalTag = globalTag; exports.handleProjections = handleProjections; exports.messagesTable = messagesTable; exports.messagesTableSQL = messagesTableSQL; exports.migration_0_42_0_FromSubscriptionsToProcessors = migration_0_42_0_FromSubscriptionsToProcessors; exports.migration_0_42_0_SQLs = migration_0_42_0_SQLs; exports.newEventsInStream = newEventsInStream; exports.processorsTable = processorsTable; exports.processorsTableSQL = processorsTableSQL; exports.projectionsTable = projectionsTable; exports.projectionsTableSQL = projectionsTableSQL; exports.readLastMessageGlobalPosition = readLastMessageGlobalPosition; exports.readMessagesBatch = readMessagesBatch; exports.readProcessorCheckpoint = readProcessorCheckpoint; exports.readStream = readStream; exports.schemaSQL = schemaSQL; exports.schema_0_41_0 = schema_0_41_0; exports.schema_0_42_0 = schema_0_42_0; exports.sqliteProjection = sqliteProjection; exports.sqliteRawBatchSQLProjection = sqliteRawBatchSQLProjection; exports.sqliteRawSQLProjection = sqliteRawSQLProjection; exports.storeProcessorCheckpoint = storeProcessorCheckpoint; exports.streamExists = streamExists; exports.streamsTable = streamsTable; exports.streamsTableSQL = streamsTableSQL; exports.unknownTag = unknownTag2;
2746
+
2747
+
2748
+
2749
+
2750
+
2751
+
2752
+
2753
+
2754
+
2755
+ exports.SQLiteEventStoreDefaultStreamVersion = SQLiteEventStoreDefaultStreamVersion; exports.SQLiteProjectionSpec = SQLiteProjectionSpec; exports.appendToStream = appendToStream; exports.assertSQLQueryResultMatches = assertSQLQueryResultMatches; exports.createEventStoreSchema = createEventStoreSchema; exports.defaultTag = defaultTag2; exports.documentDoesNotExist = documentDoesNotExist; exports.documentExists = documentExists; exports.documentMatchingExists = documentMatchingExists; exports.documentsAreTheSame = documentsAreTheSame; exports.documentsMatchingHaveCount = documentsMatchingHaveCount; exports.emmettPrefix = emmettPrefix2; exports.eventInStream = eventInStream; exports.eventsInStream = eventsInStream; exports.expectPongoDocuments = expectPongoDocuments; exports.expectSQL = expectSQL; exports.getSQLiteEventStore = getSQLiteEventStore; exports.globalNames = globalNames; exports.globalTag = globalTag; exports.handleProjections = handleProjections; exports.messagesTable = messagesTable; exports.messagesTableSQL = messagesTableSQL; exports.migration_0_42_0_FromSubscriptionsToProcessors = migration_0_42_0_FromSubscriptionsToProcessors; exports.migration_0_42_0_SQLs = migration_0_42_0_SQLs; exports.newEventsInStream = newEventsInStream; exports.pongoMultiStreamProjection = pongoMultiStreamProjection; exports.pongoProjection = pongoProjection; exports.pongoSingleStreamProjection = pongoSingleStreamProjection; exports.processorsTable = processorsTable; exports.processorsTableSQL = processorsTableSQL; exports.projectionsTable = projectionsTable; exports.projectionsTableSQL = projectionsTableSQL; exports.readLastMessageGlobalPosition = readLastMessageGlobalPosition; exports.readMessagesBatch = readMessagesBatch; exports.readProcessorCheckpoint = readProcessorCheckpoint; exports.readStream = readStream; exports.schemaSQL = schemaSQL; exports.schema_0_41_0 = schema_0_41_0; exports.schema_0_42_0 = schema_0_42_0; exports.sqliteProjection = sqliteProjection; exports.sqliteRawBatchSQLProjection = sqliteRawBatchSQLProjection; exports.sqliteRawSQLProjection = sqliteRawSQLProjection; exports.storeProcessorCheckpoint = storeProcessorCheckpoint; exports.streamExists = streamExists; exports.streamsTable = streamsTable; exports.streamsTableSQL = streamsTableSQL; exports.unknownTag = unknownTag2;
1970
2756
  //# sourceMappingURL=index.cjs.map