UNPKG

179 kBJavaScriptView Raw
1(function (global, factory) {
2typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :
3typeof define === 'function' && define.amd ? define(['exports'], factory) :
4(global = global || self, factory(global.Bacon = {}));
5}(this, (function (exports) { 'use strict';
6
7/*! *****************************************************************************
8Copyright (c) Microsoft Corporation. All rights reserved.
9Licensed under the Apache License, Version 2.0 (the "License"); you may not use
10this file except in compliance with the License. You may obtain a copy of the
11License at http://www.apache.org/licenses/LICENSE-2.0
12
13THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
14KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
15WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
16MERCHANTABLITY OR NON-INFRINGEMENT.
17
18See the Apache Version 2.0 License for specific language governing permissions
19and limitations under the License.
20***************************************************************************** */
21/* global Reflect, Promise */
22
23var extendStatics = function(d, b) {
24 extendStatics = Object.setPrototypeOf ||
25 ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
26 function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
27 return extendStatics(d, b);
28};
29
30function __extends(d, b) {
31 extendStatics(d, b);
32 function __() { this.constructor = d; }
33 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
34}
35
36function __spreadArrays() {
37 for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length;
38 for (var r = Array(s), k = 0, i = 0; i < il; i++)
39 for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++)
40 r[k] = a[j];
41 return r;
42}
43
44/** @hidden */
45function nop() { }
46/** @hidden */
47var isArray = Array.isArray || function (xs) { return xs instanceof Array; };
48/** @hidden */
49function isObservable(x) {
50 return x && x._isObservable;
51}
52
53/** @hidden */
54function all(xs, f) {
55 for (var i = 0, x; i < xs.length; i++) {
56 x = xs[i];
57 if (!f(x)) {
58 return false;
59 }
60 }
61 return true;
62}
63/** @hidden */
64function always(x) { return function () { return x; }; }
65/** @hidden */
66function any(xs, f) {
67 for (var i = 0, x; i < xs.length; i++) {
68 x = xs[i];
69 if (f(x)) {
70 return true;
71 }
72 }
73 return false;
74}
75/** @hidden */
76function bind(fn, me) {
77 return function () { return fn.apply(me, arguments); };
78}
79/** @hidden */
80function contains(xs, x) { return indexOf(xs, x) !== -1; }
81/** @hidden */
82function each(xs, f) {
83 for (var key in xs) {
84 if (Object.prototype.hasOwnProperty.call(xs, key)) {
85 var value = xs[key];
86 f(key, value);
87 }
88 }
89}
90/** @hidden */
91function empty(xs) { return xs.length === 0; }
92/** @hidden */
93function filter(f, xs) {
94 var filtered = [];
95 for (var i = 0, x; i < xs.length; i++) {
96 x = xs[i];
97 if (f(x)) {
98 filtered.push(x);
99 }
100 }
101 return filtered;
102}
103/** @hidden */
104function flatMap(f, xs) {
105 return fold(xs, [], (function (ys, x) {
106 return ys.concat(f(x));
107 }));
108}
109/** @hidden */
110function flip(f) {
111 return function (a, b) { return f(b, a); };
112}
113/** @hidden */
114function fold(xs, seed, f) {
115 for (var i = 0, x; i < xs.length; i++) {
116 x = xs[i];
117 seed = f(seed, x);
118 }
119 return seed;
120}
121/** @hidden */
122function head(xs) {
123 return xs[0];
124}
125/** @hidden */
126function id(x) { return x; }
127/** @hidden */
128function indexOfDefault(xs, x) { return xs.indexOf(x); }
129/** @hidden */
130function indexOfFallback(xs, x) {
131 for (var i = 0, y; i < xs.length; i++) {
132 y = xs[i];
133 if (x === y) {
134 return i;
135 }
136 }
137 return -1;
138}
139/** @hidden */
140var indexOf = Array.prototype.indexOf ? indexOfDefault : indexOfFallback;
141/** @hidden */
142function indexWhere(xs, f) {
143 for (var i = 0, y; i < xs.length; i++) {
144 y = xs[i];
145 if (f(y)) {
146 return i;
147 }
148 }
149 return -1;
150}
151/** @hidden */
152function isFunction(f) { return typeof f === "function"; }
153/** @hidden */
154function last(xs) { return xs[xs.length - 1]; }
155/** @hidden */
156function map(f, xs) {
157 var result = [];
158 for (var i = 0, x; i < xs.length; i++) {
159 x = xs[i];
160 result.push(f(x));
161 }
162 return result;
163}
164/** @hidden */
165function negate(f) { return function (x) { return !f(x); }; }
166/** @hidden */
167function remove(x, xs) {
168 var i = indexOf(xs, x);
169 if (i >= 0) {
170 return xs.splice(i, 1);
171 }
172}
173/** @hidden */
174function tail(xs) {
175 return xs.slice(1, xs.length);
176}
177/** @hidden */
178function toArray(xs) { return (isArray(xs) ? xs : [xs]); }
179/** @hidden */
180function toFunction(f) {
181 if (typeof f == "function") {
182 return f;
183 }
184 return function (x) { return f; };
185}
186/** @hidden */
187function toString(obj) {
188 var hasProp = {}.hasOwnProperty;
189 try {
190 recursionDepth++;
191 if (obj == null) {
192 return "undefined";
193 }
194 else if (isFunction(obj)) {
195 return "function";
196 }
197 else if (isArray(obj)) {
198 if (recursionDepth > 5) {
199 return "[..]";
200 }
201 return "[" + map(toString, obj).toString() + "]";
202 }
203 else if (((obj != null ? obj.toString : void 0) != null) && obj.toString !== Object.prototype.toString) {
204 return obj.toString();
205 }
206 else if (typeof obj === "object") {
207 if (recursionDepth > 5) {
208 return "{..}";
209 }
210 var results = [];
211 for (var key in obj) {
212 if (!hasProp.call(obj, key))
213 continue;
214 var value = (function () {
215 try {
216 return obj[key];
217 }
218 catch (error) {
219 return error;
220 }
221 })();
222 results.push(toString(key) + ":" + toString(value));
223 }
224 return "{" + results + "}";
225 }
226 else {
227 return obj;
228 }
229 }
230 finally {
231 recursionDepth--;
232 }
233}
234/** @hidden */
235function without(x, xs) {
236 return filter((function (y) { return y !== x; }), xs);
237}
238var _ = {
239 indexOf: indexOf,
240 indexWhere: indexWhere,
241 head: head,
242 always: always,
243 negate: negate,
244 empty: empty,
245 tail: tail,
246 filter: filter,
247 map: map,
248 each: each,
249 toArray: toArray,
250 contains: contains,
251 id: id,
252 last: last,
253 all: all,
254 any: any,
255 without: without,
256 remove: remove,
257 fold: fold,
258 flatMap: flatMap,
259 bind: bind,
260 isFunction: isFunction,
261 toFunction: toFunction,
262 toString: toString
263};
264var recursionDepth = 0;
265
266/**
267 * Reply for "more data, please".
268 */
269var more = undefined;
270/**
271 * Reply for "no more data, please".
272 */
273var noMore = "<no-more>";
274
275/** @hidden */
276function assert(message, condition) {
277 if (!condition) {
278 throw new Error(message);
279 }
280}
281/** @hidden */
282function assertEventStream(event) {
283 if (!(event != null ? event._isEventStream : void 0)) {
284 throw new Error("not an EventStream : " + event);
285 }
286}
287/** @hidden */
288function assertObservable(observable) {
289 if (!(observable != null ? observable._isObservable : void 0)) {
290 throw new Error("not an Observable : " + observable);
291 }
292}
293/** @hidden */
294function assertFunction(f) {
295 return assert("not a function : " + f, _.isFunction(f));
296}
297/** @hidden */
298function assertArray(xs) {
299 if (!isArray(xs)) {
300 throw new Error("not an array : " + xs);
301 }
302}
303/** @hidden */
304function assertNoArguments(args) {
305 return assert("no arguments supported", args.length === 0);
306}
307
308/** @hidden */
309var defaultScheduler = {
310 setTimeout: function (f, d) { return setTimeout(f, d); },
311 setInterval: function (f, i) { return setInterval(f, i); },
312 clearInterval: function (id) { return clearInterval(id); },
313 clearTimeout: function (id) { return clearTimeout(id); },
314 now: function () { return new Date().getTime(); }
315};
316var GlobalScheduler = {
317 scheduler: defaultScheduler
318};
319function getScheduler() {
320 return GlobalScheduler.scheduler;
321}
322function setScheduler(newScheduler) {
323 GlobalScheduler.scheduler = newScheduler;
324}
325
326var rootEvent = undefined;
327var waiterObs = [];
328var waiters = {};
329var aftersStack = [];
330var aftersStackHeight = 0;
331var flushed = {};
332var processingAfters = false;
333function toString$1() {
334 return _.toString({ rootEvent: rootEvent, processingAfters: processingAfters, waiterObs: waiterObs, waiters: waiters, aftersStack: aftersStack, aftersStackHeight: aftersStackHeight, flushed: flushed });
335}
336function ensureStackHeight(h) {
337 if (h <= aftersStackHeight)
338 return;
339 if (!aftersStack[h - 1]) {
340 aftersStack[h - 1] = [[], 0];
341 }
342 aftersStackHeight = h;
343}
344function isInTransaction() {
345 return rootEvent !== undefined;
346}
347function soonButNotYet(obs, f) {
348 if (rootEvent) {
349 // If in transaction -> perform within transaction
350 //console.log('in tx')
351 whenDoneWith(obs, f);
352 }
353 else {
354 // Otherwise -> perform with timeout
355 //console.log('with timeout')
356 GlobalScheduler.scheduler.setTimeout(f, 0);
357 }
358}
359function afterTransaction(obs, f) {
360 if (rootEvent || processingAfters) {
361 ensureStackHeight(1);
362 var stackIndexForThisObs = 0;
363 while (stackIndexForThisObs < aftersStackHeight - 1) {
364 if (containsObs(obs, aftersStack[stackIndexForThisObs][0])) {
365 // this observable is already being processed at this stack index -> use this index
366 break;
367 }
368 stackIndexForThisObs++;
369 }
370 var listFromStack = aftersStack[stackIndexForThisObs][0];
371 listFromStack.push([obs, f]);
372 if (!rootEvent) {
373 processAfters(); // wouldn't be called otherwise
374 }
375 }
376 else {
377 return f();
378 }
379}
380function containsObs(obs, aftersList) {
381 for (var i = 0; i < aftersList.length; i++) {
382 if (aftersList[i][0].id == obs.id)
383 return true;
384 }
385 return false;
386}
387function processAfters() {
388 var stackSizeAtStart = aftersStackHeight;
389 if (!stackSizeAtStart)
390 return;
391 var isRoot = !processingAfters;
392 processingAfters = true;
393 try {
394 while (aftersStackHeight >= stackSizeAtStart) { // to prevent sinking to levels started by others
395 var topOfStack = aftersStack[aftersStackHeight - 1];
396 if (!topOfStack)
397 throw new Error("Unexpected stack top: " + topOfStack);
398 var topAfters = topOfStack[0], index = topOfStack[1];
399 if (index < topAfters.length) {
400 var _a = topAfters[index], after = _a[1];
401 topOfStack[1]++; // increase index already here to indicate that this level is being processed
402 ensureStackHeight(aftersStackHeight + 1); // to ensure there's a new level for recursively added afters
403 var callSuccess = false;
404 try {
405 after();
406 callSuccess = true;
407 while (aftersStackHeight > stackSizeAtStart && aftersStack[aftersStackHeight - 1][0].length == 0) {
408 aftersStackHeight--;
409 }
410 }
411 finally {
412 if (!callSuccess) {
413 aftersStack = [];
414 aftersStackHeight = 0; // reset state to prevent stale updates after error
415 }
416 }
417 }
418 else {
419 topOfStack[0] = [];
420 topOfStack[1] = 0; // reset this level
421 break;
422 }
423 }
424 }
425 finally {
426 if (isRoot)
427 processingAfters = false;
428 }
429}
430function whenDoneWith(obs, f) {
431 if (rootEvent) {
432 var obsWaiters = waiters[obs.id];
433 if (obsWaiters === undefined) {
434 obsWaiters = waiters[obs.id] = [f];
435 return waiterObs.push(obs);
436 }
437 else {
438 return obsWaiters.push(f);
439 }
440 }
441 else {
442 return f();
443 }
444}
445function flush() {
446 while (waiterObs.length > 0) {
447 flushWaiters(0, true);
448 }
449 flushed = {};
450}
451function flushWaiters(index, deps) {
452 var obs = waiterObs[index];
453 var obsId = obs.id;
454 var obsWaiters = waiters[obsId];
455 waiterObs.splice(index, 1);
456 delete waiters[obsId];
457 if (deps && waiterObs.length > 0) {
458 flushDepsOf(obs);
459 }
460 for (var i = 0, f; i < obsWaiters.length; i++) {
461 f = obsWaiters[i];
462 f();
463 }
464}
465function flushDepsOf(obs) {
466 if (flushed[obs.id])
467 return;
468 var deps = obs.internalDeps();
469 for (var i = 0, dep; i < deps.length; i++) {
470 dep = deps[i];
471 flushDepsOf(dep);
472 if (waiters[dep.id]) {
473 var index = _.indexOf(waiterObs, dep);
474 flushWaiters(index, false);
475 }
476 }
477 flushed[obs.id] = true;
478}
479function inTransaction(event, context, f, args) {
480 if (rootEvent) {
481 //console.log("in tx")
482 return f.apply(context, args);
483 }
484 else {
485 //console.log("start tx")
486 rootEvent = event;
487 try {
488 var result = f.apply(context, args);
489 //console.log("done with tx")
490 flush();
491 }
492 finally {
493 rootEvent = undefined;
494 processAfters();
495 }
496 return result;
497 }
498}
499function currentEventId() {
500 return rootEvent ? rootEvent.id : undefined;
501}
502function wrappedSubscribe(obs, subscribe, sink) {
503 assertFunction(sink);
504 var unsubd = false;
505 var shouldUnsub = false;
506 var doUnsub = function () {
507 shouldUnsub = true;
508 };
509 var unsub = function () {
510 unsubd = true;
511 doUnsub();
512 };
513 doUnsub = subscribe(function (event) {
514 afterTransaction(obs, function () {
515 if (!unsubd) {
516 var reply = sink(event);
517 if (reply === noMore) {
518 unsub();
519 }
520 }
521 });
522 return more;
523 });
524 if (shouldUnsub) {
525 doUnsub();
526 }
527 return unsub;
528}
529function hasWaiters() { return waiterObs.length > 0; }
530var UpdateBarrier = { toString: toString$1, whenDoneWith: whenDoneWith, hasWaiters: hasWaiters, inTransaction: inTransaction, currentEventId: currentEventId, wrappedSubscribe: wrappedSubscribe, afterTransaction: afterTransaction, soonButNotYet: soonButNotYet, isInTransaction: isInTransaction };
531
532var Desc = /** @class */ (function () {
533 function Desc(context, method, args) {
534 if (args === void 0) { args = []; }
535 /** @hidden */
536 this._isDesc = true;
537 //assert("context missing", context)
538 //assert("method missing", method)
539 //assert("args missing", args)
540 this.context = context;
541 this.method = method;
542 this.args = args;
543 }
544 Desc.prototype.deps = function () {
545 if (!this.cachedDeps) {
546 this.cachedDeps = findDeps([this.context].concat(this.args));
547 }
548 return this.cachedDeps;
549 };
550 Desc.prototype.toString = function () {
551 var args = _.map(_.toString, this.args);
552 return _.toString(this.context) + "." + _.toString(this.method) + "(" + args + ")";
553 };
554 return Desc;
555}());
556/** @hidden */
557function describe(context, method) {
558 var args = [];
559 for (var _i = 2; _i < arguments.length; _i++) {
560 args[_i - 2] = arguments[_i];
561 }
562 var ref = context || method;
563 if (ref && ref._isDesc) {
564 return context || method;
565 }
566 else {
567 return new Desc(context, method, args);
568 }
569}
570/** @hidden */
571function findDeps(x) {
572 if (isArray(x)) {
573 return _.flatMap(findDeps, x);
574 }
575 else if (isObservable(x)) {
576 return [x];
577 }
578 else if ((typeof x !== "undefined" && x !== null) ? x._isSource : undefined) {
579 return [x.obs];
580 }
581 else {
582 return [];
583 }
584}
585
586/** @hidden */
587var nullSink = function () { return more; };
588/** @hidden */
589var nullVoidSink = function () { return more; };
590
591/** @hidden */
592function withStateMachine(initState, f, src) {
593 return src.transform(withStateMachineT(initState, f), new Desc(src, "withStateMachine", [initState, f]));
594}
595function withStateMachineT(initState, f) {
596 var state = initState;
597 return function (event, sink) {
598 var fromF = f(state, event);
599 var newState = fromF[0], outputs = fromF[1];
600 state = newState;
601 var reply = more;
602 for (var i = 0; i < outputs.length; i++) {
603 var output = outputs[i];
604 reply = sink(output);
605 if (reply === noMore) {
606 return reply;
607 }
608 }
609 return reply;
610 };
611}
612
613/** @hidden */
614var Some = /** @class */ (function () {
615 function Some(value) {
616 this._isSome = true;
617 this.isDefined = true;
618 this.value = value;
619 }
620 Some.prototype.getOrElse = function (arg) { return this.value; };
621 Some.prototype.get = function () { return this.value; };
622 Some.prototype.filter = function (f) {
623 if (f(this.value)) {
624 return new Some(this.value);
625 }
626 else {
627 return None;
628 }
629 };
630 Some.prototype.map = function (f) {
631 return new Some(f(this.value));
632 };
633 Some.prototype.forEach = function (f) {
634 f(this.value);
635 };
636 Some.prototype.toArray = function () { return [this.value]; };
637 Some.prototype.inspect = function () { return "Some(" + this.value + ")"; };
638 Some.prototype.toString = function () { return this.inspect(); };
639 return Some;
640}());
641/** @hidden */
642var None = {
643 _isNone: true,
644 getOrElse: function (value) { return value; },
645 get: function () { throw new Error("None.get()"); },
646 filter: function () { return None; },
647 map: function () { return None; },
648 forEach: function () { },
649 isDefined: false,
650 toArray: function () { return []; },
651 inspect: function () { return "None"; },
652 toString: function () { return this.inspect(); }
653};
654function none() { return None; }
655function toOption(v) {
656 if (v && (v._isSome || v._isNone)) {
657 return v;
658 }
659 else {
660 return new Some(v);
661 }
662}
663function isNone(object) {
664 return ((typeof object !== "undefined" && object !== null) ? object._isNone : false);
665}
666
667/** @hidden */
668var eventIdCounter = 0;
669/**
670 * Base class for all events passed through [EventStreams](eventstream.html) and [Properties](property.html).
671 */
672var Event = /** @class */ (function () {
673 function Event() {
674 this.id = ++eventIdCounter;
675 /** @hidden */
676 this.isEvent = true;
677 /** @hidden */
678 this._isEvent = true;
679 this.isEnd = false;
680 this.isInitial = false;
681 this.isNext = false;
682 this.isError = false;
683 this.hasValue = false;
684 }
685 /** @hidden */
686 Event.prototype.filter = function (f) { return true; };
687 /** @hidden */
688 Event.prototype.inspect = function () { return this.toString(); };
689 /** @hidden */
690 Event.prototype.log = function () { return this.toString(); };
691 /** @hidden */
692 Event.prototype.toNext = function () { return this; };
693 return Event;
694}());
695/**
696 * Base class for all [Events](event.html) carrying a value.
697 *
698 * Can be distinguished from other events using [hasValue](../globals.html#hasvalue)
699 **/
700var Value = /** @class */ (function (_super) {
701 __extends(Value, _super);
702 function Value(value) {
703 var _this = _super.call(this) || this;
704 _this.hasValue = true;
705 if (value instanceof Event) {
706 throw new Error$1("Wrapping an event inside other event");
707 }
708 _this.value = value;
709 return _this;
710 }
711 /** @hidden */
712 Value.prototype.fmap = function (f) {
713 return this.apply(f(this.value));
714 };
715 /** @hidden */
716 Value.prototype.filter = function (f) { return f(this.value); };
717 /** @hidden */
718 Value.prototype.toString = function () { return _.toString(this.value); };
719 //toString(): string { return "<value " + this.id + ">" + _.toString(this.value) }
720 /** @hidden */
721 Value.prototype.log = function () { return this.value; };
722 return Value;
723}(Event));
724/**
725 * Indicates a new value in an [EventStream](eventstream.html) or a [Property](property.html).
726 *
727 * Can be distinguished from other events using [isNext](../globals.html#isnext)
728 */
729var Next = /** @class */ (function (_super) {
730 __extends(Next, _super);
731 function Next(value) {
732 var _this = _super.call(this, value) || this;
733 _this.isNext = true;
734 /** @hidden */
735 _this._isNext = true; // some compatibility stuff?
736 return _this;
737 }
738 /** @hidden */
739 Next.prototype.apply = function (value) { return new Next(value); };
740 return Next;
741}(Value));
742/**
743 * An event carrying the initial value of a [Property](classes/property.html). This event can be emitted by a property
744 * immediately when subscribing to it.
745 *
746 * Can be distinguished from other events using [isInitial](../globals.html#isinitial)
747 */
748var Initial = /** @class */ (function (_super) {
749 __extends(Initial, _super);
750 function Initial(value) {
751 var _this = _super.call(this, value) || this;
752 _this.isInitial = true;
753 /** @hidden */
754 _this._isInitial = true;
755 return _this;
756 }
757 /** @hidden */
758 Initial.prototype.apply = function (value) { return new Initial(value); };
759 /** @hidden */
760 Initial.prototype.toNext = function () { return new Next(this.value); };
761 return Initial;
762}(Value));
763/**
764 * Base class for events not carrying a value.
765 */
766var NoValue = /** @class */ (function (_super) {
767 __extends(NoValue, _super);
768 function NoValue() {
769 var _this = _super !== null && _super.apply(this, arguments) || this;
770 _this.hasValue = false;
771 return _this;
772 }
773 /** @hidden */
774 NoValue.prototype.fmap = function (f) {
775 return this;
776 };
777 return NoValue;
778}(Event));
779/**
780 * An event that indicates the end of an [EventStream](classes/eventstream.html) or a [Property](classes/property.html).
781 * No more events can be emitted after this one.
782 *
783 * Can be distinguished from other events using [isEnd](../globals.html#isend)
784 */
785var End = /** @class */ (function (_super) {
786 __extends(End, _super);
787 function End() {
788 var _this = _super !== null && _super.apply(this, arguments) || this;
789 _this.isEnd = true;
790 return _this;
791 }
792 /** @hidden */
793 End.prototype.toString = function () { return "<end>"; };
794 return End;
795}(NoValue));
796/**
797 * An event carrying an error. You can use [onError](observable.html#onerror) to subscribe to errors.
798 */
799var Error$1 = /** @class */ (function (_super) {
800 __extends(Error, _super);
801 function Error(error) {
802 var _this = _super.call(this) || this;
803 _this.isError = true;
804 _this.error = error;
805 return _this;
806 }
807 /** @hidden */
808 Error.prototype.toString = function () {
809 return "<error> " + _.toString(this.error);
810 };
811 return Error;
812}(NoValue));
813/** @hidden */
814function initialEvent(value) { return new Initial(value); }
815/** @hidden */
816function nextEvent(value) { return new Next(value); }
817/** @hidden */
818function endEvent() { return new End(); }
819/** @hidden */
820function toEvent(x) {
821 if (x && x._isEvent) {
822 return x;
823 }
824 else {
825 return nextEvent(x);
826 }
827}
828/**
829 * Returns true if the given object is an [Event](classes/event.html).
830 */
831function isEvent(e) {
832 return e && e._isEvent;
833}
834/**
835 * Returns true if the given event is an [Initial](classes/initial.html) value of a [Property](classes/property.html).
836 */
837function isInitial(e) {
838 return e && e._isInitial;
839}
840/**
841 * Returns true if the given event is an [Error](classes/error.html) event of an [Observable](classes/observable.html).
842 */
843function isError(e) {
844 return e.isError;
845}
846/**
847 * Returns true if the given event is a [Value](classes/value.html), i.e. a [Next](classes/next.html) or
848 * an [Initial](classes/error.html) value of an [Observable](classes/observable.html).
849 */
850function hasValue(e) {
851 return e.hasValue;
852}
853/**
854 * Returns true if the given event is an [End](classes/end.html)
855 */
856function isEnd(e) {
857 return e.isEnd;
858}
859/**
860 * Returns true if the given event is a [Next](classes/next.html)
861 */
862function isNext(e) {
863 return e.isNext;
864}
865
866/** @hidden */
867function equals(a, b) { return a === b; }
868/** @hidden */
869function skipDuplicates(src, isEqual) {
870 if (isEqual === void 0) { isEqual = equals; }
871 var desc = new Desc(src, "skipDuplicates", []);
872 return withStateMachine(none(), function (prev, event) {
873 if (!hasValue(event)) {
874 return [prev, [event]];
875 }
876 else if (event.isInitial || isNone(prev) || !isEqual(prev.get(), event.value)) {
877 return [new Some(event.value), [event]];
878 }
879 else {
880 return [prev, []];
881 }
882 }, src).withDesc(desc);
883}
884
885/** @hidden */
886function take(count, src, desc) {
887 return src.transform(takeT(count), desc || new Desc(src, "take", [count]));
888}
889/** @hidden */
890function takeT(count) {
891 return function (e, sink) {
892 if (!e.hasValue) {
893 return sink(e);
894 }
895 else {
896 count--;
897 if (count > 0) {
898 return sink(e);
899 }
900 else {
901 if (count === 0) {
902 sink(e);
903 }
904 sink(endEvent());
905 return noMore;
906 }
907 }
908 };
909}
910
911/** @hidden */
912function log(args, src) {
913 src.subscribe(function (event) {
914 if (typeof console !== "undefined" && typeof console.log === "function") {
915 console.log.apply(console, args.concat([event.log()]));
916 }
917 return more;
918 });
919}
920
921/** @hidden */
922function doLogT(args) {
923 return function (event, sink) {
924 if (typeof console !== "undefined" && console !== null && typeof console.log === "function") {
925 console.log.apply(console, args.concat([event.log()]));
926 }
927 return sink(event);
928 };
929}
930
931/** @hidden */
932function doErrorT(f) {
933 return function (event, sink) {
934 if (isError(event)) {
935 f(event.error);
936 }
937 return sink(event);
938 };
939}
940
941/** @hidden */
942function doActionT(f) {
943 return function (event, sink) {
944 if (hasValue(event)) {
945 f(event.value);
946 }
947 return sink(event);
948 };
949}
950
951/** @hidden */
952function doEndT(f) {
953 return function (event, sink) {
954 if (isEnd(event)) {
955 f();
956 }
957 return sink(event);
958 };
959}
960
961/** @hidden */
962function scan(src, seed, f) {
963 var resultProperty;
964 var acc = seed;
965 var initHandled = false;
966 var subscribe = function (sink) {
967 var initSent = false;
968 var unsub = nop;
969 var reply = more;
970 var sendInit = function () {
971 if (!initSent) {
972 initSent = initHandled = true;
973 reply = sink(new Initial(acc));
974 if (reply === noMore) {
975 unsub();
976 unsub = nop;
977 }
978 }
979 return reply;
980 };
981 unsub = src.subscribeInternal(function (event) {
982 if (hasValue(event)) {
983 if (initHandled && event.isInitial) {
984 //console.log "skip INITIAL"
985 return more; // init already sent, skip this one
986 }
987 else {
988 if (!event.isInitial) {
989 sendInit();
990 }
991 initSent = initHandled = true;
992 var prev = acc;
993 var next = f(prev, event.value);
994 //console.log prev , ",", event.value, "->", next
995 acc = next;
996 return sink(event.apply(next));
997 }
998 }
999 else {
1000 if (event.isEnd) {
1001 reply = sendInit();
1002 }
1003 if (reply !== noMore) {
1004 return sink(event);
1005 }
1006 return reply;
1007 }
1008 });
1009 UpdateBarrier.whenDoneWith(resultProperty, sendInit);
1010 return unsub;
1011 };
1012 return resultProperty = new Property(new Desc(src, "scan", [seed, f]), subscribe);
1013}
1014
1015/** @hidden */
1016function mapEndT(f) {
1017 var theF = _.toFunction(f);
1018 return function (event, sink) {
1019 if (isEnd(event)) {
1020 sink(nextEvent(theF(event)));
1021 sink(endEvent());
1022 return noMore;
1023 }
1024 else {
1025 return sink(event);
1026 }
1027 };
1028}
1029
1030/** @hidden */
1031function mapErrorT(f) {
1032 var theF = _.toFunction(f);
1033 return function (event, sink) {
1034 if (isError(event)) {
1035 return sink(nextEvent(theF(event.error)));
1036 }
1037 else {
1038 return sink(event);
1039 }
1040 };
1041}
1042
1043/** @hidden */
1044function skipErrors(src) {
1045 return src.transform(function (event, sink) {
1046 if (isError(event)) {
1047 return more;
1048 }
1049 else {
1050 return sink(event);
1051 }
1052 }, new Desc(src, "skipErrors", []));
1053}
1054
1055/** @hidden */
1056function last$1(src) {
1057 var lastEvent;
1058 return src.transform(function (event, sink) {
1059 if (isEnd(event)) {
1060 if (lastEvent) {
1061 sink(lastEvent);
1062 }
1063 sink(endEvent());
1064 return noMore;
1065 }
1066 else if (hasValue(event)) {
1067 lastEvent = event;
1068 return more;
1069 }
1070 else {
1071 return sink(event);
1072 }
1073 }).withDesc(new Desc(src, "last", []));
1074}
1075
1076/** @hidden */
1077var CompositeUnsubscribe = /** @class */ (function () {
1078 function CompositeUnsubscribe(ss) {
1079 if (ss === void 0) { ss = []; }
1080 this.unsubscribed = false;
1081 this.unsubscribe = _.bind(this.unsubscribe, this);
1082 this.unsubscribed = false;
1083 this.subscriptions = [];
1084 this.starting = [];
1085 for (var i = 0, s; i < ss.length; i++) {
1086 s = ss[i];
1087 this.add(s);
1088 }
1089 }
1090 CompositeUnsubscribe.prototype.add = function (subscription) {
1091 var _this = this;
1092 if (!this.unsubscribed) {
1093 var ended = false;
1094 var unsub = nop;
1095 this.starting.push(subscription);
1096 var unsubMe = function () {
1097 if (_this.unsubscribed) {
1098 return;
1099 }
1100 ended = true;
1101 _this.remove(unsub);
1102 _.remove(subscription, _this.starting);
1103 };
1104 unsub = subscription(this.unsubscribe, unsubMe);
1105 if (!(this.unsubscribed || ended)) {
1106 this.subscriptions.push(unsub);
1107 }
1108 else {
1109 unsub();
1110 }
1111 _.remove(subscription, this.starting);
1112 }
1113 };
1114 CompositeUnsubscribe.prototype.remove = function (unsub) {
1115 if (this.unsubscribed) {
1116 return;
1117 }
1118 if ((_.remove(unsub, this.subscriptions)) !== undefined) {
1119 return unsub();
1120 }
1121 };
1122 CompositeUnsubscribe.prototype.unsubscribe = function () {
1123 if (this.unsubscribed) {
1124 return;
1125 }
1126 this.unsubscribed = true;
1127 var iterable = this.subscriptions;
1128 for (var i = 0; i < iterable.length; i++) {
1129 iterable[i]();
1130 }
1131 this.subscriptions = [];
1132 this.starting = [];
1133 };
1134 CompositeUnsubscribe.prototype.count = function () {
1135 if (this.unsubscribed) {
1136 return 0;
1137 }
1138 return this.subscriptions.length + this.starting.length;
1139 };
1140 CompositeUnsubscribe.prototype.empty = function () {
1141 return this.count() === 0;
1142 };
1143 return CompositeUnsubscribe;
1144}());
1145
1146/** @hidden */
1147function streamSubscribeToPropertySubscribe(initValue, streamSubscribe) {
1148 //assertFunction(streamSubscribe)
1149 return function (sink) {
1150 var initSent = false;
1151 var subbed = false;
1152 var unsub = nop;
1153 var reply = more;
1154 var sendInit = function () {
1155 if (!initSent) {
1156 return initValue.forEach(function (value) {
1157 initSent = true;
1158 reply = sink(new Initial(value));
1159 if (reply === noMore) {
1160 unsub();
1161 unsub = nop;
1162 return nop;
1163 }
1164 });
1165 }
1166 };
1167 unsub = streamSubscribe(function (event) {
1168 if (event instanceof Value) {
1169 if (event.isInitial && !subbed) {
1170 initValue = new Some(event.value);
1171 return more;
1172 }
1173 else {
1174 if (!event.isInitial) {
1175 sendInit();
1176 }
1177 initSent = true;
1178 initValue = new Some(event.value);
1179 return sink(event);
1180 }
1181 }
1182 else {
1183 if (event.isEnd) {
1184 reply = sendInit();
1185 }
1186 if (reply !== noMore) {
1187 return sink(event);
1188 }
1189 return reply;
1190 }
1191 });
1192 subbed = true;
1193 sendInit();
1194 return unsub;
1195 };
1196}
1197
1198/** @hidden */
1199function propertyFromStreamSubscribe(desc, subscribe) {
1200 assertFunction(subscribe);
1201 return new Property(desc, streamSubscribeToPropertySubscribe(none(), subscribe));
1202}
1203
1204/**
1205 Creates an EventStream that delivers the given
1206 single value for the first subscriber. The stream will end immediately
1207 after this value. You can also send an [`Bacon.Error`](#bacon-error) event instead of a
1208 value: `Bacon.once(new Bacon.Error("fail"))`.
1209
1210 @param value the value or event to emit
1211 @typeparam V Type of stream elements
1212 */
1213function once(value) {
1214 var s = new EventStream(new Desc("Bacon", "once", [value]), function (sink) {
1215 UpdateBarrier.soonButNotYet(s, function () {
1216 sink(toEvent(value));
1217 sink(endEvent());
1218 });
1219 return nop;
1220 });
1221 return s;
1222}
1223
1224/** @hidden */
1225function flatMap_(spawner, src, params) {
1226 if (params === void 0) { params = {}; }
1227 var root = src;
1228 var rootDep = [root];
1229 var childDeps = [];
1230 var isProperty = src._isProperty;
1231 var ctor = (isProperty ? propertyFromStreamSubscribe : newEventStreamAllowSync);
1232 var initialSpawned = false;
1233 var desc = params.desc || new Desc(src, "flatMap_", [spawner]);
1234 var result = ctor(desc, function (sink) {
1235 var composite = new CompositeUnsubscribe();
1236 var queue = [];
1237 function spawn(event) {
1238 if (isProperty && event.isInitial) {
1239 if (initialSpawned) {
1240 return more;
1241 }
1242 initialSpawned = true;
1243 }
1244 var child = makeObservable(spawner(event));
1245 childDeps.push(child);
1246 return composite.add(function (unsubAll, unsubMe) {
1247 return child.subscribeInternal(function (event) {
1248 if (event.isEnd) {
1249 _.remove(child, childDeps);
1250 checkQueue();
1251 checkEnd(unsubMe);
1252 return noMore;
1253 }
1254 else {
1255 event = event.toNext(); // To support Property as the spawned stream
1256 var reply = sink(event);
1257 if (reply === noMore) {
1258 unsubAll();
1259 }
1260 return reply;
1261 }
1262 });
1263 });
1264 }
1265 function checkQueue() {
1266 var event = queue.shift();
1267 if (event) {
1268 spawn(event);
1269 }
1270 }
1271 function checkEnd(unsub) {
1272 unsub();
1273 if (composite.empty()) {
1274 return sink(endEvent());
1275 }
1276 return more;
1277 }
1278 composite.add(function (__, unsubRoot) {
1279 return root.subscribeInternal(function (event) {
1280 if (event.isEnd) {
1281 return checkEnd(unsubRoot);
1282 }
1283 else if (event.isError && !params.mapError) {
1284 return sink(event);
1285 }
1286 else if (params.firstOnly && composite.count() > 1) {
1287 return more;
1288 }
1289 else {
1290 if (composite.unsubscribed) {
1291 return noMore;
1292 }
1293 if (params.limit && composite.count() > params.limit) {
1294 queue.push(event);
1295 }
1296 else {
1297 spawn(event);
1298 }
1299 return more;
1300 }
1301 });
1302 });
1303 return composite.unsubscribe;
1304 });
1305 result.internalDeps = function () {
1306 if (childDeps.length) {
1307 return rootDep.concat(childDeps);
1308 }
1309 else {
1310 return rootDep;
1311 }
1312 };
1313 return result;
1314}
1315/** @hidden */
1316function handleEventValueWith(f) {
1317 if (typeof f == "function") {
1318 return (function (event) {
1319 if (hasValue(event)) {
1320 return f(event.value);
1321 }
1322 return event;
1323 });
1324 }
1325 return (function (event) { return f; });
1326}
1327/** @hidden */
1328function makeObservable(x) {
1329 if (isObservable(x)) {
1330 return x;
1331 }
1332 else {
1333 return once(x);
1334 }
1335}
1336
1337/** @hidden */
1338function flatMapEvent(src, f) {
1339 return flatMap_(f, src, {
1340 mapError: true,
1341 desc: new Desc(src, "flatMapEvent", [f])
1342 });
1343}
1344
1345/** @hidden */
1346function endAsValue(src) {
1347 return src.transform(function (event, sink) {
1348 if (isEnd(event)) {
1349 sink(nextEvent({}));
1350 sink(endEvent());
1351 return noMore;
1352 }
1353 return more;
1354 });
1355}
1356
1357/** @hidden */
1358function endOnError(src, predicate) {
1359 if (predicate === void 0) { predicate = function (x) { return true; }; }
1360 return src.transform(function (event, sink) {
1361 if (isError(event) && predicate(event.error)) {
1362 sink(event);
1363 return sink(endEvent());
1364 }
1365 else {
1366 return sink(event);
1367 }
1368 }, new Desc(src, "endOnError", []));
1369}
1370
1371/** @hidden */
1372var Source = /** @class */ (function () {
1373 function Source(obs, sync) {
1374 this._isSource = true;
1375 this.flatten = true;
1376 this.ended = false;
1377 this.obs = obs;
1378 this.sync = sync;
1379 }
1380 Source.prototype.subscribe = function (sink) {
1381 return this.obs.subscribeInternal(sink);
1382 };
1383 Source.prototype.toString = function () {
1384 return this.obs.toString();
1385 };
1386 Source.prototype.markEnded = function () {
1387 this.ended = true;
1388 };
1389 Source.prototype.mayHave = function (count) { return true; };
1390 return Source;
1391}());
1392/** @hidden */
1393var DefaultSource = /** @class */ (function (_super) {
1394 __extends(DefaultSource, _super);
1395 function DefaultSource() {
1396 return _super !== null && _super.apply(this, arguments) || this;
1397 }
1398 DefaultSource.prototype.consume = function () {
1399 return this.value;
1400 };
1401 DefaultSource.prototype.push = function (x) {
1402 this.value = x;
1403 };
1404 DefaultSource.prototype.hasAtLeast = function (c) {
1405 return !!this.value;
1406 };
1407 return DefaultSource;
1408}(Source));
1409/** @hidden */
1410var ConsumingSource = /** @class */ (function (_super) {
1411 __extends(ConsumingSource, _super);
1412 function ConsumingSource(obs, sync) {
1413 var _this = _super.call(this, obs, sync) || this;
1414 _this.flatten = false;
1415 _this.queue = [];
1416 return _this;
1417 }
1418 ConsumingSource.prototype.consume = function () {
1419 return this.queue.shift();
1420 };
1421 ConsumingSource.prototype.push = function (x) {
1422 this.queue.push(x);
1423 };
1424 ConsumingSource.prototype.mayHave = function (count) {
1425 return !this.ended || this.queue.length >= count;
1426 };
1427 ConsumingSource.prototype.hasAtLeast = function (count) {
1428 return this.queue.length >= count;
1429 };
1430 return ConsumingSource;
1431}(Source));
1432/** @hidden */
1433var BufferingSource = /** @class */ (function (_super) {
1434 __extends(BufferingSource, _super);
1435 function BufferingSource(obs) {
1436 var _this = _super.call(this, obs, true) || this;
1437 _this.queue = [];
1438 return _this;
1439 }
1440 BufferingSource.prototype.consume = function () {
1441 var values = this.queue;
1442 this.queue = [];
1443 return {
1444 value: values
1445 };
1446 };
1447 BufferingSource.prototype.push = function (x) {
1448 return this.queue.push(x.value);
1449 };
1450 BufferingSource.prototype.hasAtLeast = function (count) {
1451 return true;
1452 };
1453 return BufferingSource;
1454}(Source));
1455/** @hidden */
1456function isTrigger(s) {
1457 if (s == null)
1458 return false;
1459 if (s._isSource) {
1460 return s.sync;
1461 }
1462 else {
1463 return s._isEventStream;
1464 }
1465}
1466/** @hidden */
1467function fromObservable(s) {
1468 if (s != null && s._isSource) {
1469 return s;
1470 }
1471 else if (s != null && s._isProperty) {
1472 return new DefaultSource(s, false);
1473 }
1474 else {
1475 return new ConsumingSource(s, true);
1476 }
1477}
1478
1479/**
1480 Creates an EventStream that immediately ends.
1481 @typeparam V Type of stream elements
1482 */
1483function never() {
1484 return new EventStream(describe("Bacon", "never"), function (sink) {
1485 sink(endEvent());
1486 return nop;
1487 });
1488}
1489
1490/**
1491 The `when` method provides a generalization of the [`zip`](classes/observable.html#zip) function. While zip
1492 synchronizes events from multiple streams pairwse, the join patterns used in `when` allow
1493 the implementation of more advanced synchronization patterns.
1494
1495 Consider implementing a game with discrete time ticks. We want to
1496 handle key-events synchronized on tick-events, with at most one key
1497 event handled per tick. If there are no key events, we want to just
1498 process a tick.
1499
1500 ```js
1501 Bacon.when(
1502 [tick, keyEvent, function(_, k) { handleKeyEvent(k); return handleTick(); }],
1503 [tick, handleTick])
1504 ```
1505
1506 Order is important here. If the [tick] patterns had been written
1507 first, this would have been tried first, and preferred at each tick.
1508
1509 Join patterns are indeed a generalization of zip, and for EventStreams, zip is
1510 equivalent to a single-rule join pattern. The following observables
1511 have the same output, assuming that all sources are EventStreams.
1512
1513 ```js
1514 Bacon.zipWith(a,b,c, combine)
1515 Bacon.when([a,b,c], combine)
1516 ```
1517
1518 Note that [`Bacon.when`](#bacon-when) does not trigger updates for events from Properties though;
1519 if you use a Property in your pattern, its value will be just sampled when all the
1520 other sources (EventStreams) have a value. This is useful when you need a value of a Property
1521 in your calculations. If you want your pattern to fire for a Property too, you can
1522 convert it into an EventStream using [`property.changes()`](#property-changes) or [`property.toEventStream()`](#property-toeventstream)
1523
1524 * @param {Pattern<O>} patterns Join patterns
1525 * @typeparam O result type
1526 */
1527function when() {
1528 var patterns = [];
1529 for (var _i = 0; _i < arguments.length; _i++) {
1530 patterns[_i] = arguments[_i];
1531 }
1532 return when_(newEventStream, patterns);
1533}
1534/** @hidden */
1535function whenP() {
1536 var patterns = [];
1537 for (var _i = 0; _i < arguments.length; _i++) {
1538 patterns[_i] = arguments[_i];
1539 }
1540 return when_(propertyFromStreamSubscribe, patterns);
1541}
1542/** @hidden */
1543function when_(ctor, patterns) {
1544 if (patterns.length === 0) {
1545 return never();
1546 }
1547 var _a = processRawPatterns(extractRawPatterns(patterns)), sources = _a[0], ixPats = _a[1];
1548 if (!sources.length) {
1549 return never();
1550 }
1551 var needsBarrier = (any(sources, function (s) { return s.flatten; })) && containsDuplicateDeps(map((function (s) { return s.obs; }), sources));
1552 var desc = new Desc("Bacon", "when", Array.prototype.slice.call(patterns));
1553 var resultStream = ctor(desc, function (sink) {
1554 var triggers = [];
1555 var ends = false;
1556 function match(p) {
1557 for (var i = 0; i < p.ixs.length; i++) {
1558 var ix = p.ixs[i];
1559 if (!sources[ix.index].hasAtLeast(ix.count)) {
1560 return false;
1561 }
1562 }
1563 return true;
1564 }
1565 function cannotMatch(p) {
1566 for (var i = 0; i < p.ixs.length; i++) {
1567 var ix = p.ixs[i];
1568 if (!sources[ix.index].mayHave(ix.count)) {
1569 return true;
1570 }
1571 }
1572 return false;
1573 }
1574 function nonFlattened(trigger) { return !trigger.source.flatten; }
1575 function part(source) {
1576 return function (unsubAll) {
1577 function flushLater() {
1578 return UpdateBarrier.whenDoneWith(resultStream, flush);
1579 }
1580 function flushWhileTriggers() {
1581 var trigger;
1582 if ((trigger = triggers.pop()) !== undefined) {
1583 var reply = more;
1584 for (var i = 0, p; i < ixPats.length; i++) {
1585 p = ixPats[i];
1586 if (match(p)) {
1587 var values = [];
1588 for (var j = 0; j < p.ixs.length; j++) {
1589 var event_1 = sources[p.ixs[j].index].consume();
1590 if (!event_1)
1591 throw new Error("Event was undefined");
1592 values.push(event_1.value);
1593 }
1594 //console.log("flushing values", values)
1595 var applied = p.f.apply(null, values);
1596 //console.log('sinking', applied)
1597 reply = sink((trigger).e.apply(applied));
1598 if (triggers.length) {
1599 triggers = filter(nonFlattened, triggers);
1600 }
1601 if (reply === noMore) {
1602 return reply;
1603 }
1604 else {
1605 return flushWhileTriggers();
1606 }
1607 }
1608 }
1609 }
1610 return more;
1611 }
1612 function flush() {
1613 //console.log "flushing", _.toString(resultStream)
1614 var reply = flushWhileTriggers();
1615 if (ends) {
1616 //console.log "ends detected"
1617 if (all(sources, cannotSync) || all(ixPats, cannotMatch)) {
1618 //console.log "actually ending"
1619 reply = noMore;
1620 sink(endEvent());
1621 }
1622 }
1623 if (reply === noMore) {
1624 unsubAll();
1625 }
1626 }
1627 return source.subscribe(function (e) {
1628 var reply = more;
1629 if (e.isEnd) {
1630 //console.log "got end"
1631 ends = true;
1632 source.markEnded();
1633 flushLater();
1634 }
1635 else if (e.isError) {
1636 reply = sink(e);
1637 }
1638 else {
1639 var valueEvent = e;
1640 //console.log "got value", e.value
1641 source.push(valueEvent);
1642 if (source.sync) {
1643 //console.log "queuing", e.toString(), toString(resultStream)
1644 triggers.push({ source: source, e: valueEvent });
1645 if (needsBarrier || UpdateBarrier.hasWaiters()) {
1646 flushLater();
1647 }
1648 else {
1649 flush();
1650 }
1651 }
1652 }
1653 if (reply === noMore) {
1654 unsubAll();
1655 }
1656 return reply;
1657 });
1658 };
1659 }
1660 return new CompositeUnsubscribe(map(part, sources)).unsubscribe;
1661 });
1662 return resultStream;
1663}
1664function processRawPatterns(rawPatterns) {
1665 var sources = [];
1666 var pats = [];
1667 for (var i = 0; i < rawPatterns.length; i++) {
1668 var _a = rawPatterns[i], patSources = _a[0], f = _a[1];
1669 var pat = { f: f, ixs: [] };
1670 var triggerFound = false;
1671 for (var j = 0, s; j < patSources.length; j++) {
1672 s = patSources[j];
1673 var index = indexOf(sources, s);
1674 if (!triggerFound) {
1675 triggerFound = isTrigger(s);
1676 }
1677 if (index < 0) {
1678 sources.push(s);
1679 index = sources.length - 1;
1680 }
1681 for (var k = 0; k < pat.ixs.length; k++) {
1682 var ix = pat.ixs[k];
1683 if (ix.index === index) {
1684 ix.count++;
1685 }
1686 }
1687 pat.ixs.push({ index: index, count: 1 });
1688 }
1689 if (patSources.length > 0 && !triggerFound) {
1690 throw new Error("At least one EventStream required, none found in " + patSources);
1691 }
1692 if (patSources.length > 0) {
1693 pats.push(pat);
1694 }
1695 }
1696 return [map(fromObservable /* sorry */, sources), pats];
1697}
1698function extractLegacyPatterns(sourceArgs) {
1699 var i = 0;
1700 var len = sourceArgs.length;
1701 var rawPatterns = [];
1702 while (i < len) {
1703 var patSources = toArray(sourceArgs[i++]);
1704 var f = toFunction(sourceArgs[i++]);
1705 rawPatterns.push([patSources, f]);
1706 }
1707 var usage = "when: expecting arguments in the form (Observable+,function)+";
1708 assert(usage, (len % 2 === 0));
1709 return rawPatterns;
1710}
1711function isTypedOrRawPattern(pattern) {
1712 return (pattern instanceof Array) && (!isObservable(pattern[pattern.length - 1]));
1713}
1714function isRawPattern(pattern) {
1715 return pattern[0] instanceof Array;
1716}
1717/** @hidden */
1718function extractRawPatterns(patterns) {
1719 var rawPatterns = [];
1720 for (var i = 0; i < patterns.length; i++) {
1721 var pattern = patterns[i];
1722 if (!isTypedOrRawPattern(pattern)) {
1723 // Fallback to legacy patterns
1724 return extractLegacyPatterns(patterns);
1725 }
1726 if (isRawPattern(pattern)) {
1727 rawPatterns.push([pattern[0], toFunction(pattern[1])]);
1728 }
1729 else { // typed pattern, then
1730 var sources = pattern.slice(0, pattern.length - 1);
1731 var f = toFunction(pattern[pattern.length - 1]);
1732 rawPatterns.push([sources, f]);
1733 }
1734 }
1735 return rawPatterns;
1736}
1737function containsDuplicateDeps(observables, state) {
1738 if (state === void 0) { state = []; }
1739 function checkObservable(obs) {
1740 if (contains(state, obs)) {
1741 return true;
1742 }
1743 else {
1744 var deps = obs.internalDeps();
1745 if (deps.length) {
1746 state.push(obs);
1747 return any(deps, checkObservable);
1748 }
1749 else {
1750 state.push(obs);
1751 return false;
1752 }
1753 }
1754 }
1755 return any(observables, checkObservable);
1756}
1757function cannotSync(source) {
1758 return !source.sync || source.ended;
1759}
1760
1761/** @hidden */
1762function withLatestFromE(sampler, samplee, f) {
1763 var result = when([new DefaultSource(samplee.toProperty(), false), new DefaultSource(sampler, true), flip(f)]);
1764 return result.withDesc(new Desc(sampler, "withLatestFrom", [samplee, f]));
1765}
1766/** @hidden */
1767function withLatestFromP(sampler, samplee, f) {
1768 var result = whenP([new DefaultSource(samplee.toProperty(), false), new DefaultSource(sampler, true), flip(f)]);
1769 return result.withDesc(new Desc(sampler, "withLatestFrom", [samplee, f]));
1770}
1771/** @hidden */
1772function withLatestFrom(sampler, samplee, f) {
1773 if (sampler instanceof Property) {
1774 return withLatestFromP(sampler, samplee, f);
1775 }
1776 else if (sampler instanceof EventStream) {
1777 return withLatestFromE(sampler, samplee, f);
1778 }
1779 else {
1780 throw new Error("Unknown observable: " + sampler);
1781 }
1782}
1783
1784/** @hidden */
1785function map$1(src, f) {
1786 if (f instanceof Property) {
1787 return withLatestFrom(src, f, function (a, b) { return b; });
1788 }
1789 return src.transform(mapT(f), new Desc(src, "map", [f]));
1790}
1791/** @hidden */
1792function mapT(f) {
1793 var theF = _.toFunction(f);
1794 return function (e, sink) {
1795 return sink(e.fmap(theF));
1796 };
1797}
1798
1799/**
1800 Creates a constant property with value `x`.
1801 */
1802function constant(x) {
1803 return new Property(new Desc("Bacon", "constant", [x]), function (sink) {
1804 sink(initialEvent(x));
1805 sink(endEvent());
1806 return nop;
1807 });
1808}
1809
1810/** @hidden */
1811function argumentsToObservables(args) {
1812 args = (Array.prototype.slice.call(args));
1813 return _.flatMap(singleToObservables, args);
1814}
1815function singleToObservables(x) {
1816 if (isObservable(x)) {
1817 return [x];
1818 }
1819 else if (isArray(x)) {
1820 return argumentsToObservables(x);
1821 }
1822 else {
1823 return [constant(x)];
1824 }
1825}
1826/** @hidden */
1827function argumentsToObservablesAndFunction(args) {
1828 if (_.isFunction(args[0])) {
1829 return [argumentsToObservables(Array.prototype.slice.call(args, 1)), args[0]];
1830 }
1831 else {
1832 return [argumentsToObservables(Array.prototype.slice.call(args, 0, args.length - 1)), _.last(args)];
1833 }
1834}
1835
1836/** @hidden */
1837function groupSimultaneous() {
1838 var streams = [];
1839 for (var _i = 0; _i < arguments.length; _i++) {
1840 streams[_i] = arguments[_i];
1841 }
1842 return groupSimultaneous_(argumentsToObservables(streams));
1843}
1844// TODO: type is not exactly correct, because different inputs may have different types.
1845// Result values are arrays where each element is the list from each input observable. Type this.
1846/** @hidden */
1847function groupSimultaneous_(streams, options) {
1848 var sources = _.map(function (stream) { return new BufferingSource(stream); }, streams);
1849 var ctor = function (desc, subscribe) { return new EventStream(desc, subscribe, undefined, options); };
1850 return when_(ctor, [sources, (function () {
1851 var xs = [];
1852 for (var _i = 0; _i < arguments.length; _i++) {
1853 xs[_i] = arguments[_i];
1854 }
1855 return xs;
1856 })]).withDesc(new Desc("Bacon", "groupSimultaneous", streams));
1857}
1858
1859/** @hidden */
1860function awaiting(src, other) {
1861 return groupSimultaneous_([src, other], allowSync)
1862 .map(function (values) { return values[1].length === 0; })
1863 .toProperty(false)
1864 .skipDuplicates()
1865 .withDesc(new Desc(src, "awaiting", [other]));
1866}
1867
1868/**
1869 Combines Properties, EventStreams and constant values so that the result Property will have an array of the latest
1870 values from all sources as its value. The inputs may contain both Properties and EventStreams.
1871
1872
1873 ```js
1874 property = Bacon.constant(1)
1875 stream = Bacon.once(2)
1876 constant = 3
1877 Bacon.combineAsArray(property, stream, constant)
1878 # produces the value [1,2,3]
1879 ```
1880
1881 * @param streams streams and properties to combine
1882 */
1883function combineAsArray() {
1884 var streams = [];
1885 for (var _i = 0; _i < arguments.length; _i++) {
1886 streams[_i] = arguments[_i];
1887 }
1888 streams = argumentsToObservables(streams);
1889 if (streams.length) {
1890 var sources = [];
1891 for (var i = 0; i < streams.length; i++) {
1892 var stream = (isObservable(streams[i])
1893 ? streams[i]
1894 : constant(streams[i]));
1895 sources.push(wrap(stream));
1896 }
1897 return whenP([sources, function () {
1898 var xs = [];
1899 for (var _i = 0; _i < arguments.length; _i++) {
1900 xs[_i] = arguments[_i];
1901 }
1902 return xs;
1903 }]).withDesc(new Desc("Bacon", "combineAsArray", streams));
1904 }
1905 else {
1906 return constant([]);
1907 }
1908}
1909function combineWith() {
1910 var args = [];
1911 for (var _i = 0; _i < arguments.length; _i++) {
1912 args[_i] = arguments[_i];
1913 }
1914 // TODO: untyped
1915 var _a = argumentsToObservablesAndFunction(arguments), streams = _a[0], f = _a[1];
1916 var desc = new Desc("Bacon", "combineWith", __spreadArrays([f], streams));
1917 return combineAsArray(streams).map(function (values) {
1918 return f.apply(void 0, values);
1919 }).withDesc(desc);
1920}
1921var combine = combineWith;
1922/** @hidden */
1923function combineTwo(left, right, f) {
1924 return whenP([[wrap(left), wrap(right)], f]).withDesc(new Desc(left, "combine", [right, f]));
1925}
1926function wrap(obs) {
1927 return new DefaultSource(obs, true);
1928}
1929
1930/** @hidden */
1931function skip(src, count) {
1932 return src.transform(function (event, sink) {
1933 if (!event.hasValue) {
1934 return sink(event);
1935 }
1936 else if (count > 0) {
1937 count--;
1938 return more;
1939 }
1940 else {
1941 return sink(event);
1942 }
1943 }, new Desc(src, "skip", [count]));
1944}
1945
1946/** @hidden */
1947function flatMapConcat(src, f) {
1948 return flatMap_(handleEventValueWith(f), src, {
1949 desc: new Desc(src, "flatMapConcat", [f]),
1950 limit: 1
1951 });
1952}
1953
1954/**
1955 If none of the other factory methods above apply, you may of course roll your own EventStream by using `fromBinder`.
1956
1957 <a name="bacon-frombinder"></a>
1958 [`Bacon.fromBinder(subscribe)`](#bacon-frombinder "Bacon.fromBinder(subscribe)") The parameter `subscribe` is a function that accepts a `sink` which is a function that your `subscribe` function can "push" events to.
1959
1960 For example:
1961
1962 ```js
1963 var stream = Bacon.fromBinder(function(sink) {
1964 sink("first value")
1965 sink([new Bacon.Next("2nd"), new Bacon.Next("3rd")])
1966 sink(new Bacon.Error("oops, an error"))
1967 sink(new Bacon.End())
1968 return function() {
1969 // unsub functionality here, this one's a no-op
1970 }
1971})
1972 stream.log()
1973 ```
1974
1975 As shown in the example, you can push
1976
1977 - A plain value, like `"first value"`
1978 - An [`Event`](#event) object including [`Bacon.Error`](#bacon-error) (wraps an error) and [`Bacon.End`](#bacon-end) (indicates
1979 stream end).
1980 - An array of [event](#event) objects at once
1981
1982 Other examples can be found on [JSFiddle](http://jsfiddle.net/PG4c4/) and the
1983 [Bacon.js blog](http://baconjs.blogspot.fi/2013/12/wrapping-things-in-bacon.html).
1984
1985 The `subscribe` function must return a function. Let's call that function
1986 `unsubscribe`. The returned function can be used by the subscriber (directly or indirectly) to
1987 unsubscribe from the EventStream. It should release all resources that the subscribe function reserved.
1988
1989 The `sink` function may return [`Bacon.noMore`](#bacon-nomore) (as well as [`Bacon.more`](#bacon-more)
1990 or any other value). If it returns [`Bacon.noMore`](#bacon-nomore), no further events will be consumed
1991 by the subscriber. The `subscribe` function may choose to clean up all resources at this point (e.g.,
1992 by calling `unsubscribe`). This is usually not necessary, because further calls to `sink` are ignored,
1993 but doing so can increase performance in [rare cases](https://github.com/baconjs/bacon.js/issues/484).
1994
1995 The EventStream will wrap your `subscribe` function so that it will
1996 only be called when the first stream listener is added, and the `unsubscribe`
1997 function is called only after the last listener has been removed.
1998 The subscribe-unsubscribe cycle may of course be repeated indefinitely,
1999 so prepare for multiple calls to the subscribe function.
2000
2001
2002 @param binder
2003 @param eventTransformer
2004 @typeparam V Type of stream elements
2005
2006 */
2007function fromBinder(binder, eventTransformer) {
2008 if (eventTransformer === void 0) { eventTransformer = _.id; }
2009 var desc = new Desc("Bacon", "fromBinder", [binder, eventTransformer]);
2010 return new EventStream(desc, function (sink) {
2011 var unbound = false;
2012 var shouldUnbind = false;
2013 var unbind = function () {
2014 if (!unbound) {
2015 if ((typeof unbinder !== "undefined" && unbinder !== null)) {
2016 unbinder();
2017 return unbound = true;
2018 }
2019 else {
2020 return shouldUnbind = true;
2021 }
2022 }
2023 };
2024 var unbinder = binder(function () {
2025 var args = [];
2026 for (var _i = 0; _i < arguments.length; _i++) {
2027 args[_i] = arguments[_i];
2028 }
2029 var value_ = eventTransformer.apply(void 0, args);
2030 var valueArray = isArray(value_) && isEvent(_.last(value_))
2031 ? value_
2032 : [value_];
2033 var reply = more;
2034 for (var i = 0; i < valueArray.length; i++) {
2035 var event_1 = toEvent(valueArray[i]);
2036 reply = sink(event_1);
2037 if (reply === noMore || event_1.isEnd) {
2038 // defer if binder calls handler in sync before returning unbinder
2039 unbind();
2040 return reply;
2041 }
2042 }
2043 return reply;
2044 });
2045 if (shouldUnbind) {
2046 unbind();
2047 }
2048 return unbind;
2049 });
2050}
2051
2052/**
2053 Polls given function with given interval.
2054 Function should return Events: either [`Bacon.Next`](classes/next.html) or [`Bacon.End`](classes/end.html). Polling occurs only
2055 when there are subscribers to the stream. Polling ends permanently when
2056 `f` returns [`Bacon.End`](classes/end.html).
2057 * @param delay poll interval in milliseconds
2058 * @param poll function to be polled
2059 * @typeparam V Type of stream elements
2060 */
2061function fromPoll(delay, poll) {
2062 var desc = new Desc("Bacon", "fromPoll", [delay, poll]);
2063 return fromBinder((function (handler) {
2064 var id = GlobalScheduler.scheduler.setInterval(handler, delay);
2065 return function () {
2066 return GlobalScheduler.scheduler.clearInterval(id);
2067 };
2068 }), poll).withDesc(desc);
2069}
2070
2071/**
2072 Repeats the single element indefinitely with the given interval (in milliseconds)
2073
2074 @param delay Repeat delay in milliseconds
2075 @param value The single value to repeat
2076 @typeparam V Type of stream elements
2077 */
2078function interval(delay, value) {
2079 return fromPoll(delay, function () {
2080 return nextEvent(value);
2081 }).withDesc(new Desc("Bacon", "interval", [delay, value]));
2082}
2083
2084function makeCombinator(combinator) {
2085 if (typeof combinator == "function") {
2086 return combinator;
2087 }
2088 else {
2089 return _.id;
2090 }
2091}
2092/** @hidden */
2093function sampledBy(samplee, sampler, f) {
2094 if (samplee instanceof EventStream) {
2095 return sampledByE(samplee, sampler, f);
2096 }
2097 else {
2098 return sampledByP(samplee, sampler, f);
2099 }
2100}
2101/** @hidden */
2102function sampledByP(samplee, sampler, f) {
2103 var combinator = makeCombinator(f);
2104 var result = withLatestFrom(sampler, samplee, flip(combinator));
2105 return result.withDesc(new Desc(samplee, "sampledBy", [sampler]));
2106}
2107/** @hidden */
2108function sampledByE(samplee, sampler, f) {
2109 return sampledByP(samplee.toProperty(), sampler, f).withDesc(new Desc(samplee, "sampledBy", [sampler]));
2110}
2111/** @hidden */
2112function sampleP(samplee, samplingInterval) {
2113 return sampledByP(samplee, interval(samplingInterval, {}), function (a, b) { return a; }).withDesc(new Desc(samplee, "sample", [samplingInterval]));
2114}
2115
2116/** @hidden */
2117function transformP(src, transformer, desc) {
2118 return new Property(new Desc(src, "transform", [transformer]), function (sink) {
2119 return src.subscribeInternal(function (e) {
2120 return transformer(e, sink);
2121 });
2122 }).withDesc(desc);
2123}
2124/** @hidden */
2125function transformE(src, transformer, desc) {
2126 return new EventStream(new Desc(src, "transform", [transformer]), function (sink) {
2127 return src.subscribeInternal(function (e) {
2128 return transformer(e, sink);
2129 });
2130 }, undefined, allowSync).withDesc(desc);
2131}
2132/** @hidden */
2133function composeT(t1, t2) {
2134 var finalSink; // mutation used to avoid closure creation while dispatching events
2135 var sink2 = function (event) {
2136 return t2(event, finalSink);
2137 };
2138 return function (event, sink) {
2139 finalSink = sink;
2140 return t1(event, sink2);
2141 };
2142}
2143
2144/** @hidden */
2145function toPredicate(f) {
2146 if (typeof f == "boolean") {
2147 return _.always(f);
2148 }
2149 else if (typeof f != "function") {
2150 throw new Error("Not a function: " + f);
2151 }
2152 else {
2153 return f;
2154 }
2155}
2156/** @hidden */
2157function withPredicate(src, f, predicateTransformer, desc) {
2158 if (f instanceof Property) {
2159 return withLatestFrom(src, f, function (p, v) { return [p, v]; })
2160 .transform(composeT(predicateTransformer((function (tuple) { return tuple[1]; })), mapT(function (tuple) { return tuple[0]; })), desc);
2161 // the `any` type above is needed because the type argument for Predicate2Transformer is fixed. We'd need higher-kinded types to be able to express this properly, I think.
2162 }
2163 return src.transform(predicateTransformer(toPredicate(f)), desc);
2164}
2165
2166/** @hidden */
2167function filter$1(src, f) {
2168 return withPredicate(src, f, filterT, new Desc(src, "filter", [f]));
2169}
2170/** @hidden */
2171function filterT(f) {
2172 return function (e, sink) {
2173 if (e.filter(f)) {
2174 return sink(e);
2175 }
2176 else {
2177 return more;
2178 }
2179 };
2180}
2181
2182/** @hidden */
2183function not(src) {
2184 return src.map(function (x) { return !x; }).withDesc(new Desc(src, "not", []));
2185}
2186/** @hidden */
2187function and(left, right) {
2188 return left.combine(toProperty(right), function (x, y) { return !!(x && y); }).withDesc(new Desc(left, "and", [right]));
2189}
2190/** @hidden */
2191function or(left, right) {
2192 return left.combine(toProperty(right), function (x, y) { return x || y; }).withDesc(new Desc(left, "or", [right]));
2193}
2194function toProperty(x) {
2195 if (isProperty(x)) {
2196 return x;
2197 }
2198 return constant(x);
2199}
2200
2201/** @hidden */
2202function flatMapFirst(src, f) {
2203 return flatMap_(handleEventValueWith(f), src, {
2204 firstOnly: true,
2205 desc: new Desc(src, "flatMapFirst", [f])
2206 });
2207}
2208
2209/** @hidden */
2210function concatE(left, right, options) {
2211 return new EventStream(new Desc(left, "concat", [right]), function (sink) {
2212 var unsubRight = nop;
2213 var unsubLeft = left.dispatcher.subscribe(function (e) {
2214 if (e.isEnd) {
2215 unsubRight = right.toEventStream().dispatcher.subscribe(sink);
2216 return more;
2217 }
2218 else {
2219 return sink(e);
2220 }
2221 });
2222 return function () {
2223 return unsubLeft(), unsubRight();
2224 };
2225 }, undefined, options);
2226}
2227/**
2228 Concatenates given array of EventStreams or Properties. Works by subscribing to the first source, and listeing to that
2229 until it ends. Then repeatedly subscribes to the next source, until all sources have ended.
2230
2231 See [`concat`](#observable-concat)
2232 */
2233function concatAll() {
2234 var streams_ = [];
2235 for (var _i = 0; _i < arguments.length; _i++) {
2236 streams_[_i] = arguments[_i];
2237 }
2238 var streams = argumentsToObservables(streams_);
2239 return (streams.length
2240 ? fold(tail(streams), head(streams).toEventStream(), function (a, b) { return a.concat(b); })
2241 : never()).withDesc(new Desc("Bacon", "concatAll", streams));
2242}
2243
2244/** @hidden */
2245function transformPropertyChanges(property, f, desc) {
2246 var initValue;
2247 var comboSink;
2248 // Create a `changes` stream to be transformed, which also snatches the Initial value for later use.
2249 var changes = new EventStream(describe(property, "changes", []), function (sink) { return property.dispatcher.subscribe(function (event) {
2250 if (!initValue && isInitial(event)) {
2251 initValue = event;
2252 UpdateBarrier.whenDoneWith(combo, function () {
2253 if (!comboSink) {
2254 throw new Error("Init sequence fail");
2255 }
2256 comboSink(initValue);
2257 });
2258 }
2259 if (!event.isInitial) {
2260 return sink(event);
2261 }
2262 return more;
2263 }); }, undefined, allowSync);
2264 var transformedChanges = f(changes);
2265 var combo = propertyFromStreamSubscribe(desc, function (sink) {
2266 comboSink = sink;
2267 return transformedChanges.dispatcher.subscribe(function (event) {
2268 sink(event);
2269 });
2270 });
2271 return combo;
2272}
2273
2274/** @hidden */
2275function fold$1(src, seed, f) {
2276 return src.scan(seed, f)
2277 .last()
2278 .withDesc(new Desc(src, "fold", [seed, f]));
2279}
2280
2281/** @hidden */
2282function startWithE(src, seed) {
2283 return once(seed).concat(src).withDesc(new Desc(src, "startWith", [seed]));
2284}
2285/** @hidden */
2286function startWithP(src, seed) {
2287 return src.scan(seed, function (prev, next) { return next; }).withDesc(new Desc(src, "startWith", [seed]));
2288}
2289
2290/** @hidden */
2291var endMarker = {};
2292/** @hidden */
2293function takeUntil(src, stopper) {
2294 var endMapped = src.mapEnd(endMarker);
2295 var withEndMarker = groupSimultaneous_([endMapped, stopper.skipErrors()], allowSync);
2296 if (src instanceof Property)
2297 withEndMarker = withEndMarker.toProperty();
2298 return withEndMarker.transform(function (event, sink) {
2299 if (hasValue(event)) {
2300 var _a = event.value, data = _a[0], stopper = _a[1];
2301 if (stopper.length) {
2302 return sink(endEvent());
2303 }
2304 else {
2305 var reply = more;
2306 for (var i = 0; i < data.length; i++) {
2307 var value = data[i];
2308 if (value === endMarker) {
2309 return sink(endEvent());
2310 }
2311 else {
2312 reply = sink(nextEvent(value));
2313 }
2314 }
2315 return reply;
2316 }
2317 }
2318 else {
2319 return sink(event);
2320 }
2321 }, new Desc(src, "takeUntil", [stopper]));
2322}
2323
2324/** @hidden */
2325function flatMap$1(src, f) {
2326 return flatMap_(handleEventValueWith(f), src, { desc: new Desc(src, "flatMap", [f]) });
2327}
2328
2329/** @hidden */
2330function flatMapError(src, f) {
2331 return flatMap_(function (x) {
2332 if (x instanceof Error$1) {
2333 var error = x.error;
2334 return f(error); // I don't understand why I need this little lie
2335 }
2336 else {
2337 return x;
2338 }
2339 }, src, {
2340 mapError: true,
2341 desc: new Desc(src, "flatMapError", [f])
2342 });
2343}
2344
2345var spies = [];
2346var running = false;
2347/** @hidden */
2348function registerObs(obs) {
2349 if (spies.length) {
2350 if (!running) {
2351 try {
2352 running = true;
2353 spies.forEach(function (spy) {
2354 spy(obs);
2355 });
2356 }
2357 finally {
2358 running = false;
2359 }
2360 }
2361 }
2362}
2363/**
2364 Adds your function as a "spy" that will get notified on all new Observables.
2365 This will allow a visualization/analytics tool to spy on all Bacon activity.
2366 */
2367var spy = function (spy) { return spies.push(spy); };
2368
2369/** @hidden */
2370function flatMapLatest(src, f_) {
2371 var f = _.toFunction(f_);
2372 var stream = isProperty(src) ? src.toEventStream(allowSync) : src;
2373 var flatMapped = flatMap$1(stream, function (value) { return makeObservable(f(value)).takeUntil(stream); });
2374 if (isProperty(src))
2375 flatMapped = flatMapped.toProperty();
2376 return flatMapped.withDesc(new Desc(src, "flatMapLatest", [f]));
2377}
2378
2379/** @hidden */
2380var Dispatcher = /** @class */ (function () {
2381 function Dispatcher(observable, _subscribe, _handleEvent) {
2382 this.pushing = false;
2383 this.ended = false;
2384 this.prevError = undefined;
2385 this.unsubSrc = undefined;
2386 this._subscribe = _subscribe;
2387 this._handleEvent = _handleEvent;
2388 this.subscribe = _.bind(this.subscribe, this);
2389 this.handleEvent = _.bind(this.handleEvent, this);
2390 this.subscriptions = [];
2391 this.observable = observable;
2392 this.queue = [];
2393 }
2394 Dispatcher.prototype.hasSubscribers = function () {
2395 return this.subscriptions.length > 0;
2396 };
2397 Dispatcher.prototype.removeSub = function (subscription) {
2398 this.subscriptions = _.without(subscription, this.subscriptions);
2399 return this.subscriptions;
2400 };
2401 Dispatcher.prototype.push = function (event) {
2402 if (event.isEnd) {
2403 this.ended = true;
2404 }
2405 return UpdateBarrier.inTransaction(event, this, this.pushIt, [event]);
2406 };
2407 Dispatcher.prototype.pushToSubscriptions = function (event) {
2408 try {
2409 var tmp = this.subscriptions;
2410 var len = tmp.length;
2411 for (var i = 0; i < len; i++) {
2412 var sub = tmp[i];
2413 var reply = sub.sink(event);
2414 if (reply === noMore || event.isEnd) {
2415 this.removeSub(sub);
2416 }
2417 }
2418 return true;
2419 }
2420 catch (error) {
2421 this.pushing = false;
2422 this.queue = []; // ditch queue in case of exception to avoid unexpected behavior
2423 throw error;
2424 }
2425 };
2426 Dispatcher.prototype.pushIt = function (event) {
2427 if (!this.pushing) {
2428 if (event === this.prevError) {
2429 return;
2430 }
2431 if (event.isError) {
2432 this.prevError = event;
2433 }
2434 this.pushing = true;
2435 this.pushToSubscriptions(event);
2436 this.pushing = false;
2437 while (true) {
2438 var e = this.queue.shift();
2439 if (e) {
2440 this.push(e);
2441 }
2442 else {
2443 break;
2444 }
2445 }
2446 if (this.hasSubscribers()) {
2447 return more;
2448 }
2449 else {
2450 this.unsubscribeFromSource();
2451 return noMore;
2452 }
2453 }
2454 else {
2455 this.queue.push(event);
2456 return more;
2457 }
2458 };
2459 Dispatcher.prototype.handleEvent = function (event) {
2460 if (this._handleEvent) {
2461 return this._handleEvent(event);
2462 }
2463 else {
2464 return this.push(event);
2465 }
2466 };
2467 Dispatcher.prototype.unsubscribeFromSource = function () {
2468 if (this.unsubSrc) {
2469 this.unsubSrc();
2470 }
2471 this.unsubSrc = undefined;
2472 };
2473 Dispatcher.prototype.subscribe = function (sink) {
2474 var _this = this;
2475 if (this.ended) {
2476 sink(endEvent());
2477 return nop;
2478 }
2479 else {
2480 assertFunction(sink);
2481 var subscription_1 = {
2482 sink: sink
2483 };
2484 this.subscriptions.push(subscription_1);
2485 if (this.subscriptions.length === 1) {
2486 this.unsubSrc = this._subscribe(this.handleEvent);
2487 assertFunction(this.unsubSrc);
2488 }
2489 return function () {
2490 _this.removeSub(subscription_1);
2491 if (!_this.hasSubscribers()) {
2492 return _this.unsubscribeFromSource();
2493 }
2494 };
2495 }
2496 };
2497 Dispatcher.prototype.inspect = function () {
2498 return this.observable.toString();
2499 };
2500 return Dispatcher;
2501}());
2502
2503/** @hidden */
2504var PropertyDispatcher = /** @class */ (function (_super) {
2505 __extends(PropertyDispatcher, _super);
2506 function PropertyDispatcher(property, subscribe, handleEvent) {
2507 var _this = _super.call(this, property, subscribe, handleEvent) || this;
2508 _this.current = none();
2509 _this.propertyEnded = false;
2510 _this.subscribe = _.bind(_this.subscribe, _this);
2511 return _this;
2512 }
2513 PropertyDispatcher.prototype.push = function (event) {
2514 //console.log("dispatch", event, "from", this)
2515 if (event.isEnd) {
2516 this.propertyEnded = true;
2517 }
2518 if (event instanceof Value) {
2519 //console.log("setting current")
2520 this.current = new Some(event);
2521 this.currentValueRootId = UpdateBarrier.currentEventId();
2522 }
2523 else if (event.hasValue) {
2524 console.error("Unknown event, two Bacons loaded?", event.constructor);
2525 }
2526 return _super.prototype.push.call(this, event);
2527 };
2528 PropertyDispatcher.prototype.maybeSubSource = function (sink, reply) {
2529 if (reply === noMore) {
2530 return nop;
2531 }
2532 else if (this.propertyEnded) {
2533 sink(endEvent());
2534 return nop;
2535 }
2536 else {
2537 return _super.prototype.subscribe.call(this, sink);
2538 }
2539 };
2540 PropertyDispatcher.prototype.subscribe = function (sink) {
2541 var _this = this;
2542 // init value is "bounced" here because the base Dispatcher class
2543 // won't add more than one subscription to the underlying observable.
2544 // without bouncing, the init value would be missing from all new subscribers
2545 // after the first one
2546 var reply = more;
2547 if (this.current.isDefined && (this.hasSubscribers() || this.propertyEnded)) {
2548 // should bounce init value
2549 var dispatchingId = UpdateBarrier.currentEventId();
2550 var valId = this.currentValueRootId;
2551 if (!this.propertyEnded && valId && dispatchingId && dispatchingId !== valId) {
2552 // when subscribing while already dispatching a value and this property hasn't been updated yet
2553 // we cannot bounce before this property is up to date.
2554 //console.log("bouncing with possibly stale value", event.value, "root at", valId, "vs", dispatchingId)
2555 UpdateBarrier.whenDoneWith(this.observable, function () {
2556 if (_this.currentValueRootId === valId) {
2557 //console.log("bouncing", this.current.get().value)
2558 return sink(initialEvent(_this.current.get().value));
2559 }
2560 });
2561 // the subscribing thing should be defered
2562 return this.maybeSubSource(sink, reply);
2563 }
2564 else {
2565 //console.log("bouncing immdiately", this.current.get().value)
2566 UpdateBarrier.inTransaction(undefined, this, function () {
2567 reply = sink(initialEvent(_this.current.get().value));
2568 return reply;
2569 }, []);
2570 return this.maybeSubSource(sink, reply);
2571 }
2572 }
2573 else {
2574 //console.log("normal subscribe", this)
2575 return this.maybeSubSource(sink, reply);
2576 }
2577 };
2578 PropertyDispatcher.prototype.inspect = function () {
2579 return this.observable + " current= " + this.current;
2580 };
2581 return PropertyDispatcher;
2582}(Dispatcher));
2583
2584/** @hidden */
2585function flatMapWithConcurrencyLimit(src, limit, f) {
2586 return flatMap_(handleEventValueWith(f), src, {
2587 desc: new Desc(src, "flatMapWithConcurrencyLimit", [limit, f]),
2588 limit: limit
2589 });
2590}
2591
2592/** @hidden */
2593function bufferWithTime(src, delay) {
2594 return bufferWithTimeOrCount(src, delay, Number.MAX_VALUE).withDesc(new Desc(src, "bufferWithTime", [delay]));
2595}
2596/** @hidden */
2597function bufferWithCount(src, count) {
2598 return bufferWithTimeOrCount(src, undefined, count).withDesc(new Desc(src, "bufferWithCount", [count]));
2599}
2600/** @hidden */
2601function bufferWithTimeOrCount(src, delay, count) {
2602 var delayFunc = toDelayFunction(delay);
2603 function flushOrSchedule(buffer) {
2604 if (buffer.values.length === count) {
2605 //console.log Bacon.scheduler.now() + ": count-flush"
2606 return buffer.flush();
2607 }
2608 else if (delayFunc !== undefined) {
2609 return buffer.schedule(delayFunc);
2610 }
2611 }
2612 var desc = new Desc(src, "bufferWithTimeOrCount", [delay, count]);
2613 return buffer(src, flushOrSchedule, flushOrSchedule).withDesc(desc);
2614}
2615var Buffer = /** @class */ (function () {
2616 function Buffer(onFlush, onInput) {
2617 this.push = function (e) { return more; };
2618 this.scheduled = null;
2619 this.end = undefined;
2620 this.values = [];
2621 this.onFlush = onFlush;
2622 this.onInput = onInput;
2623 }
2624 Buffer.prototype.flush = function () {
2625 if (this.scheduled) {
2626 GlobalScheduler.scheduler.clearTimeout(this.scheduled);
2627 this.scheduled = null;
2628 }
2629 if (this.values.length > 0) {
2630 //console.log Bacon.scheduler.now() + ": flush " + @values
2631 var valuesToPush = this.values;
2632 this.values = [];
2633 var reply = this.push(nextEvent(valuesToPush));
2634 if ((this.end != null)) {
2635 return this.push(this.end);
2636 }
2637 else if (reply !== noMore) {
2638 return this.onFlush(this);
2639 }
2640 }
2641 else {
2642 if ((this.end != null)) {
2643 return this.push(this.end);
2644 }
2645 }
2646 };
2647 Buffer.prototype.schedule = function (delay) {
2648 var _this = this;
2649 if (!this.scheduled) {
2650 return this.scheduled = delay(function () {
2651 //console.log Bacon.scheduler.now() + ": scheduled flush"
2652 return _this.flush();
2653 });
2654 }
2655 };
2656 return Buffer;
2657}());
2658function toDelayFunction(delay) {
2659 if (delay === undefined) {
2660 return undefined;
2661 }
2662 if (typeof delay === "number") {
2663 var delayMs = delay;
2664 return function (f) {
2665 //console.log Bacon.scheduler.now() + ": schedule for " + (Bacon.scheduler.now() + delayMs)
2666 return GlobalScheduler.scheduler.setTimeout(f, delayMs);
2667 };
2668 }
2669 return delay;
2670}
2671/** @hidden */
2672function buffer(src, onInput, onFlush) {
2673 if (onInput === void 0) { onInput = nop; }
2674 if (onFlush === void 0) { onFlush = nop; }
2675 var reply = more;
2676 var buffer = new Buffer(onFlush, onInput);
2677 return src.transform(function (event, sink) {
2678 buffer.push = sink;
2679 if (hasValue(event)) {
2680 buffer.values.push(event.value);
2681 //console.log Bacon.scheduler.now() + ": input " + event.value
2682 onInput(buffer);
2683 }
2684 else if (isError(event)) {
2685 reply = sink(event);
2686 }
2687 else if (isEnd(event)) {
2688 buffer.end = event;
2689 if (!buffer.scheduled) {
2690 //console.log Bacon.scheduler.now() + ": end-flush"
2691 buffer.flush();
2692 }
2693 }
2694 return reply;
2695 }).withDesc(new Desc(src, "buffer", []));
2696}
2697
2698/** @hidden */
2699function asyncWrapSubscribe(obs, subscribe) {
2700 //assertFunction(subscribe)
2701 var subscribing = false;
2702 return function wrappedSubscribe(sink) {
2703 //assertFunction(sink)
2704 var inTransaction = UpdateBarrier.isInTransaction();
2705 subscribing = true;
2706 var asyncDeliveries;
2707 function deliverAsync() {
2708 //console.log("delivering async", obs, asyncDeliveries)
2709 var toDeliverNow = asyncDeliveries || [];
2710 asyncDeliveries = undefined;
2711 for (var i = 0; i < toDeliverNow.length; i++) {
2712 var event = toDeliverNow[i];
2713 sink(event);
2714 }
2715 }
2716 try {
2717 return subscribe(function wrappedSink(event) {
2718 if (subscribing || asyncDeliveries) {
2719 // Deliver async if currently subscribing
2720 // Also queue further events until async delivery has been completed
2721 //console.log("Stream responded synchronously", obs)
2722 if (!asyncDeliveries) {
2723 asyncDeliveries = [event];
2724 if (inTransaction) {
2725 UpdateBarrier.soonButNotYet(obs, deliverAsync);
2726 }
2727 else {
2728 GlobalScheduler.scheduler.setTimeout(deliverAsync, 0);
2729 }
2730 }
2731 else {
2732 asyncDeliveries.push(event);
2733 }
2734 return more;
2735 }
2736 else {
2737 return sink(event);
2738 }
2739 });
2740 }
2741 finally {
2742 subscribing = false;
2743 }
2744 };
2745}
2746
2747/**
2748 Merges given array of EventStreams or Properties, by collecting the values from all of the sources into a single
2749 EventStream.
2750
2751 See also [`merge`](classes/eventstream.html#merge).
2752 */
2753function mergeAll() {
2754 var streams = [];
2755 for (var _i = 0; _i < arguments.length; _i++) {
2756 streams[_i] = arguments[_i];
2757 }
2758 var flattenedStreams = argumentsToObservables(streams);
2759 if (flattenedStreams.length) {
2760 return new EventStream(new Desc("Bacon", "mergeAll", flattenedStreams), function (sink) {
2761 var ends = 0;
2762 var smartSink = function (obs) {
2763 return function (unsubBoth) {
2764 return obs.subscribeInternal(function (event) {
2765 if (event.isEnd) {
2766 ends++;
2767 if (ends === flattenedStreams.length) {
2768 return sink(endEvent());
2769 }
2770 else {
2771 return more;
2772 }
2773 }
2774 else {
2775 event = event.toNext();
2776 var reply = sink(event);
2777 if (reply === noMore) {
2778 unsubBoth();
2779 }
2780 return reply;
2781 }
2782 });
2783 };
2784 };
2785 var sinks = map(smartSink, flattenedStreams);
2786 return new CompositeUnsubscribe(sinks).unsubscribe;
2787 });
2788 }
2789 else {
2790 return never();
2791 }
2792}
2793
2794/**
2795
2796 Creates a single-element stream that emits given value after given delay and ends.
2797
2798 @param delay delay in milliseconds
2799 @param value value to be emitted
2800 @typeparam V Type of stream elements
2801
2802 */
2803function later(delay, value) {
2804 return fromBinder(function (sink) {
2805 var sender = function () {
2806 return sink([toEvent(value), endEvent()]);
2807 };
2808 var id = GlobalScheduler.scheduler.setTimeout(sender, delay);
2809 return function () {
2810 return GlobalScheduler.scheduler.clearTimeout(id);
2811 };
2812 }).withDesc(new Desc("Bacon", "later", [delay, value]));
2813}
2814
2815/** @hidden */
2816function delay(src, delay) {
2817 return src.transformChanges(new Desc(src, "delay", [delay]), function (changes) {
2818 return changes.flatMap(function (value) {
2819 return later(delay, value);
2820 });
2821 });
2822}
2823
2824/** @hidden */
2825function debounce(src, delay) {
2826 return src.transformChanges(new Desc(src, "debounce", [delay]), function (changes) {
2827 return changes.flatMapLatest(function (value) {
2828 return later(delay, value);
2829 });
2830 });
2831}
2832/** @hidden */
2833function debounceImmediate(src, delay) {
2834 return src.transformChanges(new Desc(src, "debounceImmediate", [delay]), function (changes) {
2835 return changes.flatMapFirst(function (value) {
2836 return once(value).concat(later(delay, value).errors());
2837 });
2838 });
2839}
2840
2841/** @hidden */
2842function throttle(src, delay) {
2843 return src.transformChanges(new Desc(src, "throttle", [delay]), function (changes) {
2844 return changes.bufferWithTime(delay).map(function (values) { return values[values.length - 1]; });
2845 });
2846}
2847
2848/** @hidden */
2849function bufferingThrottle(src, minimumInterval) {
2850 var desc = new Desc(src, "bufferingThrottle", [minimumInterval]);
2851 return src.transformChanges(desc, function (changes) { return changes.flatMapConcat(function (x) {
2852 return once(x).concat(later(minimumInterval, x).errors());
2853 }); });
2854}
2855
2856/** @hidden */
2857function takeWhile(src, f) {
2858 return withPredicate(src, f, takeWhileT, new Desc(src, "takeWhile", [f]));
2859}
2860function takeWhileT(f) {
2861 return function (event, sink) {
2862 if (event.filter(f)) {
2863 return sink(event);
2864 }
2865 else {
2866 sink(endEvent());
2867 return noMore;
2868 }
2869 };
2870}
2871
2872/** @hidden */
2873function skipUntil(src, starter) {
2874 var started = starter
2875 .transform(composeT(takeT(1), mapT(true)))
2876 .toProperty()
2877 .startWith(false);
2878 return src.filter(started).withDesc(new Desc(src, "skipUntil", [starter]));
2879}
2880
2881/** @hidden */
2882function skipWhile(src, f) {
2883 return withPredicate(src, f, skipWhileT, new Desc(src, "skipWhile", [f]));
2884}
2885/** @hidden */
2886function skipWhileT(f) {
2887 var started = false;
2888 return function (event, sink) {
2889 if (started || !hasValue(event) || !f(event.value)) {
2890 if (event.hasValue) {
2891 started = true;
2892 }
2893 return sink(event);
2894 }
2895 else {
2896 return more;
2897 }
2898 };
2899}
2900
2901/** @hidden */
2902function groupBy(src, keyF, limitF) {
2903 if (limitF === void 0) { limitF = _.id; }
2904 var streams = {};
2905 return src.transform(composeT(filterT(function (x) { return !streams[keyF(x)]; }), mapT(function (firstValue) {
2906 var key = keyF(firstValue);
2907 var similarValues = src.changes().filter(function (x) { return keyF(x) === key; });
2908 var data = once(firstValue).concat(similarValues);
2909 var limited = limitF(data, firstValue).toEventStream().transform(function (event, sink) {
2910 var reply = sink(event);
2911 if (event.isEnd) {
2912 delete streams[key];
2913 }
2914 return reply;
2915 });
2916 streams[key] = limited;
2917 return limited;
2918 })));
2919}
2920
2921/** @hidden */
2922function slidingWindow(src, maxValues, minValues) {
2923 if (minValues === void 0) { minValues = 0; }
2924 return src.scan([], (function (window, value) {
2925 return window.concat([value]).slice(-maxValues);
2926 }))
2927 .filter((function (values) {
2928 return values.length >= minValues;
2929 })).withDesc(new Desc(src, "slidingWindow", [maxValues, minValues]));
2930}
2931
2932var nullMarker = {};
2933/** @hidden */
2934function diff(src, start, f) {
2935 return transformP(scan(src, [start, nullMarker], (function (prevTuple, next) { return [next, f(prevTuple[0], next)]; })), composeT(filterT(function (tuple) { return tuple[1] !== nullMarker; }), mapT(function (tuple) { return tuple[1]; })), new Desc(src, "diff", [start, f]));
2936}
2937
2938/** @hidden */
2939function flatScan(src, seed, f) {
2940 var current = seed;
2941 return src.flatMapConcat(function (next) {
2942 return makeObservable(f(current, next)).doAction(function (updated) { return current = updated; });
2943 }).toProperty().startWith(seed).withDesc(new Desc(src, "flatScan", [seed, f]));
2944}
2945
2946/** @hidden */
2947function holdWhen(src, valve) {
2948 var onHold = false;
2949 var bufferedValues = [];
2950 var srcIsEnded = false;
2951 return new EventStream(new Desc(src, "holdWhen", [valve]), function (sink) {
2952 var composite = new CompositeUnsubscribe();
2953 var subscribed = false;
2954 var endIfBothEnded = function (unsub) {
2955 if (unsub) {
2956 unsub();
2957 }
2958 if (composite.empty() && subscribed) {
2959 return sink(endEvent());
2960 }
2961 return more;
2962 };
2963 composite.add(function (unsubAll, unsubMe) {
2964 return valve.subscribeInternal(function (event) {
2965 if (hasValue(event)) {
2966 onHold = event.value;
2967 var result = more;
2968 if (!onHold) {
2969 var toSend = bufferedValues;
2970 bufferedValues = [];
2971 for (var i = 0; i < toSend.length; i++) {
2972 result = sink(nextEvent(toSend[i]));
2973 }
2974 if (srcIsEnded) {
2975 sink(endEvent());
2976 unsubMe();
2977 result = noMore;
2978 }
2979 }
2980 return result;
2981 }
2982 else if (event.isEnd) {
2983 return endIfBothEnded(unsubMe);
2984 }
2985 else {
2986 return sink(event);
2987 }
2988 });
2989 });
2990 composite.add(function (unsubAll, unsubMe) {
2991 return src.subscribeInternal(function (event) {
2992 if (onHold && hasValue(event)) {
2993 bufferedValues.push(event.value);
2994 return more;
2995 }
2996 else if (event.isEnd && bufferedValues.length) {
2997 srcIsEnded = true;
2998 return endIfBothEnded(unsubMe);
2999 }
3000 else {
3001 return sink(event);
3002 }
3003 });
3004 });
3005 subscribed = true;
3006 endIfBothEnded();
3007 return composite.unsubscribe;
3008 });
3009}
3010
3011/**
3012 Zips the array of EventStreams / Properties in to a new
3013 EventStream that will have an array of values from each source as
3014 its value. Zipping means that events from each source are combined
3015 pairwise so that the 1st event from each source is published first, then
3016 the 2nd event from each. The results will be published as soon as there
3017 is a value from each source.
3018
3019 Be careful not to have too much "drift" between streams. If one stream
3020 produces many more values than some other excessive buffering will
3021 occur inside the zipped observable.
3022
3023 Example:
3024
3025 ```js
3026 x = Bacon.fromArray([1,2,3])
3027 y = Bacon.fromArray([10, 20, 30])
3028 z = Bacon.fromArray([100, 200, 300])
3029 Bacon.zipAsArray(x, y, z)
3030
3031 # produces values [1, 10, 100], [2, 20, 200] and [3, 30, 300]
3032 ```
3033
3034 */
3035function zipAsArray() {
3036 var args = [];
3037 for (var _i = 0; _i < arguments.length; _i++) {
3038 args[_i] = arguments[_i];
3039 }
3040 var streams = _.map((function (s) { return s.toEventStream(); }), argumentsToObservables(args));
3041 return when([streams, function () {
3042 var xs = [];
3043 for (var _i = 0; _i < arguments.length; _i++) {
3044 xs[_i] = arguments[_i];
3045 }
3046 return xs;
3047 }]).withDesc(new Desc("Bacon", "zipAsArray", args));
3048}
3049/**
3050 Like [`zipAsArray`](#bacon-zipasarray) but uses the given n-ary
3051 function to combine the n values from n sources, instead of returning them in an Array.
3052 */
3053function zipWith(f) {
3054 var streams = [];
3055 for (var _i = 1; _i < arguments.length; _i++) {
3056 streams[_i - 1] = arguments[_i];
3057 }
3058 var _a = argumentsToObservablesAndFunction(arguments), streams = _a[0], f = _a[1];
3059 streams = _.map((function (s) { return s.toEventStream(); }), streams);
3060 return when([streams, f]).withDesc(new Desc("Bacon", "zipWith", [f].concat(streams)));
3061}
3062/** @hidden */
3063function zip(left, right, f) {
3064 return zipWith(f || Array, left, right).withDesc(new Desc(left, "zip", [right]));
3065}
3066
3067function combineTemplate(template) {
3068 function current(ctxStack) { return ctxStack[ctxStack.length - 1]; }
3069 function setValue(ctxStack, key, value) {
3070 current(ctxStack)[key] = value;
3071 return value;
3072 }
3073 function applyStreamValue(key, index) {
3074 return function (ctxStack, values) {
3075 setValue(ctxStack, key, values[index]);
3076 };
3077 }
3078 function constantValue(key, value) {
3079 return function (ctxStack) {
3080 setValue(ctxStack, key, value);
3081 };
3082 }
3083 function mkContext(template) {
3084 return isArray(template) ? [] : {};
3085 }
3086 function pushContext(key, value) {
3087 return function (ctxStack) {
3088 var newContext = mkContext(value);
3089 setValue(ctxStack, key, newContext);
3090 ctxStack.push(newContext);
3091 };
3092 }
3093 function containsObservables(value) {
3094 if (isObservable(value)) {
3095 return true;
3096 }
3097 else if (value && (value.constructor == Object || value.constructor == Array)) {
3098 for (var key in value) {
3099 if (Object.prototype.hasOwnProperty.call(value, key)) {
3100 var child = value[key];
3101 if (containsObservables(child))
3102 return true;
3103 }
3104 }
3105 }
3106 }
3107 function compile(key, value) {
3108 if (isObservable(value)) {
3109 streams.push(value);
3110 funcs.push(applyStreamValue(key, streams.length - 1));
3111 }
3112 else if (containsObservables(value)) {
3113 var popContext = function (ctxStack) { ctxStack.pop(); };
3114 funcs.push(pushContext(key, value));
3115 compileTemplate(value);
3116 funcs.push(popContext);
3117 }
3118 else {
3119 funcs.push(constantValue(key, value));
3120 }
3121 }
3122 function combinator(values) {
3123 var rootContext = mkContext(template);
3124 var ctxStack = [rootContext];
3125 for (var i = 0, f; i < funcs.length; i++) {
3126 f = funcs[i];
3127 f(ctxStack, values);
3128 }
3129 return rootContext;
3130 }
3131 function compileTemplate(template) { _.each(template, compile); }
3132 var funcs = [];
3133 var streams = [];
3134 var resultProperty = containsObservables(template)
3135 ? (compileTemplate(template), combineAsArray(streams).map(combinator))
3136 : constant(template);
3137 return resultProperty.withDesc(new Desc("Bacon", "combineTemplate", [template]));
3138}
3139
3140/** @hidden */
3141function decode(src, cases) {
3142 return src.combine(combineTemplate(cases), function (key, values) { return values[key]; })
3143 .withDesc(new Desc(src, "decode", [cases]));
3144}
3145
3146/** @hidden */
3147function firstToPromise(src, PromiseCtr) {
3148 var generator = function (resolve, reject) {
3149 return src.subscribe(function (event) {
3150 if (hasValue(event)) {
3151 resolve(event.value);
3152 }
3153 if (isError(event)) {
3154 reject(event.error);
3155 }
3156 // One event is enough
3157 return noMore;
3158 });
3159 };
3160 // Can't do in the global scope, as shim can be applied after Bacon is loaded.
3161 if (typeof PromiseCtr === "function") {
3162 return new PromiseCtr(generator);
3163 }
3164 else if (typeof Promise === "function") {
3165 return new Promise(generator);
3166 }
3167 else {
3168 throw new Error("There isn't default Promise, use shim or parameter");
3169 }
3170}
3171/** @hidden */
3172function toPromise(src, PromiseCtr) {
3173 return src.last().firstToPromise(PromiseCtr);
3174}
3175
3176var idCounter = 0;
3177/**
3178 Observable is the base class for [EventsStream](eventstream.html) and [Property](property.html)
3179
3180 @typeparam V Type of the elements/values in the stream/property
3181 */
3182var Observable = /** @class */ (function () {
3183 function Observable(desc) {
3184 /**
3185 * Unique numeric id of this Observable. Implemented using a simple counter starting from 1.
3186 */
3187 this.id = ++idCounter;
3188 /** @hidden */
3189 this._isObservable = true;
3190 this.desc = desc;
3191 this.initialDesc = desc;
3192 }
3193 /**
3194 Creates a Property that indicates whether
3195 `observable` is awaiting `otherObservable`, i.e. has produced a value after the latest
3196 value from `otherObservable`. This is handy for keeping track whether we are
3197 currently awaiting an AJAX response:
3198
3199 ```js
3200 var showAjaxIndicator = ajaxRequest.awaiting(ajaxResponse)
3201 ```
3202
3203 */
3204 Observable.prototype.awaiting = function (other) {
3205 return awaiting(this, other);
3206 };
3207 /**
3208 Throttles the observable using a buffer so that at most one value event in minimumInterval is issued.
3209 Unlike [`throttle`](#observable-throttle), it doesn't discard the excessive events but buffers them instead, outputting
3210 them with a rate of at most one value per minimumInterval.
3211
3212 Example:
3213
3214 ```js
3215 var throttled = source.bufferingThrottle(2)
3216 ```
3217
3218 ```
3219 source: asdf----asdf----
3220 throttled: a-s-d-f-a-s-d-f-
3221 ```
3222 */
3223 Observable.prototype.bufferingThrottle = function (minimumInterval) {
3224 return bufferingThrottle(this, minimumInterval);
3225 };
3226 /**
3227 Combines the latest values of the two
3228 streams or properties using a two-arg function. Similarly to [`scan`](#scan), you can use a
3229 method name instead, so you could do `a.combine(b, ".concat")` for two
3230 properties with array value. The result is a [Property](property.html).
3231 */
3232 Observable.prototype.combine = function (right, f) {
3233 return combineTwo(this, right, f).withDesc(new Desc(this, "combine", [right, f]));
3234 };
3235 /**
3236 Throttles stream/property by given amount
3237 of milliseconds, but so that event is only emitted after the given
3238 "quiet period". Does not affect emitting the initial value of a [Property](property.html).
3239 The difference of [`throttle`](#throttle) and [`debounce`](#debounce) is the same as it is in the
3240 same methods in jQuery.
3241
3242 Example:
3243
3244 ```
3245 source: asdf----asdf----
3246 source.debounce(2): -----f-------f--
3247 ```
3248
3249 */
3250 Observable.prototype.debounce = function (minimumInterval) {
3251 return debounce(this, minimumInterval);
3252 };
3253 /**
3254 Passes the first event in the
3255 stream through, but after that, only passes events after a given number
3256 of milliseconds have passed since previous output.
3257
3258 Example:
3259
3260 ```
3261 source: asdf----asdf----
3262 source.debounceImmediate(2): a-d-----a-d-----
3263 ```
3264 */
3265 Observable.prototype.debounceImmediate = function (minimumInterval) {
3266 return debounceImmediate(this, minimumInterval);
3267 };
3268 /**
3269 Decodes input using the given mapping. Is a
3270 bit like a switch-case or the decode function in Oracle SQL. For
3271 example, the following would map the value 1 into the string "mike"
3272 and the value 2 into the value of the `who` property.
3273
3274 ```js
3275 property.decode({1 : "mike", 2 : who})
3276 ```
3277
3278 This is actually based on [`combineTemplate`](#combinetemplate) so you can compose static
3279 and dynamic data quite freely, as in
3280
3281 ```js
3282 property.decode({1 : { type: "mike" }, 2 : { type: "other", whoThen : who }})
3283 ```
3284
3285 The return value of [`decode`](#decode) is always a [`Property`](property.html).
3286
3287 */
3288 //decode<T extends Record<any, any>>(src: Observable<keyof T>, cases: T): Property<DecodedValueOf<T>>
3289 Observable.prototype.decode = function (cases) {
3290 return decode(this, cases);
3291 };
3292 /**
3293 Delays the stream/property by given amount of milliseconds. Does not delay the initial value of a [`Property`](property.html).
3294
3295 ```js
3296 var delayed = source.delay(2)
3297 ```
3298
3299 ```
3300 source: asdf----asdf----
3301 delayed: --asdf----asdf--
3302 ```
3303
3304 */
3305 Observable.prototype.delay = function (delayMs) {
3306 return delay(this, delayMs);
3307 };
3308 /**
3309 * Returns the an array of dependencies that the Observable has. For instance, for `a.map(function() {}).deps()`, would return `[a]`.
3310 This method returns the "visible" dependencies only, skipping internal details. This method is thus suitable for visualization tools.
3311 Internally, many combinator functions depend on other combinators to create intermediate Observables that the result will actually depend on.
3312 The `deps` method will skip these internal dependencies. See also: [internalDeps](#internaldeps)
3313 */
3314 Observable.prototype.deps = function () {
3315 return this.desc.deps();
3316 };
3317 /**
3318 Returns a Property that represents the result of a comparison
3319 between the previous and current value of the Observable. For the initial value of the Observable,
3320 the previous value will be the given start.
3321
3322 Example:
3323
3324 ```js
3325 var distance = function (a,b) { return Math.abs(b - a) }
3326 Bacon.sequentially(1, [1,2,3]).diff(0, distance)
3327 ```
3328
3329 This would result to following elements in the result stream:
3330
3331 1 - 0 = 1
3332 2 - 1 = 1
3333 3 - 2 = 1
3334
3335 */
3336 Observable.prototype.diff = function (start, f) {
3337 return diff(this, start, f);
3338 };
3339 /**
3340 Returns a stream/property where the function f
3341 is executed for each value, before dispatching to subscribers. This is
3342 useful for debugging, but also for stuff like calling the
3343 `preventDefault()` method for events. In fact, you can
3344 also use a property-extractor string instead of a function, as in
3345 `".preventDefault"`.
3346
3347 Please note that for Properties, it's not guaranteed that the function will be called exactly once
3348 per event; when a Property loses all of its subscribers it will re-emit its current value when a
3349 new subscriber is added.
3350 */
3351 Observable.prototype.doAction = function (f) {
3352 return this.transform(doActionT(f), new Desc(this, "doAction", [f]));
3353 };
3354 Observable.prototype.doEnd = function (f) {
3355 return this.transform(doEndT(f), new Desc(this, "doEnd", [f]));
3356 };
3357 /**
3358 Returns a stream/property where the function f
3359 is executed for each error, before dispatching to subscribers.
3360 That is, same as [`doAction`](#observable-doaction) but for errors.
3361 */
3362 Observable.prototype.doError = function (f) {
3363 return this.transform(doErrorT(f), new Desc(this, "doError", [f]));
3364 };
3365 /**
3366 Logs each value of the Observable to the console. doLog() behaves like [`log`](#log)
3367 but does not subscribe to the event stream. You can think of doLog() as a
3368 logger function that – unlike log() – is safe to use in production. doLog() is
3369 safe, because it does not cause the same surprising side-effects as log()
3370 does.
3371 */
3372 Observable.prototype.doLog = function () {
3373 var args = [];
3374 for (var _i = 0; _i < arguments.length; _i++) {
3375 args[_i] = arguments[_i];
3376 }
3377 return this.transform(doLogT(args), new Desc(this, "doLog", args));
3378 };
3379 Observable.prototype.endAsValue = function () {
3380 return endAsValue(this);
3381 };
3382 /**
3383 Returns a stream/property that ends the on first [`Error`](error.html) event. The
3384 error is included in the output of the returned Observable.
3385
3386 @param predicate optional predicate function to determine whether to end on a given error
3387 */
3388 Observable.prototype.endOnError = function (predicate) {
3389 if (predicate === void 0) { predicate = function (x) { return true; }; }
3390 return endOnError(this, predicate);
3391 };
3392 /**
3393 Returns a stream containing [`Error`](error.html) events only.
3394 Same as filtering with a function that always returns false.
3395 */
3396 Observable.prototype.errors = function () {
3397 return this.filter(function (x) { return false; }).withDesc(new Desc(this, "errors"));
3398 };
3399 /**
3400 Filters values using given predicate function.
3401 Instead of a function, you can use a constant value (`true` to include all, `false` to exclude all).
3402
3403 You can also filter values based on the value of a
3404 property. Event will be included in output [if and only if](http://en.wikipedia.org/wiki/If_and_only_if) the property holds `true`
3405 at the time of the event.
3406 */
3407 Observable.prototype.filter = function (f) {
3408 return filter$1(this, f);
3409 };
3410 /**
3411 Takes the first element from the stream. Essentially `observable.take(1)`.
3412 */
3413 Observable.prototype.first = function () {
3414 return take(1, this, new Desc(this, "first"));
3415 };
3416 /**
3417 Returns a Promise which will be resolved with the first event coming from an Observable.
3418 Like [`toPromise`](#topromise), the global ES6 promise implementation will be used unless a promise
3419 constructor is given.
3420 */
3421 Observable.prototype.firstToPromise = function (PromiseCtr) {
3422 return firstToPromise(this, PromiseCtr);
3423 };
3424 /**
3425 Works like [`scan`](#scan) but only emits the final
3426 value, i.e. the value just before the observable ends. Returns a
3427 [`Property`](property.html).
3428 */
3429 Observable.prototype.fold = function (seed, f) {
3430 return fold$1(this, seed, f);
3431 };
3432 /**
3433 An alias for [onValue](#onvalue).
3434
3435 Subscribes a given handler function to the observable. Function will be called for each new value (not for errors or stream end).
3436 */
3437 Observable.prototype.forEach = function (f) {
3438 if (f === void 0) { f = nullSink; }
3439 // TODO: inefficient alias. Also, similar assign alias missing.
3440 return this.onValue(f);
3441 };
3442 /**
3443 Pauses and buffers the event stream if last event in valve is truthy.
3444 All buffered events are released when valve becomes falsy.
3445 */
3446 Observable.prototype.holdWhen = function (valve) {
3447 return holdWhen(this, valve);
3448 };
3449 Observable.prototype.inspect = function () { return this.toString(); };
3450 /**
3451 * Returns the true dependencies of the observable, including the intermediate "hidden" Observables.
3452 This method is for Bacon.js internal purposes but could be useful for debugging/analysis tools as well.
3453 See also: [deps](#deps)
3454 */
3455 Observable.prototype.internalDeps = function () {
3456 return this.initialDesc.deps();
3457 };
3458 /**
3459 Takes the last element from the stream. None, if stream is empty.
3460
3461
3462 *Note:* `neverEndingStream.last()` creates the stream which doesn't produce any events and never ends.
3463 */
3464 Observable.prototype.last = function () {
3465 return last$1(this);
3466 };
3467 /**
3468 Logs each value of the Observable to the console.
3469 It optionally takes arguments to pass to console.log() alongside each
3470 value. To assist with chaining, it returns the original Observable. Note
3471 that as a side-effect, the observable will have a constant listener and
3472 will not be garbage-collected. So, use this for debugging only and
3473 remove from production code. For example:
3474
3475 ```js
3476 myStream.log("New event in myStream")
3477 ```
3478
3479 or just
3480
3481 ```js
3482 myStream.log()
3483 ```
3484
3485 */
3486 Observable.prototype.log = function () {
3487 var args = [];
3488 for (var _i = 0; _i < arguments.length; _i++) {
3489 args[_i] = arguments[_i];
3490 }
3491 log(args, this);
3492 return this;
3493 };
3494 /**
3495 Adds an extra [`Next`](next.html) event just before End. The value is created
3496 by calling the given function when the source stream ends. Instead of a
3497 function, a static value can be used.
3498 */
3499 // TODO: mapEnd and mapError signatures should allow V|V2
3500 Observable.prototype.mapEnd = function (f) {
3501 return this.transform(mapEndT(f), new Desc(this, "mapEnd", [f]));
3502 };
3503 /**
3504 Maps errors using given function. More
3505 specifically, feeds the "error" field of the error event to the function
3506 and produces a [`Next`](next.html) event based on the return value.
3507 */
3508 Observable.prototype.mapError = function (f) {
3509 return this.transform(mapErrorT(f), new Desc(this, "mapError", [f]));
3510 };
3511 /**
3512 Sets the name of the observable. Overrides the default
3513 implementation of [`toString`](#tostring) and `inspect`.
3514 Returns the same observable, with mutated name.
3515 */
3516 Observable.prototype.name = function (name) {
3517 this._name = name;
3518 return this;
3519 };
3520 /**
3521 Subscribes a callback to stream end. The function will be called when the stream ends.
3522 Just like `subscribe`, this method returns a function for unsubscribing.
3523 */
3524 Observable.prototype.onEnd = function (f) {
3525 if (f === void 0) { f = nullVoidSink; }
3526 return this.subscribe(function (event) {
3527 if (event.isEnd) {
3528 return f();
3529 }
3530 return more;
3531 });
3532 };
3533 /**
3534 Subscribes a handler to error events. The function will be called for each error in the stream.
3535 Just like `subscribe`, this method returns a function for unsubscribing.
3536 */
3537 Observable.prototype.onError = function (f) {
3538 if (f === void 0) { f = nullSink; }
3539 return this.subscribe(function (event) {
3540 if (isError(event)) {
3541 return f(event.error);
3542 }
3543 return more;
3544 });
3545 };
3546 /**
3547 Subscribes a given handler function to the observable. Function will be called for each new value.
3548 This is the simplest way to assign a side-effect to an observable. The difference
3549 to the `subscribe` method is that the actual stream values are
3550 received, instead of [`Event`](event) objects.
3551 Just like `subscribe`, this method returns a function for unsubscribing.
3552 `stream.onValue` and `property.onValue` behave similarly, except that the latter also
3553 pushes the initial value of the property, in case there is one.
3554 */
3555 Observable.prototype.onValue = function (f) {
3556 if (f === void 0) { f = nullSink; }
3557 return this.subscribe(function (event) {
3558 if (hasValue(event)) {
3559 return f(event.value);
3560 }
3561 return more;
3562 });
3563 };
3564 /**
3565 Like [`onValue`](#onvalue), but splits the value (assuming its an array) as function arguments to `f`.
3566 Only applicable for observables with arrays as values.
3567 */
3568 Observable.prototype.onValues = function (f) {
3569 return this.onValue(function (args) { return f.apply(void 0, args); });
3570 };
3571 /** A synonym for [scan](#scan).
3572 */
3573 Observable.prototype.reduce = function (seed, f) {
3574 return fold$1(this, seed, f);
3575 };
3576 Observable.prototype.sampledBy = function (sampler) {
3577 return sampledBy(this, sampler, arguments[1]); // TODO: combinator
3578 };
3579 /**
3580 Scans stream/property with given seed value and
3581 accumulator function, resulting to a Property. For example, you might
3582 use zero as seed and a "plus" function as the accumulator to create
3583 an "integral" property. Instead of a function, you can also supply a
3584 method name such as ".concat", in which case this method is called on
3585 the accumulator value and the new stream value is used as argument.
3586
3587 Example:
3588
3589 ```js
3590 var plus = function (a,b) { return a + b }
3591 Bacon.sequentially(1, [1,2,3]).scan(0, plus)
3592 ```
3593
3594 This would result to following elements in the result stream:
3595
3596 seed value = 0
3597 0 + 1 = 1
3598 1 + 2 = 3
3599 3 + 3 = 6
3600
3601 When applied to a Property as in `r = p.scan(seed, f)`, there's a (hopefully insignificant) catch:
3602 The starting value for `r` depends on whether `p` has an
3603 initial value when scan is applied. If there's no initial value, this works
3604 identically to EventStream.scan: the `seed` will be the initial value of
3605 `r`. However, if `r` already has a current/initial value `x`, the
3606 seed won't be output as is. Instead, the initial value of `r` will be `f(seed, x)`. This makes sense,
3607 because there can only be 1 initial value for a Property at a time.
3608 */
3609 Observable.prototype.scan = function (seed, f) {
3610 return scan(this, seed, f);
3611 };
3612 /**
3613 Skips the first n elements from the stream
3614 */
3615 Observable.prototype.skip = function (count) {
3616 return skip(this, count);
3617 };
3618 /**
3619 Drops consecutive equal elements. So,
3620 from `[1, 2, 2, 1]` you'd get `[1, 2, 1]`. Uses the `===` operator for equality
3621 checking by default. If the isEqual argument is supplied, checks by calling
3622 isEqual(oldValue, newValue). For instance, to do a deep comparison,you can
3623 use the isEqual function from [underscore.js](http://underscorejs.org/)
3624 like `stream.skipDuplicates(_.isEqual)`.
3625 */
3626 Observable.prototype.skipDuplicates = function (isEqual) {
3627 return skipDuplicates(this, isEqual);
3628 };
3629 /**
3630 * Returns a new stream/property which excludes all [Error](error.html) events in the source
3631 */
3632 Observable.prototype.skipErrors = function () {
3633 return skipErrors(this);
3634 };
3635 /**
3636 Skips elements from the source, until a value event
3637 appears in the given `starter` stream/property. In other words, starts delivering values
3638 from the source after first value appears in `starter`.
3639 */
3640 Observable.prototype.skipUntil = function (starter) {
3641 return skipUntil(this, starter);
3642 };
3643 /**
3644 Skips elements until the given predicate function returns falsy once, and then
3645 lets all events pass through. Instead of a predicate you can also pass in a `Property<boolean>` to skip elements
3646 while the Property holds a truthy value.
3647 */
3648 Observable.prototype.skipWhile = function (f) {
3649 return skipWhile(this, f);
3650 };
3651 /**
3652 Returns a Property that represents a
3653 "sliding window" into the history of the values of the Observable. The
3654 result Property will have a value that is an array containing the last `n`
3655 values of the original observable, where `n` is at most the value of the
3656 `max` argument, and at least the value of the `min` argument. If the
3657 `min` argument is omitted, there's no lower limit of values.
3658
3659 For example, if you have a stream `s` with value a sequence 1 - 2 - 3 - 4 - 5, the
3660 respective values in `s.slidingWindow(2)` would be [] - [1] - [1,2] -
3661 [2,3] - [3,4] - [4,5]. The values of `s.slidingWindow(2,2)`would be
3662 [1,2] - [2,3] - [3,4] - [4,5].
3663
3664 */
3665 Observable.prototype.slidingWindow = function (maxValues, minValues) {
3666 if (minValues === void 0) { minValues = 0; }
3667 return slidingWindow(this, maxValues, minValues);
3668 };
3669 /**
3670 * subscribes given handler function to event stream. Function will receive [event](event.html) objects
3671 for all new value, end and error events in the stream.
3672 The subscribe() call returns a `unsubscribe` function that you can call to unsubscribe.
3673 You can also unsubscribe by returning [`Bacon.noMore`](../globals.html#nomore) from the handler function as a reply
3674 to an Event.
3675 `stream.subscribe` and `property.subscribe` behave similarly, except that the latter also
3676 pushes the initial value of the property, in case there is one.
3677
3678 * @param {EventSink<V>} sink the handler function
3679 * @returns {Unsub}
3680 */
3681 Observable.prototype.subscribe = function (sink) {
3682 var _this = this;
3683 if (sink === void 0) { sink = nullSink; }
3684 return UpdateBarrier.wrappedSubscribe(this, function (sink) { return _this.subscribeInternal(sink); }, sink);
3685 };
3686 /**
3687 Takes at most n values from the stream and then ends the stream. If the stream has
3688 fewer than n values then it is unaffected.
3689 Equal to [`Bacon.never()`](../globals.html#never) if `n <= 0`.
3690 */
3691 Observable.prototype.take = function (count) {
3692 return take(count, this);
3693 };
3694 /**
3695 Takes elements from source until a value event appears in the other stream.
3696 If other stream ends without value, it is ignored.
3697 */
3698 Observable.prototype.takeUntil = function (stopper) {
3699 return takeUntil(this, stopper);
3700 };
3701 /**
3702 Takes while given predicate function holds true, and then ends. Alternatively, you can supply a boolean Property to take elements while the Property holds `true`.
3703 */
3704 Observable.prototype.takeWhile = function (f) {
3705 return takeWhile(this, f);
3706 };
3707 /**
3708 Throttles stream/property by given amount
3709 of milliseconds. Events are emitted with the minimum interval of
3710 [`delay`](#observable-delay). The implementation is based on [`stream.bufferWithTime`](#stream-bufferwithtime).
3711 Does not affect emitting the initial value of a [`Property`](#property).
3712
3713 Example:
3714
3715 ```js
3716 var throttled = source.throttle(2)
3717 ```
3718
3719 ```
3720 source: asdf----asdf----
3721 throttled: --s--f----s--f--
3722 ```
3723 */
3724 Observable.prototype.throttle = function (minimumInterval) {
3725 return throttle(this, minimumInterval);
3726 };
3727 /**
3728 Returns a Promise which will be resolved with the last event coming from an Observable.
3729 The global ES6 promise implementation will be used unless a promise constructor is given.
3730 Use a shim if you need to support legacy browsers or platforms.
3731 [caniuse promises](http://caniuse.com/#feat=promises).
3732
3733 See also [firstToPromise](#firsttopromise).
3734 */
3735 Observable.prototype.toPromise = function (PromiseCtr) {
3736 return toPromise(this, PromiseCtr);
3737 };
3738 /**
3739 *Returns a textual description of the Observable. For instance, `Bacon.once(1).map(function() {}).toString()` would return "Bacon.once(1).map(function)".
3740 **/
3741 Observable.prototype.toString = function () {
3742 if (this._name) {
3743 return this._name;
3744 }
3745 else {
3746 return this.desc.toString();
3747 }
3748 };
3749 Observable.prototype.withDesc = function (desc) {
3750 if (desc)
3751 this.desc = desc;
3752 return this;
3753 };
3754 /**
3755 Sets the structured description of the observable. The [`toString`](#tostring) and `inspect` methods
3756 use this data recursively to create a string representation for the observable. This method
3757 is probably useful for Bacon core / library / plugin development only.
3758
3759 For example:
3760
3761 var src = Bacon.once(1)
3762 var obs = src.map(function(x) { return -x })
3763 console.log(obs.toString())
3764 --> Bacon.once(1).map(function)
3765 obs.withDescription(src, "times", -1)
3766 console.log(obs.toString())
3767 --> Bacon.once(1).times(-1)
3768
3769 The method returns the same observable with mutated description.
3770
3771 */
3772 Observable.prototype.withDescription = function (context, method) {
3773 var args = [];
3774 for (var _i = 2; _i < arguments.length; _i++) {
3775 args[_i - 2] = arguments[_i];
3776 }
3777 this.desc = describe.apply(void 0, __spreadArrays([context, method], args));
3778 return this;
3779 };
3780 /**
3781 Returns an EventStream with elements
3782 pair-wise lined up with events from this and the other EventStream or Property.
3783 A zipped stream will publish only when it has a value from each
3784 source and will only produce values up to when any single source ends.
3785
3786 The given function `f` is used to create the result value from value in the two
3787 sources. If no function is given, the values are zipped into an array.
3788
3789 Be careful not to have too much "drift" between streams. If one stream
3790 produces many more values than some other excessive buffering will
3791 occur inside the zipped observable.
3792
3793 Example 1:
3794
3795 ```js
3796 var x = Bacon.fromArray([1, 2])
3797 var y = Bacon.fromArray([3, 4])
3798 x.zip(y, function(x, y) { return x + y })
3799
3800 # produces values 4, 6
3801 ```
3802
3803 See also [`zipWith`](../globals.html#zipwith) and [`zipAsArray`](../globals.html/zipasarray) for zipping more than 2 sources.
3804
3805 */
3806 Observable.prototype.zip = function (other, f) {
3807 return zip(this, other, f);
3808 };
3809 return Observable;
3810}());
3811/**
3812 A reactive property. Has the concept of "current value".
3813 You can create a Property from an EventStream by using either [`toProperty`](eventstream.html#toproperty)
3814 or [`scan`](eventstream.html#scan) method. Note: depending on how a Property is created, it may or may not
3815 have an initial value. The current value stays as its last value after the stream has ended.
3816
3817 Here are the most common ways for creating Properties:
3818
3819 - Create a constant property with [constant](../globals.html#constant)
3820 - Create a property based on an EventStream with [toProperty](eventstream.html#toproperty)
3821 - Scan an EventStream with an accumulator function with [scan](eventstream.html#scan)
3822 - Create a state property based on multiple sources using [update](../globals.html#update)
3823
3824 @typeparam V Type of the elements/values in the stream/property
3825 */
3826var Property = /** @class */ (function (_super) {
3827 __extends(Property, _super);
3828 function Property(desc, subscribe, handler) {
3829 var _this = _super.call(this, desc) || this;
3830 /** @internal */
3831 _this._isProperty = true;
3832 assertFunction(subscribe);
3833 _this.dispatcher = new PropertyDispatcher(_this, subscribe, handler);
3834 registerObs(_this);
3835 return _this;
3836 }
3837 /**
3838 Combines properties with the `&&` operator. It produces a new value when either of the Properties change,
3839 combining the latest values using `&&`.
3840 */
3841 Property.prototype.and = function (other) {
3842 return and(this, other);
3843 };
3844 /**
3845 * creates a stream of changes to the Property. The stream *does not* include
3846 an event for the current value of the Property at the time this method was called.
3847 */
3848 Property.prototype.changes = function () {
3849 var _this = this;
3850 return new EventStream(new Desc(this, "changes", []), function (sink) { return _this.dispatcher.subscribe(function (event) {
3851 if (!event.isInitial) {
3852 return sink(event);
3853 }
3854 return more;
3855 }); });
3856 };
3857 Property.prototype.concat = function (other) {
3858 return this.transformChanges(describe(this, "concat", other), function (changes) { return changes.concat(other); });
3859 };
3860 /** @hidden */
3861 Property.prototype.transformChanges = function (desc, f) {
3862 return transformPropertyChanges(this, f, desc);
3863 };
3864 /**
3865 For each element in the source stream, spawn a new
3866 stream/property using the function `f`. Collect events from each of the spawned
3867 streams into the result property. Note that instead of a function, you can provide a
3868 stream/property too. Also, the return value of function `f` can be either an
3869 `Observable` (stream/property) or a constant value.
3870
3871 `stream.flatMap()` can be used conveniently with [`Bacon.once()`](../globals.html#once) and [`Bacon.never()`](../globals.html#never)
3872 for converting and filtering at the same time, including only some of the results.
3873
3874 Example - converting strings to integers, skipping empty values:
3875
3876 ```js
3877 stream.flatMap(function(text) {
3878 return (text != "") ? parseInt(text) : Bacon.never()
3879 })
3880 ```
3881 */
3882 Property.prototype.flatMap = function (f) {
3883 return flatMap$1(this, f);
3884 };
3885 /**
3886 A [`flatMapWithConcurrencyLimit`](#flatmapwithconcurrencylimit) with limit of 1.
3887 */
3888 Property.prototype.flatMapConcat = function (f) {
3889 return flatMapConcat(this, f);
3890 };
3891 /**
3892 Like [`flatMap`](#flatmap), but is applied only on [`Error`](error.html) events. Returned values go into the
3893 value stream, unless an error event is returned. As an example, one type of error could result in a retry and another just
3894 passed through, which can be implemented using flatMapError.
3895 */
3896 Property.prototype.flatMapError = function (f) {
3897 return flatMapError(this, f);
3898 };
3899 Property.prototype.flatMapEvent = function (f) {
3900 return flatMapEvent(this, f);
3901 };
3902 /**
3903 Like [`flatMap`](#observable-flatmap), but only spawns a new
3904 stream if the previously spawned stream has ended.
3905 */
3906 Property.prototype.flatMapFirst = function (f) {
3907 return flatMapFirst(this, f);
3908 };
3909 /**
3910 Like [`flatMap`](#flatmap), but instead of including events from
3911 all spawned streams, only includes them from the latest spawned stream.
3912 You can think this as switching from stream to stream.
3913 Note that instead of a function, you can provide a stream/property too.
3914 */
3915 Property.prototype.flatMapLatest = function (f) {
3916 return flatMapLatest(this, f);
3917 };
3918 /**
3919 A super method of *flatMap* family. It limits the number of open spawned streams and buffers incoming events.
3920 [`flatMapConcat`](#flatmapconcat) is `flatMapWithConcurrencyLimit(1)` (only one input active),
3921 and [`flatMap`](#flatmap) is `flatMapWithConcurrencyLimit ∞` (all inputs are piped to output).
3922 */
3923 Property.prototype.flatMapWithConcurrencyLimit = function (limit, f) {
3924 return flatMapWithConcurrencyLimit(this, limit, f);
3925 };
3926 /**
3927 Groups stream events to new streams by `keyF`. Optional `limitF` can be provided to limit grouped
3928 stream life. Stream transformed by `limitF` is passed on if provided. `limitF` gets grouped stream
3929 and the original event causing the stream to start as parameters.
3930
3931 Calculator for grouped consecutive values until group is cancelled:
3932
3933 ```
3934 var events = [
3935 {id: 1, type: "add", val: 3 },
3936 {id: 2, type: "add", val: -1 },
3937 {id: 1, type: "add", val: 2 },
3938 {id: 2, type: "cancel"},
3939 {id: 3, type: "add", val: 2 },
3940 {id: 3, type: "cancel"},
3941 {id: 1, type: "add", val: 1 },
3942 {id: 1, type: "add", val: 2 },
3943 {id: 1, type: "cancel"}
3944 ]
3945
3946 function keyF(event) {
3947 return event.id
3948 }
3949
3950 function limitF(groupedStream, groupStartingEvent) {
3951 var cancel = groupedStream.filter(function(x) { return x.type === "cancel"}).take(1)
3952 var adds = groupedStream.filter(function(x) { return x.type === "add" })
3953 return adds.takeUntil(cancel).map(".val")
3954 }
3955
3956 Bacon.sequentially(2, events)
3957 .groupBy(keyF, limitF)
3958 .flatMap(function(groupedStream) {
3959 return groupedStream.fold(0, function(acc, x) { return acc + x })
3960 })
3961 .onValue(function(sum) {
3962 console.log(sum)
3963 // returns [-1, 2, 8] in an order
3964 })
3965 ```
3966
3967 */
3968 Property.prototype.groupBy = function (keyF, limitF) {
3969 return groupBy(this, keyF, limitF);
3970 };
3971 /**
3972 Maps values using given function, returning a new
3973 stream/property. Instead of a function, you can also provide a [Property](property.html),
3974 in which case each element in the source stream will be mapped to the current value of
3975 the given property.
3976 */
3977 Property.prototype.map = function (f) {
3978 return map$1(this, f);
3979 };
3980 /** Returns a Property that inverts the value of this one (using the `!` operator). **/
3981 Property.prototype.not = function () {
3982 return not(this);
3983 };
3984 /**
3985 Combines properties with the `||` operator. It produces a new value when either of the Properties change,
3986 combining the latest values using `||`.
3987 */
3988 Property.prototype.or = function (other) {
3989 return or(this, other);
3990 };
3991 /**
3992 Creates an EventStream by sampling the
3993 property value at given interval (in milliseconds)
3994 */
3995 Property.prototype.sample = function (interval) {
3996 return sampleP(this, interval);
3997 };
3998 /**
3999 Adds an initial "default" value for the
4000 Property. If the Property doesn't have an initial value of it's own, the
4001 given value will be used as the initial value. If the property has an
4002 initial value of its own, the given value will be ignored.
4003 */
4004 Property.prototype.startWith = function (seed) {
4005 return startWithP(this, seed);
4006 };
4007 /** @hidden */
4008 Property.prototype.subscribeInternal = function (sink) {
4009 if (sink === void 0) { sink = nullSink; }
4010 return this.dispatcher.subscribe(sink);
4011 };
4012 /**
4013 Creates an EventStream based on this Property. The stream contains also an event for the current
4014 value of this Property at the time this method was called.
4015 */
4016 Property.prototype.toEventStream = function (options) {
4017 var _this = this;
4018 return new EventStream(new Desc(this, "toEventStream", []), function (sink) { return _this.subscribeInternal(function (event) {
4019 return sink(event.toNext());
4020 }); }, undefined, options);
4021 };
4022 /**
4023 Returns the Property itself.
4024 */
4025 Property.prototype.toProperty = function () {
4026 assertNoArguments(arguments);
4027 return this;
4028 };
4029 Property.prototype.transform = function (transformer, desc) {
4030 return transformP(this, transformer, desc);
4031 };
4032 /**
4033 Creates an EventStream/Property by sampling a given `samplee`
4034 stream/property value at each event from the this stream/property.
4035
4036 @param {Observable<V2>} samplee
4037 @param f function to select/calculate the result value based on the value in the source stream and the samplee
4038
4039 @typeparam V2 type of values in the samplee
4040 @typeparam R type of values in the result
4041 */
4042 Property.prototype.withLatestFrom = function (samplee, f) {
4043 return withLatestFromP(this, samplee, f);
4044 };
4045 /**
4046 Lets you run a state machine
4047 on an observable. Give it an initial state object and a state
4048 transformation function that processes each incoming event and
4049 returns an array containing the next state and an array of output
4050 events. Here's an example where we calculate the total sum of all
4051 numbers in the stream and output the value on stream end:
4052
4053 ```js
4054 Bacon.fromArray([1,2,3])
4055 .withStateMachine(0, function(sum, event) {
4056 if (event.hasValue)
4057 return [sum + event.value, []]
4058 else if (event.isEnd)
4059 return [undefined, [new Bacon.Next(sum), event]]
4060 else
4061 return [sum, [event]]
4062 })
4063 ```
4064 @param initState initial state for the state machine
4065 @param f the function that defines the state machine
4066 @typeparam State type of machine state
4067 @typeparam Out type of values to be emitted
4068 */
4069 Property.prototype.withStateMachine = function (initState, f) {
4070 return withStateMachine(initState, f, this);
4071 };
4072 return Property;
4073}(Observable));
4074/** @hidden */
4075function isProperty(x) {
4076 return !!x._isProperty;
4077}
4078// allowSync option is used for overriding the "force async" behaviour or EventStreams.
4079// ideally, this should not exist, but right now the implementation of some operations
4080// relies on using internal EventStreams that have synchronous behavior. These are not exposed
4081// to the outside world, though.
4082/** @hidden */
4083var allowSync = { forceAsync: false };
4084/**
4085 * EventStream represents a stream of events. It is an Observable object, meaning
4086 that you can listen to events in the stream using, for instance, the [`onValue`](#onvalue) method
4087 with a callback.
4088
4089 To create an EventStream, you'll want to use one of the following factory methods:
4090
4091 - From DOM EventTarget or Node.JS EventEmitter objects using [fromEvent](../globals.html#fromevent)
4092 - From a Promise using [fromPromise](../globals.html#frompromise)
4093 - From an unary callback using [fromCallback](../globals.html#fromcallback)
4094 - From a Node.js style callback using [fromNodeCallback](../globals.html#fromnodecallback)
4095 - From RxJs or Kefir observables using [fromESObservable](../globals.html#fromesobservable)
4096 - By polling a synchronous function using [fromPoll](../globals.html#fromPoll)
4097 - Emit a single event instantly using [once](../globals.html#once)
4098 - Emit a single event with a delay [later](../globals.html#later)
4099 - Emit the same event indefinitely using [interval](../globals.html#interval)
4100 - Emit an array of events instantly [fromArray](../globals.html#fromarray)
4101 - Emit an array of events with a delay [sequentially](../globals.html#sequentially)
4102 - Emit an array of events repeatedly with a delay [repeatedly](../globals.html#repeatedly)
4103 - Use a generator function to be called repeatedly [repeat](../globals.html#repeat)
4104 - Create a stream that never emits an event, ending immediately [never](../globals.html#never)
4105 - Create a stream that never emits an event, ending with a delay [silence](../globals.html#silence)
4106 - Create stream using a custom binder function [fromBinder](../globals.html#frombinder)
4107 - Wrap jQuery events using [asEventStream](../globals.html#_)
4108
4109
4110 @typeparam V Type of the elements/values in the stream/property
4111
4112 */
4113var EventStream = /** @class */ (function (_super) {
4114 __extends(EventStream, _super);
4115 function EventStream(desc, subscribe, handler, options) {
4116 var _this = _super.call(this, desc) || this;
4117 /** @hidden */
4118 _this._isEventStream = true;
4119 if (options !== allowSync) {
4120 subscribe = asyncWrapSubscribe(_this, subscribe);
4121 }
4122 _this.dispatcher = new Dispatcher(_this, subscribe, handler);
4123 registerObs(_this);
4124 return _this;
4125 }
4126 /**
4127 Buffers stream events with given delay.
4128 The buffer is flushed at most once in the given interval. So, if your input
4129 contains [1,2,3,4,5,6,7], then you might get two events containing [1,2,3,4]
4130 and [5,6,7] respectively, given that the flush occurs between numbers 4 and 5.
4131
4132 Also works with a given "defer-function" instead
4133 of a delay. Here's a simple example, which is equivalent to
4134 stream.bufferWithTime(10):
4135
4136 ```js
4137 stream.bufferWithTime(function(f) { setTimeout(f, 10) })
4138 ```
4139
4140 * @param delay buffer duration in milliseconds
4141 */
4142 EventStream.prototype.bufferWithTime = function (delay) {
4143 return bufferWithTime(this, delay);
4144 };
4145 /**
4146 Buffers stream events with given count.
4147 The buffer is flushed when it contains the given number of elements or the source stream ends.
4148
4149 So, if you buffer a stream of `[1, 2, 3, 4, 5]` with count `2`, you'll get output
4150 events with values `[1, 2]`, `[3, 4]` and `[5]`.
4151
4152 * @param {number} count
4153 */
4154 EventStream.prototype.bufferWithCount = function (count) {
4155 return bufferWithCount(this, count);
4156 };
4157 /**
4158 Buffers stream events and
4159 flushes when either the buffer contains the given number elements or the
4160 given amount of milliseconds has passed since last buffered event.
4161
4162 * @param {number | DelayFunction} delay in milliseconds or as a function
4163 * @param {number} count maximum buffer size
4164 */
4165 EventStream.prototype.bufferWithTimeOrCount = function (delay, count) {
4166 return bufferWithTimeOrCount(this, delay, count);
4167 };
4168 EventStream.prototype.changes = function () {
4169 return this;
4170 };
4171 EventStream.prototype.concat = function (other, options) {
4172 return concatE(this, other, options);
4173 };
4174 /** @hidden */
4175 EventStream.prototype.transformChanges = function (desc, f) {
4176 return f(this).withDesc(desc);
4177 };
4178 /**
4179 For each element in the source stream, spawn a new
4180 stream/property using the function `f`. Collect events from each of the spawned
4181 streams into the result stream/property. Note that instead of a function, you can provide a
4182 stream/property too. Also, the return value of function `f` can be either an
4183 `Observable` (stream/property) or a constant value.
4184
4185 `stream.flatMap()` can be used conveniently with [`Bacon.once()`](../globals.html#once) and [`Bacon.never()`](../globals.html#never)
4186 for converting and filtering at the same time, including only some of the results.
4187
4188 Example - converting strings to integers, skipping empty values:
4189
4190 ```js
4191 stream.flatMap(function(text) {
4192 return (text != "") ? parseInt(text) : Bacon.never()
4193 })
4194 ```
4195 */
4196 EventStream.prototype.flatMap = function (f) { return flatMap$1(this, f); };
4197 /**
4198 A [`flatMapWithConcurrencyLimit`](#flatmapwithconcurrencylimit) with limit of 1.
4199 */
4200 EventStream.prototype.flatMapConcat = function (f) { return flatMapConcat(this, f); };
4201 /**
4202 Like [`flatMap`](#flatmap), but is applied only on [`Error`](error.html) events. Returned values go into the
4203 value stream, unless an error event is returned. As an example, one type of error could result in a retry and another just
4204 passed through, which can be implemented using flatMapError.
4205 */
4206 EventStream.prototype.flatMapError = function (f) { return flatMapError(this, f); };
4207 /**
4208 Like [`flatMap`](#observable-flatmap), but only spawns a new
4209 stream if the previously spawned stream has ended.
4210 */
4211 EventStream.prototype.flatMapFirst = function (f) { return flatMapFirst(this, f); };
4212 /**
4213 Like [`flatMap`](#flatmap), but instead of including events from
4214 all spawned streams, only includes them from the latest spawned stream.
4215 You can think this as switching from stream to stream.
4216 Note that instead of a function, you can provide a stream/property too.
4217 */
4218 EventStream.prototype.flatMapLatest = function (f) { return flatMapLatest(this, f); };
4219 /**
4220 A super method of *flatMap* family. It limits the number of open spawned streams and buffers incoming events.
4221 [`flatMapConcat`](#flatmapconcat) is `flatMapWithConcurrencyLimit(1)` (only one input active),
4222 and [`flatMap`](#flatmap) is `flatMapWithConcurrencyLimit ∞` (all inputs are piped to output).
4223 */
4224 EventStream.prototype.flatMapWithConcurrencyLimit = function (limit, f) { return flatMapWithConcurrencyLimit(this, limit, f); };
4225 EventStream.prototype.flatMapEvent = function (f) { return flatMapEvent(this, f); };
4226 /**
4227 Scans stream with given seed value and accumulator function, resulting to a Property.
4228 Difference to [`scan`](#scan) is that the function `f` can return an [`EventStream`](eventstream.html) or a [`Property`](property.html) instead
4229 of a pure value, meaning that you can use [`flatScan`](#flatscan) for asynchronous updates of state. It serializes
4230 updates so that that the next update will be queued until the previous one has completed.
4231
4232 * @param seed initial value to start with
4233 * @param f transition function from previous state and new value to next state
4234 * @typeparam V2 state and result type
4235 */
4236 EventStream.prototype.flatScan = function (seed, f) {
4237 return flatScan(this, seed, f);
4238 };
4239 /**
4240 Groups stream events to new streams by `keyF`. Optional `limitF` can be provided to limit grouped
4241 stream life. Stream transformed by `limitF` is passed on if provided. `limitF` gets grouped stream
4242 and the original event causing the stream to start as parameters.
4243
4244 Calculator for grouped consecutive values until group is cancelled:
4245
4246 ```
4247 var events = [
4248 {id: 1, type: "add", val: 3 },
4249 {id: 2, type: "add", val: -1 },
4250 {id: 1, type: "add", val: 2 },
4251 {id: 2, type: "cancel"},
4252 {id: 3, type: "add", val: 2 },
4253 {id: 3, type: "cancel"},
4254 {id: 1, type: "add", val: 1 },
4255 {id: 1, type: "add", val: 2 },
4256 {id: 1, type: "cancel"}
4257 ]
4258
4259 function keyF(event) {
4260 return event.id
4261 }
4262
4263 function limitF(groupedStream, groupStartingEvent) {
4264 var cancel = groupedStream.filter(function(x) { return x.type === "cancel"}).take(1)
4265 var adds = groupedStream.filter(function(x) { return x.type === "add" })
4266 return adds.takeUntil(cancel).map(".val")
4267 }
4268
4269 Bacon.sequentially(2, events)
4270 .groupBy(keyF, limitF)
4271 .flatMap(function(groupedStream) {
4272 return groupedStream.fold(0, function(acc, x) { return acc + x })
4273 })
4274 .onValue(function(sum) {
4275 console.log(sum)
4276 // returns [-1, 2, 8] in an order
4277 })
4278 ```
4279
4280 */
4281 EventStream.prototype.groupBy = function (keyF, limitF) {
4282 return groupBy(this, keyF, limitF);
4283 };
4284 /**
4285 Maps values using given function, returning a new
4286 stream/property. Instead of a function, you can also provide a [Property](property.html),
4287 in which case each element in the source stream will be mapped to the current value of
4288 the given property.
4289 */
4290 EventStream.prototype.map = function (f) {
4291 return map$1(this, f);
4292 };
4293 EventStream.prototype.merge = function (other) {
4294 assertEventStream(other);
4295 return mergeAll(this, other).withDesc(new Desc(this, "merge", [other]));
4296 };
4297 /**
4298 Returns a stream/property that inverts boolean values (using `!`)
4299 */
4300 EventStream.prototype.not = function () { return not(this); };
4301 /**
4302 Adds a starting value to the stream/property, i.e. concats a
4303 single-element stream containing the single seed value with this stream.
4304 */
4305 // TODO: should allow V|V2 signature
4306 EventStream.prototype.startWith = function (seed) {
4307 return startWithE(this, seed);
4308 };
4309 /** @hidden */
4310 EventStream.prototype.subscribeInternal = function (sink) {
4311 if (sink === void 0) { sink = nullSink; }
4312 return this.dispatcher.subscribe(sink);
4313 };
4314 /**
4315 * Returns this stream.
4316 */
4317 EventStream.prototype.toEventStream = function () { return this; };
4318 /**
4319 Creates a Property based on the
4320 EventStream.
4321
4322 Without arguments, you'll get a Property without an initial value.
4323 The Property will get its first actual value from the stream, and after that it'll
4324 always have a current value.
4325
4326 You can also give an initial value that will be used as the current value until
4327 the first value comes from the stream.
4328 */
4329 EventStream.prototype.toProperty = function (initValue) {
4330 var usedInitValue = arguments.length
4331 ? toOption(initValue)
4332 : none();
4333 var disp = this.dispatcher;
4334 var desc = new Desc(this, "toProperty", Array.prototype.slice.apply(arguments));
4335 var streamSubscribe = disp.subscribe;
4336 return new Property(desc, streamSubscribeToPropertySubscribe(usedInitValue, streamSubscribe));
4337 };
4338 EventStream.prototype.transform = function (transformer, desc) {
4339 return transformE(this, transformer, desc);
4340 };
4341 /**
4342 Creates an EventStream/Property by sampling a given `samplee`
4343 stream/property value at each event from the this stream/property.
4344
4345 @param {Observable<V2>} samplee
4346 @param f function to select/calculate the result value based on the value in the source stream and the samplee
4347
4348 @typeparam V2 type of values in the samplee
4349 @typeparam R type of values in the result
4350 */
4351 EventStream.prototype.withLatestFrom = function (samplee, f) {
4352 return withLatestFromE(this, samplee, f);
4353 };
4354 /**
4355 Lets you run a state machine
4356 on an observable. Give it an initial state object and a state
4357 transformation function that processes each incoming event and
4358 returns an array containing the next state and an array of output
4359 events. Here's an example where we calculate the total sum of all
4360 numbers in the stream and output the value on stream end:
4361
4362 ```js
4363 Bacon.fromArray([1,2,3])
4364 .withStateMachine(0, function(sum, event) {
4365 if (event.hasValue)
4366 return [sum + event.value, []]
4367 else if (event.isEnd)
4368 return [undefined, [new Bacon.Next(sum), event]]
4369 else
4370 return [sum, [event]]
4371 })
4372 ```
4373 @param initState initial state for the state machine
4374 @param f the function that defines the state machine
4375 @typeparam State type of machine state
4376 @typeparam Out type of values to be emitted
4377 */
4378 EventStream.prototype.withStateMachine = function (initState, f) {
4379 return withStateMachine(initState, f, this);
4380 };
4381 return EventStream;
4382}(Observable));
4383/** @hidden */
4384function newEventStream(description, subscribe) {
4385 return new EventStream(description, subscribe);
4386}
4387/** @hidden */
4388function newEventStreamAllowSync(description, subscribe) {
4389 return new EventStream(description, subscribe, undefined, allowSync);
4390}
4391
4392function symbol(key) {
4393 if (typeof Symbol !== "undefined" && Symbol[key]) {
4394 return Symbol[key];
4395 }
4396 else if (typeof Symbol !== "undefined" && typeof Symbol.for === "function") {
4397 return Symbol[key] = Symbol.for(key);
4398 }
4399 else {
4400 return "@@" + key;
4401 }
4402}
4403
4404var ESObservable = /** @class */ (function () {
4405 function ESObservable(observable) {
4406 this.observable = observable;
4407 }
4408 ESObservable.prototype.subscribe = function (observerOrOnNext, onError, onComplete) {
4409 var observer = typeof observerOrOnNext === 'function'
4410 ? { next: observerOrOnNext, error: onError, complete: onComplete }
4411 : observerOrOnNext;
4412 var subscription = {
4413 closed: false,
4414 unsubscribe: function () {
4415 subscription.closed = true;
4416 cancel();
4417 }
4418 };
4419 var cancel = this.observable.subscribe(function (event) {
4420 if (hasValue(event) && observer.next) {
4421 observer.next(event.value);
4422 }
4423 else if (isError(event)) {
4424 if (observer.error)
4425 observer.error(event.error);
4426 subscription.unsubscribe();
4427 }
4428 else if (event.isEnd) {
4429 subscription.closed = true;
4430 if (observer.complete)
4431 observer.complete();
4432 }
4433 });
4434 return subscription;
4435 };
4436 return ESObservable;
4437}());
4438ESObservable.prototype[symbol('observable')] = function () {
4439 return this;
4440};
4441Observable.prototype.toESObservable = function () {
4442 return new ESObservable(this);
4443};
4444Observable.prototype[symbol('observable')] = Observable.prototype.toESObservable;
4445
4446/**
4447 Creates a Property from an initial value and updates the value based on multiple inputs.
4448 The inputs are defined similarly to [`Bacon.when`](#bacon-when), like this:
4449
4450 ```js
4451 var result = Bacon.update(
4452 initial,
4453 [x,y,z, (previous,x,y,z) => { ... }],
4454 [x,y, (previous,x,y) => { ... }])
4455 ```
4456
4457 As input, each function above will get the previous value of the `result` Property, along with values from the listed Observables.
4458 The value returned by the function will be used as the next value of `result`.
4459
4460 Just like in [`Bacon.when`](#when), only EventStreams will trigger an update, while Properties will be just sampled.
4461 So, if you list a single EventStream and several Properties, the value will be updated only when an event occurs in the EventStream.
4462
4463 Here's a simple gaming example:
4464
4465 ```js
4466 let scoreMultiplier = Bacon.constant(1)
4467 let hitUfo = Bacon.interval(1000)
4468 let hitMotherShip = Bacon.later(10000)
4469 let score = Bacon.update(
4470 0,
4471 [hitUfo, scoreMultiplier, (score, _, multiplier) => score + 100 * multiplier ],
4472 [hitMotherShip, (score, _) => score + 2000 ]
4473 )
4474 ```
4475
4476 In the example, the `score` property is updated when either `hitUfo` or `hitMotherShip` occur. The `scoreMultiplier` Property is sampled to take multiplier into account when `hitUfo` occurs.
4477
4478 * @param initial
4479 * @param {UpdatePattern<Out>} patterns
4480 * @returns {Property<Out>}
4481 */
4482function update(initial) {
4483 var patterns = [];
4484 for (var _i = 1; _i < arguments.length; _i++) {
4485 patterns[_i - 1] = arguments[_i];
4486 }
4487 var rawPatterns = extractRawPatterns(patterns);
4488 for (var i = 0; i < rawPatterns.length; i++) {
4489 var pattern = rawPatterns[i];
4490 pattern[1] = lateBindFirst(pattern[1]);
4491 }
4492 return when.apply(void 0, rawPatterns).scan(initial, (function (x, f) {
4493 return f(x);
4494 })).withDesc(new Desc("Bacon", "update", __spreadArrays([initial], patterns)));
4495}
4496function lateBindFirst(f) {
4497 return function () {
4498 var args = [];
4499 for (var _i = 0; _i < arguments.length; _i++) {
4500 args[_i] = arguments[_i];
4501 }
4502 return function (i) {
4503 return f.apply(void 0, [i].concat(args));
4504 };
4505 };
4506}
4507
4508/**
4509 Creates an EventStream that delivers the given
4510 series of values (given as array) to the first subscriber. The stream ends after these
4511 values have been delivered. You can also send [`Bacon.Error`](classes/error.html) events, or
4512 any combination of pure values and error events like this:
4513 `Bacon.fromArray([1, new Bacon.Error()])
4514
4515 @param values Array of values or events to repeat
4516 @typeparam V Type of stream elements
4517 */
4518function fromArray(values) {
4519 assertArray(values);
4520 if (!values.length) {
4521 return never().withDesc(new Desc("Bacon", "fromArray", values));
4522 }
4523 else {
4524 var i = 0;
4525 var stream = new EventStream(new Desc("Bacon", "fromArray", [values]), function (sink) {
4526 var unsubd = false;
4527 var reply = more;
4528 var pushing = false;
4529 var pushNeeded = false;
4530 function push() {
4531 pushNeeded = true;
4532 if (pushing) {
4533 return;
4534 }
4535 if (i === values.length) {
4536 sink(endEvent());
4537 return false;
4538 }
4539 pushing = true;
4540 while (pushNeeded) {
4541 pushNeeded = false;
4542 if ((reply !== noMore) && !unsubd) {
4543 var value = values[i++];
4544 reply = sink(toEvent(value));
4545 if (reply !== noMore) {
4546 if (i === values.length) {
4547 sink(endEvent());
4548 }
4549 else {
4550 UpdateBarrier.afterTransaction(stream, push);
4551 }
4552 }
4553 }
4554 }
4555 pushing = false;
4556 return pushing;
4557 }
4558 UpdateBarrier.soonButNotYet(stream, push);
4559 return function () {
4560 unsubd = true;
4561 return unsubd;
4562 };
4563 });
4564 return stream;
4565 }
4566}
4567
4568function isEventSourceFn(x) {
4569 return _.isFunction(x);
4570}
4571// Wrap DOM EventTarget, Node EventEmitter, or
4572// [un]bind: (Any, (Any) -> None) -> None interfaces
4573// common in MVCs as EventStream
4574//
4575// target - EventTarget or EventEmitter, source of events
4576// eventSource - event name to bind or a function that performs custom binding
4577// eventTransformer - defaults to returning the first argument to handler
4578//
4579// Example 1:
4580//
4581// Bacon.fromEventTarget(document.body, "click")
4582// # => EventStream
4583//
4584// Bacon.fromEventTarget(document.body, "scroll", {passive: true})
4585// # => EventStream
4586//
4587// Bacon.fromEventTarget (new EventEmitter(), "data")
4588// # => EventStream
4589//
4590// Returns EventStream
4591/** @hidden */
4592var eventMethods = [
4593 ["addEventListener", "removeEventListener"],
4594 ["addListener", "removeListener"],
4595 ["on", "off"],
4596 ["bind", "unbind"]
4597];
4598var findHandlerMethods = function (target) {
4599 var pair;
4600 for (var i = 0; i < eventMethods.length; i++) {
4601 pair = eventMethods[i];
4602 var methodPair = [target[pair[0]], target[pair[1]]];
4603 if (methodPair[0] && methodPair[1]) {
4604 return methodPair;
4605 }
4606 }
4607 for (var j = 0; j < eventMethods.length; j++) {
4608 pair = eventMethods[j];
4609 var addListener = target[pair[0]];
4610 if (addListener) {
4611 return [addListener, function () { }];
4612 }
4613 }
4614 throw new Error("No suitable event methods in " + target);
4615};
4616/**
4617 creates an EventStream from events
4618 on a DOM EventTarget or Node.JS EventEmitter object, or an object that supports event listeners using `on`/`off` methods.
4619 You can also pass an optional function that transforms the emitted
4620 events' parameters.
4621
4622 The simple form:
4623
4624 ```js
4625 Bacon.fromEvent(document.body, "click").onValue(function() { alert("Bacon!") })
4626 ```
4627
4628 Using a binder function:
4629
4630 ```js
4631 Bacon.fromEvent(
4632 window,
4633 function(binder, listener) {
4634 binder("scroll", listener, {passive: true})
4635 }
4636 ).onValue(function() {
4637 console.log(window.scrollY)
4638})
4639 ```
4640
4641 @param target
4642 @param eventSource
4643 @param eventTransformer
4644 @typeparam V Type of stream elements
4645
4646 */
4647function fromEvent(target, eventSource, eventTransformer) {
4648 var _a = findHandlerMethods(target), sub = _a[0], unsub = _a[1];
4649 var desc = new Desc("Bacon", "fromEvent", [target, eventSource]);
4650 return fromBinder(function (handler) {
4651 if (isEventSourceFn(eventSource)) {
4652 eventSource(sub.bind(target), handler);
4653 return function () {
4654 return eventSource(unsub.bind(target), handler);
4655 };
4656 }
4657 else {
4658 sub.call(target, eventSource, handler);
4659 return function () {
4660 return unsub.call(target, eventSource, handler);
4661 };
4662 }
4663 }, eventTransformer).withDesc(desc);
4664}
4665
4666/**
4667 A shorthand for combining multiple
4668 sources (streams, properties, constants) as array and assigning the
4669 side-effect function f for the values. The following example would log
4670 the number 3.
4671
4672 ```js
4673 function f(a, b) { console.log(a + b) }
4674 Bacon.onValues(Bacon.constant(1), Bacon.constant(2), f)
4675 ```
4676 */
4677function onValues() {
4678 var args = [];
4679 for (var _i = 0; _i < arguments.length; _i++) {
4680 args[_i] = arguments[_i];
4681 }
4682 return combineAsArray(args.slice(0, args.length - 1)).onValues(args[arguments.length - 1]);
4683}
4684
4685/**
4686 Calls generator function which is expected to return an observable. The returned EventStream contains
4687 values and errors from the spawned observable. When the spawned observable ends, the generator is called
4688 again to spawn a new observable.
4689
4690 This is repeated until the generator returns a falsy value
4691 (such as `undefined` or `false`).
4692
4693 The generator function is called with one argument — iteration number starting from `0`.
4694
4695 Here's an example:
4696
4697```js
4698Bacon.repeat(function(i) {
4699if (i < 3) {
4700 return Bacon.once(i);
4701} else {
4702 return false;
4703}
4704}).log()
4705```
4706
4707 The example will produce values 0, 1 and 2.
4708
4709 @param {(number) => (Observable<V> | null)} generator
4710 @returns {EventStream<V>}
4711 @typeparam V Type of stream elements
4712
4713 */
4714function repeat(generator) {
4715 var index = 0;
4716 return fromBinder(function (sink) {
4717 var flag = false;
4718 var reply = more;
4719 var unsub = function () { };
4720 function handleEvent(event) {
4721 if (event.isEnd) {
4722 if (!flag) {
4723 flag = true;
4724 }
4725 else {
4726 subscribeNext();
4727 }
4728 return more;
4729 }
4730 else {
4731 return reply = sink(event);
4732 }
4733 }
4734 function subscribeNext() {
4735 var next;
4736 flag = true;
4737 while (flag && reply !== noMore) {
4738 next = generator(index++);
4739 flag = false;
4740 if (next) {
4741 unsub = next.subscribeInternal(handleEvent);
4742 }
4743 else {
4744 sink(endEvent());
4745 }
4746 }
4747 flag = true;
4748 }
4749 subscribeNext();
4750 return function () { return unsub(); };
4751 }).withDesc(new Desc("Bacon", "repeat", [generator]));
4752}
4753
4754/**
4755 Repeats given elements indefinitely
4756 with given interval in milliseconds. For example, `repeatedly(10, [1,2,3])`
4757 would lead to `1,2,3,1,2,3...` to be repeated indefinitely.
4758
4759 @param delay between values, in milliseconds
4760 @param values array of values to repeat
4761 @typeparam V Type of stream elements
4762
4763 */
4764function repeatedly(delay, values) {
4765 var index = 0;
4766 return fromPoll(delay, function () {
4767 return values[index++ % values.length];
4768 }).withDesc(new Desc("Bacon", "repeatedly", [delay, values]));
4769}
4770
4771/**
4772 Creates a stream that ends after given amount of milliseconds, without emitting any values.
4773
4774 @param duration duration of silence in milliseconds
4775 @typeparam V Type of stream elements
4776 */
4777function silence(duration) {
4778 return later(duration, "")
4779 .filter(false)
4780 .withDesc(new Desc("Bacon", "silence", [duration]));
4781}
4782
4783/**
4784 Used to retry the call when there is an [`Error`](classes/error.html) event in the stream produced by the `source` function.
4785
4786 ```js
4787 var triggeringStream, ajaxCall // <- ajaxCall gives Errors on network or server errors
4788 ajaxResult = triggeringStream.flatMap(function(url) {
4789 return Bacon.retry({
4790 source: function(attemptNumber) { return ajaxCall(url) },
4791 retries: 5,
4792 isRetryable: function (error) { return error.httpStatusCode !== 404; },
4793 delay: function(context) { return 100; } // Just use the same delay always
4794 })
4795})
4796 ```
4797 * @param options (click for details)
4798 */
4799function retry(options) {
4800 if (!_.isFunction(options.source)) {
4801 throw new Error("'source' option has to be a function");
4802 }
4803 var source = options.source;
4804 var retries = options.retries || 0;
4805 var retriesDone = 0;
4806 var delay = options.delay || function () {
4807 return 0;
4808 };
4809 var isRetryable = options.isRetryable || function () {
4810 return true;
4811 };
4812 var finished = false;
4813 var errorEvent = null;
4814 return repeat(function (count) {
4815 function valueStream() {
4816 return source(count).endOnError().transform(function (event, sink) {
4817 if (isError(event)) {
4818 errorEvent = event;
4819 if (!(isRetryable(errorEvent.error) && (retries === 0 || retriesDone < retries))) {
4820 finished = true;
4821 return sink(event);
4822 }
4823 else {
4824 return more;
4825 }
4826 }
4827 else {
4828 if (hasValue(event)) {
4829 errorEvent = null;
4830 finished = true;
4831 }
4832 return sink(event);
4833 }
4834 });
4835 }
4836 if (finished) {
4837 return undefined;
4838 }
4839 else if (errorEvent) {
4840 var context = {
4841 error: errorEvent.error,
4842 retriesDone: retriesDone
4843 };
4844 var pause = silence(delay(context));
4845 retriesDone++;
4846 return pause.concat(once(null).flatMap(valueStream));
4847 }
4848 else {
4849 return valueStream();
4850 }
4851 }).withDesc(new Desc("Bacon", "retry", [options]));
4852}
4853
4854/**
4855 Creates a stream containing given
4856 values (given as array). Delivered with given interval in milliseconds.
4857
4858 @param delay between elements, in milliseconds
4859 @param array of values or events
4860 @typeparam V Type of stream elements
4861
4862 */
4863function sequentially(delay, values) {
4864 var index = 0;
4865 return fromPoll(delay, function () {
4866 var value = values[index++];
4867 if (index < values.length) {
4868 return value;
4869 }
4870 else if (index === values.length) {
4871 return [toEvent(value), endEvent()];
4872 }
4873 else {
4874 return endEvent();
4875 }
4876 }).withDesc(new Desc("Bacon", "sequentially", [delay, values]));
4877}
4878
4879function valueAndEnd(value) {
4880 return [toEvent(value), endEvent()];
4881}
4882/**
4883 * Creates an EventStream from a Promise object such as JQuery Ajax.
4884 This stream will contain a single value or an error, followed immediately by stream end.
4885 You can use the optional abort flag (i.e. ´fromPromise(p, true)´ to have the `abort` method of the given promise be called when all subscribers have been removed from the created stream.
4886 You can also pass an optional function that transforms the promise value into Events. The default is to transform the value into `[new Bacon.Next(value), new Bacon.End()]`.
4887 Check out this [example](https://github.com/raimohanska/baconjs-examples/blob/master/resources/public/index.html).
4888
4889 *
4890 * @param {Promise<V>} source promise object
4891 * @param abort should we call the `abort` method of the Promise on unsubscribe. This is a nonstandard feature you should probably ignore.
4892 * @param {EventTransformer<V>} eventTransformer
4893 * @returns {EventStream<V>}
4894 */
4895function fromPromise(promise, abort, eventTransformer) {
4896 if (eventTransformer === void 0) { eventTransformer = valueAndEnd; }
4897 return fromBinder(function (handler) {
4898 var bound = promise.then(handler, function (e) { return handler(new Error$1(e)); });
4899 if (bound && typeof bound.done === "function") {
4900 bound.done();
4901 }
4902 if (abort) {
4903 return function () {
4904 if (typeof promise.abort === "function") {
4905 return promise.abort();
4906 }
4907 };
4908 }
4909 else {
4910 return function () {
4911 };
4912 }
4913 }, eventTransformer).withDesc(new Desc("Bacon", "fromPromise", [promise]));
4914}
4915
4916function withMethodCallSupport(wrapped) {
4917 return function (f) {
4918 var args = [];
4919 for (var _i = 1; _i < arguments.length; _i++) {
4920 args[_i - 1] = arguments[_i];
4921 }
4922 if (typeof f === "object" && args.length) {
4923 var context = f;
4924 var methodName = args[0];
4925 f = function () {
4926 var args = [];
4927 for (var _i = 0; _i < arguments.length; _i++) {
4928 args[_i] = arguments[_i];
4929 }
4930 return context[methodName].apply(context, args);
4931 };
4932 args = args.slice(1);
4933 }
4934 return wrapped.apply(void 0, __spreadArrays([f], args));
4935 };
4936}
4937function partiallyApplied(f, applied) {
4938 return function () {
4939 var args = [];
4940 for (var _i = 0; _i < arguments.length; _i++) {
4941 args[_i] = arguments[_i];
4942 }
4943 return f.apply(void 0, (applied.concat(args)));
4944 };
4945}
4946var makeFunction_ = withMethodCallSupport(function (f) {
4947 var args = [];
4948 for (var _i = 1; _i < arguments.length; _i++) {
4949 args[_i - 1] = arguments[_i];
4950 }
4951 if (_.isFunction(f)) {
4952 if (args.length) {
4953 return partiallyApplied(f, args);
4954 }
4955 else {
4956 return f;
4957 }
4958 }
4959 else {
4960 return _.always(f);
4961 }
4962});
4963/** @hidden */
4964function makeFunction(f, args) {
4965 return makeFunction_.apply(void 0, __spreadArrays([f], args));
4966}
4967
4968// TODO: types/doc for the object, fnname variant
4969/**
4970 Creates an EventStream from a function that
4971 accepts a callback. The function is supposed to call its callback just
4972 once. For example:
4973
4974 ```js
4975 Bacon.fromCallback(callback => callback("bacon"))
4976 ```
4977
4978 This would create a stream that outputs a single value "Bacon!" and ends
4979 after that. The use of setTimeout causes the value to be delayed by 1
4980 second.
4981
4982 You can also give any number of arguments to [`fromCallback`](#bacon-fromcallback), which will be
4983 passed to the function. These arguments can be simple variables, Bacon
4984 EventStreams or Properties. For example the following will output "Bacon rules":
4985
4986 ```js
4987 bacon = Bacon.constant('bacon')
4988 Bacon.fromCallback(function(a, b, callback) {
4989 callback(a + ' ' + b);
4990}, bacon, 'rules').log();
4991 ```
4992
4993 * @param f
4994 * @param args
4995 * @returns {EventStream<V>}
4996 */
4997function fromCallback(f) {
4998 var args = [];
4999 for (var _i = 1; _i < arguments.length; _i++) {
5000 args[_i - 1] = arguments[_i];
5001 }
5002 return fromBinder(function (handler) {
5003 makeFunction(f, args)(handler);
5004 return nop;
5005 }, function (value) {
5006 return [value, endEvent()];
5007 }).withDesc(new Desc("Bacon", "fromCallback", __spreadArrays([f], args)));
5008}
5009/**
5010Behaves the same way as `Bacon.fromCallback`,
5011except that it expects the callback to be called in the Node.js convention:
5012`callback(error, data)`, where error is null if everything is fine. For example:
5013
5014```js
5015var Bacon = require('baconjs').Bacon,
5016fs = require('fs');
5017var read = Bacon.fromNodeCallback(fs.readFile, 'input.txt');
5018read.onError(function(error) { console.log("Reading failed: " + error); });
5019read.onValue(function(value) { console.log("Read contents: " + value); });
5020```
5021
5022 */
5023function fromNodeCallback(f) {
5024 var args = [];
5025 for (var _i = 1; _i < arguments.length; _i++) {
5026 args[_i - 1] = arguments[_i];
5027 }
5028 return fromBinder(function (handler) {
5029 makeFunction(f, args)(handler);
5030 return nop;
5031 }, function (error, value) {
5032 if (error) {
5033 return [new Error$1(error), endEvent()];
5034 }
5035 return [value, endEvent()];
5036 }).withDesc(new Desc("Bacon", "fromNodeCallback", __spreadArrays([f], args)));
5037}
5038
5039/**
5040 * Creates an EventStream from an
5041 [ES Observable](https://github.com/tc39/proposal-observable). Input can be any
5042 ES Observable implementation including RxJS and Kefir.
5043 */
5044function fromESObservable(_observable) {
5045 var observable;
5046 if (_observable[symbol("observable")]) {
5047 observable = _observable[symbol("observable")]();
5048 }
5049 else {
5050 observable = _observable;
5051 }
5052 var desc = new Desc("Bacon", "fromESObservable", [observable]);
5053 return new EventStream(desc, function (sink) {
5054 var cancel = observable.subscribe({
5055 error: function (x) {
5056 sink(new Error$1(x));
5057 sink(new End());
5058 },
5059 next: function (value) { sink(new Next(value)); },
5060 complete: function () {
5061 sink(new End());
5062 }
5063 });
5064 // Support RxJS Observables
5065 if (cancel.unsubscribe) {
5066 return function () { cancel.unsubscribe(); };
5067 }
5068 else {
5069 return cancel;
5070 }
5071 });
5072}
5073
5074/**
5075 An [`EventStream`](eventstream.html) that allows you to [`push`](#push) values into the stream.
5076
5077 It also allows plugging other streams into the Bus, as inputs. The Bus practically
5078 merges all plugged-in streams and the values pushed using the [`push`](#push)
5079 method.
5080 */
5081var Bus = /** @class */ (function (_super) {
5082 __extends(Bus, _super);
5083 function Bus() {
5084 var _this = _super.call(this, new Desc("Bacon", "Bus", []), function (sink) { return _this.subscribeAll(sink); }) || this;
5085 /** @hidden */
5086 _this.pushing = false;
5087 /** @hidden */
5088 _this.pushQueue = undefined;
5089 /** @hidden */
5090 _this.ended = false;
5091 /** @hidden */
5092 _this.subscriptions = [];
5093 _this.unsubAll = _.bind(_this.unsubAll, _this);
5094 _this.push = _.bind(_this.push, _this);
5095 _this.subscriptions = []; // new array for each Bus instance
5096 _this.ended = false;
5097 return _this;
5098 }
5099 /**
5100 Plugs the given stream as an input to the Bus. All events from
5101 the given stream will be delivered to the subscribers of the Bus.
5102 Returns a function that can be used to unplug the same stream.
5103
5104 The plug method practically allows you to merge in other streams after
5105 the creation of the Bus.
5106
5107 * @returns a function that can be called to "unplug" the source from Bus.
5108 */
5109 Bus.prototype.plug = function (input) {
5110 var _this = this;
5111 assertObservable(input);
5112 if (this.ended) {
5113 return;
5114 }
5115 var sub = { input: input, unsub: undefined };
5116 this.subscriptions.push(sub);
5117 if (typeof this.sink !== "undefined") {
5118 this.subscribeInput(sub);
5119 }
5120 return (function () { return _this.unsubscribeInput(input); });
5121 };
5122 /**
5123 Ends the stream. Sends an [End](end.html) event to all subscribers.
5124 After this call, there'll be no more events to the subscribers.
5125 Also, the [`push`](#push), [`error`](#error) and [`plug`](#plug) methods have no effect.
5126 */
5127 Bus.prototype.end = function () {
5128 this.ended = true;
5129 this.unsubAll();
5130 if (typeof this.sink === "function") {
5131 return this.sink(endEvent());
5132 }
5133 };
5134 /**
5135 * Pushes a new value to the stream.
5136 */
5137 Bus.prototype.push = function (value) {
5138 if (!this.ended && typeof this.sink === "function") {
5139 var rootPush = !this.pushing;
5140 if (!rootPush) {
5141 //console.log("recursive push")
5142 if (!this.pushQueue)
5143 this.pushQueue = [];
5144 this.pushQueue.push(value);
5145 //console.log('queued', value)
5146 return;
5147 }
5148 this.pushing = true;
5149 try {
5150 return this.sink(nextEvent(value));
5151 }
5152 finally {
5153 if (rootPush && this.pushQueue) {
5154 //console.log("start processing queue", this.pushQueue.length)
5155 var i = 0;
5156 while (i < this.pushQueue.length) {
5157 //console.log("in loop", i, this.pushQueue[i])
5158 var v = this.pushQueue[i];
5159 this.sink(nextEvent(v));
5160 i++;
5161 }
5162 this.pushQueue = undefined;
5163 }
5164 this.pushing = false;
5165 }
5166 }
5167 };
5168 /**
5169 * Pushes an error to this stream.
5170 */
5171 Bus.prototype.error = function (error) {
5172 if (typeof this.sink === "function") {
5173 return this.sink(new Error$1(error));
5174 }
5175 };
5176 /** @hidden */
5177 Bus.prototype.unsubAll = function () {
5178 var iterable = this.subscriptions;
5179 for (var i = 0, sub; i < iterable.length; i++) {
5180 sub = iterable[i];
5181 if (typeof sub.unsub === "function") {
5182 sub.unsub();
5183 }
5184 }
5185 };
5186 /** @hidden */
5187 Bus.prototype.subscribeAll = function (newSink) {
5188 if (this.ended) {
5189 newSink(endEvent());
5190 }
5191 else {
5192 this.sink = newSink;
5193 var iterable = this.subscriptions.slice();
5194 for (var i = 0, subscription; i < iterable.length; i++) {
5195 subscription = iterable[i];
5196 this.subscribeInput(subscription);
5197 }
5198 }
5199 return this.unsubAll;
5200 };
5201 /** @hidden */
5202 Bus.prototype.guardedSink = function (input) {
5203 var _this = this;
5204 return function (event) {
5205 if (event.isEnd) {
5206 _this.unsubscribeInput(input);
5207 return noMore;
5208 }
5209 else if (_this.sink) {
5210 return _this.sink(event);
5211 }
5212 else {
5213 return more;
5214 }
5215 };
5216 };
5217 /** @hidden */
5218 Bus.prototype.subscribeInput = function (subscription) {
5219 subscription.unsub = subscription.input.subscribeInternal(this.guardedSink(subscription.input));
5220 return subscription.unsub;
5221 };
5222 /** @hidden */
5223 Bus.prototype.unsubscribeInput = function (input) {
5224 var iterable = this.subscriptions;
5225 for (var i = 0, sub; i < iterable.length; i++) {
5226 sub = iterable[i];
5227 if (sub.input === input) {
5228 if (typeof sub.unsub === "function") {
5229 sub.unsub();
5230 }
5231 this.subscriptions.splice(i, 1);
5232 return;
5233 }
5234 }
5235 };
5236 return Bus;
5237}(EventStream));
5238
5239/** @hidden */
5240function tryF(f) {
5241 return function (value) {
5242 try {
5243 return once(f(value));
5244 }
5245 catch (e) {
5246 return once(new Error$1(e));
5247 }
5248 };
5249}
5250
5251/**
5252 * JQuery/Zepto integration support
5253 */
5254var $ = {
5255 /**
5256 Creates an EventStream from events on a
5257 jQuery or Zepto.js object. You can pass optional arguments to add a
5258 jQuery live selector and/or a function that processes the jQuery
5259 event and its parameters, if given, like this:
5260
5261 ```js
5262 $("#my-div").asEventStream("click", ".more-specific-selector")
5263 $("#my-div").asEventStream("click", ".more-specific-selector", function(event, args) { return args[0] })
5264 $("#my-div").asEventStream("click", function(event, args) { return args[0] })
5265 ```
5266
5267 Note: you need to install the `asEventStream` method on JQuery by calling
5268 [init()](#_.aseventstream) as in `Bacon.$.init($)`.
5269 */
5270 asEventStream: function (eventName, selector, eventTransformer) {
5271 var _this = this;
5272 if (_.isFunction(selector)) {
5273 eventTransformer = selector;
5274 selector = undefined;
5275 }
5276 return fromBinder(function (handler) {
5277 _this.on(eventName, selector, handler);
5278 return (function () { return _this.off(eventName, selector, handler); });
5279 }, eventTransformer).withDesc(new Desc(this.selector || this, "asEventStream", [eventName]));
5280 },
5281 /**
5282 * Installs the [asEventStream](#_.aseventstream) to the given jQuery/Zepto object (the `$` object).
5283 */
5284 init: function (jQuery) {
5285 jQuery.fn.asEventStream = $.asEventStream;
5286 }
5287};
5288
5289/**
5290 * Bacon.js version as string
5291 */
5292var version = '3.0.17';
5293
5294exports.$ = $;
5295exports.Bus = Bus;
5296exports.CompositeUnsubscribe = CompositeUnsubscribe;
5297exports.Desc = Desc;
5298exports.End = End;
5299exports.Error = Error$1;
5300exports.Event = Event;
5301exports.EventStream = EventStream;
5302exports.Initial = Initial;
5303exports.Next = Next;
5304exports.Observable = Observable;
5305exports.Property = Property;
5306exports.Value = Value;
5307exports._ = _;
5308exports.combine = combine;
5309exports.combineAsArray = combineAsArray;
5310exports.combineTemplate = combineTemplate;
5311exports.combineTwo = combineTwo;
5312exports.combineWith = combineWith;
5313exports.concatAll = concatAll;
5314exports.constant = constant;
5315exports.fromArray = fromArray;
5316exports.fromBinder = fromBinder;
5317exports.fromCallback = fromCallback;
5318exports.fromESObservable = fromESObservable;
5319exports.fromEvent = fromEvent;
5320exports.fromEventTarget = fromEvent;
5321exports.fromNodeCallback = fromNodeCallback;
5322exports.fromPoll = fromPoll;
5323exports.fromPromise = fromPromise;
5324exports.getScheduler = getScheduler;
5325exports.groupSimultaneous = groupSimultaneous;
5326exports.hasValue = hasValue;
5327exports.interval = interval;
5328exports.isEnd = isEnd;
5329exports.isError = isError;
5330exports.isEvent = isEvent;
5331exports.isInitial = isInitial;
5332exports.isNext = isNext;
5333exports.later = later;
5334exports.mergeAll = mergeAll;
5335exports.more = more;
5336exports.never = never;
5337exports.noMore = noMore;
5338exports.nullSink = nullSink;
5339exports.nullVoidSink = nullVoidSink;
5340exports.onValues = onValues;
5341exports.once = once;
5342exports.repeat = repeat;
5343exports.repeatedly = repeatedly;
5344exports.retry = retry;
5345exports.sequentially = sequentially;
5346exports.setScheduler = setScheduler;
5347exports.silence = silence;
5348exports.spy = spy;
5349exports.try = tryF;
5350exports.update = update;
5351exports.version = version;
5352exports.when = when;
5353exports.zipAsArray = zipAsArray;
5354exports.zipWith = zipWith;
5355
5356Object.defineProperty(exports, '__esModule', { value: true });
5357
5358})));