es6-module-loader.src.js 80 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863
  1. !function(e){"object"==typeof exports?module.exports=e():"function"==typeof define&&define.amd?define(e):"undefined"!=typeof window?window.Promise=e():"undefined"!=typeof global?global.Promise=e():"undefined"!=typeof self&&(self.Promise=e())}(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);throw new Error("Cannot find module '"+o+"'")}var f=n[o]={exports:{}};t[o][0].call(f.exports,function(e){var n=t[o][1][e];return s(n?n:e)},f,f.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){
  2. /** @license MIT License (c) copyright 2010-2014 original author or authors */
  3. /** @author Brian Cavalier */
  4. /** @author John Hann */
  5. /**
  6. * ES6 global Promise shim
  7. */
  8. var unhandledRejections = require('../lib/decorators/unhandledRejection');
  9. var PromiseConstructor = unhandledRejections(require('../lib/Promise'));
  10. module.exports = typeof global != 'undefined' ? (global.Promise = PromiseConstructor)
  11. : typeof self != 'undefined' ? (self.Promise = PromiseConstructor)
  12. : PromiseConstructor;
  13. },{"../lib/Promise":2,"../lib/decorators/unhandledRejection":4}],2:[function(require,module,exports){
  14. /** @license MIT License (c) copyright 2010-2014 original author or authors */
  15. /** @author Brian Cavalier */
  16. /** @author John Hann */
  17. (function(define) { 'use strict';
  18. define(function (require) {
  19. var makePromise = require('./makePromise');
  20. var Scheduler = require('./Scheduler');
  21. var async = require('./env').asap;
  22. return makePromise({
  23. scheduler: new Scheduler(async)
  24. });
  25. });
  26. })(typeof define === 'function' && define.amd ? define : function (factory) { module.exports = factory(require); });
  27. },{"./Scheduler":3,"./env":5,"./makePromise":7}],3:[function(require,module,exports){
  28. /** @license MIT License (c) copyright 2010-2014 original author or authors */
  29. /** @author Brian Cavalier */
  30. /** @author John Hann */
  31. (function(define) { 'use strict';
  32. define(function() {
  33. // Credit to Twisol (https://github.com/Twisol) for suggesting
  34. // this type of extensible queue + trampoline approach for next-tick conflation.
  35. /**
  36. * Async task scheduler
  37. * @param {function} async function to schedule a single async function
  38. * @constructor
  39. */
  40. function Scheduler(async) {
  41. this._async = async;
  42. this._running = false;
  43. this._queue = this;
  44. this._queueLen = 0;
  45. this._afterQueue = {};
  46. this._afterQueueLen = 0;
  47. var self = this;
  48. this.drain = function() {
  49. self._drain();
  50. };
  51. }
  52. /**
  53. * Enqueue a task
  54. * @param {{ run:function }} task
  55. */
  56. Scheduler.prototype.enqueue = function(task) {
  57. this._queue[this._queueLen++] = task;
  58. this.run();
  59. };
  60. /**
  61. * Enqueue a task to run after the main task queue
  62. * @param {{ run:function }} task
  63. */
  64. Scheduler.prototype.afterQueue = function(task) {
  65. this._afterQueue[this._afterQueueLen++] = task;
  66. this.run();
  67. };
  68. Scheduler.prototype.run = function() {
  69. if (!this._running) {
  70. this._running = true;
  71. this._async(this.drain);
  72. }
  73. };
  74. /**
  75. * Drain the handler queue entirely, and then the after queue
  76. */
  77. Scheduler.prototype._drain = function() {
  78. var i = 0;
  79. for (; i < this._queueLen; ++i) {
  80. this._queue[i].run();
  81. this._queue[i] = void 0;
  82. }
  83. this._queueLen = 0;
  84. this._running = false;
  85. for (i = 0; i < this._afterQueueLen; ++i) {
  86. this._afterQueue[i].run();
  87. this._afterQueue[i] = void 0;
  88. }
  89. this._afterQueueLen = 0;
  90. };
  91. return Scheduler;
  92. });
  93. }(typeof define === 'function' && define.amd ? define : function(factory) { module.exports = factory(); }));
  94. },{}],4:[function(require,module,exports){
  95. /** @license MIT License (c) copyright 2010-2014 original author or authors */
  96. /** @author Brian Cavalier */
  97. /** @author John Hann */
  98. (function(define) { 'use strict';
  99. define(function(require) {
  100. var setTimer = require('../env').setTimer;
  101. var format = require('../format');
  102. return function unhandledRejection(Promise) {
  103. var logError = noop;
  104. var logInfo = noop;
  105. var localConsole;
  106. if(typeof console !== 'undefined') {
  107. // Alias console to prevent things like uglify's drop_console option from
  108. // removing console.log/error. Unhandled rejections fall into the same
  109. // category as uncaught exceptions, and build tools shouldn't silence them.
  110. localConsole = console;
  111. logError = typeof localConsole.error !== 'undefined'
  112. ? function (e) { localConsole.error(e); }
  113. : function (e) { localConsole.log(e); };
  114. logInfo = typeof localConsole.info !== 'undefined'
  115. ? function (e) { localConsole.info(e); }
  116. : function (e) { localConsole.log(e); };
  117. }
  118. Promise.onPotentiallyUnhandledRejection = function(rejection) {
  119. enqueue(report, rejection);
  120. };
  121. Promise.onPotentiallyUnhandledRejectionHandled = function(rejection) {
  122. enqueue(unreport, rejection);
  123. };
  124. Promise.onFatalRejection = function(rejection) {
  125. enqueue(throwit, rejection.value);
  126. };
  127. var tasks = [];
  128. var reported = [];
  129. var running = null;
  130. function report(r) {
  131. if(!r.handled) {
  132. reported.push(r);
  133. logError('Potentially unhandled rejection [' + r.id + '] ' + format.formatError(r.value));
  134. }
  135. }
  136. function unreport(r) {
  137. var i = reported.indexOf(r);
  138. if(i >= 0) {
  139. reported.splice(i, 1);
  140. logInfo('Handled previous rejection [' + r.id + '] ' + format.formatObject(r.value));
  141. }
  142. }
  143. function enqueue(f, x) {
  144. tasks.push(f, x);
  145. if(running === null) {
  146. running = setTimer(flush, 0);
  147. }
  148. }
  149. function flush() {
  150. running = null;
  151. while(tasks.length > 0) {
  152. tasks.shift()(tasks.shift());
  153. }
  154. }
  155. return Promise;
  156. };
  157. function throwit(e) {
  158. throw e;
  159. }
  160. function noop() {}
  161. });
  162. }(typeof define === 'function' && define.amd ? define : function(factory) { module.exports = factory(require); }));
  163. },{"../env":5,"../format":6}],5:[function(require,module,exports){
  164. /** @license MIT License (c) copyright 2010-2014 original author or authors */
  165. /** @author Brian Cavalier */
  166. /** @author John Hann */
  167. /*global process,document,setTimeout,clearTimeout,MutationObserver,WebKitMutationObserver*/
  168. (function(define) { 'use strict';
  169. define(function(require) {
  170. /*jshint maxcomplexity:6*/
  171. // Sniff "best" async scheduling option
  172. // Prefer process.nextTick or MutationObserver, then check for
  173. // setTimeout, and finally vertx, since its the only env that doesn't
  174. // have setTimeout
  175. var MutationObs;
  176. var capturedSetTimeout = typeof setTimeout !== 'undefined' && setTimeout;
  177. // Default env
  178. var setTimer = function(f, ms) { return setTimeout(f, ms); };
  179. var clearTimer = function(t) { return clearTimeout(t); };
  180. var asap = function (f) { return capturedSetTimeout(f, 0); };
  181. // Detect specific env
  182. if (isNode()) { // Node
  183. asap = function (f) { return process.nextTick(f); };
  184. } else if (MutationObs = hasMutationObserver()) { // Modern browser
  185. asap = initMutationObserver(MutationObs);
  186. } else if (!capturedSetTimeout) { // vert.x
  187. var vertxRequire = require;
  188. var vertx = vertxRequire('vertx');
  189. setTimer = function (f, ms) { return vertx.setTimer(ms, f); };
  190. clearTimer = vertx.cancelTimer;
  191. asap = vertx.runOnLoop || vertx.runOnContext;
  192. }
  193. return {
  194. setTimer: setTimer,
  195. clearTimer: clearTimer,
  196. asap: asap
  197. };
  198. function isNode () {
  199. return typeof process !== 'undefined' && process !== null &&
  200. typeof process.nextTick === 'function';
  201. }
  202. function hasMutationObserver () {
  203. return (typeof MutationObserver === 'function' && MutationObserver) ||
  204. (typeof WebKitMutationObserver === 'function' && WebKitMutationObserver);
  205. }
  206. function initMutationObserver(MutationObserver) {
  207. var scheduled;
  208. var node = document.createTextNode('');
  209. var o = new MutationObserver(run);
  210. o.observe(node, { characterData: true });
  211. function run() {
  212. var f = scheduled;
  213. scheduled = void 0;
  214. f();
  215. }
  216. var i = 0;
  217. return function (f) {
  218. scheduled = f;
  219. node.data = (i ^= 1);
  220. };
  221. }
  222. });
  223. }(typeof define === 'function' && define.amd ? define : function(factory) { module.exports = factory(require); }));
  224. },{}],6:[function(require,module,exports){
  225. /** @license MIT License (c) copyright 2010-2014 original author or authors */
  226. /** @author Brian Cavalier */
  227. /** @author John Hann */
  228. (function(define) { 'use strict';
  229. define(function() {
  230. return {
  231. formatError: formatError,
  232. formatObject: formatObject,
  233. tryStringify: tryStringify
  234. };
  235. /**
  236. * Format an error into a string. If e is an Error and has a stack property,
  237. * it's returned. Otherwise, e is formatted using formatObject, with a
  238. * warning added about e not being a proper Error.
  239. * @param {*} e
  240. * @returns {String} formatted string, suitable for output to developers
  241. */
  242. function formatError(e) {
  243. var s = typeof e === 'object' && e !== null && e.stack ? e.stack : formatObject(e);
  244. return e instanceof Error ? s : s + ' (WARNING: non-Error used)';
  245. }
  246. /**
  247. * Format an object, detecting "plain" objects and running them through
  248. * JSON.stringify if possible.
  249. * @param {Object} o
  250. * @returns {string}
  251. */
  252. function formatObject(o) {
  253. var s = String(o);
  254. if(s === '[object Object]' && typeof JSON !== 'undefined') {
  255. s = tryStringify(o, s);
  256. }
  257. return s;
  258. }
  259. /**
  260. * Try to return the result of JSON.stringify(x). If that fails, return
  261. * defaultValue
  262. * @param {*} x
  263. * @param {*} defaultValue
  264. * @returns {String|*} JSON.stringify(x) or defaultValue
  265. */
  266. function tryStringify(x, defaultValue) {
  267. try {
  268. return JSON.stringify(x);
  269. } catch(e) {
  270. return defaultValue;
  271. }
  272. }
  273. });
  274. }(typeof define === 'function' && define.amd ? define : function(factory) { module.exports = factory(); }));
  275. },{}],7:[function(require,module,exports){
  276. /** @license MIT License (c) copyright 2010-2014 original author or authors */
  277. /** @author Brian Cavalier */
  278. /** @author John Hann */
  279. (function(define) { 'use strict';
  280. define(function() {
  281. return function makePromise(environment) {
  282. var tasks = environment.scheduler;
  283. var emitRejection = initEmitRejection();
  284. var objectCreate = Object.create ||
  285. function(proto) {
  286. function Child() {}
  287. Child.prototype = proto;
  288. return new Child();
  289. };
  290. /**
  291. * Create a promise whose fate is determined by resolver
  292. * @constructor
  293. * @returns {Promise} promise
  294. * @name Promise
  295. */
  296. function Promise(resolver, handler) {
  297. this._handler = resolver === Handler ? handler : init(resolver);
  298. }
  299. /**
  300. * Run the supplied resolver
  301. * @param resolver
  302. * @returns {Pending}
  303. */
  304. function init(resolver) {
  305. var handler = new Pending();
  306. try {
  307. resolver(promiseResolve, promiseReject, promiseNotify);
  308. } catch (e) {
  309. promiseReject(e);
  310. }
  311. return handler;
  312. /**
  313. * Transition from pre-resolution state to post-resolution state, notifying
  314. * all listeners of the ultimate fulfillment or rejection
  315. * @param {*} x resolution value
  316. */
  317. function promiseResolve (x) {
  318. handler.resolve(x);
  319. }
  320. /**
  321. * Reject this promise with reason, which will be used verbatim
  322. * @param {Error|*} reason rejection reason, strongly suggested
  323. * to be an Error type
  324. */
  325. function promiseReject (reason) {
  326. handler.reject(reason);
  327. }
  328. /**
  329. * @deprecated
  330. * Issue a progress event, notifying all progress listeners
  331. * @param {*} x progress event payload to pass to all listeners
  332. */
  333. function promiseNotify (x) {
  334. handler.notify(x);
  335. }
  336. }
  337. // Creation
  338. Promise.resolve = resolve;
  339. Promise.reject = reject;
  340. Promise.never = never;
  341. Promise._defer = defer;
  342. Promise._handler = getHandler;
  343. /**
  344. * Returns a trusted promise. If x is already a trusted promise, it is
  345. * returned, otherwise returns a new trusted Promise which follows x.
  346. * @param {*} x
  347. * @return {Promise} promise
  348. */
  349. function resolve(x) {
  350. return isPromise(x) ? x
  351. : new Promise(Handler, new Async(getHandler(x)));
  352. }
  353. /**
  354. * Return a reject promise with x as its reason (x is used verbatim)
  355. * @param {*} x
  356. * @returns {Promise} rejected promise
  357. */
  358. function reject(x) {
  359. return new Promise(Handler, new Async(new Rejected(x)));
  360. }
  361. /**
  362. * Return a promise that remains pending forever
  363. * @returns {Promise} forever-pending promise.
  364. */
  365. function never() {
  366. return foreverPendingPromise; // Should be frozen
  367. }
  368. /**
  369. * Creates an internal {promise, resolver} pair
  370. * @private
  371. * @returns {Promise}
  372. */
  373. function defer() {
  374. return new Promise(Handler, new Pending());
  375. }
  376. // Transformation and flow control
  377. /**
  378. * Transform this promise's fulfillment value, returning a new Promise
  379. * for the transformed result. If the promise cannot be fulfilled, onRejected
  380. * is called with the reason. onProgress *may* be called with updates toward
  381. * this promise's fulfillment.
  382. * @param {function=} onFulfilled fulfillment handler
  383. * @param {function=} onRejected rejection handler
  384. * @param {function=} onProgress @deprecated progress handler
  385. * @return {Promise} new promise
  386. */
  387. Promise.prototype.then = function(onFulfilled, onRejected, onProgress) {
  388. var parent = this._handler;
  389. var state = parent.join().state();
  390. if ((typeof onFulfilled !== 'function' && state > 0) ||
  391. (typeof onRejected !== 'function' && state < 0)) {
  392. // Short circuit: value will not change, simply share handler
  393. return new this.constructor(Handler, parent);
  394. }
  395. var p = this._beget();
  396. var child = p._handler;
  397. parent.chain(child, parent.receiver, onFulfilled, onRejected, onProgress);
  398. return p;
  399. };
  400. /**
  401. * If this promise cannot be fulfilled due to an error, call onRejected to
  402. * handle the error. Shortcut for .then(undefined, onRejected)
  403. * @param {function?} onRejected
  404. * @return {Promise}
  405. */
  406. Promise.prototype['catch'] = function(onRejected) {
  407. return this.then(void 0, onRejected);
  408. };
  409. /**
  410. * Creates a new, pending promise of the same type as this promise
  411. * @private
  412. * @returns {Promise}
  413. */
  414. Promise.prototype._beget = function() {
  415. return begetFrom(this._handler, this.constructor);
  416. };
  417. function begetFrom(parent, Promise) {
  418. var child = new Pending(parent.receiver, parent.join().context);
  419. return new Promise(Handler, child);
  420. }
  421. // Array combinators
  422. Promise.all = all;
  423. Promise.race = race;
  424. Promise._traverse = traverse;
  425. /**
  426. * Return a promise that will fulfill when all promises in the
  427. * input array have fulfilled, or will reject when one of the
  428. * promises rejects.
  429. * @param {array} promises array of promises
  430. * @returns {Promise} promise for array of fulfillment values
  431. */
  432. function all(promises) {
  433. return traverseWith(snd, null, promises);
  434. }
  435. /**
  436. * Array<Promise<X>> -> Promise<Array<f(X)>>
  437. * @private
  438. * @param {function} f function to apply to each promise's value
  439. * @param {Array} promises array of promises
  440. * @returns {Promise} promise for transformed values
  441. */
  442. function traverse(f, promises) {
  443. return traverseWith(tryCatch2, f, promises);
  444. }
  445. function traverseWith(tryMap, f, promises) {
  446. var handler = typeof f === 'function' ? mapAt : settleAt;
  447. var resolver = new Pending();
  448. var pending = promises.length >>> 0;
  449. var results = new Array(pending);
  450. for (var i = 0, x; i < promises.length && !resolver.resolved; ++i) {
  451. x = promises[i];
  452. if (x === void 0 && !(i in promises)) {
  453. --pending;
  454. continue;
  455. }
  456. traverseAt(promises, handler, i, x, resolver);
  457. }
  458. if(pending === 0) {
  459. resolver.become(new Fulfilled(results));
  460. }
  461. return new Promise(Handler, resolver);
  462. function mapAt(i, x, resolver) {
  463. if(!resolver.resolved) {
  464. traverseAt(promises, settleAt, i, tryMap(f, x, i), resolver);
  465. }
  466. }
  467. function settleAt(i, x, resolver) {
  468. results[i] = x;
  469. if(--pending === 0) {
  470. resolver.become(new Fulfilled(results));
  471. }
  472. }
  473. }
  474. function traverseAt(promises, handler, i, x, resolver) {
  475. if (maybeThenable(x)) {
  476. var h = getHandlerMaybeThenable(x);
  477. var s = h.state();
  478. if (s === 0) {
  479. h.fold(handler, i, void 0, resolver);
  480. } else if (s > 0) {
  481. handler(i, h.value, resolver);
  482. } else {
  483. resolver.become(h);
  484. visitRemaining(promises, i+1, h);
  485. }
  486. } else {
  487. handler(i, x, resolver);
  488. }
  489. }
  490. Promise._visitRemaining = visitRemaining;
  491. function visitRemaining(promises, start, handler) {
  492. for(var i=start; i<promises.length; ++i) {
  493. markAsHandled(getHandler(promises[i]), handler);
  494. }
  495. }
  496. function markAsHandled(h, handler) {
  497. if(h === handler) {
  498. return;
  499. }
  500. var s = h.state();
  501. if(s === 0) {
  502. h.visit(h, void 0, h._unreport);
  503. } else if(s < 0) {
  504. h._unreport();
  505. }
  506. }
  507. /**
  508. * Fulfill-reject competitive race. Return a promise that will settle
  509. * to the same state as the earliest input promise to settle.
  510. *
  511. * WARNING: The ES6 Promise spec requires that race()ing an empty array
  512. * must return a promise that is pending forever. This implementation
  513. * returns a singleton forever-pending promise, the same singleton that is
  514. * returned by Promise.never(), thus can be checked with ===
  515. *
  516. * @param {array} promises array of promises to race
  517. * @returns {Promise} if input is non-empty, a promise that will settle
  518. * to the same outcome as the earliest input promise to settle. if empty
  519. * is empty, returns a promise that will never settle.
  520. */
  521. function race(promises) {
  522. if(typeof promises !== 'object' || promises === null) {
  523. return reject(new TypeError('non-iterable passed to race()'));
  524. }
  525. // Sigh, race([]) is untestable unless we return *something*
  526. // that is recognizable without calling .then() on it.
  527. return promises.length === 0 ? never()
  528. : promises.length === 1 ? resolve(promises[0])
  529. : runRace(promises);
  530. }
  531. function runRace(promises) {
  532. var resolver = new Pending();
  533. var i, x, h;
  534. for(i=0; i<promises.length; ++i) {
  535. x = promises[i];
  536. if (x === void 0 && !(i in promises)) {
  537. continue;
  538. }
  539. h = getHandler(x);
  540. if(h.state() !== 0) {
  541. resolver.become(h);
  542. visitRemaining(promises, i+1, h);
  543. break;
  544. } else {
  545. h.visit(resolver, resolver.resolve, resolver.reject);
  546. }
  547. }
  548. return new Promise(Handler, resolver);
  549. }
  550. // Promise internals
  551. // Below this, everything is @private
  552. /**
  553. * Get an appropriate handler for x, without checking for cycles
  554. * @param {*} x
  555. * @returns {object} handler
  556. */
  557. function getHandler(x) {
  558. if(isPromise(x)) {
  559. return x._handler.join();
  560. }
  561. return maybeThenable(x) ? getHandlerUntrusted(x) : new Fulfilled(x);
  562. }
  563. /**
  564. * Get a handler for thenable x.
  565. * NOTE: You must only call this if maybeThenable(x) == true
  566. * @param {object|function|Promise} x
  567. * @returns {object} handler
  568. */
  569. function getHandlerMaybeThenable(x) {
  570. return isPromise(x) ? x._handler.join() : getHandlerUntrusted(x);
  571. }
  572. /**
  573. * Get a handler for potentially untrusted thenable x
  574. * @param {*} x
  575. * @returns {object} handler
  576. */
  577. function getHandlerUntrusted(x) {
  578. try {
  579. var untrustedThen = x.then;
  580. return typeof untrustedThen === 'function'
  581. ? new Thenable(untrustedThen, x)
  582. : new Fulfilled(x);
  583. } catch(e) {
  584. return new Rejected(e);
  585. }
  586. }
  587. /**
  588. * Handler for a promise that is pending forever
  589. * @constructor
  590. */
  591. function Handler() {}
  592. Handler.prototype.when
  593. = Handler.prototype.become
  594. = Handler.prototype.notify // deprecated
  595. = Handler.prototype.fail
  596. = Handler.prototype._unreport
  597. = Handler.prototype._report
  598. = noop;
  599. Handler.prototype._state = 0;
  600. Handler.prototype.state = function() {
  601. return this._state;
  602. };
  603. /**
  604. * Recursively collapse handler chain to find the handler
  605. * nearest to the fully resolved value.
  606. * @returns {object} handler nearest the fully resolved value
  607. */
  608. Handler.prototype.join = function() {
  609. var h = this;
  610. while(h.handler !== void 0) {
  611. h = h.handler;
  612. }
  613. return h;
  614. };
  615. Handler.prototype.chain = function(to, receiver, fulfilled, rejected, progress) {
  616. this.when({
  617. resolver: to,
  618. receiver: receiver,
  619. fulfilled: fulfilled,
  620. rejected: rejected,
  621. progress: progress
  622. });
  623. };
  624. Handler.prototype.visit = function(receiver, fulfilled, rejected, progress) {
  625. this.chain(failIfRejected, receiver, fulfilled, rejected, progress);
  626. };
  627. Handler.prototype.fold = function(f, z, c, to) {
  628. this.when(new Fold(f, z, c, to));
  629. };
  630. /**
  631. * Handler that invokes fail() on any handler it becomes
  632. * @constructor
  633. */
  634. function FailIfRejected() {}
  635. inherit(Handler, FailIfRejected);
  636. FailIfRejected.prototype.become = function(h) {
  637. h.fail();
  638. };
  639. var failIfRejected = new FailIfRejected();
  640. /**
  641. * Handler that manages a queue of consumers waiting on a pending promise
  642. * @constructor
  643. */
  644. function Pending(receiver, inheritedContext) {
  645. Promise.createContext(this, inheritedContext);
  646. this.consumers = void 0;
  647. this.receiver = receiver;
  648. this.handler = void 0;
  649. this.resolved = false;
  650. }
  651. inherit(Handler, Pending);
  652. Pending.prototype._state = 0;
  653. Pending.prototype.resolve = function(x) {
  654. this.become(getHandler(x));
  655. };
  656. Pending.prototype.reject = function(x) {
  657. if(this.resolved) {
  658. return;
  659. }
  660. this.become(new Rejected(x));
  661. };
  662. Pending.prototype.join = function() {
  663. if (!this.resolved) {
  664. return this;
  665. }
  666. var h = this;
  667. while (h.handler !== void 0) {
  668. h = h.handler;
  669. if (h === this) {
  670. return this.handler = cycle();
  671. }
  672. }
  673. return h;
  674. };
  675. Pending.prototype.run = function() {
  676. var q = this.consumers;
  677. var handler = this.handler;
  678. this.handler = this.handler.join();
  679. this.consumers = void 0;
  680. for (var i = 0; i < q.length; ++i) {
  681. handler.when(q[i]);
  682. }
  683. };
  684. Pending.prototype.become = function(handler) {
  685. if(this.resolved) {
  686. return;
  687. }
  688. this.resolved = true;
  689. this.handler = handler;
  690. if(this.consumers !== void 0) {
  691. tasks.enqueue(this);
  692. }
  693. if(this.context !== void 0) {
  694. handler._report(this.context);
  695. }
  696. };
  697. Pending.prototype.when = function(continuation) {
  698. if(this.resolved) {
  699. tasks.enqueue(new ContinuationTask(continuation, this.handler));
  700. } else {
  701. if(this.consumers === void 0) {
  702. this.consumers = [continuation];
  703. } else {
  704. this.consumers.push(continuation);
  705. }
  706. }
  707. };
  708. /**
  709. * @deprecated
  710. */
  711. Pending.prototype.notify = function(x) {
  712. if(!this.resolved) {
  713. tasks.enqueue(new ProgressTask(x, this));
  714. }
  715. };
  716. Pending.prototype.fail = function(context) {
  717. var c = typeof context === 'undefined' ? this.context : context;
  718. this.resolved && this.handler.join().fail(c);
  719. };
  720. Pending.prototype._report = function(context) {
  721. this.resolved && this.handler.join()._report(context);
  722. };
  723. Pending.prototype._unreport = function() {
  724. this.resolved && this.handler.join()._unreport();
  725. };
  726. /**
  727. * Wrap another handler and force it into a future stack
  728. * @param {object} handler
  729. * @constructor
  730. */
  731. function Async(handler) {
  732. this.handler = handler;
  733. }
  734. inherit(Handler, Async);
  735. Async.prototype.when = function(continuation) {
  736. tasks.enqueue(new ContinuationTask(continuation, this));
  737. };
  738. Async.prototype._report = function(context) {
  739. this.join()._report(context);
  740. };
  741. Async.prototype._unreport = function() {
  742. this.join()._unreport();
  743. };
  744. /**
  745. * Handler that wraps an untrusted thenable and assimilates it in a future stack
  746. * @param {function} then
  747. * @param {{then: function}} thenable
  748. * @constructor
  749. */
  750. function Thenable(then, thenable) {
  751. Pending.call(this);
  752. tasks.enqueue(new AssimilateTask(then, thenable, this));
  753. }
  754. inherit(Pending, Thenable);
  755. /**
  756. * Handler for a fulfilled promise
  757. * @param {*} x fulfillment value
  758. * @constructor
  759. */
  760. function Fulfilled(x) {
  761. Promise.createContext(this);
  762. this.value = x;
  763. }
  764. inherit(Handler, Fulfilled);
  765. Fulfilled.prototype._state = 1;
  766. Fulfilled.prototype.fold = function(f, z, c, to) {
  767. runContinuation3(f, z, this, c, to);
  768. };
  769. Fulfilled.prototype.when = function(cont) {
  770. runContinuation1(cont.fulfilled, this, cont.receiver, cont.resolver);
  771. };
  772. var errorId = 0;
  773. /**
  774. * Handler for a rejected promise
  775. * @param {*} x rejection reason
  776. * @constructor
  777. */
  778. function Rejected(x) {
  779. Promise.createContext(this);
  780. this.id = ++errorId;
  781. this.value = x;
  782. this.handled = false;
  783. this.reported = false;
  784. this._report();
  785. }
  786. inherit(Handler, Rejected);
  787. Rejected.prototype._state = -1;
  788. Rejected.prototype.fold = function(f, z, c, to) {
  789. to.become(this);
  790. };
  791. Rejected.prototype.when = function(cont) {
  792. if(typeof cont.rejected === 'function') {
  793. this._unreport();
  794. }
  795. runContinuation1(cont.rejected, this, cont.receiver, cont.resolver);
  796. };
  797. Rejected.prototype._report = function(context) {
  798. tasks.afterQueue(new ReportTask(this, context));
  799. };
  800. Rejected.prototype._unreport = function() {
  801. if(this.handled) {
  802. return;
  803. }
  804. this.handled = true;
  805. tasks.afterQueue(new UnreportTask(this));
  806. };
  807. Rejected.prototype.fail = function(context) {
  808. this.reported = true;
  809. emitRejection('unhandledRejection', this);
  810. Promise.onFatalRejection(this, context === void 0 ? this.context : context);
  811. };
  812. function ReportTask(rejection, context) {
  813. this.rejection = rejection;
  814. this.context = context;
  815. }
  816. ReportTask.prototype.run = function() {
  817. if(!this.rejection.handled && !this.rejection.reported) {
  818. this.rejection.reported = true;
  819. emitRejection('unhandledRejection', this.rejection) ||
  820. Promise.onPotentiallyUnhandledRejection(this.rejection, this.context);
  821. }
  822. };
  823. function UnreportTask(rejection) {
  824. this.rejection = rejection;
  825. }
  826. UnreportTask.prototype.run = function() {
  827. if(this.rejection.reported) {
  828. emitRejection('rejectionHandled', this.rejection) ||
  829. Promise.onPotentiallyUnhandledRejectionHandled(this.rejection);
  830. }
  831. };
  832. // Unhandled rejection hooks
  833. // By default, everything is a noop
  834. Promise.createContext
  835. = Promise.enterContext
  836. = Promise.exitContext
  837. = Promise.onPotentiallyUnhandledRejection
  838. = Promise.onPotentiallyUnhandledRejectionHandled
  839. = Promise.onFatalRejection
  840. = noop;
  841. // Errors and singletons
  842. var foreverPendingHandler = new Handler();
  843. var foreverPendingPromise = new Promise(Handler, foreverPendingHandler);
  844. function cycle() {
  845. return new Rejected(new TypeError('Promise cycle'));
  846. }
  847. // Task runners
  848. /**
  849. * Run a single consumer
  850. * @constructor
  851. */
  852. function ContinuationTask(continuation, handler) {
  853. this.continuation = continuation;
  854. this.handler = handler;
  855. }
  856. ContinuationTask.prototype.run = function() {
  857. this.handler.join().when(this.continuation);
  858. };
  859. /**
  860. * Run a queue of progress handlers
  861. * @constructor
  862. */
  863. function ProgressTask(value, handler) {
  864. this.handler = handler;
  865. this.value = value;
  866. }
  867. ProgressTask.prototype.run = function() {
  868. var q = this.handler.consumers;
  869. if(q === void 0) {
  870. return;
  871. }
  872. for (var c, i = 0; i < q.length; ++i) {
  873. c = q[i];
  874. runNotify(c.progress, this.value, this.handler, c.receiver, c.resolver);
  875. }
  876. };
  877. /**
  878. * Assimilate a thenable, sending it's value to resolver
  879. * @param {function} then
  880. * @param {object|function} thenable
  881. * @param {object} resolver
  882. * @constructor
  883. */
  884. function AssimilateTask(then, thenable, resolver) {
  885. this._then = then;
  886. this.thenable = thenable;
  887. this.resolver = resolver;
  888. }
  889. AssimilateTask.prototype.run = function() {
  890. var h = this.resolver;
  891. tryAssimilate(this._then, this.thenable, _resolve, _reject, _notify);
  892. function _resolve(x) { h.resolve(x); }
  893. function _reject(x) { h.reject(x); }
  894. function _notify(x) { h.notify(x); }
  895. };
  896. function tryAssimilate(then, thenable, resolve, reject, notify) {
  897. try {
  898. then.call(thenable, resolve, reject, notify);
  899. } catch (e) {
  900. reject(e);
  901. }
  902. }
  903. /**
  904. * Fold a handler value with z
  905. * @constructor
  906. */
  907. function Fold(f, z, c, to) {
  908. this.f = f; this.z = z; this.c = c; this.to = to;
  909. this.resolver = failIfRejected;
  910. this.receiver = this;
  911. }
  912. Fold.prototype.fulfilled = function(x) {
  913. this.f.call(this.c, this.z, x, this.to);
  914. };
  915. Fold.prototype.rejected = function(x) {
  916. this.to.reject(x);
  917. };
  918. Fold.prototype.progress = function(x) {
  919. this.to.notify(x);
  920. };
  921. // Other helpers
  922. /**
  923. * @param {*} x
  924. * @returns {boolean} true iff x is a trusted Promise
  925. */
  926. function isPromise(x) {
  927. return x instanceof Promise;
  928. }
  929. /**
  930. * Test just enough to rule out primitives, in order to take faster
  931. * paths in some code
  932. * @param {*} x
  933. * @returns {boolean} false iff x is guaranteed *not* to be a thenable
  934. */
  935. function maybeThenable(x) {
  936. return (typeof x === 'object' || typeof x === 'function') && x !== null;
  937. }
  938. function runContinuation1(f, h, receiver, next) {
  939. if(typeof f !== 'function') {
  940. return next.become(h);
  941. }
  942. Promise.enterContext(h);
  943. tryCatchReject(f, h.value, receiver, next);
  944. Promise.exitContext();
  945. }
  946. function runContinuation3(f, x, h, receiver, next) {
  947. if(typeof f !== 'function') {
  948. return next.become(h);
  949. }
  950. Promise.enterContext(h);
  951. tryCatchReject3(f, x, h.value, receiver, next);
  952. Promise.exitContext();
  953. }
  954. /**
  955. * @deprecated
  956. */
  957. function runNotify(f, x, h, receiver, next) {
  958. if(typeof f !== 'function') {
  959. return next.notify(x);
  960. }
  961. Promise.enterContext(h);
  962. tryCatchReturn(f, x, receiver, next);
  963. Promise.exitContext();
  964. }
  965. function tryCatch2(f, a, b) {
  966. try {
  967. return f(a, b);
  968. } catch(e) {
  969. return reject(e);
  970. }
  971. }
  972. /**
  973. * Return f.call(thisArg, x), or if it throws return a rejected promise for
  974. * the thrown exception
  975. */
  976. function tryCatchReject(f, x, thisArg, next) {
  977. try {
  978. next.become(getHandler(f.call(thisArg, x)));
  979. } catch(e) {
  980. next.become(new Rejected(e));
  981. }
  982. }
  983. /**
  984. * Same as above, but includes the extra argument parameter.
  985. */
  986. function tryCatchReject3(f, x, y, thisArg, next) {
  987. try {
  988. f.call(thisArg, x, y, next);
  989. } catch(e) {
  990. next.become(new Rejected(e));
  991. }
  992. }
  993. /**
  994. * @deprecated
  995. * Return f.call(thisArg, x), or if it throws, *return* the exception
  996. */
  997. function tryCatchReturn(f, x, thisArg, next) {
  998. try {
  999. next.notify(f.call(thisArg, x));
  1000. } catch(e) {
  1001. next.notify(e);
  1002. }
  1003. }
  1004. function inherit(Parent, Child) {
  1005. Child.prototype = objectCreate(Parent.prototype);
  1006. Child.prototype.constructor = Child;
  1007. }
  1008. function snd(x, y) {
  1009. return y;
  1010. }
  1011. function noop() {}
  1012. function initEmitRejection() {
  1013. /*global process, self, CustomEvent*/
  1014. if(typeof process !== 'undefined' && process !== null
  1015. && typeof process.emit === 'function') {
  1016. // Returning falsy here means to call the default
  1017. // onPotentiallyUnhandledRejection API. This is safe even in
  1018. // browserify since process.emit always returns falsy in browserify:
  1019. // https://github.com/defunctzombie/node-process/blob/master/browser.js#L40-L46
  1020. return function(type, rejection) {
  1021. return type === 'unhandledRejection'
  1022. ? process.emit(type, rejection.value, rejection)
  1023. : process.emit(type, rejection);
  1024. };
  1025. } else if(typeof self !== 'undefined' && typeof CustomEvent === 'function') {
  1026. return (function(noop, self, CustomEvent) {
  1027. var hasCustomEvent = false;
  1028. try {
  1029. var ev = new CustomEvent('unhandledRejection');
  1030. hasCustomEvent = ev instanceof CustomEvent;
  1031. } catch (e) {}
  1032. return !hasCustomEvent ? noop : function(type, rejection) {
  1033. var ev = new CustomEvent(type, {
  1034. detail: {
  1035. reason: rejection.value,
  1036. key: rejection
  1037. },
  1038. bubbles: false,
  1039. cancelable: true
  1040. });
  1041. return !self.dispatchEvent(ev);
  1042. };
  1043. }(noop, self, CustomEvent));
  1044. }
  1045. return noop;
  1046. }
  1047. return Promise;
  1048. };
  1049. });
  1050. }(typeof define === 'function' && define.amd ? define : function(factory) { module.exports = factory(); }));
  1051. },{}]},{},[1])
  1052. (1)
  1053. });
  1054. ;
  1055. (function(__global) {
  1056. $__Object$getPrototypeOf = Object.getPrototypeOf || function(obj) {
  1057. return obj.__proto__;
  1058. };
  1059. var $__Object$defineProperty;
  1060. (function () {
  1061. try {
  1062. if (!!Object.defineProperty({}, 'a', {})) {
  1063. $__Object$defineProperty = Object.defineProperty;
  1064. }
  1065. } catch (e) {
  1066. $__Object$defineProperty = function (obj, prop, opt) {
  1067. try {
  1068. obj[prop] = opt.value || opt.get.call(obj);
  1069. }
  1070. catch(e) {}
  1071. }
  1072. }
  1073. }());
  1074. $__Object$create = Object.create || function(o, props) {
  1075. function F() {}
  1076. F.prototype = o;
  1077. if (typeof(props) === "object") {
  1078. for (prop in props) {
  1079. if (props.hasOwnProperty((prop))) {
  1080. F[prop] = props[prop];
  1081. }
  1082. }
  1083. }
  1084. return new F();
  1085. };
  1086. /*
  1087. *********************************************************************************************
  1088. Dynamic Module Loader Polyfill
  1089. - Implemented exactly to the former 2014-08-24 ES6 Specification Draft Rev 27, Section 15
  1090. http://wiki.ecmascript.org/doku.php?id=harmony:specification_drafts#august_24_2014_draft_rev_27
  1091. - Functions are commented with their spec numbers, with spec differences commented.
  1092. - Spec bugs are commented in this code with links.
  1093. - Abstract functions have been combined where possible, and their associated functions
  1094. commented.
  1095. - Realm implementation is entirely omitted.
  1096. *********************************************************************************************
  1097. */
  1098. // Some Helpers
  1099. // logs a linkset snapshot for debugging
  1100. /* function snapshot(loader) {
  1101. console.log('---Snapshot---');
  1102. for (var i = 0; i < loader.loads.length; i++) {
  1103. var load = loader.loads[i];
  1104. var linkSetLog = ' ' + load.name + ' (' + load.status + '): ';
  1105. for (var j = 0; j < load.linkSets.length; j++) {
  1106. linkSetLog += '{' + logloads(load.linkSets[j].loads) + '} ';
  1107. }
  1108. console.log(linkSetLog);
  1109. }
  1110. console.log('');
  1111. }
  1112. function logloads(loads) {
  1113. var log = '';
  1114. for (var k = 0; k < loads.length; k++)
  1115. log += loads[k].name + (k != loads.length - 1 ? ' ' : '');
  1116. return log;
  1117. } */
  1118. /* function checkInvariants() {
  1119. // see https://bugs.ecmascript.org/show_bug.cgi?id=2603#c1
  1120. var loads = System._loader.loads;
  1121. var linkSets = [];
  1122. for (var i = 0; i < loads.length; i++) {
  1123. var load = loads[i];
  1124. console.assert(load.status == 'loading' || load.status == 'loaded', 'Each load is loading or loaded');
  1125. for (var j = 0; j < load.linkSets.length; j++) {
  1126. var linkSet = load.linkSets[j];
  1127. for (var k = 0; k < linkSet.loads.length; k++)
  1128. console.assert(loads.indexOf(linkSet.loads[k]) != -1, 'linkSet loads are a subset of loader loads');
  1129. if (linkSets.indexOf(linkSet) == -1)
  1130. linkSets.push(linkSet);
  1131. }
  1132. }
  1133. for (var i = 0; i < loads.length; i++) {
  1134. var load = loads[i];
  1135. for (var j = 0; j < linkSets.length; j++) {
  1136. var linkSet = linkSets[j];
  1137. if (linkSet.loads.indexOf(load) != -1)
  1138. console.assert(load.linkSets.indexOf(linkSet) != -1, 'linkSet contains load -> load contains linkSet');
  1139. if (load.linkSets.indexOf(linkSet) != -1)
  1140. console.assert(linkSet.loads.indexOf(load) != -1, 'load contains linkSet -> linkSet contains load');
  1141. }
  1142. }
  1143. for (var i = 0; i < linkSets.length; i++) {
  1144. var linkSet = linkSets[i];
  1145. for (var j = 0; j < linkSet.loads.length; j++) {
  1146. var load = linkSet.loads[j];
  1147. for (var k = 0; k < load.dependencies.length; k++) {
  1148. var depName = load.dependencies[k].value;
  1149. var depLoad;
  1150. for (var l = 0; l < loads.length; l++) {
  1151. if (loads[l].name != depName)
  1152. continue;
  1153. depLoad = loads[l];
  1154. break;
  1155. }
  1156. // loading records are allowed not to have their dependencies yet
  1157. // if (load.status != 'loading')
  1158. // console.assert(depLoad, 'depLoad found');
  1159. // console.assert(linkSet.loads.indexOf(depLoad) != -1, 'linkset contains all dependencies');
  1160. }
  1161. }
  1162. }
  1163. } */
  1164. (function() {
  1165. var Promise = __global.Promise || require('when/es6-shim/Promise');
  1166. if (__global.console)
  1167. console.assert = console.assert || function() {};
  1168. // IE8 support
  1169. var indexOf = Array.prototype.indexOf || function(item) {
  1170. for (var i = 0, thisLen = this.length; i < thisLen; i++) {
  1171. if (this[i] === item) {
  1172. return i;
  1173. }
  1174. }
  1175. return -1;
  1176. };
  1177. var defineProperty = $__Object$defineProperty;
  1178. // 15.2.3 - Runtime Semantics: Loader State
  1179. // 15.2.3.11
  1180. function createLoaderLoad(object) {
  1181. return {
  1182. // modules is an object for ES5 implementation
  1183. modules: {},
  1184. loads: [],
  1185. loaderObj: object
  1186. };
  1187. }
  1188. // 15.2.3.2 Load Records and LoadRequest Objects
  1189. // 15.2.3.2.1
  1190. function createLoad(name) {
  1191. return {
  1192. status: 'loading',
  1193. name: name,
  1194. linkSets: [],
  1195. dependencies: [],
  1196. metadata: {}
  1197. };
  1198. }
  1199. // 15.2.3.2.2 createLoadRequestObject, absorbed into calling functions
  1200. // 15.2.4
  1201. // 15.2.4.1
  1202. function loadModule(loader, name, options) {
  1203. return new Promise(asyncStartLoadPartwayThrough({
  1204. step: options.address ? 'fetch' : 'locate',
  1205. loader: loader,
  1206. moduleName: name,
  1207. // allow metadata for import https://bugs.ecmascript.org/show_bug.cgi?id=3091
  1208. moduleMetadata: options && options.metadata || {},
  1209. moduleSource: options.source,
  1210. moduleAddress: options.address
  1211. }));
  1212. }
  1213. // 15.2.4.2
  1214. function requestLoad(loader, request, refererName, refererAddress) {
  1215. // 15.2.4.2.1 CallNormalize
  1216. return new Promise(function(resolve, reject) {
  1217. resolve(loader.loaderObj.normalize(request, refererName, refererAddress));
  1218. })
  1219. // 15.2.4.2.2 GetOrCreateLoad
  1220. .then(function(name) {
  1221. var load;
  1222. if (loader.modules[name]) {
  1223. load = createLoad(name);
  1224. load.status = 'linked';
  1225. // https://bugs.ecmascript.org/show_bug.cgi?id=2795
  1226. load.module = loader.modules[name];
  1227. return load;
  1228. }
  1229. for (var i = 0, l = loader.loads.length; i < l; i++) {
  1230. load = loader.loads[i];
  1231. if (load.name != name)
  1232. continue;
  1233. console.assert(load.status == 'loading' || load.status == 'loaded', 'loading or loaded');
  1234. return load;
  1235. }
  1236. load = createLoad(name);
  1237. loader.loads.push(load);
  1238. proceedToLocate(loader, load);
  1239. return load;
  1240. });
  1241. }
  1242. // 15.2.4.3
  1243. function proceedToLocate(loader, load) {
  1244. proceedToFetch(loader, load,
  1245. Promise.resolve()
  1246. // 15.2.4.3.1 CallLocate
  1247. .then(function() {
  1248. return loader.loaderObj.locate({ name: load.name, metadata: load.metadata });
  1249. })
  1250. );
  1251. }
  1252. // 15.2.4.4
  1253. function proceedToFetch(loader, load, p) {
  1254. proceedToTranslate(loader, load,
  1255. p
  1256. // 15.2.4.4.1 CallFetch
  1257. .then(function(address) {
  1258. // adjusted, see https://bugs.ecmascript.org/show_bug.cgi?id=2602
  1259. if (load.status != 'loading')
  1260. return;
  1261. load.address = address;
  1262. return loader.loaderObj.fetch({ name: load.name, metadata: load.metadata, address: address });
  1263. })
  1264. );
  1265. }
  1266. var anonCnt = 0;
  1267. // 15.2.4.5
  1268. function proceedToTranslate(loader, load, p) {
  1269. p
  1270. // 15.2.4.5.1 CallTranslate
  1271. .then(function(source) {
  1272. if (load.status != 'loading')
  1273. return;
  1274. return Promise.resolve(loader.loaderObj.translate({ name: load.name, metadata: load.metadata, address: load.address, source: source }))
  1275. // 15.2.4.5.2 CallInstantiate
  1276. .then(function(source) {
  1277. load.source = source;
  1278. return loader.loaderObj.instantiate({ name: load.name, metadata: load.metadata, address: load.address, source: source });
  1279. })
  1280. // 15.2.4.5.3 InstantiateSucceeded
  1281. .then(function(instantiateResult) {
  1282. if (instantiateResult === undefined) {
  1283. load.address = load.address || '<Anonymous Module ' + ++anonCnt + '>';
  1284. // instead of load.kind, use load.isDeclarative
  1285. load.isDeclarative = true;
  1286. return loader.loaderObj.transpile(load)
  1287. .then(function(transpiled) {
  1288. // Hijack System.register to set declare function
  1289. var curSystem = __global.System;
  1290. var curRegister = curSystem.register;
  1291. curSystem.register = function(name, deps, declare) {
  1292. if (typeof name != 'string') {
  1293. declare = deps;
  1294. deps = name;
  1295. }
  1296. // store the registered declaration as load.declare
  1297. // store the deps as load.deps
  1298. load.declare = declare;
  1299. load.depsList = deps;
  1300. }
  1301. __eval(transpiled, __global, load);
  1302. curSystem.register = curRegister;
  1303. });
  1304. }
  1305. else if (typeof instantiateResult == 'object') {
  1306. load.depsList = instantiateResult.deps || [];
  1307. load.execute = instantiateResult.execute;
  1308. load.isDeclarative = false;
  1309. }
  1310. else
  1311. throw TypeError('Invalid instantiate return value');
  1312. })
  1313. // 15.2.4.6 ProcessLoadDependencies
  1314. .then(function() {
  1315. load.dependencies = [];
  1316. var depsList = load.depsList;
  1317. var loadPromises = [];
  1318. for (var i = 0, l = depsList.length; i < l; i++) (function(request, index) {
  1319. loadPromises.push(
  1320. requestLoad(loader, request, load.name, load.address)
  1321. // 15.2.4.6.1 AddDependencyLoad (load is parentLoad)
  1322. .then(function(depLoad) {
  1323. // adjusted from spec to maintain dependency order
  1324. // this is due to the System.register internal implementation needs
  1325. load.dependencies[index] = {
  1326. key: request,
  1327. value: depLoad.name
  1328. };
  1329. if (depLoad.status != 'linked') {
  1330. var linkSets = load.linkSets.concat([]);
  1331. for (var i = 0, l = linkSets.length; i < l; i++)
  1332. addLoadToLinkSet(linkSets[i], depLoad);
  1333. }
  1334. // console.log('AddDependencyLoad ' + depLoad.name + ' for ' + load.name);
  1335. // snapshot(loader);
  1336. })
  1337. );
  1338. })(depsList[i], i);
  1339. return Promise.all(loadPromises);
  1340. })
  1341. // 15.2.4.6.2 LoadSucceeded
  1342. .then(function() {
  1343. // console.log('LoadSucceeded ' + load.name);
  1344. // snapshot(loader);
  1345. console.assert(load.status == 'loading', 'is loading');
  1346. load.status = 'loaded';
  1347. var linkSets = load.linkSets.concat([]);
  1348. for (var i = 0, l = linkSets.length; i < l; i++)
  1349. updateLinkSetOnLoad(linkSets[i], load);
  1350. });
  1351. })
  1352. // 15.2.4.5.4 LoadFailed
  1353. ['catch'](function(exc) {
  1354. load.status = 'failed';
  1355. load.exception = exc;
  1356. var linkSets = load.linkSets.concat([]);
  1357. for (var i = 0, l = linkSets.length; i < l; i++) {
  1358. linkSetFailed(linkSets[i], load, exc);
  1359. }
  1360. console.assert(load.linkSets.length == 0, 'linkSets not removed');
  1361. });
  1362. }
  1363. // 15.2.4.7 PromiseOfStartLoadPartwayThrough absorbed into calling functions
  1364. // 15.2.4.7.1
  1365. function asyncStartLoadPartwayThrough(stepState) {
  1366. return function(resolve, reject) {
  1367. var loader = stepState.loader;
  1368. var name = stepState.moduleName;
  1369. var step = stepState.step;
  1370. if (loader.modules[name])
  1371. throw new TypeError('"' + name + '" already exists in the module table');
  1372. // adjusted to pick up existing loads
  1373. var existingLoad;
  1374. for (var i = 0, l = loader.loads.length; i < l; i++) {
  1375. if (loader.loads[i].name == name) {
  1376. existingLoad = loader.loads[i];
  1377. if(step == 'translate' && !existingLoad.source) {
  1378. existingLoad.address = stepState.moduleAddress;
  1379. proceedToTranslate(loader, existingLoad, Promise.resolve(stepState.moduleSource));
  1380. }
  1381. return existingLoad.linkSets[0].done.then(function() {
  1382. resolve(existingLoad);
  1383. });
  1384. }
  1385. }
  1386. var load = createLoad(name);
  1387. load.metadata = stepState.moduleMetadata;
  1388. var linkSet = createLinkSet(loader, load);
  1389. loader.loads.push(load);
  1390. resolve(linkSet.done);
  1391. if (step == 'locate')
  1392. proceedToLocate(loader, load);
  1393. else if (step == 'fetch')
  1394. proceedToFetch(loader, load, Promise.resolve(stepState.moduleAddress));
  1395. else {
  1396. console.assert(step == 'translate', 'translate step');
  1397. load.address = stepState.moduleAddress;
  1398. proceedToTranslate(loader, load, Promise.resolve(stepState.moduleSource));
  1399. }
  1400. }
  1401. }
  1402. // Declarative linking functions run through alternative implementation:
  1403. // 15.2.5.1.1 CreateModuleLinkageRecord not implemented
  1404. // 15.2.5.1.2 LookupExport not implemented
  1405. // 15.2.5.1.3 LookupModuleDependency not implemented
  1406. // 15.2.5.2.1
  1407. function createLinkSet(loader, startingLoad) {
  1408. var linkSet = {
  1409. loader: loader,
  1410. loads: [],
  1411. startingLoad: startingLoad, // added see spec bug https://bugs.ecmascript.org/show_bug.cgi?id=2995
  1412. loadingCount: 0
  1413. };
  1414. linkSet.done = new Promise(function(resolve, reject) {
  1415. linkSet.resolve = resolve;
  1416. linkSet.reject = reject;
  1417. });
  1418. addLoadToLinkSet(linkSet, startingLoad);
  1419. return linkSet;
  1420. }
  1421. // 15.2.5.2.2
  1422. function addLoadToLinkSet(linkSet, load) {
  1423. console.assert(load.status == 'loading' || load.status == 'loaded', 'loading or loaded on link set');
  1424. for (var i = 0, l = linkSet.loads.length; i < l; i++)
  1425. if (linkSet.loads[i] == load)
  1426. return;
  1427. linkSet.loads.push(load);
  1428. load.linkSets.push(linkSet);
  1429. // adjustment, see https://bugs.ecmascript.org/show_bug.cgi?id=2603
  1430. if (load.status != 'loaded') {
  1431. linkSet.loadingCount++;
  1432. }
  1433. var loader = linkSet.loader;
  1434. for (var i = 0, l = load.dependencies.length; i < l; i++) {
  1435. var name = load.dependencies[i].value;
  1436. if (loader.modules[name])
  1437. continue;
  1438. for (var j = 0, d = loader.loads.length; j < d; j++) {
  1439. if (loader.loads[j].name != name)
  1440. continue;
  1441. addLoadToLinkSet(linkSet, loader.loads[j]);
  1442. break;
  1443. }
  1444. }
  1445. // console.log('add to linkset ' + load.name);
  1446. // snapshot(linkSet.loader);
  1447. }
  1448. // linking errors can be generic or load-specific
  1449. // this is necessary for debugging info
  1450. function doLink(linkSet) {
  1451. var error = false;
  1452. try {
  1453. link(linkSet, function(load, exc) {
  1454. linkSetFailed(linkSet, load, exc);
  1455. error = true;
  1456. });
  1457. }
  1458. catch(e) {
  1459. linkSetFailed(linkSet, null, e);
  1460. error = true;
  1461. }
  1462. return error;
  1463. }
  1464. // 15.2.5.2.3
  1465. function updateLinkSetOnLoad(linkSet, load) {
  1466. // console.log('update linkset on load ' + load.name);
  1467. // snapshot(linkSet.loader);
  1468. console.assert(load.status == 'loaded' || load.status == 'linked', 'loaded or linked');
  1469. linkSet.loadingCount--;
  1470. if (linkSet.loadingCount > 0)
  1471. return;
  1472. // adjusted for spec bug https://bugs.ecmascript.org/show_bug.cgi?id=2995
  1473. var startingLoad = linkSet.startingLoad;
  1474. // non-executing link variation for loader tracing
  1475. // on the server. Not in spec.
  1476. /***/
  1477. if (linkSet.loader.loaderObj.execute === false) {
  1478. var loads = [].concat(linkSet.loads);
  1479. for (var i = 0, l = loads.length; i < l; i++) {
  1480. var load = loads[i];
  1481. load.module = !load.isDeclarative ? {
  1482. module: _newModule({})
  1483. } : {
  1484. name: load.name,
  1485. module: _newModule({}),
  1486. evaluated: true
  1487. };
  1488. load.status = 'linked';
  1489. finishLoad(linkSet.loader, load);
  1490. }
  1491. return linkSet.resolve(startingLoad);
  1492. }
  1493. /***/
  1494. var abrupt = doLink(linkSet);
  1495. if (abrupt)
  1496. return;
  1497. console.assert(linkSet.loads.length == 0, 'loads cleared');
  1498. linkSet.resolve(startingLoad);
  1499. }
  1500. // 15.2.5.2.4
  1501. function linkSetFailed(linkSet, load, exc) {
  1502. var loader = linkSet.loader;
  1503. if (load && linkSet.loads[0].name != load.name)
  1504. exc = addToError(exc, 'Error loading "' + load.name + '" from "' + linkSet.loads[0].name + '" at ' + (linkSet.loads[0].address || '<unknown>') + '\n');
  1505. if (load)
  1506. exc = addToError(exc, 'Error loading "' + load.name + '" at ' + (load.address || '<unknown>') + '\n');
  1507. var loads = linkSet.loads.concat([]);
  1508. for (var i = 0, l = loads.length; i < l; i++) {
  1509. var load = loads[i];
  1510. // store all failed load records
  1511. loader.loaderObj.failed = loader.loaderObj.failed || [];
  1512. if (indexOf.call(loader.loaderObj.failed, load) == -1)
  1513. loader.loaderObj.failed.push(load);
  1514. var linkIndex = indexOf.call(load.linkSets, linkSet);
  1515. console.assert(linkIndex != -1, 'link not present');
  1516. load.linkSets.splice(linkIndex, 1);
  1517. if (load.linkSets.length == 0) {
  1518. var globalLoadsIndex = indexOf.call(linkSet.loader.loads, load);
  1519. if (globalLoadsIndex != -1)
  1520. linkSet.loader.loads.splice(globalLoadsIndex, 1);
  1521. }
  1522. }
  1523. linkSet.reject(exc);
  1524. }
  1525. // 15.2.5.2.5
  1526. function finishLoad(loader, load) {
  1527. // add to global trace if tracing
  1528. if (loader.loaderObj.trace) {
  1529. if (!loader.loaderObj.loads)
  1530. loader.loaderObj.loads = {};
  1531. var depMap = {};
  1532. load.dependencies.forEach(function(dep) {
  1533. depMap[dep.key] = dep.value;
  1534. });
  1535. loader.loaderObj.loads[load.name] = {
  1536. name: load.name,
  1537. deps: load.dependencies.map(function(dep){ return dep.key }),
  1538. depMap: depMap,
  1539. address: load.address,
  1540. metadata: load.metadata,
  1541. source: load.source,
  1542. kind: load.isDeclarative ? 'declarative' : 'dynamic'
  1543. };
  1544. }
  1545. // if not anonymous, add to the module table
  1546. if (load.name) {
  1547. console.assert(!loader.modules[load.name], 'load not in module table');
  1548. loader.modules[load.name] = load.module;
  1549. }
  1550. var loadIndex = indexOf.call(loader.loads, load);
  1551. if (loadIndex != -1)
  1552. loader.loads.splice(loadIndex, 1);
  1553. for (var i = 0, l = load.linkSets.length; i < l; i++) {
  1554. loadIndex = indexOf.call(load.linkSets[i].loads, load);
  1555. if (loadIndex != -1)
  1556. load.linkSets[i].loads.splice(loadIndex, 1);
  1557. }
  1558. load.linkSets.splice(0, load.linkSets.length);
  1559. }
  1560. // 15.2.5.3 Module Linking Groups
  1561. // 15.2.5.3.2 BuildLinkageGroups alternative implementation
  1562. // Adjustments (also see https://bugs.ecmascript.org/show_bug.cgi?id=2755)
  1563. // 1. groups is an already-interleaved array of group kinds
  1564. // 2. load.groupIndex is set when this function runs
  1565. // 3. load.groupIndex is the interleaved index ie 0 declarative, 1 dynamic, 2 declarative, ... (or starting with dynamic)
  1566. function buildLinkageGroups(load, loads, groups) {
  1567. groups[load.groupIndex] = groups[load.groupIndex] || [];
  1568. // if the load already has a group index and its in its group, its already been done
  1569. // this logic naturally handles cycles
  1570. if (indexOf.call(groups[load.groupIndex], load) != -1)
  1571. return;
  1572. // now add it to the group to indicate its been seen
  1573. groups[load.groupIndex].push(load);
  1574. for (var i = 0, l = loads.length; i < l; i++) {
  1575. var loadDep = loads[i];
  1576. // dependencies not found are already linked
  1577. for (var j = 0; j < load.dependencies.length; j++) {
  1578. if (loadDep.name == load.dependencies[j].value) {
  1579. // by definition all loads in linkset are loaded, not linked
  1580. console.assert(loadDep.status == 'loaded', 'Load in linkSet not loaded!');
  1581. // if it is a group transition, the index of the dependency has gone up
  1582. // otherwise it is the same as the parent
  1583. var loadDepGroupIndex = load.groupIndex + (loadDep.isDeclarative != load.isDeclarative);
  1584. // the group index of an entry is always the maximum
  1585. if (loadDep.groupIndex === undefined || loadDep.groupIndex < loadDepGroupIndex) {
  1586. // if already in a group, remove from the old group
  1587. if (loadDep.groupIndex !== undefined) {
  1588. groups[loadDep.groupIndex].splice(indexOf.call(groups[loadDep.groupIndex], loadDep), 1);
  1589. // if the old group is empty, then we have a mixed depndency cycle
  1590. if (groups[loadDep.groupIndex].length == 0)
  1591. throw new TypeError("Mixed dependency cycle detected");
  1592. }
  1593. loadDep.groupIndex = loadDepGroupIndex;
  1594. }
  1595. buildLinkageGroups(loadDep, loads, groups);
  1596. }
  1597. }
  1598. }
  1599. }
  1600. function doDynamicExecute(linkSet, load, linkError) {
  1601. try {
  1602. var module = load.execute();
  1603. }
  1604. catch(e) {
  1605. linkError(load, e);
  1606. return;
  1607. }
  1608. if (!module || !(module instanceof Module))
  1609. linkError(load, new TypeError('Execution must define a Module instance'));
  1610. else
  1611. return module;
  1612. }
  1613. // 15.2.5.4
  1614. function link(linkSet, linkError) {
  1615. var loader = linkSet.loader;
  1616. if (!linkSet.loads.length)
  1617. return;
  1618. // console.log('linking {' + logloads(linkSet.loads) + '}');
  1619. // snapshot(loader);
  1620. // 15.2.5.3.1 LinkageGroups alternative implementation
  1621. // build all the groups
  1622. // because the first load represents the top of the tree
  1623. // for a given linkset, we can work down from there
  1624. var groups = [];
  1625. var startingLoad = linkSet.loads[0];
  1626. startingLoad.groupIndex = 0;
  1627. buildLinkageGroups(startingLoad, linkSet.loads, groups);
  1628. // determine the kind of the bottom group
  1629. var curGroupDeclarative = startingLoad.isDeclarative == groups.length % 2;
  1630. // run through the groups from bottom to top
  1631. for (var i = groups.length - 1; i >= 0; i--) {
  1632. var group = groups[i];
  1633. for (var j = 0; j < group.length; j++) {
  1634. var load = group[j];
  1635. // 15.2.5.5 LinkDeclarativeModules adjusted
  1636. if (curGroupDeclarative) {
  1637. linkDeclarativeModule(load, linkSet.loads, loader);
  1638. }
  1639. // 15.2.5.6 LinkDynamicModules adjusted
  1640. else {
  1641. var module = doDynamicExecute(linkSet, load, linkError);
  1642. if (!module)
  1643. return;
  1644. load.module = {
  1645. name: load.name,
  1646. module: module
  1647. };
  1648. load.status = 'linked';
  1649. }
  1650. finishLoad(loader, load);
  1651. }
  1652. // alternative current kind for next loop
  1653. curGroupDeclarative = !curGroupDeclarative;
  1654. }
  1655. }
  1656. // custom module records for binding graph
  1657. // store linking module records in a separate table
  1658. function getOrCreateModuleRecord(name, loader) {
  1659. var moduleRecords = loader.moduleRecords;
  1660. return moduleRecords[name] || (moduleRecords[name] = {
  1661. name: name,
  1662. dependencies: [],
  1663. module: new Module(), // start from an empty module and extend
  1664. importers: []
  1665. });
  1666. }
  1667. // custom declarative linking function
  1668. function linkDeclarativeModule(load, loads, loader) {
  1669. if (load.module)
  1670. return;
  1671. var module = load.module = getOrCreateModuleRecord(load.name, loader);
  1672. var moduleObj = load.module.module;
  1673. var registryEntry = load.declare.call(__global, function(name, value) {
  1674. // NB This should be an Object.defineProperty, but that is very slow.
  1675. // By disaling this module write-protection we gain performance.
  1676. // It could be useful to allow an option to enable or disable this.
  1677. module.locked = true;
  1678. moduleObj[name] = value;
  1679. for (var i = 0, l = module.importers.length; i < l; i++) {
  1680. var importerModule = module.importers[i];
  1681. if (!importerModule.locked) {
  1682. var importerIndex = indexOf.call(importerModule.dependencies, module);
  1683. importerModule.setters[importerIndex](moduleObj);
  1684. }
  1685. }
  1686. module.locked = false;
  1687. return value;
  1688. });
  1689. // setup our setters and execution function
  1690. module.setters = registryEntry.setters;
  1691. module.execute = registryEntry.execute;
  1692. // now link all the module dependencies
  1693. // amending the depMap as we go
  1694. for (var i = 0, l = load.dependencies.length; i < l; i++) {
  1695. var depName = load.dependencies[i].value;
  1696. var depModule = loader.modules[depName];
  1697. // if dependency not already in the module registry
  1698. // then try and link it now
  1699. if (!depModule) {
  1700. // get the dependency load record
  1701. for (var j = 0; j < loads.length; j++) {
  1702. if (loads[j].name != depName)
  1703. continue;
  1704. // only link if already not already started linking (stops at circular / dynamic)
  1705. if (!loads[j].module) {
  1706. linkDeclarativeModule(loads[j], loads, loader);
  1707. depModule = loads[j].module;
  1708. }
  1709. // if circular, create the module record
  1710. else {
  1711. depModule = getOrCreateModuleRecord(depName, loader);
  1712. }
  1713. }
  1714. }
  1715. // only declarative modules have dynamic bindings
  1716. if (depModule.importers) {
  1717. module.dependencies.push(depModule);
  1718. depModule.importers.push(module);
  1719. }
  1720. else {
  1721. // track dynamic records as null module records as already linked
  1722. module.dependencies.push(null);
  1723. }
  1724. // run the setter for this dependency
  1725. if (module.setters[i])
  1726. module.setters[i](depModule.module);
  1727. }
  1728. load.status = 'linked';
  1729. }
  1730. // 15.2.5.5.1 LinkImports not implemented
  1731. // 15.2.5.7 ResolveExportEntries not implemented
  1732. // 15.2.5.8 ResolveExports not implemented
  1733. // 15.2.5.9 ResolveExport not implemented
  1734. // 15.2.5.10 ResolveImportEntries not implemented
  1735. // 15.2.6.1
  1736. function evaluateLoadedModule(loader, load) {
  1737. console.assert(load.status == 'linked', 'is linked ' + load.name);
  1738. doEnsureEvaluated(load.module, [], loader);
  1739. return load.module.module;
  1740. }
  1741. /*
  1742. * Module Object non-exotic for ES5:
  1743. *
  1744. * module.module bound module object
  1745. * module.execute execution function for module
  1746. * module.dependencies list of module objects for dependencies
  1747. * See getOrCreateModuleRecord for all properties
  1748. *
  1749. */
  1750. function doExecute(module) {
  1751. try {
  1752. module.execute.call(__global);
  1753. }
  1754. catch(e) {
  1755. return e;
  1756. }
  1757. }
  1758. // propogate execution errors
  1759. // see https://bugs.ecmascript.org/show_bug.cgi?id=2993
  1760. function doEnsureEvaluated(module, seen, loader) {
  1761. var err = ensureEvaluated(module, seen, loader);
  1762. if (err)
  1763. throw err;
  1764. }
  1765. // 15.2.6.2 EnsureEvaluated adjusted
  1766. function ensureEvaluated(module, seen, loader) {
  1767. if (module.evaluated || !module.dependencies)
  1768. return;
  1769. seen.push(module);
  1770. var deps = module.dependencies;
  1771. var err;
  1772. for (var i = 0, l = deps.length; i < l; i++) {
  1773. var dep = deps[i];
  1774. // dynamic dependencies are empty in module.dependencies
  1775. // as they are already linked
  1776. if (!dep)
  1777. continue;
  1778. if (indexOf.call(seen, dep) == -1) {
  1779. err = ensureEvaluated(dep, seen, loader);
  1780. // stop on error, see https://bugs.ecmascript.org/show_bug.cgi?id=2996
  1781. if (err) {
  1782. err = addToError(err, 'Error evaluating ' + dep.name + '\n');
  1783. return err;
  1784. }
  1785. }
  1786. }
  1787. if (module.failed)
  1788. return new Error('Module failed execution.');
  1789. if (module.evaluated)
  1790. return;
  1791. module.evaluated = true;
  1792. err = doExecute(module);
  1793. if (err) {
  1794. module.failed = true;
  1795. }
  1796. else if (Object.preventExtensions) {
  1797. // spec variation
  1798. // we don't create a new module here because it was created and ammended
  1799. // we just disable further extensions instead
  1800. Object.preventExtensions(module.module);
  1801. }
  1802. module.execute = undefined;
  1803. return err;
  1804. }
  1805. function addToError(err, msg) {
  1806. if (err instanceof Error)
  1807. err.message = msg + err.message;
  1808. else
  1809. err = msg + err;
  1810. return err;
  1811. }
  1812. // 26.3 Loader
  1813. // 26.3.1.1
  1814. function Loader(options) {
  1815. if (typeof options != 'object')
  1816. throw new TypeError('Options must be an object');
  1817. if (options.normalize)
  1818. this.normalize = options.normalize;
  1819. if (options.locate)
  1820. this.locate = options.locate;
  1821. if (options.fetch)
  1822. this.fetch = options.fetch;
  1823. if (options.translate)
  1824. this.translate = options.translate;
  1825. if (options.instantiate)
  1826. this.instantiate = options.instantiate;
  1827. this._loader = {
  1828. loaderObj: this,
  1829. loads: [],
  1830. modules: {},
  1831. importPromises: {},
  1832. moduleRecords: {}
  1833. };
  1834. // 26.3.3.6
  1835. defineProperty(this, 'global', {
  1836. get: function() {
  1837. return __global;
  1838. }
  1839. });
  1840. // 26.3.3.13 realm not implemented
  1841. }
  1842. function Module() {}
  1843. // importPromises adds ability to import a module twice without error - https://bugs.ecmascript.org/show_bug.cgi?id=2601
  1844. function createImportPromise(loader, name, promise) {
  1845. var importPromises = loader._loader.importPromises;
  1846. return importPromises[name] = promise.then(function(m) {
  1847. importPromises[name] = undefined;
  1848. return m;
  1849. }, function(e) {
  1850. importPromises[name] = undefined;
  1851. throw e;
  1852. });
  1853. }
  1854. Loader.prototype = {
  1855. // 26.3.3.1
  1856. constructor: Loader,
  1857. // 26.3.3.2
  1858. define: function(name, source, options) {
  1859. // check if already defined
  1860. if (this._loader.importPromises[name])
  1861. throw new TypeError('Module is already loading.');
  1862. return createImportPromise(this, name, new Promise(asyncStartLoadPartwayThrough({
  1863. step: 'translate',
  1864. loader: this._loader,
  1865. moduleName: name,
  1866. moduleMetadata: options && options.metadata || {},
  1867. moduleSource: source,
  1868. moduleAddress: options && options.address
  1869. })));
  1870. },
  1871. // 26.3.3.3
  1872. 'delete': function(name) {
  1873. var loader = this._loader;
  1874. delete loader.importPromises[name];
  1875. delete loader.moduleRecords[name];
  1876. return loader.modules[name] ? delete loader.modules[name] : false;
  1877. },
  1878. // 26.3.3.4 entries not implemented
  1879. // 26.3.3.5
  1880. get: function(key) {
  1881. if (!this._loader.modules[key])
  1882. return;
  1883. doEnsureEvaluated(this._loader.modules[key], [], this);
  1884. return this._loader.modules[key].module;
  1885. },
  1886. // 26.3.3.7
  1887. has: function(name) {
  1888. return !!this._loader.modules[name];
  1889. },
  1890. // 26.3.3.8
  1891. 'import': function(name, options) {
  1892. // run normalize first
  1893. var loaderObj = this;
  1894. // added, see https://bugs.ecmascript.org/show_bug.cgi?id=2659
  1895. return Promise.resolve(loaderObj.normalize(name, options && options.name, options && options.address))
  1896. .then(function(name) {
  1897. var loader = loaderObj._loader;
  1898. if (loader.modules[name]) {
  1899. doEnsureEvaluated(loader.modules[name], [], loader._loader);
  1900. return loader.modules[name].module;
  1901. }
  1902. return loader.importPromises[name] || createImportPromise(loaderObj, name,
  1903. loadModule(loader, name, options || {})
  1904. .then(function(load) {
  1905. delete loader.importPromises[name];
  1906. return evaluateLoadedModule(loader, load);
  1907. }));
  1908. });
  1909. },
  1910. // 26.3.3.9 keys not implemented
  1911. // 26.3.3.10
  1912. load: function(name, options) {
  1913. if (this._loader.modules[name]) {
  1914. doEnsureEvaluated(this._loader.modules[name], [], this._loader);
  1915. return Promise.resolve(this._loader.modules[name].module);
  1916. }
  1917. return this._loader.importPromises[name] || createImportPromise(this, name, loadModule(this._loader, name, {}));
  1918. },
  1919. // 26.3.3.11
  1920. module: function(source, options) {
  1921. var load = createLoad();
  1922. load.address = options && options.address;
  1923. var linkSet = createLinkSet(this._loader, load);
  1924. var sourcePromise = Promise.resolve(source);
  1925. var loader = this._loader;
  1926. var p = linkSet.done.then(function() {
  1927. return evaluateLoadedModule(loader, load);
  1928. });
  1929. proceedToTranslate(loader, load, sourcePromise);
  1930. return p;
  1931. },
  1932. // 26.3.3.12
  1933. newModule: function (obj) {
  1934. if (typeof obj != 'object')
  1935. throw new TypeError('Expected object');
  1936. // we do this to be able to tell if a module is a module privately in ES5
  1937. // by doing m instanceof Module
  1938. var m = new Module();
  1939. var pNames;
  1940. if (Object.getOwnPropertyNames && obj != null) {
  1941. pNames = Object.getOwnPropertyNames(obj);
  1942. }
  1943. else {
  1944. pNames = [];
  1945. for (var key in obj)
  1946. pNames.push(key);
  1947. }
  1948. for (var i = 0; i < pNames.length; i++) (function(key) {
  1949. defineProperty(m, key, {
  1950. configurable: false,
  1951. enumerable: true,
  1952. get: function () {
  1953. return obj[key];
  1954. }
  1955. });
  1956. })(pNames[i]);
  1957. if (Object.preventExtensions)
  1958. Object.preventExtensions(m);
  1959. return m;
  1960. },
  1961. // 26.3.3.14
  1962. set: function(name, module) {
  1963. if (!(module instanceof Module))
  1964. throw new TypeError('Loader.set(' + name + ', module) must be a module');
  1965. this._loader.modules[name] = {
  1966. module: module
  1967. };
  1968. },
  1969. // 26.3.3.15 values not implemented
  1970. // 26.3.3.16 @@iterator not implemented
  1971. // 26.3.3.17 @@toStringTag not implemented
  1972. // 26.3.3.18.1
  1973. normalize: function(name, referrerName, referrerAddress) {
  1974. return name;
  1975. },
  1976. // 26.3.3.18.2
  1977. locate: function(load) {
  1978. return load.name;
  1979. },
  1980. // 26.3.3.18.3
  1981. fetch: function(load) {
  1982. throw new TypeError('Fetch not implemented');
  1983. },
  1984. // 26.3.3.18.4
  1985. translate: function(load) {
  1986. return load.source;
  1987. },
  1988. // 26.3.3.18.5
  1989. instantiate: function(load) {
  1990. }
  1991. };
  1992. var _newModule = Loader.prototype.newModule;
  1993. if (typeof exports === 'object')
  1994. module.exports = Loader;
  1995. __global.Reflect = __global.Reflect || {};
  1996. __global.Reflect.Loader = __global.Reflect.Loader || Loader;
  1997. __global.Reflect.global = __global.Reflect.global || __global;
  1998. __global.LoaderPolyfill = Loader;
  1999. })();
  2000. /*
  2001. * Traceur and Babel transpile hook for Loader
  2002. */
  2003. (function(Loader) {
  2004. var g = __global;
  2005. function getTranspilerModule(loader, globalName) {
  2006. return loader.newModule({ 'default': g[globalName], __useDefault: true });
  2007. }
  2008. // use Traceur by default
  2009. Loader.prototype.transpiler = 'traceur';
  2010. Loader.prototype.transpile = function(load) {
  2011. var self = this;
  2012. // pick up Transpiler modules from existing globals on first run if set
  2013. if (!self.transpilerHasRun) {
  2014. if (g.traceur && !self.has('traceur'))
  2015. self.set('traceur', getTranspilerModule(self, 'traceur'));
  2016. if (g.babel && !self.has('babel'))
  2017. self.set('babel', getTranspilerModule(self, 'babel'));
  2018. self.transpilerHasRun = true;
  2019. }
  2020. return self['import'](self.transpiler).then(function(transpiler) {
  2021. if (transpiler.__useDefault)
  2022. transpiler = transpiler['default'];
  2023. return 'var __moduleAddress = "' + load.address + '";' + (transpiler.Compiler ? traceurTranspile : babelTranspile).call(self, load, transpiler);
  2024. });
  2025. };
  2026. Loader.prototype.instantiate = function(load) {
  2027. var self = this;
  2028. return Promise.resolve(self.normalize(self.transpiler))
  2029. .then(function(transpilerNormalized) {
  2030. // load transpiler as a global (avoiding System clobbering)
  2031. if (load.name === transpilerNormalized) {
  2032. return {
  2033. deps: [],
  2034. execute: function() {
  2035. var curSystem = g.System;
  2036. var curLoader = g.Reflect.Loader;
  2037. // ensure not detected as CommonJS
  2038. __eval('(function(require,exports,module){' + load.source + '})();', g, load);
  2039. g.System = curSystem;
  2040. g.Reflect.Loader = curLoader;
  2041. return getTranspilerModule(self, load.name);
  2042. }
  2043. };
  2044. }
  2045. });
  2046. };
  2047. function traceurTranspile(load, traceur) {
  2048. var options = this.traceurOptions || {};
  2049. options.modules = 'instantiate';
  2050. options.script = false;
  2051. options.sourceMaps = 'inline';
  2052. options.filename = load.address;
  2053. options.inputSourceMap = load.metadata.sourceMap;
  2054. options.moduleName = false;
  2055. var compiler = new traceur.Compiler(options);
  2056. var source = doTraceurCompile(load.source, compiler, options.filename);
  2057. // add "!eval" to end of Traceur sourceURL
  2058. // I believe this does something?
  2059. return source + '\n//# sourceURL=' + load.address + '!eval';
  2060. }
  2061. function doTraceurCompile(source, compiler, filename) {
  2062. try {
  2063. return compiler.compile(source, filename);
  2064. }
  2065. catch(e) {
  2066. // traceur throws an error array
  2067. throw e[0];
  2068. }
  2069. }
  2070. function babelTranspile(load, babel) {
  2071. var options = this.babelOptions || {};
  2072. options.modules = 'system';
  2073. options.sourceMap = 'inline';
  2074. options.filename = load.address;
  2075. options.code = true;
  2076. options.ast = false;
  2077. if (!options.blacklist)
  2078. options.blacklist = ['react'];
  2079. var source = babel.transform(load.source, options).code;
  2080. // add "!eval" to end of Babel sourceURL
  2081. // I believe this does something?
  2082. return source + '\n//# sourceURL=' + load.address + '!eval';
  2083. }
  2084. })(__global.LoaderPolyfill);
  2085. /*
  2086. *********************************************************************************************
  2087. System Loader Implementation
  2088. - Implemented to https://github.com/jorendorff/js-loaders/blob/master/browser-loader.js
  2089. - <script type="module"> supported
  2090. *********************************************************************************************
  2091. */
  2092. (function() {
  2093. var isBrowser = typeof window != 'undefined' && typeof document != 'undefined';
  2094. var isWindows = typeof process != 'undefined' && !!process.platform.match(/^win/);
  2095. var Promise = __global.Promise || require('when/es6-shim/Promise');
  2096. // Helpers
  2097. // Absolute URL parsing, from https://gist.github.com/Yaffle/1088850
  2098. function parseURI(url) {
  2099. var m = String(url).replace(/^\s+|\s+$/g, '').match(/^([^:\/?#]+:)?(\/\/(?:[^:@\/?#]*(?::[^:@\/?#]*)?@)?(([^:\/?#]*)(?::(\d*))?))?([^?#]*)(\?[^#]*)?(#[\s\S]*)?/);
  2100. // authority = '//' + user + ':' + pass '@' + hostname + ':' port
  2101. return (m ? {
  2102. href : m[0] || '',
  2103. protocol : m[1] || '',
  2104. authority: m[2] || '',
  2105. host : m[3] || '',
  2106. hostname : m[4] || '',
  2107. port : m[5] || '',
  2108. pathname : m[6] || '',
  2109. search : m[7] || '',
  2110. hash : m[8] || ''
  2111. } : null);
  2112. }
  2113. function removeDotSegments(input) {
  2114. var output = [];
  2115. input.replace(/^(\.\.?(\/|$))+/, '')
  2116. .replace(/\/(\.(\/|$))+/g, '/')
  2117. .replace(/\/\.\.$/, '/../')
  2118. .replace(/\/?[^\/]*/g, function (p) {
  2119. if (p === '/..')
  2120. output.pop();
  2121. else
  2122. output.push(p);
  2123. });
  2124. return output.join('').replace(/^\//, input.charAt(0) === '/' ? '/' : '');
  2125. }
  2126. function toAbsoluteURL(base, href) {
  2127. if (isWindows)
  2128. href = href.replace(/\\/g, '/');
  2129. href = parseURI(href || '');
  2130. base = parseURI(base || '');
  2131. return !href || !base ? null : (href.protocol || base.protocol) +
  2132. (href.protocol || href.authority ? href.authority : base.authority) +
  2133. removeDotSegments(href.protocol || href.authority || href.pathname.charAt(0) === '/' ? href.pathname : (href.pathname ? ((base.authority && !base.pathname ? '/' : '') + base.pathname.slice(0, base.pathname.lastIndexOf('/') + 1) + href.pathname) : base.pathname)) +
  2134. (href.protocol || href.authority || href.pathname ? href.search : (href.search || base.search)) +
  2135. href.hash;
  2136. }
  2137. var fetchTextFromURL;
  2138. if (typeof XMLHttpRequest != 'undefined') {
  2139. fetchTextFromURL = function(url, fulfill, reject) {
  2140. var xhr = new XMLHttpRequest();
  2141. var sameDomain = true;
  2142. var doTimeout = false;
  2143. if (!('withCredentials' in xhr)) {
  2144. // check if same domain
  2145. var domainCheck = /^(\w+:)?\/\/([^\/]+)/.exec(url);
  2146. if (domainCheck) {
  2147. sameDomain = domainCheck[2] === window.location.host;
  2148. if (domainCheck[1])
  2149. sameDomain &= domainCheck[1] === window.location.protocol;
  2150. }
  2151. }
  2152. if (!sameDomain && typeof XDomainRequest != 'undefined') {
  2153. xhr = new XDomainRequest();
  2154. xhr.onload = load;
  2155. xhr.onerror = error;
  2156. xhr.ontimeout = error;
  2157. xhr.onprogress = function() {};
  2158. xhr.timeout = 0;
  2159. doTimeout = true;
  2160. }
  2161. function load() {
  2162. fulfill(xhr.responseText);
  2163. }
  2164. function error() {
  2165. reject(xhr.statusText + ': ' + url || 'XHR error');
  2166. }
  2167. xhr.onreadystatechange = function () {
  2168. if (xhr.readyState === 4) {
  2169. if (xhr.status === 200 || (xhr.status == 0 && xhr.responseText)) {
  2170. load();
  2171. } else {
  2172. error();
  2173. }
  2174. }
  2175. };
  2176. xhr.open("GET", url, true);
  2177. if (doTimeout)
  2178. setTimeout(function() {
  2179. xhr.send();
  2180. }, 0);
  2181. xhr.send(null);
  2182. }
  2183. }
  2184. else if (typeof require != 'undefined') {
  2185. var fs;
  2186. fetchTextFromURL = function(url, fulfill, reject) {
  2187. if (url.substr(0, 5) != 'file:')
  2188. throw 'Only file URLs of the form file: allowed running in Node.';
  2189. fs = fs || require('fs');
  2190. url = url.substr(5);
  2191. if (isWindows)
  2192. url = url.replace(/\//g, '\\');
  2193. return fs.readFile(url, function(err, data) {
  2194. if (err)
  2195. return reject(err);
  2196. else
  2197. fulfill(data + '');
  2198. });
  2199. }
  2200. }
  2201. else {
  2202. throw new TypeError('No environment fetch API available.');
  2203. }
  2204. var SystemLoader = function($__super) {
  2205. function SystemLoader(options) {
  2206. $__super.call(this, options || {});
  2207. // Set default baseURL and paths
  2208. if (typeof location != 'undefined' && location.href) {
  2209. var href = __global.location.href.split('#')[0].split('?')[0];
  2210. this.baseURL = href.substring(0, href.lastIndexOf('/') + 1);
  2211. }
  2212. else if (typeof process != 'undefined' && process.cwd) {
  2213. this.baseURL = 'file:' + process.cwd() + '/';
  2214. if (isWindows)
  2215. this.baseURL = this.baseURL.replace(/\\/g, '/');
  2216. }
  2217. else {
  2218. throw new TypeError('No environment baseURL');
  2219. }
  2220. this.paths = { '*': '*.js' };
  2221. }
  2222. SystemLoader.__proto__ = ($__super !== null ? $__super : Function.prototype);
  2223. SystemLoader.prototype = $__Object$create(($__super !== null ? $__super.prototype : null));
  2224. $__Object$defineProperty(SystemLoader.prototype, "constructor", {
  2225. value: SystemLoader
  2226. });
  2227. $__Object$defineProperty(SystemLoader.prototype, "global", {
  2228. get: function() {
  2229. return __global;
  2230. },
  2231. enumerable: false
  2232. });
  2233. $__Object$defineProperty(SystemLoader.prototype, "strict", {
  2234. get: function() { return true; },
  2235. enumerable: false
  2236. });
  2237. $__Object$defineProperty(SystemLoader.prototype, "normalize", {
  2238. value: function(name, parentName, parentAddress) {
  2239. if (typeof name != 'string')
  2240. throw new TypeError('Module name must be a string');
  2241. var segments = name.split('/');
  2242. if (segments.length == 0)
  2243. throw new TypeError('No module name provided');
  2244. // current segment
  2245. var i = 0;
  2246. // is the module name relative
  2247. var rel = false;
  2248. // number of backtracking segments
  2249. var dotdots = 0;
  2250. if (segments[0] == '.') {
  2251. i++;
  2252. if (i == segments.length)
  2253. throw new TypeError('Illegal module name "' + name + '"');
  2254. rel = true;
  2255. }
  2256. else {
  2257. while (segments[i] == '..') {
  2258. i++;
  2259. if (i == segments.length)
  2260. throw new TypeError('Illegal module name "' + name + '"');
  2261. }
  2262. if (i)
  2263. rel = true;
  2264. dotdots = i;
  2265. }
  2266. for (var j = i; j < segments.length; j++) {
  2267. var segment = segments[j];
  2268. if (segment == '' || segment == '.' || segment == '..')
  2269. throw new TypeError('Illegal module name "' + name + '"');
  2270. }
  2271. if (!rel)
  2272. return name;
  2273. // build the full module name
  2274. var normalizedParts = [];
  2275. var parentParts = (parentName || '').split('/');
  2276. var normalizedLen = parentParts.length - 1 - dotdots;
  2277. normalizedParts = normalizedParts.concat(parentParts.splice(0, parentParts.length - 1 - dotdots));
  2278. normalizedParts = normalizedParts.concat(segments.splice(i, segments.length - i));
  2279. return normalizedParts.join('/');
  2280. },
  2281. enumerable: false,
  2282. writable: true
  2283. });
  2284. $__Object$defineProperty(SystemLoader.prototype, "locate", {
  2285. value: function(load) {
  2286. var name = load.name;
  2287. // NB no specification provided for System.paths, used ideas discussed in https://github.com/jorendorff/js-loaders/issues/25
  2288. // most specific (longest) match wins
  2289. var pathMatch = '', wildcard;
  2290. // check to see if we have a paths entry
  2291. for (var p in this.paths) {
  2292. var pathParts = p.split('*');
  2293. if (pathParts.length > 2)
  2294. throw new TypeError('Only one wildcard in a path is permitted');
  2295. // exact path match
  2296. if (pathParts.length == 1) {
  2297. if (name == p && p.length > pathMatch.length) {
  2298. pathMatch = p;
  2299. break;
  2300. }
  2301. }
  2302. // wildcard path match
  2303. else {
  2304. if (name.substr(0, pathParts[0].length) == pathParts[0] && name.substr(name.length - pathParts[1].length) == pathParts[1]) {
  2305. pathMatch = p;
  2306. wildcard = name.substr(pathParts[0].length, name.length - pathParts[1].length - pathParts[0].length);
  2307. }
  2308. }
  2309. }
  2310. var outPath = this.paths[pathMatch];
  2311. if (wildcard)
  2312. outPath = outPath.replace('*', wildcard);
  2313. // percent encode just '#' in module names
  2314. // according to https://github.com/jorendorff/js-loaders/blob/master/browser-loader.js#L238
  2315. // we should encode everything, but it breaks for servers that don't expect it
  2316. // like in (https://github.com/systemjs/systemjs/issues/168)
  2317. if (isBrowser)
  2318. outPath = outPath.replace(/#/g, '%23');
  2319. return toAbsoluteURL(this.baseURL, outPath);
  2320. },
  2321. enumerable: false,
  2322. writable: true
  2323. });
  2324. $__Object$defineProperty(SystemLoader.prototype, "fetch", {
  2325. value: function(load) {
  2326. var self = this;
  2327. return new Promise(function(resolve, reject) {
  2328. fetchTextFromURL(toAbsoluteURL(self.baseURL, load.address), function(source) {
  2329. resolve(source);
  2330. }, reject);
  2331. });
  2332. },
  2333. enumerable: false,
  2334. writable: true
  2335. });
  2336. return SystemLoader;
  2337. }(__global.LoaderPolyfill);
  2338. var System = new SystemLoader();
  2339. // note we have to export before runing "init" below
  2340. if (typeof exports === 'object')
  2341. module.exports = System;
  2342. __global.System = System;
  2343. // <script type="module"> support
  2344. // allow a data-init function callback once loaded
  2345. if (isBrowser && document.getElementsByTagName) {
  2346. var curScript = document.getElementsByTagName('script');
  2347. curScript = curScript[curScript.length - 1];
  2348. function completed() {
  2349. document.removeEventListener( "DOMContentLoaded", completed, false );
  2350. window.removeEventListener( "load", completed, false );
  2351. ready();
  2352. }
  2353. function ready() {
  2354. var scripts = document.getElementsByTagName('script');
  2355. for (var i = 0; i < scripts.length; i++) {
  2356. var script = scripts[i];
  2357. if (script.type == 'module') {
  2358. var source = script.innerHTML.substr(1);
  2359. // It is important to reference the global System, rather than the one
  2360. // in our closure. We want to ensure that downstream users/libraries
  2361. // can override System w/ custom behavior.
  2362. __global.System.module(source)['catch'](function(err) { setTimeout(function() { throw err; }); });
  2363. }
  2364. }
  2365. }
  2366. // DOM ready, taken from https://github.com/jquery/jquery/blob/master/src/core/ready.js#L63
  2367. if (document.readyState === 'complete') {
  2368. setTimeout(ready);
  2369. }
  2370. else if (document.addEventListener) {
  2371. document.addEventListener('DOMContentLoaded', completed, false);
  2372. window.addEventListener('load', completed, false);
  2373. }
  2374. // run the data-init function on the script tag
  2375. if (curScript.getAttribute('data-init'))
  2376. window[curScript.getAttribute('data-init')]();
  2377. }
  2378. })();
  2379. // Define our eval outside of the scope of any other reference defined in this
  2380. // file to avoid adding those references to the evaluation scope.
  2381. function __eval(__source, __global, __load) {
  2382. try {
  2383. eval('(function() { var __moduleName = "' + (__load.name || '').replace('"', '\"') + '"; ' + __source + ' \n }).call(__global);');
  2384. }
  2385. catch(e) {
  2386. if (e.name == 'SyntaxError' || e.name == 'TypeError')
  2387. e.message = 'Evaluating ' + (__load.name || load.address) + '\n\t' + e.message;
  2388. throw e;
  2389. }
  2390. }
  2391. })(typeof window != 'undefined' ? window : (typeof global != 'undefined' ? global : self));