-
Notifications
You must be signed in to change notification settings - Fork 0
/
angular-ui-router.js
10140 lines (10049 loc) · 414 KB
/
angular-ui-router.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* State-based routing for AngularJS 1.x
* NOTICE: This monolithic bundle also bundles the @uirouter/core code.
* This causes it to be incompatible with plugins that depend on @uirouter/core.
* We recommend switching to the ui-router-core.js and ui-router-angularjs.js bundles instead.
* For more information, see https://ui-router.github.io/blog/uirouter-for-angularjs-umd-bundles
* @version v1.0.15
* @link https://ui-router.github.io
* @license MIT License, http://www.opensource.org/licenses/MIT
*/
(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('angular')) :
typeof define === 'function' && define.amd ? define(['exports', 'angular'], factory) :
(factory((global['@uirouter/angularjs'] = {}),global.angular));
}(this, (function (exports,ng_from_import) { 'use strict';
var ng_from_global = angular;
var ng = (ng_from_import && ng_from_import.module) ? ng_from_import : ng_from_global;
/**
* Higher order functions
*
* These utility functions are exported, but are subject to change without notice.
*
* @module common_hof
*/ /** */
/**
* Returns a new function for [Partial Application](https://en.wikipedia.org/wiki/Partial_application) of the original function.
*
* Given a function with N parameters, returns a new function that supports partial application.
* The new function accepts anywhere from 1 to N parameters. When that function is called with M parameters,
* where M is less than N, it returns a new function that accepts the remaining parameters. It continues to
* accept more parameters until all N parameters have been supplied.
*
*
* This contrived example uses a partially applied function as an predicate, which returns true
* if an object is found in both arrays.
* @example
* ```
* // returns true if an object is in both of the two arrays
* function inBoth(array1, array2, object) {
* return array1.indexOf(object) !== -1 &&
* array2.indexOf(object) !== 1;
* }
* let obj1, obj2, obj3, obj4, obj5, obj6, obj7
* let foos = [obj1, obj3]
* let bars = [obj3, obj4, obj5]
*
* // A curried "copy" of inBoth
* let curriedInBoth = curry(inBoth);
* // Partially apply both the array1 and array2
* let inFoosAndBars = curriedInBoth(foos, bars);
*
* // Supply the final argument; since all arguments are
* // supplied, the original inBoth function is then called.
* let obj1InBoth = inFoosAndBars(obj1); // false
*
* // Use the inFoosAndBars as a predicate.
* // Filter, on each iteration, supplies the final argument
* let allObjs = [ obj1, obj2, obj3, obj4, obj5, obj6, obj7 ];
* let foundInBoth = allObjs.filter(inFoosAndBars); // [ obj3 ]
*
* ```
*
* Stolen from: http://stackoverflow.com/questions/4394747/javascript-curry-function
*
* @param fn
* @returns {*|function(): (*|any)}
*/
function curry(fn) {
var initial_args = [].slice.apply(arguments, [1]);
var func_args_length = fn.length;
function curried(args) {
if (args.length >= func_args_length)
return fn.apply(null, args);
return function () {
return curried(args.concat([].slice.apply(arguments)));
};
}
return curried(initial_args);
}
/**
* Given a varargs list of functions, returns a function that composes the argument functions, right-to-left
* given: f(x), g(x), h(x)
* let composed = compose(f,g,h)
* then, composed is: f(g(h(x)))
*/
function compose() {
var args = arguments;
var start = args.length - 1;
return function () {
var i = start, result = args[start].apply(this, arguments);
while (i--)
result = args[i].call(this, result);
return result;
};
}
/**
* Given a varargs list of functions, returns a function that is composes the argument functions, left-to-right
* given: f(x), g(x), h(x)
* let piped = pipe(f,g,h);
* then, piped is: h(g(f(x)))
*/
function pipe() {
var funcs = [];
for (var _i = 0; _i < arguments.length; _i++) {
funcs[_i] = arguments[_i];
}
return compose.apply(null, [].slice.call(arguments).reverse());
}
/**
* Given a property name, returns a function that returns that property from an object
* let obj = { foo: 1, name: "blarg" };
* let getName = prop("name");
* getName(obj) === "blarg"
*/
var prop = function (name) {
return function (obj) { return obj && obj[name]; };
};
/**
* Given a property name and a value, returns a function that returns a boolean based on whether
* the passed object has a property that matches the value
* let obj = { foo: 1, name: "blarg" };
* let getName = propEq("name", "blarg");
* getName(obj) === true
*/
var propEq = curry(function (name, _val, obj) { return obj && obj[name] === _val; });
/**
* Given a dotted property name, returns a function that returns a nested property from an object, or undefined
* let obj = { id: 1, nestedObj: { foo: 1, name: "blarg" }, };
* let getName = prop("nestedObj.name");
* getName(obj) === "blarg"
* let propNotFound = prop("this.property.doesnt.exist");
* propNotFound(obj) === undefined
*/
var parse = function (name) {
return pipe.apply(null, name.split('.').map(prop));
};
/**
* Given a function that returns a truthy or falsey value, returns a
* function that returns the opposite (falsey or truthy) value given the same inputs
*/
var not = function (fn) {
return function () {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
return !fn.apply(null, args);
};
};
/**
* Given two functions that return truthy or falsey values, returns a function that returns truthy
* if both functions return truthy for the given arguments
*/
function and(fn1, fn2) {
return function () {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
return fn1.apply(null, args) && fn2.apply(null, args);
};
}
/**
* Given two functions that return truthy or falsey values, returns a function that returns truthy
* if at least one of the functions returns truthy for the given arguments
*/
function or(fn1, fn2) {
return function () {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
return fn1.apply(null, args) || fn2.apply(null, args);
};
}
/**
* Check if all the elements of an array match a predicate function
*
* @param fn1 a predicate function `fn1`
* @returns a function which takes an array and returns true if `fn1` is true for all elements of the array
*/
var all = function (fn1) {
return function (arr) { return arr.reduce(function (b, x) { return b && !!fn1(x); }, true); };
};
// tslint:disable-next-line:variable-name
var any = function (fn1) {
return function (arr) { return arr.reduce(function (b, x) { return b || !!fn1(x); }, false); };
};
/** Given a class, returns a Predicate function that returns true if the object is of that class */
var is = function (ctor) {
return function (obj) {
return (obj != null && obj.constructor === ctor || obj instanceof ctor);
};
};
/** Given a value, returns a Predicate function that returns true if another value is === equal to the original value */
var eq = function (value) { return function (other) {
return value === other;
}; };
/** Given a value, returns a function which returns the value */
var val = function (v) { return function () { return v; }; };
function invoke(fnName, args) {
return function (obj) {
return obj[fnName].apply(obj, args);
};
}
/**
* Sorta like Pattern Matching (a functional programming conditional construct)
*
* See http://c2.com/cgi/wiki?PatternMatching
*
* This is a conditional construct which allows a series of predicates and output functions
* to be checked and then applied. Each predicate receives the input. If the predicate
* returns truthy, then its matching output function (mapping function) is provided with
* the input and, then the result is returned.
*
* Each combination (2-tuple) of predicate + output function should be placed in an array
* of size 2: [ predicate, mapFn ]
*
* These 2-tuples should be put in an outer array.
*
* @example
* ```
*
* // Here's a 2-tuple where the first element is the isString predicate
* // and the second element is a function that returns a description of the input
* let firstTuple = [ angular.isString, (input) => `Heres your string ${input}` ];
*
* // Second tuple: predicate "isNumber", mapfn returns a description
* let secondTuple = [ angular.isNumber, (input) => `(${input}) That's a number!` ];
*
* let third = [ (input) => input === null, (input) => `Oh, null...` ];
*
* let fourth = [ (input) => input === undefined, (input) => `notdefined` ];
*
* let descriptionOf = pattern([ firstTuple, secondTuple, third, fourth ]);
*
* console.log(descriptionOf(undefined)); // 'notdefined'
* console.log(descriptionOf(55)); // '(55) That's a number!'
* console.log(descriptionOf("foo")); // 'Here's your string foo'
* ```
*
* @param struct A 2D array. Each element of the array should be an array, a 2-tuple,
* with a Predicate and a mapping/output function
* @returns {function(any): *}
*/
function pattern(struct) {
return function (x) {
for (var i = 0; i < struct.length; i++) {
if (struct[i][0](x))
return struct[i][1](x);
}
};
}
/**
* @coreapi
* @module core
*/
/**
* Matches state names using glob-like pattern strings.
*
* Globs can be used in specific APIs including:
*
* - [[StateService.is]]
* - [[StateService.includes]]
* - The first argument to Hook Registration functions like [[TransitionService.onStart]]
* - [[HookMatchCriteria]] and [[HookMatchCriterion]]
*
* A `Glob` string is a pattern which matches state names.
* Nested state names are split into segments (separated by a dot) when processing.
* The state named `foo.bar.baz` is split into three segments ['foo', 'bar', 'baz']
*
* Globs work according to the following rules:
*
* ### Exact match:
*
* The glob `'A.B'` matches the state named exactly `'A.B'`.
*
* | Glob |Matches states named|Does not match state named|
* |:------------|:--------------------|:---------------------|
* | `'A'` | `'A'` | `'B'` , `'A.C'` |
* | `'A.B'` | `'A.B'` | `'A'` , `'A.B.C'` |
* | `'foo'` | `'foo'` | `'FOO'` , `'foo.bar'`|
*
* ### Single star (`*`)
*
* A single star (`*`) is a wildcard that matches exactly one segment.
*
* | Glob |Matches states named |Does not match state named |
* |:------------|:---------------------|:--------------------------|
* | `'*'` | `'A'` , `'Z'` | `'A.B'` , `'Z.Y.X'` |
* | `'A.*'` | `'A.B'` , `'A.C'` | `'A'` , `'A.B.C'` |
* | `'A.*.*'` | `'A.B.C'` , `'A.X.Y'`| `'A'`, `'A.B'` , `'Z.Y.X'`|
*
* ### Double star (`**`)
*
* A double star (`'**'`) is a wildcard that matches *zero or more segments*
*
* | Glob |Matches states named |Does not match state named |
* |:------------|:----------------------------------------------|:----------------------------------|
* | `'**'` | `'A'` , `'A.B'`, `'Z.Y.X'` | (matches all states) |
* | `'A.**'` | `'A'` , `'A.B'` , `'A.C.X'` | `'Z.Y.X'` |
* | `'**.X'` | `'X'` , `'A.X'` , `'Z.Y.X'` | `'A'` , `'A.login.Z'` |
* | `'A.**.X'` | `'A.X'` , `'A.B.X'` , `'A.B.C.X'` | `'A'` , `'A.B.C'` |
*
*/
var Glob = /** @class */ (function () {
function Glob(text) {
this.text = text;
this.glob = text.split('.');
var regexpString = this.text.split('.')
.map(function (seg) {
if (seg === '**')
return '(?:|(?:\\.[^.]*)*)';
if (seg === '*')
return '\\.[^.]*';
return '\\.' + seg;
}).join('');
this.regexp = new RegExp('^' + regexpString + '$');
}
/** Returns true if the string has glob-like characters in it */
Glob.is = function (text) {
return !!/[!,*]+/.exec(text);
};
/** Returns a glob from the string, or null if the string isn't Glob-like */
Glob.fromString = function (text) {
return Glob.is(text) ? new Glob(text) : null;
};
Glob.prototype.matches = function (name) {
return this.regexp.test('.' + name);
};
return Glob;
}());
/**
* Internal representation of a UI-Router state.
*
* Instances of this class are created when a [[StateDeclaration]] is registered with the [[StateRegistry]].
*
* A registered [[StateDeclaration]] is augmented with a getter ([[StateDeclaration.$$state]]) which returns the corresponding [[StateObject]] object.
*
* This class prototypally inherits from the corresponding [[StateDeclaration]].
* Each of its own properties (i.e., `hasOwnProperty`) are built using builders from the [[StateBuilder]].
*/
var StateObject = /** @class */ (function () {
/** @deprecated use State.create() */
function StateObject(config) {
return StateObject.create(config || {});
}
/**
* Create a state object to put the private/internal implementation details onto.
* The object's prototype chain looks like:
* (Internal State Object) -> (Copy of State.prototype) -> (State Declaration object) -> (State Declaration's prototype...)
*
* @param stateDecl the user-supplied State Declaration
* @returns {StateObject} an internal State object
*/
StateObject.create = function (stateDecl) {
stateDecl = StateObject.isStateClass(stateDecl) ? new stateDecl() : stateDecl;
var state = inherit(inherit(stateDecl, StateObject.prototype));
stateDecl.$$state = function () { return state; };
state.self = stateDecl;
state.__stateObjectCache = {
nameGlob: Glob.fromString(state.name),
};
return state;
};
/**
* Returns true if the provided parameter is the same state.
*
* Compares the identity of the state against the passed value, which is either an object
* reference to the actual `State` instance, the original definition object passed to
* `$stateProvider.state()`, or the fully-qualified name.
*
* @param ref Can be one of (a) a `State` instance, (b) an object that was passed
* into `$stateProvider.state()`, (c) the fully-qualified name of a state as a string.
* @returns Returns `true` if `ref` matches the current `State` instance.
*/
StateObject.prototype.is = function (ref) {
return this === ref || this.self === ref || this.fqn() === ref;
};
/**
* @deprecated this does not properly handle dot notation
* @returns Returns a dot-separated name of the state.
*/
StateObject.prototype.fqn = function () {
if (!this.parent || !(this.parent instanceof this.constructor))
return this.name;
var name = this.parent.fqn();
return name ? name + '.' + this.name : this.name;
};
/**
* Returns the root node of this state's tree.
*
* @returns The root of this state's tree.
*/
StateObject.prototype.root = function () {
return this.parent && this.parent.root() || this;
};
/**
* Gets the state's `Param` objects
*
* Gets the list of [[Param]] objects owned by the state.
* If `opts.inherit` is true, it also includes the ancestor states' [[Param]] objects.
* If `opts.matchingKeys` exists, returns only `Param`s whose `id` is a key on the `matchingKeys` object
*
* @param opts options
*/
StateObject.prototype.parameters = function (opts) {
opts = defaults(opts, { inherit: true, matchingKeys: null });
var inherited = opts.inherit && this.parent && this.parent.parameters() || [];
return inherited.concat(values(this.params))
.filter(function (param) { return !opts.matchingKeys || opts.matchingKeys.hasOwnProperty(param.id); });
};
/**
* Returns a single [[Param]] that is owned by the state
*
* If `opts.inherit` is true, it also searches the ancestor states` [[Param]]s.
* @param id the name of the [[Param]] to return
* @param opts options
*/
StateObject.prototype.parameter = function (id, opts) {
if (opts === void 0) { opts = {}; }
return (this.url && this.url.parameter(id, opts) ||
find(values(this.params), propEq('id', id)) ||
opts.inherit && this.parent && this.parent.parameter(id));
};
StateObject.prototype.toString = function () {
return this.fqn();
};
/** Predicate which returns true if the object is an class with @State() decorator */
StateObject.isStateClass = function (stateDecl) {
return isFunction(stateDecl) && stateDecl['__uiRouterState'] === true;
};
/** Predicate which returns true if the object is an internal [[StateObject]] object */
StateObject.isState = function (obj) {
return isObject(obj['__stateObjectCache']);
};
return StateObject;
}());
/** Predicates
*
* These predicates return true/false based on the input.
* Although these functions are exported, they are subject to change without notice.
*
* @module common_predicates
*/
/** */
var toStr = Object.prototype.toString;
var tis = function (t) { return function (x) { return typeof (x) === t; }; };
var isUndefined = tis('undefined');
var isDefined = not(isUndefined);
var isNull = function (o) { return o === null; };
var isNullOrUndefined = or(isNull, isUndefined);
var isFunction = tis('function');
var isNumber = tis('number');
var isString = tis('string');
var isObject = function (x) { return x !== null && typeof x === 'object'; };
var isArray = Array.isArray;
var isDate = (function (x) { return toStr.call(x) === '[object Date]'; });
var isRegExp = (function (x) { return toStr.call(x) === '[object RegExp]'; });
var isState = StateObject.isState;
/**
* Predicate which checks if a value is injectable
*
* A value is "injectable" if it is a function, or if it is an ng1 array-notation-style array
* where all the elements in the array are Strings, except the last one, which is a Function
*/
function isInjectable(val$$1) {
if (isArray(val$$1) && val$$1.length) {
var head = val$$1.slice(0, -1), tail = val$$1.slice(-1);
return !(head.filter(not(isString)).length || tail.filter(not(isFunction)).length);
}
return isFunction(val$$1);
}
/**
* Predicate which checks if a value looks like a Promise
*
* It is probably a Promise if it's an object, and it has a `then` property which is a Function
*/
var isPromise = and(isObject, pipe(prop('then'), isFunction));
var notImplemented = function (fnname) { return function () {
throw new Error(fnname + "(): No coreservices implementation for UI-Router is loaded.");
}; };
var services = {
$q: undefined,
$injector: undefined,
};
/**
* Random utility functions used in the UI-Router code
*
* These functions are exported, but are subject to change without notice.
*
* @preferred
* @module common
*/
/** for typedoc */
var root = (typeof self === 'object' && self.self === self && self) ||
(typeof global === 'object' && global.global === global && global) || undefined;
var angular$1 = root.angular || {};
var fromJson = angular$1.fromJson || JSON.parse.bind(JSON);
var toJson = angular$1.toJson || JSON.stringify.bind(JSON);
var forEach = angular$1.forEach || _forEach;
var extend = Object.assign || _extend;
var equals = angular$1.equals || _equals;
function identity(x) { return x; }
function noop() { }
/**
* Builds proxy functions on the `to` object which pass through to the `from` object.
*
* For each key in `fnNames`, creates a proxy function on the `to` object.
* The proxy function calls the real function on the `from` object.
*
*
* #### Example:
* This example creates an new class instance whose functions are prebound to the new'd object.
* ```js
* class Foo {
* constructor(data) {
* // Binds all functions from Foo.prototype to 'this',
* // then copies them to 'this'
* bindFunctions(Foo.prototype, this, this);
* this.data = data;
* }
*
* log() {
* console.log(this.data);
* }
* }
*
* let myFoo = new Foo([1,2,3]);
* var logit = myFoo.log;
* logit(); // logs [1, 2, 3] from the myFoo 'this' instance
* ```
*
* #### Example:
* This example creates a bound version of a service function, and copies it to another object
* ```
*
* var SomeService = {
* this.data = [3, 4, 5];
* this.log = function() {
* console.log(this.data);
* }
* }
*
* // Constructor fn
* function OtherThing() {
* // Binds all functions from SomeService to SomeService,
* // then copies them to 'this'
* bindFunctions(SomeService, this, SomeService);
* }
*
* let myOtherThing = new OtherThing();
* myOtherThing.log(); // logs [3, 4, 5] from SomeService's 'this'
* ```
*
* @param source A function that returns the source object which contains the original functions to be bound
* @param target A function that returns the target object which will receive the bound functions
* @param bind A function that returns the object which the functions will be bound to
* @param fnNames The function names which will be bound (Defaults to all the functions found on the 'from' object)
* @param latebind If true, the binding of the function is delayed until the first time it's invoked
*/
function createProxyFunctions(source, target, bind, fnNames, latebind) {
if (latebind === void 0) { latebind = false; }
var bindFunction = function (fnName) {
return source()[fnName].bind(bind());
};
var makeLateRebindFn = function (fnName) { return function lateRebindFunction() {
target[fnName] = bindFunction(fnName);
return target[fnName].apply(null, arguments);
}; };
fnNames = fnNames || Object.keys(source());
return fnNames.reduce(function (acc, name) {
acc[name] = latebind ? makeLateRebindFn(name) : bindFunction(name);
return acc;
}, target);
}
/**
* prototypal inheritance helper.
* Creates a new object which has `parent` object as its prototype, and then copies the properties from `extra` onto it
*/
var inherit = function (parent, extra) {
return extend(Object.create(parent), extra);
};
/** Given an array, returns true if the object is found in the array, (using indexOf) */
var inArray = curry(_inArray);
function _inArray(array, obj) {
return array.indexOf(obj) !== -1;
}
/**
* Given an array, and an item, if the item is found in the array, it removes it (in-place).
* The same array is returned
*/
var removeFrom = curry(_removeFrom);
function _removeFrom(array, obj) {
var idx = array.indexOf(obj);
if (idx >= 0)
array.splice(idx, 1);
return array;
}
/** pushes a values to an array and returns the value */
var pushTo = curry(_pushTo);
function _pushTo(arr, val$$1) {
return (arr.push(val$$1), val$$1);
}
/** Given an array of (deregistration) functions, calls all functions and removes each one from the source array */
var deregAll = function (functions) {
return functions.slice().forEach(function (fn) {
typeof fn === 'function' && fn();
removeFrom(functions, fn);
});
};
/**
* Applies a set of defaults to an options object. The options object is filtered
* to only those properties of the objects in the defaultsList.
* Earlier objects in the defaultsList take precedence when applying defaults.
*/
function defaults(opts) {
var defaultsList = [];
for (var _i = 1; _i < arguments.length; _i++) {
defaultsList[_i - 1] = arguments[_i];
}
var _defaultsList = defaultsList.concat({}).reverse();
var defaultVals = extend.apply(null, _defaultsList);
return extend({}, defaultVals, pick(opts || {}, Object.keys(defaultVals)));
}
/** Reduce function that merges each element of the list into a single object, using extend */
var mergeR = function (memo, item) { return extend(memo, item); };
/**
* Finds the common ancestor path between two states.
*
* @param {Object} first The first state.
* @param {Object} second The second state.
* @return {Array} Returns an array of state names in descending order, not including the root.
*/
function ancestors(first, second) {
var path = [];
for (var n in first.path) {
if (first.path[n] !== second.path[n])
break;
path.push(first.path[n]);
}
return path;
}
/**
* Return a copy of the object only containing the whitelisted properties.
*
* #### Example:
* ```
* var foo = { a: 1, b: 2, c: 3 };
* var ab = pick(foo, ['a', 'b']); // { a: 1, b: 2 }
* ```
* @param obj the source object
* @param propNames an Array of strings, which are the whitelisted property names
*/
function pick(obj, propNames) {
var objCopy = {};
for (var _prop in obj) {
if (propNames.indexOf(_prop) !== -1) {
objCopy[_prop] = obj[_prop];
}
}
return objCopy;
}
/**
* Return a copy of the object omitting the blacklisted properties.
*
* @example
* ```
*
* var foo = { a: 1, b: 2, c: 3 };
* var ab = omit(foo, ['a', 'b']); // { c: 3 }
* ```
* @param obj the source object
* @param propNames an Array of strings, which are the blacklisted property names
*/
function omit(obj, propNames) {
return Object.keys(obj)
.filter(not(inArray(propNames)))
.reduce(function (acc, key) { return (acc[key] = obj[key], acc); }, {});
}
/**
* Maps an array, or object to a property (by name)
*/
function pluck(collection, propName) {
return map(collection, prop(propName));
}
/** Filters an Array or an Object's properties based on a predicate */
function filter(collection, callback) {
var arr = isArray(collection), result = arr ? [] : {};
var accept = arr ? function (x) { return result.push(x); } : function (x, key) { return result[key] = x; };
forEach(collection, function (item, i) {
if (callback(item, i))
accept(item, i);
});
return result;
}
/** Finds an object from an array, or a property of an object, that matches a predicate */
function find(collection, callback) {
var result;
forEach(collection, function (item, i) {
if (result)
return;
if (callback(item, i))
result = item;
});
return result;
}
/** Given an object, returns a new object, where each property is transformed by the callback function */
var mapObj = map;
/** Maps an array or object properties using a callback function */
function map(collection, callback, target) {
target = target || (isArray(collection) ? [] : {});
forEach(collection, function (item, i) { return target[i] = callback(item, i); });
return target;
}
/**
* Given an object, return its enumerable property values
*
* @example
* ```
*
* let foo = { a: 1, b: 2, c: 3 }
* let vals = values(foo); // [ 1, 2, 3 ]
* ```
*/
var values = function (obj) {
return Object.keys(obj).map(function (key) { return obj[key]; });
};
/**
* Reduce function that returns true if all of the values are truthy.
*
* @example
* ```
*
* let vals = [ 1, true, {}, "hello world"];
* vals.reduce(allTrueR, true); // true
*
* vals.push(0);
* vals.reduce(allTrueR, true); // false
* ```
*/
var allTrueR = function (memo, elem) { return memo && elem; };
/**
* Reduce function that returns true if any of the values are truthy.
*
* * @example
* ```
*
* let vals = [ 0, null, undefined ];
* vals.reduce(anyTrueR, true); // false
*
* vals.push("hello world");
* vals.reduce(anyTrueR, true); // true
* ```
*/
var anyTrueR = function (memo, elem) { return memo || elem; };
/**
* Reduce function which un-nests a single level of arrays
* @example
* ```
*
* let input = [ [ "a", "b" ], [ "c", "d" ], [ [ "double", "nested" ] ] ];
* input.reduce(unnestR, []) // [ "a", "b", "c", "d", [ "double, "nested" ] ]
* ```
*/
var unnestR = function (memo, elem) { return memo.concat(elem); };
/**
* Reduce function which recursively un-nests all arrays
*
* @example
* ```
*
* let input = [ [ "a", "b" ], [ "c", "d" ], [ [ "double", "nested" ] ] ];
* input.reduce(unnestR, []) // [ "a", "b", "c", "d", "double, "nested" ]
* ```
*/
var flattenR = function (memo, elem) {
return isArray(elem) ? memo.concat(elem.reduce(flattenR, [])) : pushR(memo, elem);
};
/**
* Reduce function that pushes an object to an array, then returns the array.
* Mostly just for [[flattenR]] and [[uniqR]]
*/
function pushR(arr, obj) {
arr.push(obj);
return arr;
}
/** Reduce function that filters out duplicates */
var uniqR = function (acc, token) {
return inArray(acc, token) ? acc : pushR(acc, token);
};
/**
* Return a new array with a single level of arrays unnested.
*
* @example
* ```
*
* let input = [ [ "a", "b" ], [ "c", "d" ], [ [ "double", "nested" ] ] ];
* unnest(input) // [ "a", "b", "c", "d", [ "double, "nested" ] ]
* ```
*/
var unnest = function (arr) { return arr.reduce(unnestR, []); };
/**
* Return a completely flattened version of an array.
*
* @example
* ```
*
* let input = [ [ "a", "b" ], [ "c", "d" ], [ [ "double", "nested" ] ] ];
* flatten(input) // [ "a", "b", "c", "d", "double, "nested" ]
* ```
*/
var flatten = function (arr) { return arr.reduce(flattenR, []); };
/**
* Given a .filter Predicate, builds a .filter Predicate which throws an error if any elements do not pass.
* @example
* ```
*
* let isNumber = (obj) => typeof(obj) === 'number';
* let allNumbers = [ 1, 2, 3, 4, 5 ];
* allNumbers.filter(assertPredicate(isNumber)); //OK
*
* let oneString = [ 1, 2, 3, 4, "5" ];
* oneString.filter(assertPredicate(isNumber, "Not all numbers")); // throws Error(""Not all numbers"");
* ```
*/
var assertPredicate = assertFn;
/**
* Given a .map function, builds a .map function which throws an error if any mapped elements do not pass a truthyness test.
* @example
* ```
*
* var data = { foo: 1, bar: 2 };
*
* let keys = [ 'foo', 'bar' ]
* let values = keys.map(assertMap(key => data[key], "Key not found"));
* // values is [1, 2]
*
* let keys = [ 'foo', 'bar', 'baz' ]
* let values = keys.map(assertMap(key => data[key], "Key not found"));
* // throws Error("Key not found")
* ```
*/
var assertMap = assertFn;
function assertFn(predicateOrMap, errMsg) {
if (errMsg === void 0) { errMsg = 'assert failure'; }
return function (obj) {
var result = predicateOrMap(obj);
if (!result) {
throw new Error(isFunction(errMsg) ? errMsg(obj) : errMsg);
}
return result;
};
}
/**
* Like _.pairs: Given an object, returns an array of key/value pairs
*
* @example
* ```
*
* pairs({ foo: "FOO", bar: "BAR }) // [ [ "foo", "FOO" ], [ "bar": "BAR" ] ]
* ```
*/
var pairs = function (obj) {
return Object.keys(obj).map(function (key) { return [key, obj[key]]; });
};
/**
* Given two or more parallel arrays, returns an array of tuples where
* each tuple is composed of [ a[i], b[i], ... z[i] ]
*
* @example
* ```
*
* let foo = [ 0, 2, 4, 6 ];
* let bar = [ 1, 3, 5, 7 ];
* let baz = [ 10, 30, 50, 70 ];
* arrayTuples(foo, bar); // [ [0, 1], [2, 3], [4, 5], [6, 7] ]
* arrayTuples(foo, bar, baz); // [ [0, 1, 10], [2, 3, 30], [4, 5, 50], [6, 7, 70] ]
* ```
*/
function arrayTuples() {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
if (args.length === 0)
return [];
var maxArrayLen = args.reduce(function (min, arr) { return Math.min(arr.length, min); }, 9007199254740991); // aka 2^53 − 1 aka Number.MAX_SAFE_INTEGER
var result = [];
var _loop_1 = function (i) {
// This is a hot function
// Unroll when there are 1-4 arguments
switch (args.length) {
case 1:
result.push([args[0][i]]);
break;
case 2:
result.push([args[0][i], args[1][i]]);
break;
case 3:
result.push([args[0][i], args[1][i], args[2][i]]);
break;
case 4:
result.push([args[0][i], args[1][i], args[2][i], args[3][i]]);
break;
default:
result.push(args.map(function (array) { return array[i]; }));
break;
}
};
for (var i = 0; i < maxArrayLen; i++) {
_loop_1(i);
}
return result;
}
/**
* Reduce function which builds an object from an array of [key, value] pairs.
*
* Each iteration sets the key/val pair on the memo object, then returns the memo for the next iteration.
*
* Each keyValueTuple should be an array with values [ key: string, value: any ]
*
* @example
* ```
*
* var pairs = [ ["fookey", "fooval"], ["barkey", "barval"] ]
*
* var pairsToObj = pairs.reduce((memo, pair) => applyPairs(memo, pair), {})
* // pairsToObj == { fookey: "fooval", barkey: "barval" }
*
* // Or, more simply:
* var pairsToObj = pairs.reduce(applyPairs, {})
* // pairsToObj == { fookey: "fooval", barkey: "barval" }
* ```
*/
function applyPairs(memo, keyValTuple) {
var key, value;
if (isArray(keyValTuple))
key = keyValTuple[0], value = keyValTuple[1];
if (!isString(key))
throw new Error('invalid parameters to applyPairs');
memo[key] = value;
return memo;
}
/** Get the last element of an array */
function tail(arr) {
return arr.length && arr[arr.length - 1] || undefined;
}
/**
* shallow copy from src to dest
*/
function copy(src, dest) {
if (dest)
Object.keys(dest).forEach(function (key) { return delete dest[key]; });
if (!dest)
dest = {};
return extend(dest, src);
}
/** Naive forEach implementation works with Objects or Arrays */
function _forEach(obj, cb, _this) {
if (isArray(obj))
return obj.forEach(cb, _this);
Object.keys(obj).forEach(function (key) { return cb(obj[key], key); });
}
function _extend(toObj) {
for (var i = 1; i < arguments.length; i++) {
var obj = arguments[i];
if (!obj)
continue;
var keys = Object.keys(obj);
for (var j = 0; j < keys.length; j++) {
toObj[keys[j]] = obj[keys[j]];
}
}
return toObj;
}
function _equals(o1, o2) {
if (o1 === o2)
return true;
if (o1 === null || o2 === null)
return false;
if (o1 !== o1 && o2 !== o2)
return true; // NaN === NaN
var t1 = typeof o1, t2 = typeof o2;
if (t1 !== t2 || t1 !== 'object')
return false;
var tup = [o1, o2];
if (all(isArray)(tup))
return _arraysEq(o1, o2);
if (all(isDate)(tup))
return o1.getTime() === o2.getTime();
if (all(isRegExp)(tup))
return o1.toString() === o2.toString();