-
Notifications
You must be signed in to change notification settings - Fork 11
Expand file tree
/
Copy pathdefine.promise.js
More file actions
748 lines (675 loc) · 20.4 KB
/
define.promise.js
File metadata and controls
748 lines (675 loc) · 20.4 KB
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
/**
* DefineJS v0.2.9 2015-04-16T23:09Z
* Copyright (c) 2014 Mehran Hatami and define.js contributors.
* Available via the MIT license.
* license found at http://github.com/fixjs/define.js/raw/master/LICENSE
*/
(function (g, undefined) {
var global = g();
var fix = {
options: {
paths: null
},
modules: {},
installed: {},
waitingList: {},
failedList: {},
definedModules: {}
};
var urlCache = {};
function isObject(value) {
// Avoid a V8 JIT bug in Chrome 19-20.
// See https://code.google.com/p/v8/issues/detail?id=2291 for more details.
var type = typeof value;
return type === 'function' || (value && type === 'object') || false;
}
function toObject(value) {
return isObject(value) ? value : Object(value);
}
function forOwn(object, iteratee) {
var iterable = toObject(object),
props = Object.keys(iterable),
length = props.length,
index = -1,
key;
while (++index < length) {
key = props[index];
if (iteratee(iterable[key], key, iterable) === false) {
break;
}
}
return object;
}
//This function solves #10 issue
function loadMap(modulePath) {
var depMap = fix.options.dependencyMap;
forOwn(depMap, function (modulesList, fileName) {
if (modulesList.indexOf(modulePath) > -1) {
modulePath = fileName;
return false;
}
});
return modulePath;
}
var tags = {
func: '[object Function]',
opera: '[object Opera]',
array: '[object Array]',
string: '[object String]'
};
var objToString = Object.prototype.toString;
var isFunction = function (value) {
// Avoid a Chakra JIT bug in compatibility modes of IE 11.
// See https://github.com/jashkenas/underscore/issues/1621 for more details.
return typeof value === 'function' || false;
};
// Fallback for environments that return incorrect `typeof` operator results.
if (isFunction(/x/) || (Uint8Array && !isFunction(Uint8Array))) {
isFunction = function (value) {
return objToString.call(value) === tags.func;
};
}
var MAX_SAFE_INTEGER = Math.pow(2, 53) - 1;
function isLength(value) {
return typeof value === 'number' && value > -1 && value % 1 === 0 && value <= MAX_SAFE_INTEGER;
}
function each(array, iteratee) {
var length = array ? array.length : 0;
if (!isLength(length)) {
return forOwn(array, iteratee);
}
var index = -1,
iterable = toObject(array);
while (++index < length) {
if (iteratee(iterable[index], index, iterable) === false) {
break;
}
}
return array;
}
function extract(base, path) {
if (typeof path !== 'string') {
return;
}
var parts = path.split('.');
each(parts, function (part) {
return isObject(base = base[part]);
});
return base;
}
function getShimObject(moduleName) {
var shim = fix.options.shim && fix.options.shim[moduleName];
if (!shim) {
return false;
}
if (!isObject(shim.object)) {
if (isFunction(shim.init)) {
shim.object = shim.init.apply(global, arguments);
}
if (!isObject(shim.object)) {
shim.object = extract(global, shim.exports);
}
}
return shim.object;
}
var doc = global.document;
function baseInfo() {
var currentScript = doc.currentScript,
filePathRgx = /^(.*[\\\/])/;
//script injection when using BASE tag is now supported
baseInfo.head = doc.head || doc.getElementsByTagName('head')[0];
baseInfo.baseElement = doc.getElementsByTagName('base')[0];
if (baseInfo.baseElement) {
baseInfo.head = baseInfo.baseElement.parentNode;
}
//phantomjs does not provide the "currentScript" property in global document object
if (currentScript) {
baseInfo.baseUrl = currentScript.getAttribute('base') || currentScript.src.match(filePathRgx)[1];
baseInfo.baseGlobal = currentScript.getAttribute('global');
} else {
baseInfo.baseUrl = '';
}
}
baseInfo();
function will(promise) {
return {
done: function (onFulfilled, onRejected) {
var self = arguments.length ? promise.then.apply(promise, arguments) : promise;
self.then(null, function (err) {
setTimeout(function () {
throw err;
}, 0);
});
}
};
}
function isObjectLike(value) {
return (value && typeof value === 'object') || false;
}
function isPromiseAlike(obj) {
return isObjectLike(obj) && isFunction(obj.then) || false;
}
function deferImpl(Promise) {
function resolve(value, baseFulfill, baseReject, save) {
var promise;
if (isPromiseAlike(value)) {
will(value).done(baseFulfill, baseReject);
promise = value;
} else {
promise = new Promise(function (fulfill) {
fulfill(value);
baseFulfill(value);
});
}
save(promise);
}
function reject(reason, baseReject, save) {
save(new Promise(function (fulfill, reject) {
reject(reason);
baseReject(reason);
}));
}
function defer() {
var resolvedPromise,
baseFulfill,
baseReject,
dfd = {},
promise = new Promise(function (fulfill, reject) {
baseFulfill = fulfill;
baseReject = reject;
});
function save(newPromise) {
resolvedPromise = newPromise;
promise.source = newPromise;
}
dfd.promise = promise;
dfd.resolve = function (value) {
if (resolvedPromise) {
return;
}
resolve(value, baseFulfill, baseReject, save);
};
dfd.reject = function (reason) {
if (resolvedPromise) {
return;
}
reject(reason, baseReject, save);
};
return dfd;
}
return defer;
}
var GeneratorFunction;
/* jshint ignore:start */
GeneratorFunction = Object.getPrototypeOf(function * () {}).constructor;
/* jshint ignore:end */
function isGenerator(fn) {
if (typeof fn === 'function') {
//Function.prototype.isGenerator is supported in Firefox 5.0 or later
//https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/isGenerator
if (typeof fn.isGenerator === 'function') {
return fn.isGenerator();
}
return /^function\s*\*/.test(fn.toString());
}
return false;
}
var isArray = Array.isArray || function (value) {
return (isObjectLike(value) && isLength(value.length) && objToString.call(value) === tags.array) || false;
};
var NativePromise = global.Promise,
genCache = new Map();
//A function by Forbes Lindesay which helps us code in synchronous style
//using yield keyword, whereas the actual scenario is an asynchronous process
//https://www.promisejs.org/generators/
function forbesAsync(makeGenerator) {
return function () {
var generator = makeGenerator.apply(this, arguments);
function handle(result) {
// result => { done: [Boolean], value: [Object] }
if (result.done) return Promise.resolve(result.value);
return Promise.resolve(result.value).then(function (res) {
return handle(generator.next(res));
}, function (err) {
return handle(generator.throw(err));
});
}
try {
return handle(generator.next());
} catch (ex) {
return Promise.reject(ex);
}
};
}
function async(makeGenerator) {
var asyncGenerator;
if (genCache.has(makeGenerator)) {
return genCache.get(makeGenerator);
}
asyncGenerator = forbesAsync(makeGenerator);
genCache.set(makeGenerator, asyncGenerator);
return asyncGenerator;
}
GeneratorFunction.prototype.async = function () {
return async(this);
};
GeneratorFunction.prototype.go = function () {
return this.async().apply(undefined, arguments);
};
// Note: It is up to devs who use this prototype function to first check if isArray(args)
GeneratorFunction.prototype.goWith = function (args) {
return this.async().apply(undefined, args);
};
GeneratorFunction.prototype.goThen = function (onFulfilled, onRejected) {
return this.goWith().then(onFulfilled, onRejected);
};
function makeAsync(fn) {
return isGenerator(fn) ? fn.async() : fn;
}
function Promise(fn) {
this.promise = isPromiseAlike(fn) ? fn : new NativePromise(makeAsync(fn));
}
Promise.prototype.then = function (onFulfilled, onRejected) {
return new Promise(this.promise.then(makeAsync(onFulfilled), makeAsync(onRejected)));
};
Promise.prototype['catch'] = function (onRejected) {
return new Promise(this.promise['catch'](makeAsync(onRejected)));
};
Promise.prototype.done = function (onFulfilled, onRejected) {
will(this.promise).done(makeAsync(onFulfilled), makeAsync(onRejected));
};
Promise.all = function (obj) {
return new Promise(NativePromise.all(obj));
};
Promise.race = function (obj) {
return new Promise(NativePromise.race(obj));
};
Promise.resolve = function (obj) {
return new Promise(NativePromise.resolve(obj));
};
Promise.reject = function (obj) {
return new Promise(NativePromise.reject(obj));
};
Promise.async = async;
var defer = deferImpl(Promise);
function makeUrl(modulePath) {
var url,
urlArgs = (typeof fix.options.urlArgs === 'string') ?
('?' + fix.options.urlArgs) :
(typeof fix.options.urlArgs === 'function') ? ('?' + fix.options.urlArgs()) : '';
if (fix.options.baseUrl) {
url = fix.options.baseUrl;
} else {
url = baseInfo.baseUrl;
}
forOwn(fix.options.paths, function (pathUrl, path) {
if (typeof pathUrl === 'string' && modulePath.indexOf(path + '/') === 0) {
modulePath = modulePath.replace(path, pathUrl);
return false;
}
});
if (url && url.charAt(url.length - 1) !== '/' && modulePath.charAt(0) !== '/') {
url += '/';
}
url += modulePath + '.js' + urlArgs;
return url;
}
function getUrl(url) {
return urlCache[url] || (urlCache[url] = makeUrl(url));
}
var isOldOpera = isObjectLike(global.opera) && global.opera.toString() === tags.opera;
var readyStateLoadedRgx = /^(complete|loaded)$/;
function loadFN(callback) {
return function fn(e) {
var el = e.currentTarget || e.srcElement;
if (e.type === 'load' || readyStateLoadedRgx.test(el.readyState)) {
callback('success');
}
if (el.detachEvent && !isOldOpera) {
el.detachEvent('onreadystatechange', fn);
} else {
el.removeEventListener('load', fn, false);
}
};
}
function errorFN(callback) {
return function fn(e) {
var el = e.currentTarget || e.srcElement;
if (e.type === 'load' || readyStateLoadedRgx.test(el.readyState)) {
callback('error');
}
if (typeof el.removeEventListener === 'function') {
el.removeEventListener('error', fn, false);
}
};
}
function createScript(url) {
var el,
dfd = defer();
//in case DefineJS were used along with something like svg in XML based use-cases,
//then "xhtml" should be set to "true" like config({ xhtml: true });
if (fix.options.xhtml) {
el = doc.createElementNS('http://www.w3.org/1999/xhtml', 'script');
} else {
el = doc.createElement('script');
}
el.async = true;
el.type = fix.options.scriptType || 'text/javascript';
el.charset = 'utf-8';
url = getUrl(url);
if (el.attachEvent && !isOldOpera) {
el.attachEvent('onreadystatechange', loadFN(dfd.resolve));
} else {
el.addEventListener('load', loadFN(dfd.resolve), false);
el.addEventListener('error', errorFN(dfd.reject), false);
}
if (baseInfo.baseElement) {
baseInfo.head.insertBefore(el, baseInfo.baseElement);
} else {
baseInfo.head.appendChild(el);
}
el.src = url;
return dfd.promise;
}
function install(moduleName, status) {
var callbacks;
if (status === 'success') {
if (fix.installed[moduleName]) {
console.warn('[DefineJS][install][' + moduleName + ']: this module is already installed!');
return;
}
fix.installed[moduleName] = true;
} else {
fix.failedList[moduleName] = true;
}
callbacks = fix.waitingList[moduleName];
if (isArray(callbacks)) {
each(callbacks, function (dfd) {
try {
dfd.resolve(fix.modules[moduleName]);
} catch (err) {
dfd.reject(err);
}
});
callbacks.length = 0;
}
}
function loadDemand(name, url, dfd) {
var shimObject;
//This solves #10 issue
url = loadMap(url);
//for those which are already loaded in the page
shimObject = getShimObject(name);
if (shimObject) {
fix.modules[name] = shimObject;
fix.installed[name] = true;
dfd.resolve(shimObject);
} else {
if (urlCache[url] || fix.definedModules[name] || loader.loadShim(name, url, dfd)) {
return;
} else {
createScript(url).then(function (status) {
if (!fix.definedModules[name]) {
install(name, status);
dfd.resolve(fix.modules[name]);
}
});
}
}
}
var cleanUrlRgx = /[\?|#]([^]*)$/,
fileNameRgx = /\/([^/]*)$/,
cleanExtRgx = /.*?(?=\.|$)/;
function matchUrl(url) {
var fileName,
matchResult;
url = url.replace(cleanUrlRgx, '');
fileName = (matchResult = url.match(fileNameRgx)) ? matchResult[1] : url;
fileName = fileName.match(cleanExtRgx)[0];
return fileName;
}
var files = {};
function getFileName(url) {
return files[url] || (files[url] = matchUrl(url));
}
function loadPromise(modulePath) {
var dfd = defer(),
isFirstLoadDemand = false,
moduleName = getFileName(modulePath);
if (fix.installed[moduleName]) {
if (fix.modules[moduleName] !== undefined) {
dfd.resolve(fix.modules[moduleName]);
} else {
dfd.reject(new Error(moduleName + ': has no returned module definition.'));
}
} else {
if (!isArray(fix.waitingList[moduleName])) {
fix.waitingList[moduleName] = [];
isFirstLoadDemand = true;
}
fix.waitingList[moduleName].push(dfd);
if (isFirstLoadDemand) {
loadDemand(moduleName, modulePath, dfd);
}
}
return dfd.promise;
}
function getShim(moduleName, modulePath, dfd) {
return createScript(modulePath)
.then(function (status) {
fix.modules[moduleName] = getShimObject(moduleName);
fix.waitingList[moduleName].push(dfd);
install(moduleName, status);
});
}
var globalPromise = new Promise(function (fulfill) {
fulfill(global);
}),
promiseStorage = {
global: globalPromise,
g: globalPromise
},
loader;
loader = {
load: function load(modulePath) {
if (promiseStorage[modulePath] === undefined) {
promiseStorage[modulePath] = loadPromise(modulePath);
}
return promiseStorage[modulePath];
},
loadAll: function loadAll(list) {
return Promise.all(list.map(loader.load));
},
loadShim: function (moduleName, modulePath, dfd) {
var shim = fix.options.shim && fix.options.shim[moduleName];
if (isObject(shim)) {
if (shim.deps && shim.deps.length) {
loader
.loadAll(shim.deps)
.then(function () {
getShim(moduleName, modulePath, dfd);
});
} else {
getShim(moduleName, modulePath, dfd);
}
return true;
}
return false;
}
};
var emptyArray = [];
function execute(fn, args) {
var fnData,
dfd = defer();
if (!isArray(args)) {
args = emptyArray;
}
if (isGenerator(fn)) {
fn.invokeWith(args).then(dfd.resolve, dfd.reject);
} else if (isFunction(fn)) {
try {
fnData = fn.apply(undefined, args);
dfd.resolve(fnData);
} catch (err) {
dfd.reject(err);
}
} else {
dfd.resolve(args);
}
return dfd.promise;
}
function isString(value) {
return typeof value === 'string' || (isObjectLike(value) && objToString.call(value) === tags.string);
}
function setup(name, definition, deps) {
var dfd = defer();
if (!isString(name) || !isFunction(definition)) {
dfd.reject(new TypeError('Expected a string and a function'));
return;
} else {
return execute(definition, deps)
.then(function (value) {
fix.modules[name] = value;
install(name, 'success');
dfd.resolve(fix.modules[name]);
});
}
return dfd.promise;
}
function fixDefine(name, list, definition) {
fix.definedModules[name] = true;
return loader
.loadAll(list)
.then(function (deps) {
return setup(name, definition, deps);
});
}
function setDepsHash(list, deps) {
if (isArray(deps) && deps.length) {
each(list, function (dep, index) {
deps[dep] = deps[index];
});
}
}
function fixRequire(list, fn) {
return loader
.loadAll(list)
.then(function (deps) {
setDepsHash(list, deps);
return execute(fn, deps);
});
}
function core(_, amd) {
if (!isObject(_)) {
_ = global;
}
_.define = function (moduleName, array, moduleDefinition) {
return core.define(amd, moduleName, array, moduleDefinition);
};
_.require = function (array, fn) {
return amd.require(array, fn);
};
_.use = function (array) {
return _.require(array);
};
_.config = function (cnfOptions) {
if (!isObject(cnfOptions)) {
console.error('Invalid parameter to set up the config');
return;
}
forOwn(cnfOptions, function (option, key) {
fix.options[key] = option;
});
};
_.require.config = _.config;
_.define.amd = {};
_.define.fix = fix;
_.define.defer = defer;
return _;
}
core.define = function (amd, moduleName, array, moduleDefinition) {
if (typeof moduleName === 'function') {
//define(moduleDefinition)
moduleDefinition = moduleName;
moduleName = undefined;
array = emptyArray;
} else if (isArray(moduleName)) {
//define(array, moduleDefinition)
moduleDefinition = array;
array = moduleName;
moduleName = undefined;
} else if (typeof moduleName === 'string') {
//define(moduleName, moduleDefinition)
if (typeof array === 'function') {
moduleDefinition = array;
array = emptyArray;
}
}
if (typeof moduleDefinition !== 'function') {
console.error('Invalid input parameter to define a module');
return false;
}
if (moduleName === undefined) {
moduleName = getFileName(document.currentScript.src);
}
return amd.define(moduleName, array, moduleDefinition);
};
function amd() {
if (amd.definejs) {
return amd.definejs;
}
var definejs = function (_) {
_ = core(_, amd);
function * loadGenerator(modulePath) {
return yield loader.load(modulePath);
}
function CJS(definition) {
return function * cjs() {
var exportsObj = {},
moduleObj = {
exports: exportsObj
};
var data = yield definition.go(exportsObj, moduleObj);
if (data) {
return data;
}
if (moduleObj.exports !== exportsObj || Object.keys(exportsObj).length > 0) {
return moduleObj.exports;
}
};
}
amd.define = function (moduleName, array, definition) {
if (isGenerator(definition)) {
return _.define(CJS(definition).async());
}
return fixDefine(moduleName, array, definition);
};
amd.require = function (array, fn) {
if (typeof array === 'function' && isGenerator(array)) {
return array.go();
}
if (typeof array === 'string' && typeof fn === 'undefined') {
return loadGenerator.go(array);
}
return fixRequire(array, fn);
};
_.define.Promise = Promise;
};
amd.definejs = definejs;
return definejs;
}
if (typeof exports === 'object') {
module.exports = amd();
} else if (typeof define === 'function' && define.amd) {
define([], amd);
} else {
var definejs = amd();
if (baseInfo.baseGlobal && isObject(global[baseInfo.baseGlobal])) {
definejs(global[baseInfo.baseGlobal]);
} else {
global.definejs = definejs;
}
}
}(function g() {
return this;
}));