@robinmalfait/event-source 0.0.2 → 0.0.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,1673 +0,0 @@
1
- import { randomUUID } from 'crypto';
2
- import yamlify from 'yamlify-object';
3
-
4
- function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) {
5
- try {
6
- var info = gen[key](arg);
7
- var value = info.value;
8
- } catch (error) {
9
- reject(error);
10
- return;
11
- }
12
-
13
- if (info.done) {
14
- resolve(value);
15
- } else {
16
- Promise.resolve(value).then(_next, _throw);
17
- }
18
- }
19
-
20
- function _asyncToGenerator(fn) {
21
- return function () {
22
- var self = this,
23
- args = arguments;
24
- return new Promise(function (resolve, reject) {
25
- var gen = fn.apply(self, args);
26
-
27
- function _next(value) {
28
- asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value);
29
- }
30
-
31
- function _throw(err) {
32
- asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err);
33
- }
34
-
35
- _next(undefined);
36
- });
37
- };
38
- }
39
-
40
- function _defineProperties(target, props) {
41
- for (var i = 0; i < props.length; i++) {
42
- var descriptor = props[i];
43
- descriptor.enumerable = descriptor.enumerable || false;
44
- descriptor.configurable = true;
45
- if ("value" in descriptor) descriptor.writable = true;
46
- Object.defineProperty(target, descriptor.key, descriptor);
47
- }
48
- }
49
-
50
- function _createClass(Constructor, protoProps, staticProps) {
51
- if (protoProps) _defineProperties(Constructor.prototype, protoProps);
52
- if (staticProps) _defineProperties(Constructor, staticProps);
53
- return Constructor;
54
- }
55
-
56
- function _extends() {
57
- _extends = Object.assign || function (target) {
58
- for (var i = 1; i < arguments.length; i++) {
59
- var source = arguments[i];
60
-
61
- for (var key in source) {
62
- if (Object.prototype.hasOwnProperty.call(source, key)) {
63
- target[key] = source[key];
64
- }
65
- }
66
- }
67
-
68
- return target;
69
- };
70
-
71
- return _extends.apply(this, arguments);
72
- }
73
-
74
- function _unsupportedIterableToArray(o, minLen) {
75
- if (!o) return;
76
- if (typeof o === "string") return _arrayLikeToArray(o, minLen);
77
- var n = Object.prototype.toString.call(o).slice(8, -1);
78
- if (n === "Object" && o.constructor) n = o.constructor.name;
79
- if (n === "Map" || n === "Set") return Array.from(o);
80
- if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen);
81
- }
82
-
83
- function _arrayLikeToArray(arr, len) {
84
- if (len == null || len > arr.length) len = arr.length;
85
-
86
- for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i];
87
-
88
- return arr2;
89
- }
90
-
91
- function _createForOfIteratorHelperLoose(o, allowArrayLike) {
92
- var it;
93
-
94
- if (typeof Symbol === "undefined" || o[Symbol.iterator] == null) {
95
- if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") {
96
- if (it) o = it;
97
- var i = 0;
98
- return function () {
99
- if (i >= o.length) return {
100
- done: true
101
- };
102
- return {
103
- done: false,
104
- value: o[i++]
105
- };
106
- };
107
- }
108
-
109
- throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
110
- }
111
-
112
- it = o[Symbol.iterator]();
113
- return it.next.bind(it);
114
- }
115
-
116
- function createError(message, attributes) {
117
- var error = Object.assign(new Error(message), attributes); // In V8, Error objects keep the closure scope chain alive until the
118
- // This means that your stack trace will be useful and point to the place
119
- // where the error is possibly thrown and _not_ to this function!
120
-
121
- if (Error.captureStackTrace) Error.captureStackTrace(error, createError);
122
- return error;
123
- }
124
-
125
- function abort(message, attributes) {
126
- var error = createError(message, attributes); // This allows us to remove this abort function from the stack trace.
127
- // This means that your stack trace will be useful and point to the place
128
- // where the error is possibly thrown and _not_ to this function!
129
-
130
- if (Error.captureStackTrace) Error.captureStackTrace(error, abort);
131
- throw error;
132
- }
133
-
134
- function deepFreeze(object) {
135
- Object.freeze(object);
136
-
137
- for (var _iterator = _createForOfIteratorHelperLoose(Object.getOwnPropertyNames(object)), _step; !(_step = _iterator()).done;) {
138
- var prop = _step.value;
139
-
140
- if (object.hasOwnProperty(prop) && object[prop] !== null && (typeof object[prop] === 'object' || typeof object[prop] === 'function') && !Object.isFrozen(object[prop])) {
141
- deepFreeze(object[prop]);
142
- }
143
- }
144
-
145
- return object;
146
- }
147
-
148
- var Aggregate = /*#__PURE__*/function () {
149
- function Aggregate() {
150
- this.version = 0;
151
- this.recordedEvents = [];
152
- }
153
-
154
- var _proto = Aggregate.prototype;
155
-
156
- _proto.replayEvents = function replayEvents(events) {
157
- if (events === void 0) {
158
- events = [];
159
- }
160
-
161
- for (var _iterator = _createForOfIteratorHelperLoose(events), _step; !(_step = _iterator()).done;) {
162
- var event = _step.value;
163
- this.applyAnEvent(event);
164
- }
165
-
166
- return this;
167
- };
168
-
169
- _proto.applyAnEvent = function applyAnEvent(event) {
170
- if (process.env.NODE_ENV === 'test') deepFreeze(event);
171
-
172
- if (this[event.eventName] === undefined) {
173
- if (event.eventName.match(/^[$A-Z_][0-9A-Z_$]*$/i)) {
174
- abort("Aggregate \"" + this.constructor.name + "\" has no method:\n\n" + event.eventName + "(event) {\n\t// Code goes here...\n}");
175
- } else {
176
- abort("Aggregate \"" + this.constructor.name + "\" has no method:\n\n['" + event.eventName + "'](event) {\n\t// Code goes here...\n}");
177
- }
178
- }
179
-
180
- try {
181
- ;
182
- this[event.eventName](event);
183
- } catch (err) {
184
- console.error("An error occurred inside your \"%s\" function:\n", event.eventName, err.stack.split('\n').map(function (line) {
185
- return " " + line;
186
- }).join('\n'));
187
- } finally {
188
- this.version++;
189
- }
190
-
191
- return this;
192
- };
193
-
194
- _proto.recordThat = function recordThat(event) {
195
- var eventToStore = _extends({}, event, {
196
- version: this.version
197
- });
198
-
199
- this.applyAnEvent(eventToStore);
200
- this.recordedEvents.push(eventToStore);
201
- return this;
202
- };
203
-
204
- _proto.releaseEvents = function releaseEvents() {
205
- return this.recordedEvents.splice(0);
206
- };
207
-
208
- return Aggregate;
209
- }();
210
-
211
- function Command(type, payload) {
212
- return {
213
- type: type,
214
- payload: payload
215
- };
216
- }
217
-
218
- function Event(eventName, aggregateId, payload) {
219
- return {
220
- aggregateId: aggregateId,
221
- eventId: randomUUID(),
222
- eventName: eventName,
223
- payload: payload,
224
- recordedAt: new Date(),
225
- version: -1
226
- };
227
- }
228
-
229
- function createCommonjsModule(fn, module) {
230
- return module = { exports: {} }, fn(module, module.exports), module.exports;
231
- }
232
-
233
- var runtime_1 = createCommonjsModule(function (module) {
234
- /**
235
- * Copyright (c) 2014-present, Facebook, Inc.
236
- *
237
- * This source code is licensed under the MIT license found in the
238
- * LICENSE file in the root directory of this source tree.
239
- */
240
-
241
- var runtime = (function (exports) {
242
-
243
- var Op = Object.prototype;
244
- var hasOwn = Op.hasOwnProperty;
245
- var undefined$1; // More compressible than void 0.
246
- var $Symbol = typeof Symbol === "function" ? Symbol : {};
247
- var iteratorSymbol = $Symbol.iterator || "@@iterator";
248
- var asyncIteratorSymbol = $Symbol.asyncIterator || "@@asyncIterator";
249
- var toStringTagSymbol = $Symbol.toStringTag || "@@toStringTag";
250
-
251
- function define(obj, key, value) {
252
- Object.defineProperty(obj, key, {
253
- value: value,
254
- enumerable: true,
255
- configurable: true,
256
- writable: true
257
- });
258
- return obj[key];
259
- }
260
- try {
261
- // IE 8 has a broken Object.defineProperty that only works on DOM objects.
262
- define({}, "");
263
- } catch (err) {
264
- define = function(obj, key, value) {
265
- return obj[key] = value;
266
- };
267
- }
268
-
269
- function wrap(innerFn, outerFn, self, tryLocsList) {
270
- // If outerFn provided and outerFn.prototype is a Generator, then outerFn.prototype instanceof Generator.
271
- var protoGenerator = outerFn && outerFn.prototype instanceof Generator ? outerFn : Generator;
272
- var generator = Object.create(protoGenerator.prototype);
273
- var context = new Context(tryLocsList || []);
274
-
275
- // The ._invoke method unifies the implementations of the .next,
276
- // .throw, and .return methods.
277
- generator._invoke = makeInvokeMethod(innerFn, self, context);
278
-
279
- return generator;
280
- }
281
- exports.wrap = wrap;
282
-
283
- // Try/catch helper to minimize deoptimizations. Returns a completion
284
- // record like context.tryEntries[i].completion. This interface could
285
- // have been (and was previously) designed to take a closure to be
286
- // invoked without arguments, but in all the cases we care about we
287
- // already have an existing method we want to call, so there's no need
288
- // to create a new function object. We can even get away with assuming
289
- // the method takes exactly one argument, since that happens to be true
290
- // in every case, so we don't have to touch the arguments object. The
291
- // only additional allocation required is the completion record, which
292
- // has a stable shape and so hopefully should be cheap to allocate.
293
- function tryCatch(fn, obj, arg) {
294
- try {
295
- return { type: "normal", arg: fn.call(obj, arg) };
296
- } catch (err) {
297
- return { type: "throw", arg: err };
298
- }
299
- }
300
-
301
- var GenStateSuspendedStart = "suspendedStart";
302
- var GenStateSuspendedYield = "suspendedYield";
303
- var GenStateExecuting = "executing";
304
- var GenStateCompleted = "completed";
305
-
306
- // Returning this object from the innerFn has the same effect as
307
- // breaking out of the dispatch switch statement.
308
- var ContinueSentinel = {};
309
-
310
- // Dummy constructor functions that we use as the .constructor and
311
- // .constructor.prototype properties for functions that return Generator
312
- // objects. For full spec compliance, you may wish to configure your
313
- // minifier not to mangle the names of these two functions.
314
- function Generator() {}
315
- function GeneratorFunction() {}
316
- function GeneratorFunctionPrototype() {}
317
-
318
- // This is a polyfill for %IteratorPrototype% for environments that
319
- // don't natively support it.
320
- var IteratorPrototype = {};
321
- IteratorPrototype[iteratorSymbol] = function () {
322
- return this;
323
- };
324
-
325
- var getProto = Object.getPrototypeOf;
326
- var NativeIteratorPrototype = getProto && getProto(getProto(values([])));
327
- if (NativeIteratorPrototype &&
328
- NativeIteratorPrototype !== Op &&
329
- hasOwn.call(NativeIteratorPrototype, iteratorSymbol)) {
330
- // This environment has a native %IteratorPrototype%; use it instead
331
- // of the polyfill.
332
- IteratorPrototype = NativeIteratorPrototype;
333
- }
334
-
335
- var Gp = GeneratorFunctionPrototype.prototype =
336
- Generator.prototype = Object.create(IteratorPrototype);
337
- GeneratorFunction.prototype = Gp.constructor = GeneratorFunctionPrototype;
338
- GeneratorFunctionPrototype.constructor = GeneratorFunction;
339
- GeneratorFunction.displayName = define(
340
- GeneratorFunctionPrototype,
341
- toStringTagSymbol,
342
- "GeneratorFunction"
343
- );
344
-
345
- // Helper for defining the .next, .throw, and .return methods of the
346
- // Iterator interface in terms of a single ._invoke method.
347
- function defineIteratorMethods(prototype) {
348
- ["next", "throw", "return"].forEach(function(method) {
349
- define(prototype, method, function(arg) {
350
- return this._invoke(method, arg);
351
- });
352
- });
353
- }
354
-
355
- exports.isGeneratorFunction = function(genFun) {
356
- var ctor = typeof genFun === "function" && genFun.constructor;
357
- return ctor
358
- ? ctor === GeneratorFunction ||
359
- // For the native GeneratorFunction constructor, the best we can
360
- // do is to check its .name property.
361
- (ctor.displayName || ctor.name) === "GeneratorFunction"
362
- : false;
363
- };
364
-
365
- exports.mark = function(genFun) {
366
- if (Object.setPrototypeOf) {
367
- Object.setPrototypeOf(genFun, GeneratorFunctionPrototype);
368
- } else {
369
- genFun.__proto__ = GeneratorFunctionPrototype;
370
- define(genFun, toStringTagSymbol, "GeneratorFunction");
371
- }
372
- genFun.prototype = Object.create(Gp);
373
- return genFun;
374
- };
375
-
376
- // Within the body of any async function, `await x` is transformed to
377
- // `yield regeneratorRuntime.awrap(x)`, so that the runtime can test
378
- // `hasOwn.call(value, "__await")` to determine if the yielded value is
379
- // meant to be awaited.
380
- exports.awrap = function(arg) {
381
- return { __await: arg };
382
- };
383
-
384
- function AsyncIterator(generator, PromiseImpl) {
385
- function invoke(method, arg, resolve, reject) {
386
- var record = tryCatch(generator[method], generator, arg);
387
- if (record.type === "throw") {
388
- reject(record.arg);
389
- } else {
390
- var result = record.arg;
391
- var value = result.value;
392
- if (value &&
393
- typeof value === "object" &&
394
- hasOwn.call(value, "__await")) {
395
- return PromiseImpl.resolve(value.__await).then(function(value) {
396
- invoke("next", value, resolve, reject);
397
- }, function(err) {
398
- invoke("throw", err, resolve, reject);
399
- });
400
- }
401
-
402
- return PromiseImpl.resolve(value).then(function(unwrapped) {
403
- // When a yielded Promise is resolved, its final value becomes
404
- // the .value of the Promise<{value,done}> result for the
405
- // current iteration.
406
- result.value = unwrapped;
407
- resolve(result);
408
- }, function(error) {
409
- // If a rejected Promise was yielded, throw the rejection back
410
- // into the async generator function so it can be handled there.
411
- return invoke("throw", error, resolve, reject);
412
- });
413
- }
414
- }
415
-
416
- var previousPromise;
417
-
418
- function enqueue(method, arg) {
419
- function callInvokeWithMethodAndArg() {
420
- return new PromiseImpl(function(resolve, reject) {
421
- invoke(method, arg, resolve, reject);
422
- });
423
- }
424
-
425
- return previousPromise =
426
- // If enqueue has been called before, then we want to wait until
427
- // all previous Promises have been resolved before calling invoke,
428
- // so that results are always delivered in the correct order. If
429
- // enqueue has not been called before, then it is important to
430
- // call invoke immediately, without waiting on a callback to fire,
431
- // so that the async generator function has the opportunity to do
432
- // any necessary setup in a predictable way. This predictability
433
- // is why the Promise constructor synchronously invokes its
434
- // executor callback, and why async functions synchronously
435
- // execute code before the first await. Since we implement simple
436
- // async functions in terms of async generators, it is especially
437
- // important to get this right, even though it requires care.
438
- previousPromise ? previousPromise.then(
439
- callInvokeWithMethodAndArg,
440
- // Avoid propagating failures to Promises returned by later
441
- // invocations of the iterator.
442
- callInvokeWithMethodAndArg
443
- ) : callInvokeWithMethodAndArg();
444
- }
445
-
446
- // Define the unified helper method that is used to implement .next,
447
- // .throw, and .return (see defineIteratorMethods).
448
- this._invoke = enqueue;
449
- }
450
-
451
- defineIteratorMethods(AsyncIterator.prototype);
452
- AsyncIterator.prototype[asyncIteratorSymbol] = function () {
453
- return this;
454
- };
455
- exports.AsyncIterator = AsyncIterator;
456
-
457
- // Note that simple async functions are implemented on top of
458
- // AsyncIterator objects; they just return a Promise for the value of
459
- // the final result produced by the iterator.
460
- exports.async = function(innerFn, outerFn, self, tryLocsList, PromiseImpl) {
461
- if (PromiseImpl === void 0) PromiseImpl = Promise;
462
-
463
- var iter = new AsyncIterator(
464
- wrap(innerFn, outerFn, self, tryLocsList),
465
- PromiseImpl
466
- );
467
-
468
- return exports.isGeneratorFunction(outerFn)
469
- ? iter // If outerFn is a generator, return the full iterator.
470
- : iter.next().then(function(result) {
471
- return result.done ? result.value : iter.next();
472
- });
473
- };
474
-
475
- function makeInvokeMethod(innerFn, self, context) {
476
- var state = GenStateSuspendedStart;
477
-
478
- return function invoke(method, arg) {
479
- if (state === GenStateExecuting) {
480
- throw new Error("Generator is already running");
481
- }
482
-
483
- if (state === GenStateCompleted) {
484
- if (method === "throw") {
485
- throw arg;
486
- }
487
-
488
- // Be forgiving, per 25.3.3.3.3 of the spec:
489
- // https://people.mozilla.org/~jorendorff/es6-draft.html#sec-generatorresume
490
- return doneResult();
491
- }
492
-
493
- context.method = method;
494
- context.arg = arg;
495
-
496
- while (true) {
497
- var delegate = context.delegate;
498
- if (delegate) {
499
- var delegateResult = maybeInvokeDelegate(delegate, context);
500
- if (delegateResult) {
501
- if (delegateResult === ContinueSentinel) continue;
502
- return delegateResult;
503
- }
504
- }
505
-
506
- if (context.method === "next") {
507
- // Setting context._sent for legacy support of Babel's
508
- // function.sent implementation.
509
- context.sent = context._sent = context.arg;
510
-
511
- } else if (context.method === "throw") {
512
- if (state === GenStateSuspendedStart) {
513
- state = GenStateCompleted;
514
- throw context.arg;
515
- }
516
-
517
- context.dispatchException(context.arg);
518
-
519
- } else if (context.method === "return") {
520
- context.abrupt("return", context.arg);
521
- }
522
-
523
- state = GenStateExecuting;
524
-
525
- var record = tryCatch(innerFn, self, context);
526
- if (record.type === "normal") {
527
- // If an exception is thrown from innerFn, we leave state ===
528
- // GenStateExecuting and loop back for another invocation.
529
- state = context.done
530
- ? GenStateCompleted
531
- : GenStateSuspendedYield;
532
-
533
- if (record.arg === ContinueSentinel) {
534
- continue;
535
- }
536
-
537
- return {
538
- value: record.arg,
539
- done: context.done
540
- };
541
-
542
- } else if (record.type === "throw") {
543
- state = GenStateCompleted;
544
- // Dispatch the exception by looping back around to the
545
- // context.dispatchException(context.arg) call above.
546
- context.method = "throw";
547
- context.arg = record.arg;
548
- }
549
- }
550
- };
551
- }
552
-
553
- // Call delegate.iterator[context.method](context.arg) and handle the
554
- // result, either by returning a { value, done } result from the
555
- // delegate iterator, or by modifying context.method and context.arg,
556
- // setting context.delegate to null, and returning the ContinueSentinel.
557
- function maybeInvokeDelegate(delegate, context) {
558
- var method = delegate.iterator[context.method];
559
- if (method === undefined$1) {
560
- // A .throw or .return when the delegate iterator has no .throw
561
- // method always terminates the yield* loop.
562
- context.delegate = null;
563
-
564
- if (context.method === "throw") {
565
- // Note: ["return"] must be used for ES3 parsing compatibility.
566
- if (delegate.iterator["return"]) {
567
- // If the delegate iterator has a return method, give it a
568
- // chance to clean up.
569
- context.method = "return";
570
- context.arg = undefined$1;
571
- maybeInvokeDelegate(delegate, context);
572
-
573
- if (context.method === "throw") {
574
- // If maybeInvokeDelegate(context) changed context.method from
575
- // "return" to "throw", let that override the TypeError below.
576
- return ContinueSentinel;
577
- }
578
- }
579
-
580
- context.method = "throw";
581
- context.arg = new TypeError(
582
- "The iterator does not provide a 'throw' method");
583
- }
584
-
585
- return ContinueSentinel;
586
- }
587
-
588
- var record = tryCatch(method, delegate.iterator, context.arg);
589
-
590
- if (record.type === "throw") {
591
- context.method = "throw";
592
- context.arg = record.arg;
593
- context.delegate = null;
594
- return ContinueSentinel;
595
- }
596
-
597
- var info = record.arg;
598
-
599
- if (! info) {
600
- context.method = "throw";
601
- context.arg = new TypeError("iterator result is not an object");
602
- context.delegate = null;
603
- return ContinueSentinel;
604
- }
605
-
606
- if (info.done) {
607
- // Assign the result of the finished delegate to the temporary
608
- // variable specified by delegate.resultName (see delegateYield).
609
- context[delegate.resultName] = info.value;
610
-
611
- // Resume execution at the desired location (see delegateYield).
612
- context.next = delegate.nextLoc;
613
-
614
- // If context.method was "throw" but the delegate handled the
615
- // exception, let the outer generator proceed normally. If
616
- // context.method was "next", forget context.arg since it has been
617
- // "consumed" by the delegate iterator. If context.method was
618
- // "return", allow the original .return call to continue in the
619
- // outer generator.
620
- if (context.method !== "return") {
621
- context.method = "next";
622
- context.arg = undefined$1;
623
- }
624
-
625
- } else {
626
- // Re-yield the result returned by the delegate method.
627
- return info;
628
- }
629
-
630
- // The delegate iterator is finished, so forget it and continue with
631
- // the outer generator.
632
- context.delegate = null;
633
- return ContinueSentinel;
634
- }
635
-
636
- // Define Generator.prototype.{next,throw,return} in terms of the
637
- // unified ._invoke helper method.
638
- defineIteratorMethods(Gp);
639
-
640
- define(Gp, toStringTagSymbol, "Generator");
641
-
642
- // A Generator should always return itself as the iterator object when the
643
- // @@iterator function is called on it. Some browsers' implementations of the
644
- // iterator prototype chain incorrectly implement this, causing the Generator
645
- // object to not be returned from this call. This ensures that doesn't happen.
646
- // See https://github.com/facebook/regenerator/issues/274 for more details.
647
- Gp[iteratorSymbol] = function() {
648
- return this;
649
- };
650
-
651
- Gp.toString = function() {
652
- return "[object Generator]";
653
- };
654
-
655
- function pushTryEntry(locs) {
656
- var entry = { tryLoc: locs[0] };
657
-
658
- if (1 in locs) {
659
- entry.catchLoc = locs[1];
660
- }
661
-
662
- if (2 in locs) {
663
- entry.finallyLoc = locs[2];
664
- entry.afterLoc = locs[3];
665
- }
666
-
667
- this.tryEntries.push(entry);
668
- }
669
-
670
- function resetTryEntry(entry) {
671
- var record = entry.completion || {};
672
- record.type = "normal";
673
- delete record.arg;
674
- entry.completion = record;
675
- }
676
-
677
- function Context(tryLocsList) {
678
- // The root entry object (effectively a try statement without a catch
679
- // or a finally block) gives us a place to store values thrown from
680
- // locations where there is no enclosing try statement.
681
- this.tryEntries = [{ tryLoc: "root" }];
682
- tryLocsList.forEach(pushTryEntry, this);
683
- this.reset(true);
684
- }
685
-
686
- exports.keys = function(object) {
687
- var keys = [];
688
- for (var key in object) {
689
- keys.push(key);
690
- }
691
- keys.reverse();
692
-
693
- // Rather than returning an object with a next method, we keep
694
- // things simple and return the next function itself.
695
- return function next() {
696
- while (keys.length) {
697
- var key = keys.pop();
698
- if (key in object) {
699
- next.value = key;
700
- next.done = false;
701
- return next;
702
- }
703
- }
704
-
705
- // To avoid creating an additional object, we just hang the .value
706
- // and .done properties off the next function object itself. This
707
- // also ensures that the minifier will not anonymize the function.
708
- next.done = true;
709
- return next;
710
- };
711
- };
712
-
713
- function values(iterable) {
714
- if (iterable) {
715
- var iteratorMethod = iterable[iteratorSymbol];
716
- if (iteratorMethod) {
717
- return iteratorMethod.call(iterable);
718
- }
719
-
720
- if (typeof iterable.next === "function") {
721
- return iterable;
722
- }
723
-
724
- if (!isNaN(iterable.length)) {
725
- var i = -1, next = function next() {
726
- while (++i < iterable.length) {
727
- if (hasOwn.call(iterable, i)) {
728
- next.value = iterable[i];
729
- next.done = false;
730
- return next;
731
- }
732
- }
733
-
734
- next.value = undefined$1;
735
- next.done = true;
736
-
737
- return next;
738
- };
739
-
740
- return next.next = next;
741
- }
742
- }
743
-
744
- // Return an iterator with no values.
745
- return { next: doneResult };
746
- }
747
- exports.values = values;
748
-
749
- function doneResult() {
750
- return { value: undefined$1, done: true };
751
- }
752
-
753
- Context.prototype = {
754
- constructor: Context,
755
-
756
- reset: function(skipTempReset) {
757
- this.prev = 0;
758
- this.next = 0;
759
- // Resetting context._sent for legacy support of Babel's
760
- // function.sent implementation.
761
- this.sent = this._sent = undefined$1;
762
- this.done = false;
763
- this.delegate = null;
764
-
765
- this.method = "next";
766
- this.arg = undefined$1;
767
-
768
- this.tryEntries.forEach(resetTryEntry);
769
-
770
- if (!skipTempReset) {
771
- for (var name in this) {
772
- // Not sure about the optimal order of these conditions:
773
- if (name.charAt(0) === "t" &&
774
- hasOwn.call(this, name) &&
775
- !isNaN(+name.slice(1))) {
776
- this[name] = undefined$1;
777
- }
778
- }
779
- }
780
- },
781
-
782
- stop: function() {
783
- this.done = true;
784
-
785
- var rootEntry = this.tryEntries[0];
786
- var rootRecord = rootEntry.completion;
787
- if (rootRecord.type === "throw") {
788
- throw rootRecord.arg;
789
- }
790
-
791
- return this.rval;
792
- },
793
-
794
- dispatchException: function(exception) {
795
- if (this.done) {
796
- throw exception;
797
- }
798
-
799
- var context = this;
800
- function handle(loc, caught) {
801
- record.type = "throw";
802
- record.arg = exception;
803
- context.next = loc;
804
-
805
- if (caught) {
806
- // If the dispatched exception was caught by a catch block,
807
- // then let that catch block handle the exception normally.
808
- context.method = "next";
809
- context.arg = undefined$1;
810
- }
811
-
812
- return !! caught;
813
- }
814
-
815
- for (var i = this.tryEntries.length - 1; i >= 0; --i) {
816
- var entry = this.tryEntries[i];
817
- var record = entry.completion;
818
-
819
- if (entry.tryLoc === "root") {
820
- // Exception thrown outside of any try block that could handle
821
- // it, so set the completion value of the entire function to
822
- // throw the exception.
823
- return handle("end");
824
- }
825
-
826
- if (entry.tryLoc <= this.prev) {
827
- var hasCatch = hasOwn.call(entry, "catchLoc");
828
- var hasFinally = hasOwn.call(entry, "finallyLoc");
829
-
830
- if (hasCatch && hasFinally) {
831
- if (this.prev < entry.catchLoc) {
832
- return handle(entry.catchLoc, true);
833
- } else if (this.prev < entry.finallyLoc) {
834
- return handle(entry.finallyLoc);
835
- }
836
-
837
- } else if (hasCatch) {
838
- if (this.prev < entry.catchLoc) {
839
- return handle(entry.catchLoc, true);
840
- }
841
-
842
- } else if (hasFinally) {
843
- if (this.prev < entry.finallyLoc) {
844
- return handle(entry.finallyLoc);
845
- }
846
-
847
- } else {
848
- throw new Error("try statement without catch or finally");
849
- }
850
- }
851
- }
852
- },
853
-
854
- abrupt: function(type, arg) {
855
- for (var i = this.tryEntries.length - 1; i >= 0; --i) {
856
- var entry = this.tryEntries[i];
857
- if (entry.tryLoc <= this.prev &&
858
- hasOwn.call(entry, "finallyLoc") &&
859
- this.prev < entry.finallyLoc) {
860
- var finallyEntry = entry;
861
- break;
862
- }
863
- }
864
-
865
- if (finallyEntry &&
866
- (type === "break" ||
867
- type === "continue") &&
868
- finallyEntry.tryLoc <= arg &&
869
- arg <= finallyEntry.finallyLoc) {
870
- // Ignore the finally entry if control is not jumping to a
871
- // location outside the try/catch block.
872
- finallyEntry = null;
873
- }
874
-
875
- var record = finallyEntry ? finallyEntry.completion : {};
876
- record.type = type;
877
- record.arg = arg;
878
-
879
- if (finallyEntry) {
880
- this.method = "next";
881
- this.next = finallyEntry.finallyLoc;
882
- return ContinueSentinel;
883
- }
884
-
885
- return this.complete(record);
886
- },
887
-
888
- complete: function(record, afterLoc) {
889
- if (record.type === "throw") {
890
- throw record.arg;
891
- }
892
-
893
- if (record.type === "break" ||
894
- record.type === "continue") {
895
- this.next = record.arg;
896
- } else if (record.type === "return") {
897
- this.rval = this.arg = record.arg;
898
- this.method = "return";
899
- this.next = "end";
900
- } else if (record.type === "normal" && afterLoc) {
901
- this.next = afterLoc;
902
- }
903
-
904
- return ContinueSentinel;
905
- },
906
-
907
- finish: function(finallyLoc) {
908
- for (var i = this.tryEntries.length - 1; i >= 0; --i) {
909
- var entry = this.tryEntries[i];
910
- if (entry.finallyLoc === finallyLoc) {
911
- this.complete(entry.completion, entry.afterLoc);
912
- resetTryEntry(entry);
913
- return ContinueSentinel;
914
- }
915
- }
916
- },
917
-
918
- "catch": function(tryLoc) {
919
- for (var i = this.tryEntries.length - 1; i >= 0; --i) {
920
- var entry = this.tryEntries[i];
921
- if (entry.tryLoc === tryLoc) {
922
- var record = entry.completion;
923
- if (record.type === "throw") {
924
- var thrown = record.arg;
925
- resetTryEntry(entry);
926
- }
927
- return thrown;
928
- }
929
- }
930
-
931
- // The context.catch method must only be called with a location
932
- // argument that corresponds to a known catch block.
933
- throw new Error("illegal catch attempt");
934
- },
935
-
936
- delegateYield: function(iterable, resultName, nextLoc) {
937
- this.delegate = {
938
- iterator: values(iterable),
939
- resultName: resultName,
940
- nextLoc: nextLoc
941
- };
942
-
943
- if (this.method === "next") {
944
- // Deliberately forget the last sent value so that we don't
945
- // accidentally pass it on to the delegate.
946
- this.arg = undefined$1;
947
- }
948
-
949
- return ContinueSentinel;
950
- }
951
- };
952
-
953
- // Regardless of whether this script is executing as a CommonJS module
954
- // or not, return the runtime object so that we can declare the variable
955
- // regeneratorRuntime in the outer scope, which allows this module to be
956
- // injected easily by `bin/regenerator --include-runtime script.js`.
957
- return exports;
958
-
959
- }(
960
- // If this script is executing as a CommonJS module, use module.exports
961
- // as the regeneratorRuntime namespace. Otherwise create a new empty
962
- // object. Either way, the resulting object will be used to initialize
963
- // the regeneratorRuntime variable at the top of this file.
964
- module.exports
965
- ));
966
-
967
- try {
968
- regeneratorRuntime = runtime;
969
- } catch (accidentalStrictMode) {
970
- // This module should not be running in strict mode, so the above
971
- // assignment should always work unless something is misconfigured. Just
972
- // in case runtime.js accidentally runs in strict mode, we can escape
973
- // strict mode using a global Function call. This could conceivably fail
974
- // if a Content Security Policy forbids using Function, but in that case
975
- // the proper solution is to fix the accidental strict mode problem. If
976
- // you've misconfigured your bundler to force strict mode and applied a
977
- // CSP to forbid Function, and you're not willing to fix either of those
978
- // problems, please detail your unique predicament in a GitHub issue.
979
- Function("r", "regeneratorRuntime = r")(runtime);
980
- }
981
- });
982
-
983
- function createEventSource(config) {
984
- var commandHandlers = config.commandHandlers,
985
- _config$eventHandlers = config.eventHandlers,
986
- eventHandlers = _config$eventHandlers === void 0 ? [] : _config$eventHandlers,
987
- _config$projectors = config.projectors,
988
- projectors = _config$projectors === void 0 ? [] : _config$projectors,
989
- storePromise = config.store;
990
- var startupPromises = [];
991
- var api = {
992
- dispatch: function dispatch(command) {
993
- return _asyncToGenerator( /*#__PURE__*/runtime_1.mark(function _callee() {
994
- var handle;
995
- return runtime_1.wrap(function _callee$(_context) {
996
- while (1) {
997
- switch (_context.prev = _context.next) {
998
- case 0:
999
- if (commandHandlers[command.type] === undefined) {
1000
- abort("There is no command handler for the \"" + command.type + "\" command");
1001
- }
1002
-
1003
- handle = commandHandlers[command.type];
1004
- _context.next = 4;
1005
- return handle(command, api);
1006
-
1007
- case 4:
1008
- return _context.abrupt("return", command);
1009
-
1010
- case 5:
1011
- case "end":
1012
- return _context.stop();
1013
- }
1014
- }
1015
- }, _callee);
1016
- }))();
1017
- },
1018
- loadEvents: function loadEvents() {
1019
- return _asyncToGenerator( /*#__PURE__*/runtime_1.mark(function _callee2() {
1020
- var store;
1021
- return runtime_1.wrap(function _callee2$(_context2) {
1022
- while (1) {
1023
- switch (_context2.prev = _context2.next) {
1024
- case 0:
1025
- _context2.next = 2;
1026
- return storePromise;
1027
-
1028
- case 2:
1029
- store = _context2.sent;
1030
- _context2.next = 5;
1031
- return store.loadEvents();
1032
-
1033
- case 5:
1034
- return _context2.abrupt("return", _context2.sent);
1035
-
1036
- case 6:
1037
- case "end":
1038
- return _context2.stop();
1039
- }
1040
- }
1041
- }, _callee2);
1042
- }))();
1043
- },
1044
- load: function load(aggregate, aggregateId) {
1045
- return _asyncToGenerator( /*#__PURE__*/runtime_1.mark(function _callee3() {
1046
- var store, events;
1047
- return runtime_1.wrap(function _callee3$(_context3) {
1048
- while (1) {
1049
- switch (_context3.prev = _context3.next) {
1050
- case 0:
1051
- _context3.next = 2;
1052
- return storePromise;
1053
-
1054
- case 2:
1055
- store = _context3.sent;
1056
- _context3.next = 5;
1057
- return store.load(aggregateId);
1058
-
1059
- case 5:
1060
- events = _context3.sent;
1061
-
1062
- if (events.length <= 0) {
1063
- abort("Aggregate(" + aggregate.constructor.name + ") with ID(" + aggregateId + ") does not exist.", {
1064
- aggregate: aggregate.constructor.name,
1065
- aggregateId: aggregateId
1066
- });
1067
- }
1068
-
1069
- return _context3.abrupt("return", aggregate.replayEvents(events));
1070
-
1071
- case 8:
1072
- case "end":
1073
- return _context3.stop();
1074
- }
1075
- }
1076
- }, _callee3);
1077
- }))();
1078
- },
1079
- persist: function persist(aggregate) {
1080
- return _asyncToGenerator( /*#__PURE__*/runtime_1.mark(function _callee6() {
1081
- var store, events, _loop, _iterator, _step;
1082
-
1083
- return runtime_1.wrap(function _callee6$(_context7) {
1084
- while (1) {
1085
- switch (_context7.prev = _context7.next) {
1086
- case 0:
1087
- _context7.next = 2;
1088
- return Promise.all(startupPromises);
1089
-
1090
- case 2:
1091
- _context7.next = 4;
1092
- return storePromise;
1093
-
1094
- case 4:
1095
- store = _context7.sent;
1096
- // Get all the events that have been produced by the aggregate
1097
- events = aggregate.releaseEvents(); // Let's persist all the events
1098
-
1099
- _context7.next = 8;
1100
- return store.persist(events);
1101
-
1102
- case 8:
1103
- _loop = /*#__PURE__*/runtime_1.mark(function _loop() {
1104
- var event;
1105
- return runtime_1.wrap(function _loop$(_context6) {
1106
- while (1) {
1107
- switch (_context6.prev = _context6.next) {
1108
- case 0:
1109
- event = _step.value;
1110
- _context6.next = 3;
1111
- return Promise.all(projectors.map( /*#__PURE__*/function () {
1112
- var _ref = _asyncToGenerator( /*#__PURE__*/runtime_1.mark(function _callee4(projector) {
1113
- return runtime_1.wrap(function _callee4$(_context4) {
1114
- while (1) {
1115
- switch (_context4.prev = _context4.next) {
1116
- case 0:
1117
- _context4.prev = 0;
1118
- _context4.next = 3;
1119
- return projector.update(event);
1120
-
1121
- case 3:
1122
- _context4.next = 9;
1123
- break;
1124
-
1125
- case 5:
1126
- _context4.prev = 5;
1127
- _context4.t0 = _context4["catch"](0);
1128
- console.error("An error occurred in one of your projections: " + projector.name + ", given an event", _context4.t0.stack.split('\n').map(function (line) {
1129
- return " " + line;
1130
- }).join('\n'));
1131
- throw _context4.t0;
1132
-
1133
- case 9:
1134
- case "end":
1135
- return _context4.stop();
1136
- }
1137
- }
1138
- }, _callee4, null, [[0, 5]]);
1139
- }));
1140
-
1141
- return function (_x) {
1142
- return _ref.apply(this, arguments);
1143
- };
1144
- }()));
1145
-
1146
- case 3:
1147
- _context6.next = 5;
1148
- return Promise.all(eventHandlers.map( /*#__PURE__*/function () {
1149
- var _ref2 = _asyncToGenerator( /*#__PURE__*/runtime_1.mark(function _callee5(eventHandler) {
1150
- return runtime_1.wrap(function _callee5$(_context5) {
1151
- while (1) {
1152
- switch (_context5.prev = _context5.next) {
1153
- case 0:
1154
- _context5.prev = 0;
1155
- _context5.next = 3;
1156
- return eventHandler(event, api);
1157
-
1158
- case 3:
1159
- _context5.next = 9;
1160
- break;
1161
-
1162
- case 5:
1163
- _context5.prev = 5;
1164
- _context5.t0 = _context5["catch"](0);
1165
- console.error("An error occurred in one of your event handlers: " + eventHandler.name + ", given an event", _context5.t0.stack.split('\n').map(function (line) {
1166
- return " " + line;
1167
- }).join('\n'));
1168
- throw _context5.t0;
1169
-
1170
- case 9:
1171
- case "end":
1172
- return _context5.stop();
1173
- }
1174
- }
1175
- }, _callee5, null, [[0, 5]]);
1176
- }));
1177
-
1178
- return function (_x2) {
1179
- return _ref2.apply(this, arguments);
1180
- };
1181
- }()));
1182
-
1183
- case 5:
1184
- case "end":
1185
- return _context6.stop();
1186
- }
1187
- }
1188
- }, _loop);
1189
- });
1190
- _iterator = _createForOfIteratorHelperLoose(events);
1191
-
1192
- case 10:
1193
- if ((_step = _iterator()).done) {
1194
- _context7.next = 14;
1195
- break;
1196
- }
1197
-
1198
- return _context7.delegateYield(_loop(), "t0", 12);
1199
-
1200
- case 12:
1201
- _context7.next = 10;
1202
- break;
1203
-
1204
- case 14:
1205
- case "end":
1206
- return _context7.stop();
1207
- }
1208
- }
1209
- }, _callee6);
1210
- }))();
1211
- },
1212
- loadPersist: function loadPersist(aggregate, aggregateId, handle) {
1213
- var _this = this;
1214
-
1215
- return _asyncToGenerator( /*#__PURE__*/runtime_1.mark(function _callee7() {
1216
- return runtime_1.wrap(function _callee7$(_context8) {
1217
- while (1) {
1218
- switch (_context8.prev = _context8.next) {
1219
- case 0:
1220
- _context8.next = 2;
1221
- return _this.load(aggregate, aggregateId);
1222
-
1223
- case 2:
1224
- _context8.next = 4;
1225
- return handle(aggregate);
1226
-
1227
- case 4:
1228
- return _context8.abrupt("return", _this.persist(aggregate));
1229
-
1230
- case 5:
1231
- case "end":
1232
- return _context8.stop();
1233
- }
1234
- }
1235
- }, _callee7);
1236
- }))();
1237
- }
1238
- }; // Run all projection initializers
1239
-
1240
- for (var _iterator2 = _createForOfIteratorHelperLoose(projectors), _step2; !(_step2 = _iterator2()).done;) {
1241
- var projector = _step2.value;
1242
- startupPromises.push(projector.init(api));
1243
- }
1244
-
1245
- return api;
1246
- }
1247
-
1248
- function createEventMapper(mapper) {
1249
- return function (event, es) {
1250
- var _mapper$event$eventNa;
1251
-
1252
- return (_mapper$event$eventNa = mapper[event.eventName]) == null ? void 0 : _mapper$event$eventNa.call(mapper, event, es);
1253
- };
1254
- }
1255
-
1256
- var instances = /*#__PURE__*/new WeakMap();
1257
- /**
1258
- * This code allows us to store secret/private values for objects. In JavaScript
1259
- * you can't really store secrets on an object. There is this convention with
1260
- * for naming a variable `this._somePrivateField` but that is still accessible.
1261
- *
1262
- * Another trick you can use is to use symbols, but if you get access to the
1263
- * symbol, you can still retrieve the data.
1264
- *
1265
- * This approach uses a WeakMap. The WeakMap has a key which should be an
1266
- * object, so that you can store avlues specifically for this reference.
1267
- */
1268
-
1269
- function set(key, data) {
1270
- if (instances.has(key)) {
1271
- var original = instances.get(key);
1272
-
1273
- for (var _key in data) {
1274
- original[_key] = data[_key];
1275
- }
1276
- } else {
1277
- instances.set(key, data);
1278
- }
1279
- }
1280
- function get(key) {
1281
- return instances.get(key);
1282
- }
1283
-
1284
- var State;
1285
-
1286
- (function (State) {
1287
- State[State["IDLE"] = 0] = "IDLE";
1288
- State[State["STARTED"] = 1] = "STARTED";
1289
- })(State || (State = {}));
1290
-
1291
- var Queue = /*#__PURE__*/function () {
1292
- function Queue() {
1293
- set(this, {
1294
- jobs: [],
1295
- state: State.IDLE
1296
- });
1297
- }
1298
-
1299
- var _proto = Queue.prototype;
1300
-
1301
- _proto.start = /*#__PURE__*/function () {
1302
- var _start = /*#__PURE__*/_asyncToGenerator( /*#__PURE__*/runtime_1.mark(function _callee() {
1303
- var _get, state, jobs, job, settled;
1304
-
1305
- return runtime_1.wrap(function _callee$(_context) {
1306
- while (1) {
1307
- switch (_context.prev = _context.next) {
1308
- case 0:
1309
- _get = get(this), state = _get.state, jobs = _get.jobs;
1310
-
1311
- if (!(state === State.STARTED || jobs.length <= 0)) {
1312
- _context.next = 3;
1313
- break;
1314
- }
1315
-
1316
- return _context.abrupt("return");
1317
-
1318
- case 3:
1319
- set(this, {
1320
- state: State.STARTED
1321
- });
1322
-
1323
- case 4:
1324
- if (!(jobs.length > 0)) {
1325
- _context.next = 11;
1326
- break;
1327
- }
1328
-
1329
- job = jobs.shift(); // Handle the job
1330
-
1331
- settled = Promise.resolve().then(job.handle); // Resolve / reject the job promise wrapper
1332
-
1333
- _context.next = 9;
1334
- return settled.then(job.resolve, job.reject);
1335
-
1336
- case 9:
1337
- _context.next = 4;
1338
- break;
1339
-
1340
- case 11:
1341
- set(this, {
1342
- state: State.IDLE
1343
- });
1344
-
1345
- case 12:
1346
- case "end":
1347
- return _context.stop();
1348
- }
1349
- }
1350
- }, _callee, this);
1351
- }));
1352
-
1353
- function start() {
1354
- return _start.apply(this, arguments);
1355
- }
1356
-
1357
- return start;
1358
- }();
1359
-
1360
- _proto.push = function push(handle) {
1361
- var _this = this;
1362
-
1363
- return new Promise(function (resolve, reject) {
1364
- var _get2 = get(_this),
1365
- jobs = _get2.jobs;
1366
-
1367
- jobs.push({
1368
- handle: handle,
1369
- resolve: resolve,
1370
- reject: reject
1371
- });
1372
- setImmediate(function () {
1373
- return _this.start();
1374
- });
1375
- });
1376
- };
1377
-
1378
- _createClass(Queue, [{
1379
- key: "length",
1380
- get: function get$1() {
1381
- return get(this).jobs.length;
1382
- }
1383
- }]);
1384
-
1385
- return Queue;
1386
- }();
1387
-
1388
- function noop() {}
1389
-
1390
- function createProjector(name, mapper, initializer) {
1391
- if (initializer === void 0) {
1392
- initializer = noop;
1393
- }
1394
-
1395
- var q = new Queue();
1396
- return {
1397
- name: name,
1398
- init: function init(es) {
1399
- return _asyncToGenerator( /*#__PURE__*/runtime_1.mark(function _callee() {
1400
- var initialized, events;
1401
- return runtime_1.wrap(function _callee$(_context) {
1402
- while (1) {
1403
- switch (_context.prev = _context.next) {
1404
- case 0:
1405
- // Let's run the initializer
1406
- initialized = q.push(initializer); // Re-build the projection from scratch
1407
-
1408
- _context.next = 3;
1409
- return es.loadEvents();
1410
-
1411
- case 3:
1412
- events = _context.sent;
1413
- _context.next = 6;
1414
- return Promise.all(events.map(function (event) {
1415
- return q.push(function () {
1416
- var _mapper$event$eventNa;
1417
-
1418
- return (_mapper$event$eventNa = mapper[event.eventName]) == null ? void 0 : _mapper$event$eventNa.call(mapper, event);
1419
- });
1420
- }));
1421
-
1422
- case 6:
1423
- _context.next = 8;
1424
- return initialized;
1425
-
1426
- case 8:
1427
- case "end":
1428
- return _context.stop();
1429
- }
1430
- }
1431
- }, _callee);
1432
- }))();
1433
- },
1434
- update: function update(event) {
1435
- return q.push(function () {
1436
- var _mapper$event$eventNa2;
1437
-
1438
- return (_mapper$event$eventNa2 = mapper[event.eventName]) == null ? void 0 : _mapper$event$eventNa2.call(mapper, event);
1439
- });
1440
- }
1441
- };
1442
- }
1443
-
1444
- var YAMLIFY_OPTIONS = {
1445
- indent: ' ',
1446
- colors: {
1447
- date: identity,
1448
- error: identity,
1449
- symbol: identity,
1450
- string: identity,
1451
- number: identity,
1452
- "boolean": identity,
1453
- "null": identity,
1454
- undefined: identity
1455
- }
1456
- };
1457
-
1458
- function identity(input) {
1459
- return input;
1460
- }
1461
-
1462
- function objectToYaml(object) {
1463
- if (object instanceof Error) {
1464
- return objectToYaml(_extends({}, object));
1465
- }
1466
-
1467
- return yamlify(object, YAMLIFY_OPTIONS).split('\n').slice(1).join('\n');
1468
- }
1469
-
1470
- var PLACEHOLDER = /*#__PURE__*/Symbol('__placeholder__');
1471
- var info = {
1472
- usedTestEventStoreInTest: false,
1473
- calledThenHandler: false
1474
- };
1475
-
1476
- if (process.env.NODE_ENV === 'test') {
1477
- beforeEach(function () {
1478
- info.usedTestEventStoreInTest = false;
1479
- info.calledThenHandler = false;
1480
- });
1481
- afterEach(function () {
1482
- if (info.usedTestEventStoreInTest && !info.calledThenHandler) {
1483
- abort('It seems like you used `createTestEventStore()`\nwithout using the `await then([expected, events, go, here, ...])`');
1484
- }
1485
- });
1486
- }
1487
-
1488
- function cleanThrow(cb, fn) {
1489
- try {
1490
- return cb();
1491
- } catch (e) {
1492
- if (Error.captureStackTrace) Error.captureStackTrace(e, fn);
1493
- throw e;
1494
- }
1495
- }
1496
-
1497
- function createTestEventStore(commandHandlers, projectors) {
1498
- if (projectors === void 0) {
1499
- projectors = [];
1500
- }
1501
-
1502
- var db = [];
1503
- var producedEvents = [];
1504
- info.usedTestEventStoreInTest = true;
1505
-
1506
- function createTestRecordingProjector() {
1507
- return {
1508
- name: 'test-recording-projector',
1509
- init: function init() {
1510
- db.splice(0);
1511
- },
1512
- update: function update(event) {
1513
- producedEvents.push(event);
1514
- }
1515
- };
1516
- }
1517
-
1518
- var es = createEventSource({
1519
- store: {
1520
- load: function load(aggregateId) {
1521
- return _asyncToGenerator( /*#__PURE__*/runtime_1.mark(function _callee() {
1522
- return runtime_1.wrap(function _callee$(_context) {
1523
- while (1) {
1524
- switch (_context.prev = _context.next) {
1525
- case 0:
1526
- return _context.abrupt("return", db.filter(function (event) {
1527
- return event.aggregateId === aggregateId;
1528
- }));
1529
-
1530
- case 1:
1531
- case "end":
1532
- return _context.stop();
1533
- }
1534
- }
1535
- }, _callee);
1536
- }))();
1537
- },
1538
- loadEvents: function loadEvents() {
1539
- return db;
1540
- },
1541
- persist: function persist(events) {
1542
- db.push.apply(db, events);
1543
- }
1544
- },
1545
- commandHandlers: commandHandlers,
1546
- projectors: [].concat(projectors, [createTestRecordingProjector()])
1547
- });
1548
- var caughtError;
1549
- var returnValue = {
1550
- ___: PLACEHOLDER,
1551
- given: function given(events) {
1552
- return _asyncToGenerator( /*#__PURE__*/runtime_1.mark(function _callee2() {
1553
- return runtime_1.wrap(function _callee2$(_context2) {
1554
- while (1) {
1555
- switch (_context2.prev = _context2.next) {
1556
- case 0:
1557
- if (events === void 0) {
1558
- events = [];
1559
- }
1560
-
1561
- db.push.apply(db, events);
1562
-
1563
- case 2:
1564
- case "end":
1565
- return _context2.stop();
1566
- }
1567
- }
1568
- }, _callee2);
1569
- }))();
1570
- },
1571
- when: function when(command) {
1572
- return _asyncToGenerator( /*#__PURE__*/runtime_1.mark(function _callee3() {
1573
- return runtime_1.wrap(function _callee3$(_context3) {
1574
- while (1) {
1575
- switch (_context3.prev = _context3.next) {
1576
- case 0:
1577
- _context3.prev = 0;
1578
- _context3.next = 3;
1579
- return es.dispatch(command);
1580
-
1581
- case 3:
1582
- return _context3.abrupt("return", _context3.sent);
1583
-
1584
- case 6:
1585
- _context3.prev = 6;
1586
- _context3.t0 = _context3["catch"](0);
1587
- caughtError = _context3.t0;
1588
- return _context3.abrupt("return", command);
1589
-
1590
- case 10:
1591
- case "end":
1592
- return _context3.stop();
1593
- }
1594
- }
1595
- }, _callee3, null, [[0, 6]]);
1596
- }))();
1597
- },
1598
- then: function then(events) {
1599
- return _asyncToGenerator( /*#__PURE__*/runtime_1.mark(function _callee4() {
1600
- return runtime_1.wrap(function _callee4$(_context4) {
1601
- while (1) {
1602
- switch (_context4.prev = _context4.next) {
1603
- case 0:
1604
- // Mark that we called the then function. If not we probably had a
1605
- // successful test that actually didn't test anything!
1606
- info.calledThenHandler = true; // We expect errors, so let's verify the error
1607
-
1608
- if (!(events instanceof Error)) {
1609
- _context4.next = 4;
1610
- break;
1611
- }
1612
-
1613
- cleanThrow(function () {
1614
- return expect(caughtError).toEqual(events);
1615
- }, returnValue.then);
1616
- return _context4.abrupt("return");
1617
-
1618
- case 4:
1619
- if (!caughtError) {
1620
- _context4.next = 7;
1621
- break;
1622
- }
1623
-
1624
- if (Object.keys(caughtError).length > 0) {
1625
- caughtError.message = ['With properties:', "\n" + objectToYaml(caughtError) + "\n\n---\n\n"].join('\n');
1626
- }
1627
-
1628
- throw caughtError;
1629
-
1630
- case 7:
1631
- cleanThrow(function () {
1632
- // Verify that the actual events and expected events have the same length
1633
- expect(events).toHaveLength(producedEvents.length); // Verify each individual event
1634
-
1635
- events.forEach(function (event, index) {
1636
- var _producedEvents$index = producedEvents[index],
1637
- aggregateId = _producedEvents$index.aggregateId,
1638
- eventName = _producedEvents$index.eventName,
1639
- payload = _producedEvents$index.payload;
1640
- expect(event.aggregateId).toEqual(aggregateId);
1641
- expect(event.eventName).toEqual(eventName);
1642
-
1643
- if (event.payload === null || event.payload === undefined) {
1644
- expect(event.payload).toEqual(payload);
1645
- }
1646
-
1647
- for (var key in event.payload) {
1648
- var value = event.payload[key];
1649
-
1650
- if (value === PLACEHOLDER) {
1651
- expect(payload).toHaveProperty(key);
1652
- expect(payload[key]).toBeDefined();
1653
- } else {
1654
- expect(payload[key]).toEqual(value);
1655
- }
1656
- }
1657
- });
1658
- }, returnValue.then);
1659
-
1660
- case 8:
1661
- case "end":
1662
- return _context4.stop();
1663
- }
1664
- }
1665
- }, _callee4);
1666
- }))();
1667
- }
1668
- };
1669
- return returnValue;
1670
- }
1671
-
1672
- export { Aggregate, Command, Event, abort, createEventMapper, createEventSource, createProjector, createTestEventStore };
1673
- //# sourceMappingURL=event-source.esm.js.map