/
smoke-umd.js
2191 lines (1990 loc) · 81.5 KB
/
smoke-umd.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
(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :
typeof define === 'function' && define.amd ? define(factory) :
(global = global || self, global.smoke = factory());
}(this, (function () { 'use strict';
const isBrowser = typeof window !== 'undefined';
const isNode = !isBrowser;
function getTimerClass() {
if (typeof window !== 'undefined') {
if (window.performance) {
return class {
constructor() {
this.startMark = performance.now();
}
start() {
this.startMark = performance.now();
}
get time() {
// return elapsed time in ms since the last call of start or construction
return (performance.now() - this.startMark) * 1000;
}
get startTime() {
return this.startMark;
}
};
} else {
return class {
constructor() {
this.startMark = new Date();
}
start() {
this.startMark = new Date();
}
get time() {
// return elapsed time in ms since the last call of start or construction
return (new Date()).getTime() - this.startMark.getTime();
}
get startTime() {
return this.startMark;
}
};
}
} else {
return class {
constructor() {
this.startMark = process.hrtime();
}
start() {
return (this.startMark = process.hrtime());
}
get time() {
// return elapsed time in ms since the last call of start or construction
const diff = process.hrtime(this.startMark);
return (diff[0] * 1000) + (diff[1] / 1000000);
}
get startTime() {
return this.startMark;
}
};
}
}
const Timer = getTimerClass();
/* eslint-disable no-console */
const Logger = class {
constructor(options) {
this.options = {
nameSeparator: '/',
console: true,
consoleErrorPrinter(e) {
console.log(e);
}
};
this.reset(options);
}
reset(options) {
const result = this.getResults();
this.options = { ...this.options, ...options };
if (this.options.console && typeof this.options.console !== 'object') {
this.options.console = console;
}
if (!this.options.console) {
this.options.console = {
log() {
// no-op
}
};
}
this._idSeed = 0;
this._unexpected = false;
this._totalCount = 0;
this._passCount = 0;
this._failCount = 0;
this._scaffoldFailCount = 0;
this._results = [];
this._logs = {};
return result;
}
updateOptions(options) {
this.options = { ...this.options, ...options };
}
getResults() {
return {
unexpected: this._unexpected,
totalCount: this._totalCount,
passCount: this._passCount,
failCount: this._failCount,
scaffoldFailCount: this._scaffoldFailCount,
results: this._results,
logs: this._logs
};
}
get totalCount() {
return this._totalCount;
}
get passCount() {
return this._passCount;
}
get failCount() {
return this._failCount;
}
get scaffoldFailCount() {
return this._scaffoldFailCount;
}
get unexpected() {
return this._unexpected;
}
get results() {
return this._results;
}
get logs() {
return this._logs;
}
getLog(id) {
return this._logs[id];
}
getName(context, node, testId) {
// eslint-disable-next-line no-shadow
return context.map(node => node.id).join(this.options.nameSeparator) +
(node ? this.options.nameSeparator + node.id : '') +
(testId ? this.options.nameSeparator + testId : '');
}
getNameById(loggerId) {
return this._results[loggerId][0];
}
getScaffoldName(context, node) {
const name = [];
for (let i = 0, end = context.length; i < end; i++) {
name.push(context[i].id);
if (context[i] === node) break;
}
return name.join(this.options.nameSeparator);
}
startTest(context) {
this._totalCount++;
const id = ++(this._idSeed);
this._results[id] = [this.getName(context), (new Date()).getTime(), new Timer()];
return id;
}
passTest(id) {
this._passCount++;
const result = this._results[id];
result[2] = result[2].time;
this.options.console.log(`PASS[${result[0]}]`);
}
failTest(id, error) {
this._failCount++;
const result = this._results[id];
result[2] = false;
result[3] = [error.message, ...(error.stack.split('\n'))];
this.options.console.log(`FAIL[${result[0]}]`);
this.options.consoleErrorPrinter(error);
}
excludeTest(context) {
if (this.options.logExcludes) {
const name = this.getName(context);
this.log('EXCLUDED', 0, [name]);
}
}
failScaffold(context, node, phaseText, error) {
this._scaffoldFailCount++;
const scaffoldName = this.getScaffoldName(context, node);
this.log('SCAFFOLD FAIL', 0, [`${scaffoldName}:${phaseText}`, error], true);
this.options.console.log(`SCAFFOLD FAIL[${scaffoldName}:${phaseText}]`);
this.options.consoleErrorPrinter(error);
}
logNote(note, noConsole) {
this.log('note', 0, [note], true);
!noConsole && this.options.console.log(`NOTE: ${note}`);
}
log(id, testId, entry, noConsole) {
// if you want to say noConsole==true, then you _must_ provide a testId
if (arguments.length === 2) {
noConsole = entry;
entry = testId;
testId = 0;
// noConsole is undefined
}
if (testId) {
id = `${id}:${testId}`;
}
let errorObject = 0;
if (Array.isArray(entry)) {
const lastEntry = entry[entry.length - 1];
if (lastEntry instanceof Error) {
errorObject = entry.pop();
} else if (entry.length === 1) {
entry = entry[0];
}
} else if (entry instanceof Error) {
errorObject = entry;
entry = [];
}
if (errorObject) {
entry.push(`${errorObject}`);
!isNode && entry.push(errorObject.stack);
!isNode && entry.push(errorObject);
}
if (/unexpected$/.test(id)) {
this._unexpected = true;
}
if (/error/.test(id)) {
this._failCount++;
}
(this._logs[id] || (this._logs[id] = [])).push(entry);
if (!noConsole) {
if (Array.isArray(entry)) {
this.options.console.log(`LOG[${id}]`);
entry.forEach(item => this.options.console.log(item));
this.options.console.log('.');
} else {
this.options.console.log(`LOG[${id}]`, entry);
}
}
return id;
}
};
function getPromise(resolver, rejecter) {
// provide a new Promise with addition capabilities...
// methods resolve and reject
// properties resolved, rejected, proxy, and promise
let resolve = 0;
let reject = 0;
let queuedSettlementValue;
let queuedSettlement = false; // | "resolve" | "reject"
const p = new Promise((_resolve, _reject) => {
resolve = _resolve;
reject = _reject;
if (queuedSettlement) {
p[queuedSettlement](queuedSettlementValue);
}
});
// the underlying promise
p.promise = p;
// resolve/reject the promise
// add the read-only properties resolved/rejected accordingly
p.resolve = value => {
if (!resolve) {
queuedSettlementValue = value;
queuedSettlement = 'resolve';
return;
}
value = resolver ? resolver(value) : value;
Object.defineProperties(p, {
resolved: { value: true, enumerable: true },
rejected: { value: false, enumerable: true },
});
resolve(value);
};
p.reject = value => {
if (!reject) {
queuedSettlementValue = value;
queuedSettlement = 'reject';
return;
}
value = rejecter ? rejecter(value) : value;
Object.defineProperties(p, {
resolved: { value: false, enumerable: true },
rejected: { value: true, enumerable: true },
});
reject(value);
};
// proxy hands out an interface to p that cannot resolve or reject p
p.proxy = Object.seal({
get resolved() {
return !!p.resolved;
},
get rejected() {
return !!p.rejected;
},
get promise() {
return p;
},
then(onFulfilled, onRejected) {
return p.then(onFulfilled, onRejected);
},
catch(onRejected) {
return p.catch(onRejected);
},
finally(onFinally) {
return p.finally(onFinally);
}
});
return p;
}
function getLoadControlClass(log, onResourceLoadComplete, onLoadingComplete) {
class LoadControl {
constructor(resourceName, status, resolution, errorInfo) {
const promise = getPromise();
if (!status) {
status = 'started';
} else if (resolution !== undefined) {
promise.resolve(resolution);
}
Object.defineProperties(this, {
order: { value: ++LoadControl.counter },
resourceName: { value: resourceName },
loadedName: { value: resolution !== undefined ? resourceName : false, writable: true },
status: { value: status, writable: true },
promise: { value: promise },
errorInfo: { value: errorInfo || false, writable: true },
});
// make sure we have a live loading promise so that check done can work...
if (!LoadControl.loadingPromise || LoadControl.loadingPromise.resolved) {
LoadControl.loadingError = undefined;
LoadControl.loadingPromise = getPromise();
}
promise.then(LoadControl.checkDone);
}
get isRequested() {
return !!this.loadedName;
}
get injectRelativePrefix() {
return LoadControl.injectRelativePrefix;
}
set injectRelativePrefix(injectRelativePrefix) {
if (injectRelativePrefix !== LoadControl.injectRelativePrefix) {
LoadControl.injectRelativePrefix = injectRelativePrefix;
log(`root directory for relative injection paths: '${LoadControl.injectRelativePrefix}'`);
}
}
resolve(resolution, errorInfo) {
if (this.promise.resolved) {
// eslint-disable-next-line no-console
console.warn('unexpected');
return;
}
this.status = resolution;
if (resolution === false) {
const logEntry = [this.resourceName, 'failed to load'];
if (this.loadedName !== this.resourceName) {
logEntry.push(`(loaded as ${this.loadedName})`);
}
if (errorInfo) {
this.errorInfo = errorInfo;
logEntry.push(errorInfo);
}
log(...logEntry);
} else if (resolution !== true) {
this.loadedValue = resolution;
this.status = true;
}
onResourceLoadComplete(this);
this.promise.resolve(resolution);
}
static isLegalResourceName(name, type) {
if (typeof name !== 'string') {
log(`a resource name was given to load a ${type} resource that is not a string`);
return false;
}
if (type === 'AMD' && /^\./.test(name)) {
log(`illegal to AMD require a relative module name (${name})`);
return false;
}
return true;
}
static getControl(resourceName, type) {
// false if (resourceName, type) is illegal; otherwise the control record for resourceName
if (!LoadControl.isLegalResourceName(resourceName, type)) {
return false;
}
if (LoadControl.injections.has(resourceName)) {
return LoadControl.injections.get(resourceName);
} else {
let control;
if (type === 'CSS' && isNode) {
control = new LoadControl(resourceName, 'ignored', true, 'CSS resources are ignored when running on node');
} else if (/.+\.es6\.js$/.test(resourceName) && isNode) {
// .js6 types indicate the resource may include import or export directives
// what about when node does support import/export ?
control = new LoadControl(resourceName, 'ignored', true, 'js6 resources are ignored when running on node');
} else {
control = new LoadControl(resourceName);
}
LoadControl.injections.set(resourceName, control);
return control;
}
}
static checkDone() {
let done = true;
let error = false;
// eslint-disable-next-line no-restricted-syntax
for (const control of LoadControl.injections.values()) {
if (!done || !control.promise.resolved) {
done = false;
}
error = error || control.status === false;
}
if (done) {
onLoadingComplete();
LoadControl.loadingError = error;
LoadControl.loadingPromise.resolve(error);
}
}
static load(resourceName, type, proc) {
const control = LoadControl.getControl(resourceName, type);
if (!control) {
return false;
}
if (control.isRequested) {
return control.promise.proxy;
}
let name = resourceName;
if (/^\./.test(name)) {
// if resourceName is relative, then it"s relative to the project directory
// TODO: make this an option?
name = LoadControl.injectRelativePrefix + name;
}
proc(control, name);
return control.promise.proxy;
}
static browserInject(control, tag, props) {
let node;
const handler = e => {
control.loadedName = node.src;
if (e.type === 'load') {
// TODO: make sure this kind of failure is detected on node also
control.resolve(!LoadControl.windowErrors[node.src]);
} else {
control.resolve(false, e);
}
};
try {
node = document.createElement(tag);
node.addEventListener('load', handler, false);
node.addEventListener('error', handler, false);
Object.keys(props).forEach(p => (node[p] = props[p]));
document.getElementsByTagName('script')[0].parentNode.appendChild(node);
} catch (e) {
control.resolve(false, e);
}
}
static injectScript(resourceName, type) {
return LoadControl.load(resourceName, 'script', (control, src) => {
if (type === undefined) {
type = /\.es5\.js$/.test(src) ? '' : 'module';
}
LoadControl.browserInject(control, 'script', { src: control.loadedName = src, type: type || '' });
});
}
static injectCss(resourceName) {
return LoadControl.load(resourceName, 'CSS', (control, href) => {
LoadControl.browserInject(control, 'link', {
href: control.loadedName = href,
type: 'text/css',
rel: 'stylesheet'
});
});
}
static loadNodeModule(moduleName) {
return LoadControl.load(moduleName, 'node module', (control, fileName) => {
try {
// load relative to injectRelativePrefix unless absolute since the directory
// this file resides in is meaningless to clients
if (!/^\//.test(fileName)) {
fileName = `${LoadControl.injectRelativePrefix}./${fileName}`;
}
// eslint-disable-next-line global-require,import/no-dynamic-require
require((control.loadedName = fileName));
control.resolve(true);
} catch (e) {
control.resolve(false, e);
}
});
}
static loadAmdModule(moduleName) {
return LoadControl.load(moduleName, 'script', (control, module) => {
try {
// eslint-disable-next-line global-require,import/no-dynamic-require
require([module], () => {
control.resolve(true);
});
} catch (e) {
control.resolve(false, e);
}
});
}
}
LoadControl.counter = 0;
LoadControl.injections = new Map();
LoadControl.loadingPromise = getPromise();
LoadControl.loadingPromise.resolve(true);
LoadControl.loadingError = false;
LoadControl.injectRelativePrefix = '';
LoadControl.windowErrors = {};
if (isBrowser) {
window.addEventListener('error', e => {
if (e.filename) {
LoadControl.windowErrors[e.filename] = true;
}
});
}
return LoadControl;
}
class Action {
constructor(name, id, proc) {
this.name = name;
this.id = id;
this.proc = proc || (() => {
// no-op
});
}
static getNewActionUid() {
return ++Action.uidSeed;
}
static get(key) {
return Action.actionCatalog[key];
}
static add(name, proc) {
const id = Action.getNewActionUid();
return Action.actionCatalog[name] = Action.actionCatalog[id] = Action.action[name] = new Action(name, id, proc);
}
static execute(list, driver) {
// list is always an array of a pairs of [action-id, args]
const driverActions = driver.actions({ bridge: true });
// let driverActions = driver.actions();
const scratch = {};
while (list.length) {
const instruction = list.shift();
const action = Action.get(instruction[0]);
if (action === Action.actionTestComplete) {
// the test has completed or been aborted
if (list.length) {
// eslint-disable-next-line no-console
console.warn('unexpected');
}
return driverActions.perform().then(() => instruction[1][0]);
} else {
action.proc(driver, driverActions, scratch, ...instruction[1]);
}
}
return driverActions.perform().then(() => false);
}
static action(...list) {
const result = [];
let i = 0;
const end = list.length;
if (typeof list[i] === 'string') {
result.prompt = list[i++];
}
while (i < end) {
const args = [];
result.push([list[i++], args]);
while (i < end && !(list[i] instanceof Action)) args.push(list[i++]);
}
return result;
}
}
Action.uidSeed = 0;
Action.actionCatalog = {};
Action.actionTestComplete = 0;
Action.actionTestComplete = Action.add('testComplete');
Action.add('sendKeys', (driver, action, scratch, ...args) => {
action.sendKeys(...args);
});
Action.add('keyDown', (driver, action, scratch, ...args) => {
args.forEach(k => {
action.keyDown(k);
});
});
Action.add('keyUp', (driver, action, scratch, ...args) => {
args.forEach(k => {
action.keyUp(k);
});
});
Action.add('click', (driver, action, scratch, id) => {
action.click(driver.findElement({ id }));
});
// these are take verbatim from selenium-webdriver
Action.action.keys = {
null: '\uE000',
cancel: '\uE001',
help: '\uE002',
back_space: '\uE003',
tab: '\uE004',
clear: '\uE005',
return: '\uE006',
enter: '\uE007',
shift: '\uE008',
control: '\uE009',
alt: '\uE00A',
pause: '\uE00B',
escape: '\uE00C',
space: '\uE00D',
pageUp: '\uE00E',
pageDown: '\uE00F',
end: '\uE010',
home: '\uE011',
arrowLeft: '\uE012',
left: '\uE012',
arrowUp: '\uE013',
up: '\uE013',
arrowRight: '\uE014',
right: '\uE014',
arrowDown: '\uE015',
down: '\uE015',
insert: '\uE016',
delete: '\uE017',
semicolon: '\uE018',
equals: '\uE019',
numpad0: '\uE01A',
numpad1: '\uE01B',
numpad2: '\uE01C',
numpad3: '\uE01D',
numpad4: '\uE01E',
numpad5: '\uE01F',
numpad6: '\uE020',
numpad7: '\uE021',
numpad8: '\uE022',
numpad9: '\uE023',
multiply: '\uE024',
add: '\uE025',
separator: '\uE026',
subtract: '\uE027',
decimal: '\uE028',
divide: '\uE029',
f1: '\uE031',
f2: '\uE032',
f3: '\uE033',
f4: '\uE034',
f5: '\uE035',
f6: '\uE036',
f7: '\uE037',
f8: '\uE038',
f9: '\uE039',
f10: '\uE03A',
f11: '\uE03B',
f12: '\uE03C',
command: '\uE03D',
meta: '\uE03D',
zenkakuHankaku: '\uE040'
};
function getStringify(indentFactor, newLine, typeFilter) {
let
nameStack,
_seen,
spaces = ' ';
function indent(n) {
n *= indentFactor;
while (spaces.length < n) {
spaces += spaces;
}
return spaces.substring(0, n);
}
function propName(name) {
return /[^a-zA-Z0-9_$]/.test(name) ? (`'${name}':`) : (`${name}:`);
}
function seen(it) {
if (_seen.has(it)) {
return _seen.get(it);
} else {
_seen.set(it, nameStack.join('.'));
return false;
}
}
function stringify(it, level, name) {
let text;
if (!level) {
_seen = new Map();
nameStack = [];
level = 1;
} else {
level++;
nameStack.push(name);
}
let seenName;
const typeofIt = typeof it;
switch (typeofIt) {
case 'undefined':
text = 'undefined';
break;
case 'boolean':
text = (it ? 'true' : 'false');
break;
case 'number':
text = it.toString();
break;
case 'string':
text = JSON.stringify(it);
break;
case 'object':
if (it === null) {
text = 'null';
} else if (it instanceof RegExp) {
text = it.toString();
} else if ((seenName = seen(it))) {
text = `[circular --> ${seenName}]`;
} else if (it instanceof Array) {
const stringifiedContent = it.map((value, i) => {
const valueText = stringify(value, level, `[${i}]`);
return valueText ? (indent(level) + valueText) : false;
}).filter(x => x);
if (stringifiedContent.length) {
text = (
`[${newLine}${stringifiedContent.join(`,${newLine}`)}${newLine}${indent(level - 1)}]`
);
} else {
text = '[]';
}
} else {
const stringifiedContent = Object.keys(it).sort().map(key => {
const valueText = stringify(it[key], level, key);
return valueText ? (indent(level) + propName(key) + valueText) : false;
}).filter(x => x);
if (stringifiedContent.length) {
text = (
`{${newLine}${stringifiedContent.join(`,${newLine}`)}${newLine}${indent(level - 1)}}`
);
} else {
text = '{}';
}
}
break;
default:
text = typeFilter && typeFilter(typeofIt) ? `[${typeof it}]` : false;
}
nameStack.pop();
return text;
}
return stringify;
}
const stringify = getStringify(4, '\n', type => (!(/function|symbol/.test(type))));
stringify.makeStringify = getStringify;
let assertCount = 0;
function resetAssertCount() {
assertCount = 0;
}
function bumpAssertCount() {
++assertCount;
}
function getAssertCount() {
return assertCount;
}
function assert(value, message) {
// trivial assert; any function that throws upon a detected error will work
bumpAssertCount();
if (!value) {
throw new Error(message || 'fail');
}
}
function normalizeOptionName(name) {
// strip the leading dashes...
name = name.trim();
name = name && name.match(/^-*(.+)/)[1];
switch (name) {
case 'p':
case 'profile':
case 'l':
case 'load':
return 'load';
case 'i':
case 'include':
return 'include';
default:
return name;
}
}
function getUrlArgs(useHash) {
const urlParams = [];
const location = window.location;
const qString = decodeURIComponent(useHash ? location.hash.substring(1) : location.search.substring(1)) || '';
qString.split('&').forEach(arg => urlParams.push(arg.trim()));
urlParams.push(`cwd=${(window.location.origin + window.location.pathname).match(/(.+)\/[^/]+$/)[1]}`);
return urlParams;
}
function argsToOptions(args, _normalizeOptionName) {
// args is an array of strings...usually either the command line args (node) or a lightly processed
// hash string (browser) transform options into key-> value | [values] for options of the form "key=value"
// and key->true for options of the form "key" for any value of the form "<value>" or '<value>', remove
// the surrounding quotes make sure everything is trimmed up
const normalizeName = _normalizeOptionName ? name => (normalizeOptionName(_normalizeOptionName(name))) : normalizeOptionName;
const options = {};
args.forEach(arg => {
arg = arg.trim();
if (/.+=.+/.test(arg)) {
let match = arg.match(/([^=]+)=(.+)/);
const name = normalizeName(match[1]);
let value = match[2];
match = value.trim().match(/^['"](.+)['"]$/);
value = match ? match[1] : value;
if (name in options) {
if (!Array.isArray(options[name])) {
options[name] = [options[name], value];
} else {
options[name].push(value);
}
} else {
options[name] = value;
}
} else if (arg) {
arg = normalizeName(arg);
if (/^!(.+)/.test(arg)) {
options[arg.substring(1)] = false;
} else {
options[arg] = true;
}
}// else ignore an empty string
});
return options;
}
// toArray also filters out falsey values
const toArray = src => (Array.isArray(src) ? src : [src]).filter(x => !!x);
const processInclude = (dest, value) => {
value.split(/[;,]/).forEach(item => {
item = item.split(/[./]/).map(x => x.trim()).filter(x => !!x);
item.length && dest.push(item);
});
return dest;
};
const commaListToArray = src => src.split(/[,;]/).map(s => s.trim()).filter(x => !!x);
const processCommaList = (dest, src) => {
return dest.concat(commaListToArray(src));
};
function processOptions(options, dest) {
// process everything except the profiles into dest; this allows modules loaded via profiles to use the options
Object.keys(options).forEach(name => {
const value = options[name];
switch (name) {
// notice that include is cumulative when multiple configurations are processed
case 'include':
dest.include = toArray(value).reduce(processInclude, dest.include || []);
break;
case 'package':
toArray(value).forEach(item => {
commaListToArray(item).forEach(p => {
const split = p.split(':').map(s => s.trim());
require.config({ packages: [{ name: split[0], location: split[1], main: split[2] }] });
});
});
break;
case 'load':
dest.load = toArray(value).reduce(processCommaList, dest.load || []);
break;
case 'remoteTests':
dest.remoteTests = toArray(value).reduce(processCommaList, dest.remoteTests || []);
break;
case 'cap':
dest.cap = toArray(value).reduce(processCommaList, dest.cap || []);
break;
case 'capPreset':
dest.capPreset = toArray(value).reduce(processCommaList, dest.capPreset || []);
break;
case 'css':
dest.css = toArray(value).reduce(processCommaList, dest.css || []);
break;
case 'remotelyControlled':
dest.remotelyControlled = true;
dest.autoRun = false;
break;
default:
dest[name] = value;
}
});
}
const browser = Object.freeze({
toString() {
return 'browser';
}
});
const node = Object.freeze({
toString() {
return 'node';
}
});
const both = Object.freeze({
toString() {
return 'both';
}
});
const remote = Object.freeze({
toString() {
return 'remote';
}
});
const testTypes = Object.freeze({
browser,
node,
both,
remote