Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
Browse files

splitting source code into different polyfills for better reusability

  • Loading branch information...
commit 9734603326c05d2a7db7e09af8f34c8fb5110fe5 1 parent 932e4aa
@caridy caridy authored
View
1  .gitignore
@@ -1 +1,2 @@
node_modules
+tmp
View
38 Gruntfile.js
@@ -9,12 +9,35 @@ module.exports = function (grunt) {
' * Copyright (c) <%= grunt.template.today("yyyy") %> <%= pkg.author.name %>;' +
' Licensed <%= _.pluck(pkg.licenses, "type").join(", ") %>\n */\n'
},
+ jshint: {
+ options: {
+ jshintrc: '.jshintrc'
+ },
+ dist: [
+ 'lib/index.js',
+ 'lib/promise.js',
+ 'lib/module.js',
+ 'lib/loader.js',
+ 'lib/system.js'
+ ]
+ },
+ concat: {
+ dist: {
+ src: [
+ 'lib/promise.js',
+ 'lib/module.js',
+ 'lib/loader.js',
+ 'lib/system.js'
+ ],
+ dest: 'tmp/<%= pkg.name %>.js'
+ }
+ },
uglify: {
options: {
banner: '<%= meta.banner %>'
},
dist: {
- src: 'lib/<%= pkg.name %>.js',
+ src: 'tmp/<%= pkg.name %>.js',
dest: 'dist/<%= pkg.name %>.js'
},
traceur: {
@@ -24,20 +47,13 @@ module.exports = function (grunt) {
src: 'lib/traceur.js',
dest: 'dist/traceur.js'
}
- },
- jshint: {
- options: {
- jshintrc: '.jshintrc'
- },
- dist: [
- 'lib/es6-module-loader.js',
- 'test/es6-module-loader_test.js'
- ]
}
});
+ grunt.loadNpmTasks('grunt-contrib-concat');
grunt.loadNpmTasks('grunt-contrib-jshint');
grunt.loadNpmTasks('grunt-contrib-uglify');
- grunt.registerTask('default', [/*'jshint', */'uglify']);
+ grunt.registerTask('lint', ['jshint']);
+ grunt.registerTask('default', [/*'jshint', */'concat', 'uglify']);
};
View
2  dist/es6-module-loader.js
@@ -4,4 +4,4 @@
* Implemented to the 2013-12-02 ES6 module specification draft
* Copyright (c) 2014 Guy Bedford, Luke Hoban, Addy Osmani; Licensed MIT
*/
-!function(){function a(a,b,c,d){try{Function("global",'var __moduleName = "'+(d||"").replace('"','"')+'"; with(global) { '+a+" \n }"+(c&&!a.match(/\/\/[@#] ?(sourceURL|sourceMappingURL)=([^\n]+)/)?"\n//# sourceURL="+c:"")).call(b,b)}catch(e){throw"SyntaxError"==e.name&&(e.message="Evaluating "+c+"\n "+e.message),e}}!function(){function b(a,b){b||console.log("Assertion Failed - "+a)}function c(a,b,c){Object.defineProperty?Object.defineProperty(a,b,c):a[b]=c.value||c.get.call(a)}function d(a){Object.preventExtensions&&Object.preventExtensions(a)}function e(a){return{status:"loading",name:a,metadata:{},linkSets:[]}}function f(a,c,d,f){return new E(function(b){b(a.normalize(c,d,f))}).then(function(c){var d;if(a._modules[c])return d=e(c),d.status="linked",d;for(var f=0,h=a._loads.length;h>f;f++)if(d=a._loads[f],d.name==c)return b("loading or loaded","loading"==d.status||"loaded"==d.status),d;return d=e(c),a._loads.push(d),g(a,d),d})}function g(a,b){h(a,b,E.resolve().then(function(){return a.locate({name:b.name,metadata:b.metadata})}))}function h(a,b,c){i(a,b,c.then(function(c){return"failed"==b.status?void 0:(b.address=c,a.fetch({name:b.name,metadata:b.metadata,address:c}))}))}function i(a,c,d){d.then(function(b){return"failed"==c.status?void 0:a.translate({name:c.name,metadata:c.metadata,address:c.address,source:b})}).then(function(b){return"failed"==c.status?void 0:(c.source=b,a.instantiate({name:c.name,metadata:c.metadata,address:c.address,source:b}))}).then(function(d){if("failed"==c.status)return void 0;var e;if(void 0===d)throw"Declarative parsing is not implemented by the polyfill.";if("object"!=typeof d)throw TypeError("Invalid instantiate return value");e=d.deps||[],c.execute=d.execute,c.kind="dynamic",c.dependencies={},c.depsList=e;for(var g=[],h=0,i=e.length;i>h;h++)(function(d){var e=f(a,d,c.name,c.address);e.then(function(a){if(b("not already a dependency",!c.dependencies[d]),c.dependencies[d]=a.name,"linked"!=a.status)for(var e=c.linkSets.concat([]),f=0,g=e.length;g>f;f++)k(e[f],a)}),g.push(e)})(e[h]);return E.all(g)}).then(function(){b("is loading","loading"==c.status),c.status="loaded";for(var a=c.linkSets.concat([]),d=0,e=a.length;e>d;d++)l(a[d],c)},function(a){b("is loading on fail","loading"==c.status),c.status="failed",c.exception=a;for(var d=0,e=c.linkSets.length;e>d;d++)m(c.linkSets[d],a);b("fail linkSets removed",0==c.linkSets.length)})}function j(a,b){var c,d,e=new E(function(a,b){c=a,d=b}),f={loader:a,loads:[],done:e,resolve:c,reject:d,loadingCount:0};return k(f,b),f}function k(a,c){b("loading or loaded on link set","loading"==c.status||"loaded"==c.status);for(var d=0,e=a.loads.length;e>d;d++)if(a.loads[d]==c)return;a.loads.push(c),c.linkSets.push(a),"loaded"!=c.status&&a.loadingCount++;var f=a.loader;for(var g in c.dependencies){var h=c.dependencies[g];if(!f._modules[h])for(var d=0,e=f._loads.length;e>d;d++)if(f._loads[d].name==h){k(a,f._loads[d]);break}}}function l(a,c){if(b("loaded or linked","loaded"==c.status||"linked"==c.status),a.loadingCount--,!(a.loadingCount>0)){var d=a.loads[0];try{s(a.loads,a.loader)}catch(e){return m(a,e)}b("loads cleared",0==a.loads.length),a.resolve(d)}}function m(a,c){for(var d=a.loads.concat([]),e=0,f=d.length;f>e;e++){var g=d[e],h=F.call(g.linkSets,a);if(b("link not present",-1!=h),g.linkSets.splice(h,1),0==g.linkSets.length){var i=F.call(a.loader._loads,g);-1!=i&&a.loader._loads.splice(i,1)}}a.reject(c)}function n(a,c){c.name&&(b("load not in module table",!a._modules[c.name]),a._modules[c.name]=c.module);var d=F.call(a._loads,c);-1!=d&&a._loads.splice(d,1);for(var e=0,f=c.linkSets.length;f>e;e++)d=F.call(c.linkSets[e].loads,c),c.linkSets[e].loads.splice(d,1);c.linkSets=[]}function o(a,b,c){return new E(p(a,b,c&&c.address?"fetch":"locate",void 0,c&&c.address,void 0)).then(function(a){return a})}function p(a,c,d,f,k,l){return function(m,n){if(a._modules[c])throw new TypeError('Module "'+c+'" already exists in the module table');for(var o=0,p=a._loads.length;p>o;o++)if(a._loads[o].name==c)throw new TypeError('Module "'+c+'" is already loading');var q=e(c);f&&(q.metadata=f);var r=j(a,q);a._loads.push(q),r.done.then(m,n),"locate"==d?g(a,q):"fetch"==d?h(a,q,E.resolve(k)):(b("translate step","translate"==d),q.address=k,i(a,q,E.resolve(l)))}}function q(a,c){return b("is linked "+c.name,"linked"==c.status),b("is a module",c.module instanceof r),c.module}function r(a){if("object"!=typeof a)throw new TypeError("Expected object");if(!(this instanceof r))return new r(a);var b=this;for(var e in a)!function(a,d){c(b,a,{configurable:!1,enumerable:!0,get:function(){return d}})}(e,a[e]);d(this)}function s(a,b){for(var c=0;a.length;){c++;a:for(var d=0;d<a.length;d++){var e=a[d],f=[];for(var g in e.dependencies){var h=e.dependencies[g];if(!b._modules[h])continue a;var i=e.depsList.indexOf(g);f[i]=h}var j=e.execute.apply(null,f);if(!(j instanceof r))throw new TypeError("Execution must define a Module instance");e.module=j,e.status="linked",n(b,e)}if(1e3===c)return console.log("Circular Dependency Detected"),void 0}}function t(a){if("object"!=typeof a)throw new TypeError("Options must be an object");a.normalize&&(this.normalize=a.normalize),a.locate&&(this.locate=a.locate),a.fetch&&(this.fetch=a.fetch),a.translate&&(this.translate=a.translate),a.instantiate&&(this.instantiate=a.instantiate),c(this,"global",{get:function(){throw new TypeError("global accessor not provided by polyfill")}}),c(this,"realm",{get:function(){throw new TypeError("Realms not implemented in polyfill")}}),this._modules={},this._loads=[]}function u(a){var b=String(a).replace(/^\s+|\s+$/g,"").match(/^([^:\/?#]+:)?(\/\/(?:[^:@]*(?::[^:@]*)?@)?(([^:\/?#]*)(?::(\d*))?))?([^?#]*)(\?[^#]*)?(#[\s\S]*)?/);return b?{href:b[0]||"",protocol:b[1]||"",authority:b[2]||"",host:b[3]||"",hostname:b[4]||"",port:b[5]||"",pathname:b[6]||"",search:b[7]||"",hash:b[8]||""}:null}function v(a,b){function c(a){var b=[];return a.replace(/^(\.\.?(\/|$))+/,"").replace(/\/(\.(\/|$))+/g,"/").replace(/\/\.\.$/,"/../").replace(/\/?[^\/]*/g,function(a){"/.."===a?b.pop():b.push(a)}),b.join("").replace(/^\//,"/"===a.charAt(0)?"/":"")}return b=u(b||""),a=u(a||""),b&&a?(b.protocol||a.protocol)+(b.protocol||b.authority?b.authority:a.authority)+c(b.protocol||b.authority||"/"===b.pathname.charAt(0)?b.pathname:b.pathname?(a.authority&&!a.pathname?"/":"")+a.pathname.slice(0,a.pathname.lastIndexOf("/")+1)+b.pathname:a.pathname)+(b.protocol||b.authority||b.pathname?b.search:b.search||a.search)+b.hash:null}function w(){return M?E.resolve(M||(M=B.traceur)):N?N:N=(A?C.System.import:function(){return E.resolve(require("traceur"))}).call(C.System,"traceur",{address:Q}).then(function(a){return N=null,A&&(a=B.traceur),M=a,M.codegeneration.ModuleLoaderTransformer=x(M.codegeneration.ParseTreeFactory,M.codegeneration.ParseTreeTransformer),M})}function x(a,b){var c=a.createAssignmentExpression,d=a.createVariableDeclaration,e=(a.createCallExpression,a.createVariableDeclarationList),f=a.createStringLiteral,g=a.createIdentifierExpression,h=a.createMemberLookupExpression,i=a.createCommaExpression,j=a.createVariableStatement,k=a.createAssignmentStatement,l=a.createExpressionStatement,m=function(a,b){this.depMap=a,this.exportGlobal=b};return m.prototype=Object.create(b.prototype),m.prototype.createModuleVariableDeclaration=function(a,b,c,f){var g=this,h=b.map(function(b,e){return d(b,g.createImportExpression(a,c[e]))}),i=e("var",h);return i.location=f,j(i)},m.prototype.createImportExpression=function(a,b){var c=g(this.depMap[a]);return b?h(c,f(b)):c},m.prototype.createExportExpression=function(a){return h(g(this.exportGlobal),f(a))},m.prototype.transformImportDeclaration=function(a){var b=a.moduleSpecifier.token.processedValue,c=[],d=[];if(a.importClause){if(a.importClause&&a.importClause.binding)c.push(a.importClause.binding.identifierToken),d.push("default");else if(a.importClause)for(var e=a.importClause.specifiers,f=0;f<e.length;f++){var g=e[f];c.push(g.rhs?g.rhs.value:g.lhs.value),d.push(g.lhs.value)}return this.createModuleVariableDeclaration(b,c,d,a.location)}},m.prototype.transformModuleDeclaration=function(a){var b=a.expression.token.processedValue;return this.createModuleVariableDeclaration(b,[a.identifier],[null],a.location)},m.prototype.transformExportDeclaration=function(a){var b=a.declaration;if("NAMED_EXPORT"==b.type){var f=b.moduleSpecifier&&b.moduleSpecifier.token.processedValue;if("EXPORT_STAR"!=b.specifierSet.type){for(var h=[],j=b.specifierSet.specifiers,m=0;m<j.length;m++){var n=j[m];h.push(c(this.createExportExpression(n.rhs?n.rhs.value:n.lhs.value),f?this.createImportExpression(f,n.lhs.value):g(n.lhs.value)))}var o=l(i(h));return o.location=a.location,o}var p=k(g(this.exportGlobal),this.createImportExpression(f));return p.location=a.location,p}if("VARIABLE_STATEMENT"==b.type){var q=b.declarations.declarations[0];return q.initialiser=c(this.createExportExpression(q.lvalue.identifierToken.value),this.transformAny(q.initialiser)),b}if("FUNCTION_DECLARATION"==b.type){var q=d(b.name.identifierToken.value,k(this.createExportExpression(b.name.identifierToken.value),this.transformAny(b)));return q.location=a.location,e("var",[q])}return"EXPORT_DEFAULT"==b.type?k(this.createExportExpression("default"),this.transformAny(b.expression)):a},m}function y(a,b,c,d){var e,f;if(b(a,c,d)!==!1)for(e in a)a.hasOwnProperty(e)&&"location"!=e&&"type"!=e&&(f=a[e],"object"==typeof f&&null!==f&&y(f,b,a,e))}function z(a){function b(a){-1==F.call(c,a)&&c.push(a)}var c=[];return y(a,function(a){"EXPORT_DECLARATION"==a.type?a.declaration.moduleSpecifier&&b(a.declaration.moduleSpecifier.token.processedValue):"IMPORT_DECLARATION"==a.type?b(a.moduleSpecifier.token.processedValue):"MODULE_DECLARATION"==a.type&&b(a.expression.token.processedValue)}),c}var A="undefined"!=typeof window,B=A?window:this,C=A?window:module.exports,D=A?function(a){setTimeout(a,1)}:process.nextTick,E=B.Promise;if(E)if(E.all&&E.resolve&&E.reject){E=B.Promise;{new E(function(a){"function"!=typeof a&&(E=null)})}}else E=null;E||(B.Promise=E=function(a,b,c){function d(a,b){return(typeof b)[0]==a}function e(a,h){return h=function i(j,k,l,m,n,o){function p(a){return function(b){n&&(n=0,i(d,a,b))}}if(m=i.q,j!=d)return e(function(a,b){m.push({p:this,r:a,j:b,1:j,0:k})});if(l&&d(b,l)|d(c,l))try{n=l.then}catch(q){k=0,l=q}if(d(b,n))try{n.call(l,p(1),k=p(0))}catch(q){k(q)}else for(h=f(a,l,k),o=0;o<m.length;)n=m[o++],d(b,j=n[k])?g(n.p,n.r,n.j,l,j):(k?n.r:n.j)(l)},h.q=[],a.call(a={then:function(a,b){return h(a,b)},"catch":function(a){return h(0,a)}},function(a){h(d,1,a)},function(a){h(d,0,a)}),a}function f(a,c,f){return function(h,i){return d(b,h=f?h:i)?e(function(a,b){g(this,a,b,c,h)}):a}}function g(e,f,g,h,i){a(function(){try{h=i(h),i=h&&d(c,h)|d(b,h)&&h.then,d(b,i)?h==e?g(new TypeError):i.call(h,f,g):f(h)}catch(a){g(a)}})}return e.resolve=function(a){return e(function(b){b(a)})},e.reject=function(a){return e(function(b,c){c(a)})},e.all=function(b){return new e(function(c,d){if(!b.length)return a(c);for(var e=[],f=0,g=0,h=b.length;h>g;g++)(function(a){b[a].then(function(d){e[a]=d,f++,f==b.length&&c(e)},d)})(g)})},e}(D,"f","o"));var F=Array.prototype.indexOf||function(a){for(var b=0,c=this.length;c>b;b++)if(this[b]===a)return b;return-1},G={};t.prototype={define:function(a,b,c){if(G[a])throw new TypeError("Module is already loading.");return G[a]=new E(p(this,a,c&&c.address?"fetch":"translate",c&&c.meta||{},c&&c.address,b)),G[a].then(function(){delete G[a]})},load:function(a,b){return this._modules[a]?E.resolve(this._modules[a]):G[a]?G[a]:(G[a]=o(this,a,b),G[a].then(function(){delete G[a]}))},module:function(a,b){var c=e();c.address=b&&b.address;var d=j(this,c),f=E.resolve(a),g=d.done.then(function(){q(this,c)});return i(this,c,f),g},"import":function(a,b){return this._modules[a]?E.resolve(this._modules[a]):(G[a]||(G[a]=o(this,a,b))).then(function(b){return delete G[a],q(this,b)})},eval:function(){throw new TypeError("Eval not implemented in polyfill")},get:function(a){return this._modules[a]},has:function(a){return!!this._modules[a]},set:function(a,b){if(!(b instanceof r))throw new TypeError("Set must be a module");this._modules[a]=b},"delete":function(a){return this._modules[a]?delete this._modules[a]:!1},entries:function(){throw new TypeError("Iteration not yet implemented in the polyfill")},keys:function(){throw new TypeError("Iteration not yet implemented in the polyfill")},values:function(){throw new TypeError("Iteration not yet implemented in the polyfill")},normalize:function(a){return a},locate:function(a){return a.name},fetch:function(){throw new TypeError("Fetch not implemented")},translate:function(a){return a.source},instantiate:function(){}};var H;if(A)H=function(a,b,c){function d(){b(f.responseText)}function e(){c(f.statusText+": "+a||"XHR error")}var f=new XMLHttpRequest,g=!0;if(!("withCredentials"in f)){var h=/^(\w+:)?\/\/([^\/]+)/.exec(a);h&&(g=h[2]===window.location.host,h[1]&&(g&=h[1]===window.location.protocol))}g||(f=new XDomainRequest,f.onload=d,f.onerror=e,f.ontimeout=e),f.onreadystatechange=function(){4===f.readyState&&(200===f.status||0==f.status&&f.responseText?d():e())},f.open("GET",a,!0),f.send(null)};else{var I=require("fs");H=function(a,b,c){return I.readFile(a,function(a,d){return a?c(a):(b(d+""),void 0)})}}var J=new t({global:A?window:B,strict:!0,normalize:function(a,b){if("string"!=typeof a)throw new TypeError("Module name must be a string");var c=a.split("/");if(0==c.length)throw new TypeError("No module name provided");var d=0,e=!1,f=0;if("."==c[0]){if(d++,d==c.length)throw new TypeError('Illegal module name "'+a+'"');e=!0}else{for(;".."==c[d];)if(d++,d==c.length)throw new TypeError('Illegal module name "'+a+'"');d&&(e=!0),f=d}for(var g=d;g<c.length;g++){var h=c[g];if(""==h||"."==h||".."==h)throw new TypeError('Illegal module name"'+a+'"')}if(!e)return a;{var i=[],j=(b||"").split("/");j.length-1-f}return i=i.concat(j.splice(0,j.length-1-f)),i=i.concat(c.splice(d)),i.join("/")},locate:function(a){var b,c=a.name,d="";for(var e in this.paths){var f=e.split("*");if(f.length>2)throw new TypeError("Only one wildcard in a path is permitted");1==f.length?c==e&&e.length>d.length&&(d=e):c.substr(0,f[0].length)==f[0]&&c.substr(c.length-f[1].length)==f[1]&&(d=e,b=c.substr(f[0].length,c.length-f[1].length-f[0].length))}var g=this.paths[d];return b&&(g=g.replace("*",b)),v(this.baseURL,g)},fetch:function(a){var b,c,d=new E(function(a,d){b=a,c=d});return H(v(this.baseURL,a.address),function(a){b(a)},c),d},instantiate:function(b){if(!b.source)return{deps:[],execute:function(){return new B.Module({})}};if(!b.metadata.es6&&b.name&&(b.metadata.es6===!1||!b.source.match(O)))return{deps:[],execute:function(){return a(b.source,B,b.address,b.name),"traceur"==b.name&&A&&(B.traceur=B.System.get("../src/traceur.js"),B.System=J),new r({})}};var c,d=this;return(c=b.source.match(P))?{deps:[c[1]||c[2]],execute:function(a){return d._modules[a]}}:(b.address=b.address||"anonymous-module-"+K++,w().then(function(c){c.options.sourceMaps=!0,c.options.modules="parse";var d=new c.util.ErrorReporter;d.reportMessageInternal=function(a,b){throw b+"\n"+a};var e=new c.syntax.Parser(d,new c.syntax.SourceFile(b.address,b.source)),f=e.parseModule(),g=z(f);return{deps:g,execute:function(){for(var e={},h=0;h<arguments.length;h++){var i="__moduleDependency"+h;B[i]=J.get(arguments[h]),e[g[h]]=i}var j=new c.codegeneration.FromOptionsTransformer(d);j.append(function(a){return new c.codegeneration.ModuleLoaderTransformer(e,"__exports").transformAny(a)}),f=j.transform(f);var k=new c.outputgeneration.SourceMapGenerator({file:b.address}),l={sourceMapGenerator:k};source=c.outputgeneration.TreeWriter.write(f,l),A&&window.btoa&&(source+="\n//# sourceMappingURL=data:application/json;base64,"+btoa(unescape(encodeURIComponent(l.sourceMap)))+"\n"),B.__exports={},a(source,B,b.address,b.name);var m=B.__exports;delete B.__exports;for(var h=0;h<arguments.length;h++)delete B["__moduleDependency"+h];return new r(m)}}}))}}),K=1;if(A){var L=window.location.href.split("#")[0].split("?")[0];J.baseURL=L.substring(0,L.lastIndexOf("/")+1)}else J.baseURL="./";J.paths={"*":"*.js"};var M,N,O=/(?:^\s*|[}{\(\);,\n]\s*)(import\s+['"]|(import|module)\s+[^"'\(\)\n;]+\s+from\s+['"]|export\s+(\*|\{|default|function|var|const|let|[_$a-zA-Z\xA0-\uFFFF][_$a-zA-Z0-9\xA0-\uFFFF]*))/,P=/^\s*export\s*\*\s*from\s*(?:'([^']+)'|"([^"]+)")/;C.Loader=t,C.Module=r,C.System=J;var Q;if(A){var R=document.getElementsByTagName("script");R=R[R.length-1],Q=R.getAttribute("data-traceur-src")||R.src.substr(0,R.src.lastIndexOf("/")+1)+"traceur.js",document.onreadystatechange=function(){if("interactive"==document.readyState)for(var a=document.getElementsByTagName("script"),b=0;b<a.length;b++){var c=a[b];if("module"==c.type){var d=c.getAttribute("name"),e=c.getAttribute("src"),f=c.innerHTML;(d?J.define(d,f,{address:e}):J.module(f,{address:e})).then(function(){},function(a){D(function(){throw a})})}}},R.getAttribute("data-init")&&window[R.getAttribute("data-init")]()}}()}();
+!function(a){var b="undefined"!=typeof window,c=b?function(a){setTimeout(a,1)}:process.nextTick,d=a.Promise;if(d)if(d.all&&d.resolve&&d.reject){d=a.Promise;{new d(function(a){"function"!=typeof a&&(d=null)})}}else d=null;d||(d=function(a,b,c){function d(a,b){return(typeof b)[0]==a}function e(a,h){return h=function i(j,k,l,m,n,o){function p(a){return function(b){n&&(n=0,i(d,a,b))}}if(m=i.q,j!=d)return e(function(a,b){m.push({p:this,r:a,j:b,1:j,0:k})});if(l&&d(b,l)|d(c,l))try{n=l.then}catch(q){k=0,l=q}if(d(b,n))try{n.call(l,p(1),k=p(0))}catch(q){k(q)}else for(h=f(a,l,k),o=0;o<m.length;)n=m[o++],d(b,j=n[k])?g(n.p,n.r,n.j,l,j):(k?n.r:n.j)(l)},h.q=[],a.call(a={then:function(a,b){return h(a,b)},"catch":function(a){return h(0,a)}},function(a){h(d,1,a)},function(a){h(d,0,a)}),a}function f(a,c,f){return function(h,i){return d(b,h=f?h:i)?e(function(a,b){g(this,a,b,c,h)}):a}}function g(e,f,g,h,i){a(function(){try{h=i(h),i=h&&d(c,h)|d(b,h)&&h.then,d(b,i)?h==e?g(new TypeError):i.call(h,f,g):f(h)}catch(a){g(a)}})}return e.resolve=function(a){return e(function(b){b(a)})},e.reject=function(a){return e(function(b,c){c(a)})},e.all=function(b){return new e(function(c,d){if(!b.length)return a(c);for(var e=[],f=0,g=0,h=b.length;h>g;g++)(function(a){b[a].then(function(d){e[a]=d,f++,f==b.length&&c(e)},d)})(g)})},e}(c,"f","o")),"object"==typeof exports&&(module.exports=d),a.Promise||(a.Promise=d),a.PromisePolyfill=d}("undefined"!=typeof global?global:this),function(a){function b(a){if("object"!=typeof a)throw new TypeError("Expected object");if(!(this instanceof b))return new b(a);var d=this;for(var e in a)!function(a,b){c(d,a,{configurable:!1,enumerable:!0,get:function(){return b}})}(e,a[e]);Object.preventExtensions&&Object.preventExtensions(this)}var c;try{Object.defineProperty({},"a",{})&&(c=Object.defineProperty)}catch(d){c=function(a,b,c){a[b]=c.value||c.get.call(a)}}"object"==typeof exports&&(module.exports=b),a.Module||(a.Module=b),a.ModulePolyfill=b}("undefined"!=typeof global?global:this),function(a){function b(a,b){b||console.log("Assertion Failed - "+a)}function c(a){return{status:"loading",name:a,metadata:{},linkSets:[]}}function d(a,d,f,g){return new t(function(b){b(a.normalize(d,f,g))}).then(function(d){var f;if(a._modules[d])return f=c(d),f.status="linked",f;for(var g=0,h=a._loads.length;h>g;g++)if(f=a._loads[g],f.name==d)return b("loading or loaded","loading"==f.status||"loaded"==f.status),f;return f=c(d),a._loads.push(f),e(a,f),f})}function e(a,b){f(a,b,t.resolve().then(function(){return a.locate({name:b.name,metadata:b.metadata})}))}function f(a,b,c){g(a,b,c.then(function(c){return"failed"==b.status?void 0:(b.address=c,a.fetch({name:b.name,metadata:b.metadata,address:c}))}))}function g(a,c,e){e.then(function(b){return"failed"==c.status?void 0:a.translate({name:c.name,metadata:c.metadata,address:c.address,source:b})}).then(function(b){return"failed"==c.status?void 0:(c.source=b,a.instantiate({name:c.name,metadata:c.metadata,address:c.address,source:b}))}).then(function(e){if("failed"==c.status)return void 0;var f;if(void 0===e)throw"Declarative parsing is not implemented by the polyfill.";if("object"!=typeof e)throw TypeError("Invalid instantiate return value");f=e.deps||[],c.execute=e.execute,c.kind="dynamic",c.dependencies={},c.depsList=f;for(var g=[],h=0,j=f.length;j>h;h++)(function(e){var f=d(a,e,c.name,c.address);f.then(function(a){if(b("not already a dependency",!c.dependencies[e]),c.dependencies[e]=a.name,"linked"!=a.status)for(var d=c.linkSets.concat([]),f=0,g=d.length;g>f;f++)i(d[f],a)}),g.push(f)})(f[h]);return t.all(g)}).then(function(){b("is loading","loading"==c.status),c.status="loaded";for(var a=c.linkSets.concat([]),d=0,e=a.length;e>d;d++)j(a[d],c)},function(a){b("is loading on fail","loading"==c.status),c.status="failed",c.exception=a;for(var d=0,e=c.linkSets.length;e>d;d++)k(c.linkSets[d],a);b("fail linkSets removed",0==c.linkSets.length)})}function h(a,b){var c,d,e=new t(function(a,b){c=a,d=b}),f={loader:a,loads:[],done:e,resolve:c,reject:d,loadingCount:0};return i(f,b),f}function i(a,c){b("loading or loaded on link set","loading"==c.status||"loaded"==c.status);for(var d=0,e=a.loads.length;e>d;d++)if(a.loads[d]==c)return;a.loads.push(c),c.linkSets.push(a),"loaded"!=c.status&&a.loadingCount++;var f=a.loader;for(var g in c.dependencies){var h=c.dependencies[g];if(!f._modules[h])for(var d=0,e=f._loads.length;e>d;d++)if(f._loads[d].name==h){i(a,f._loads[d]);break}}}function j(a,c){if(b("loaded or linked","loaded"==c.status||"linked"==c.status),a.loadingCount--,!(a.loadingCount>0)){var d=a.loads[0];try{p(a.loads,a.loader)}catch(e){return k(a,e)}b("loads cleared",0==a.loads.length),a.resolve(d)}}function k(a,c){for(var d=a.loads.concat([]),e=0,f=d.length;f>e;e++){var g=d[e],h=v.call(g.linkSets,a);if(b("link not present",-1!=h),g.linkSets.splice(h,1),0==g.linkSets.length){var i=v.call(a.loader._loads,g);-1!=i&&a.loader._loads.splice(i,1)}}a.reject(c)}function l(a,c){c.name&&(b("load not in module table",!a._modules[c.name]),a._modules[c.name]=c.module);var d=v.call(a._loads,c);-1!=d&&a._loads.splice(d,1);for(var e=0,f=c.linkSets.length;f>e;e++)d=v.call(c.linkSets[e].loads,c),c.linkSets[e].loads.splice(d,1);c.linkSets=[]}function m(a,b,c){return new t(n(a,b,c&&c.address?"fetch":"locate",void 0,c&&c.address,void 0)).then(function(a){return a})}function n(a,d,i,j,k,l){return function(m,n){if(a._modules[d])throw new TypeError('Module "'+d+'" already exists in the module table');for(var o=0,p=a._loads.length;p>o;o++)if(a._loads[o].name==d)throw new TypeError('Module "'+d+'" is already loading');var q=c(d);j&&(q.metadata=j);var r=h(a,q);a._loads.push(q),r.done.then(m,n),"locate"==i?e(a,q):"fetch"==i?f(a,q,t.resolve(k)):(b("translate step","translate"==i),q.address=k,g(a,q,t.resolve(l)))}}function o(a,c){return b("is linked "+c.name,"linked"==c.status),b("is a module",c.module instanceof s),c.module}function p(a,b){for(var c=0;a.length;){c++;a:for(var d=0;d<a.length;d++){var e=a[d],f=[];for(var g in e.dependencies){var h=e.dependencies[g];if(!b._modules[h])continue a;var i=e.depsList.indexOf(g);f[i]=h}var j=e.execute.apply(null,f);if(!(j instanceof s))throw new TypeError("Execution must define a Module instance");e.module=j,e.status="linked",l(b,e)}if(1e3===c)return void console.log("Circular Dependency Detected")}}function q(a){if("object"!=typeof a)throw new TypeError("Options must be an object");a.normalize&&(this.normalize=a.normalize),a.locate&&(this.locate=a.locate),a.fetch&&(this.fetch=a.fetch),a.translate&&(this.translate=a.translate),a.instantiate&&(this.instantiate=a.instantiate),r(this,"global",{get:function(){throw new TypeError("global accessor not provided by polyfill")}}),r(this,"realm",{get:function(){throw new TypeError("Realms not implemented in polyfill")}}),this._modules={},this._loads=[]}var r,s=a.Module||require("./module.js"),t=a.Promise||require("./promise.js");try{Object.defineProperty({},"a",{})&&(r=Object.defineProperty)}catch(u){r=function(a,b,c){a[b]=c.value||c.get.call(a)}}var v=Array.prototype.indexOf||function(a){for(var b=0,c=this.length;c>b;b++)if(this[b]===a)return b;return-1},w={};q.prototype={define:function(a,b,c){if(w[a])throw new TypeError("Module is already loading.");return w[a]=new t(n(this,a,c&&c.address?"fetch":"translate",c&&c.meta||{},c&&c.address,b)),w[a].then(function(){delete w[a]})},load:function(a,b){return this._modules[a]?t.resolve(this._modules[a]):w[a]?w[a]:(w[a]=m(this,a,b),w[a].then(function(){delete w[a]}))},module:function(a,b){var d=c();d.address=b&&b.address;var e=h(this,d),f=t.resolve(a),i=e.done.then(function(){o(this,d)});return g(this,d,f),i},"import":function(a,b){return this._modules[a]?t.resolve(this._modules[a]):(w[a]||(w[a]=m(this,a,b))).then(function(b){return delete w[a],o(this,b)})},eval:function(){throw new TypeError("Eval not implemented in polyfill")},get:function(a){return this._modules[a]},has:function(a){return!!this._modules[a]},set:function(a,b){if(!(b instanceof s))throw new TypeError("Set must be a module");this._modules[a]=b},"delete":function(a){return this._modules[a]?delete this._modules[a]:!1},entries:function(){throw new TypeError("Iteration not yet implemented in the polyfill")},keys:function(){throw new TypeError("Iteration not yet implemented in the polyfill")},values:function(){throw new TypeError("Iteration not yet implemented in the polyfill")},normalize:function(a){return a},locate:function(a){return a.name},fetch:function(){throw new TypeError("Fetch not implemented")},translate:function(a){return a.source},instantiate:function(){}},"object"==typeof exports&&(module.exports=q),a.Loader||(a.Loader=q),a.LoaderPolyfill=q}("undefined"!=typeof global?global:this),function(a){function b(a){var b=String(a).replace(/^\s+|\s+$/g,"").match(/^([^:\/?#]+:)?(\/\/(?:[^:@]*(?::[^:@]*)?@)?(([^:\/?#]*)(?::(\d*))?))?([^?#]*)(\?[^#]*)?(#[\s\S]*)?/);return b?{href:b[0]||"",protocol:b[1]||"",authority:b[2]||"",host:b[3]||"",hostname:b[4]||"",port:b[5]||"",pathname:b[6]||"",search:b[7]||"",hash:b[8]||""}:null}function c(a,c){function d(a){var b=[];return a.replace(/^(\.\.?(\/|$))+/,"").replace(/\/(\.(\/|$))+/g,"/").replace(/\/\.\.$/,"/../").replace(/\/?[^\/]*/g,function(a){"/.."===a?b.pop():b.push(a)}),b.join("").replace(/^\//,"/"===a.charAt(0)?"/":"")}return c=b(c||""),a=b(a||""),c&&a?(c.protocol||a.protocol)+(c.protocol||c.authority?c.authority:a.authority)+d(c.protocol||c.authority||"/"===c.pathname.charAt(0)?c.pathname:c.pathname?(a.authority&&!a.pathname?"/":"")+a.pathname.slice(0,a.pathname.lastIndexOf("/")+1)+c.pathname:a.pathname)+(c.protocol||c.authority||c.pathname?c.search:c.search||a.search)+c.hash:null}function d(){return s?m.resolve(s||(s=a.traceur)):t?t:t=(j?p.import:function(){return m.resolve(require("traceur"))}).call(p,"traceur",{address:w}).then(function(b){return t=null,j&&(b=a.traceur),s=b,s.codegeneration.ModuleLoaderTransformer=e(s.codegeneration.ParseTreeFactory,s.codegeneration.ParseTreeTransformer),s})}function e(a,b){var c=a.createAssignmentExpression,d=a.createVariableDeclaration,e=(a.createCallExpression,a.createVariableDeclarationList),f=a.createStringLiteral,g=a.createIdentifierExpression,h=a.createMemberLookupExpression,i=a.createCommaExpression,j=a.createVariableStatement,k=a.createAssignmentStatement,l=a.createExpressionStatement,m=function(a,b){this.depMap=a,this.exportGlobal=b};return m.prototype=Object.create(b.prototype),m.prototype.createModuleVariableDeclaration=function(a,b,c,f){var g=this,h=b.map(function(b,e){return d(b,g.createImportExpression(a,c[e]))}),i=e("var",h);return i.location=f,j(i)},m.prototype.createImportExpression=function(a,b){var c=g(this.depMap[a]);return b?h(c,f(b)):c},m.prototype.createExportExpression=function(a){return h(g(this.exportGlobal),f(a))},m.prototype.transformImportDeclaration=function(a){var b=a.moduleSpecifier.token.processedValue,c=[],d=[];if(a.importClause){if(a.importClause&&a.importClause.binding)c.push(a.importClause.binding.identifierToken),d.push("default");else if(a.importClause)for(var e=a.importClause.specifiers,f=0;f<e.length;f++){var g=e[f];c.push(g.rhs?g.rhs.value:g.lhs.value),d.push(g.lhs.value)}return this.createModuleVariableDeclaration(b,c,d,a.location)}},m.prototype.transformModuleDeclaration=function(a){var b=a.expression.token.processedValue;return this.createModuleVariableDeclaration(b,[a.identifier],[null],a.location)},m.prototype.transformExportDeclaration=function(a){var b=a.declaration;if("NAMED_EXPORT"==b.type){var f=b.moduleSpecifier&&b.moduleSpecifier.token.processedValue;if("EXPORT_STAR"!=b.specifierSet.type){for(var h=[],j=b.specifierSet.specifiers,m=0;m<j.length;m++){var n=j[m];h.push(c(this.createExportExpression(n.rhs?n.rhs.value:n.lhs.value),f?this.createImportExpression(f,n.lhs.value):g(n.lhs.value)))}var o=l(i(h));return o.location=a.location,o}var p=k(g(this.exportGlobal),this.createImportExpression(f));return p.location=a.location,p}if("VARIABLE_STATEMENT"==b.type){var q=b.declarations.declarations[0];return q.initialiser=c(this.createExportExpression(q.lvalue.identifierToken.value),this.transformAny(q.initialiser)),b}if("FUNCTION_DECLARATION"==b.type){var q=d(b.name.identifierToken.value,k(this.createExportExpression(b.name.identifierToken.value),this.transformAny(b)));return q.location=a.location,e("var",[q])}return"EXPORT_DEFAULT"==b.type?k(this.createExportExpression("default"),this.transformAny(b.expression)):a},m}function f(a,b,c,d){var e,g;if(b(a,c,d)!==!1)for(e in a)a.hasOwnProperty(e)&&"location"!=e&&"type"!=e&&(g=a[e],"object"==typeof g&&null!==g&&f(g,b,a,e))}function g(a){function b(a){-1==n.call(c,a)&&c.push(a)}var c=[];return f(a,function(a){"EXPORT_DECLARATION"==a.type?a.declaration.moduleSpecifier&&b(a.declaration.moduleSpecifier.token.processedValue):"IMPORT_DECLARATION"==a.type?b(a.moduleSpecifier.token.processedValue):"MODULE_DECLARATION"==a.type&&b(a.expression.token.processedValue)}),c}function h(a,b,c,d){try{Function("global",'var __moduleName = "'+(d||"").replace('"','"')+'"; with(global) { '+a+" \n }"+(c&&!a.match(/\/\/[@#] ?(sourceURL|sourceMappingURL)=([^\n]+)/)?"\n//# sourceURL="+c:"")).call(b,b)}catch(e){throw"SyntaxError"==e.name&&(e.message="Evaluating "+c+"\n "+e.message),e}}var i,j="undefined"!=typeof window,k=a.Module||require("./module.js"),l=a.Loader||require("./loader.js"),m=a.Promise||require("./promise.js"),n=Array.prototype.indexOf||function(a){for(var b=0,c=this.length;c>b;b++)if(this[b]===a)return b;return-1};if(j)i=function(a,b,c){function d(){b(f.responseText)}function e(){c(f.statusText+": "+a||"XHR error")}var f=new XMLHttpRequest,g=!0;if(!("withCredentials"in f)){var h=/^(\w+:)?\/\/([^\/]+)/.exec(a);h&&(g=h[2]===window.location.host,h[1]&&(g&=h[1]===window.location.protocol))}g||(f=new XDomainRequest,f.onload=d,f.onerror=e,f.ontimeout=e),f.onreadystatechange=function(){4===f.readyState&&(200===f.status||0==f.status&&f.responseText?d():e())},f.open("GET",a,!0),f.send(null)};else{var o=require("fs");i=function(a,b,c){return o.readFile(a,function(a,d){return a?c(a):void b(d+"")})}}var p=new l({global:j?window:a,strict:!0,normalize:function(a,b){if("string"!=typeof a)throw new TypeError("Module name must be a string");var c=a.split("/");if(0==c.length)throw new TypeError("No module name provided");var d=0,e=!1,f=0;if("."==c[0]){if(d++,d==c.length)throw new TypeError('Illegal module name "'+a+'"');e=!0}else{for(;".."==c[d];)if(d++,d==c.length)throw new TypeError('Illegal module name "'+a+'"');d&&(e=!0),f=d}for(var g=d;g<c.length;g++){var h=c[g];if(""==h||"."==h||".."==h)throw new TypeError('Illegal module name"'+a+'"')}if(!e)return a;{var i=[],j=(b||"").split("/");j.length-1-f}return i=i.concat(j.splice(0,j.length-1-f)),i=i.concat(c.splice(d)),i.join("/")},locate:function(a){var b,d=a.name,e="";for(var f in this.paths){var g=f.split("*");if(g.length>2)throw new TypeError("Only one wildcard in a path is permitted");1==g.length?d==f&&f.length>e.length&&(e=f):d.substr(0,g[0].length)==g[0]&&d.substr(d.length-g[1].length)==g[1]&&(e=f,b=d.substr(g[0].length,d.length-g[1].length-g[0].length))}var h=this.paths[e];return b&&(h=h.replace("*",b)),c(this.baseURL,h)},fetch:function(a){var b,d,e=new m(function(a,c){b=a,d=c});return i(c(this.baseURL,a.address),function(a){b(a)},d),e},instantiate:function(b){if(!b.source)return{deps:[],execute:function(){return new k({})}};if(!b.metadata.es6&&b.name&&(b.metadata.es6===!1||!b.source.match(u)))return{deps:[],execute:function(){return h(b.source,a,b.address,b.name),"traceur"==b.name&&j&&(a.traceur=a.System.get("../src/traceur.js"),a.System=p),new k({})}};var c,e=this;return(c=b.source.match(v))?{deps:[c[1]||c[2]],execute:function(a){return e._modules[a]}}:(b.address=b.address||"anonymous-module-"+q++,d().then(function(c){c.options.sourceMaps=!0,c.options.modules="parse";var d=new c.util.ErrorReporter;d.reportMessageInternal=function(a,b){throw b+"\n"+a};var e=new c.syntax.Parser(d,new c.syntax.SourceFile(b.address,b.source)),f=e.parseModule(),i=g(f);return{deps:i,execute:function(){for(var e={},g=0;g<arguments.length;g++){var l="__moduleDependency"+g;a[l]=p.get(arguments[g]),e[i[g]]=l}var m=new c.codegeneration.FromOptionsTransformer(d);m.append(function(a){return new c.codegeneration.ModuleLoaderTransformer(e,"__exports").transformAny(a)}),f=m.transform(f);var n=new c.outputgeneration.SourceMapGenerator({file:b.address}),o={sourceMapGenerator:n};source=c.outputgeneration.TreeWriter.write(f,o),j&&window.btoa&&(source+="\n//# sourceMappingURL=data:application/json;base64,"+btoa(unescape(encodeURIComponent(o.sourceMap)))+"\n"),a.__exports={},h(source,a,b.address,b.name);var q=a.__exports;delete a.__exports;for(var g=0;g<arguments.length;g++)delete a["__moduleDependency"+g];return new k(q)}}}))}}),q=1;if(j){var r=window.location.href.split("#")[0].split("?")[0];p.baseURL=r.substring(0,r.lastIndexOf("/")+1)}else p.baseURL="./";p.paths={"*":"*.js"};var s,t,u=/(?:^\s*|[}{\(\);,\n]\s*)(import\s+['"]|(import|module)\s+[^"'\(\)\n;]+\s+from\s+['"]|export\s+(\*|\{|default|function|var|const|let|[_$a-zA-Z\xA0-\uFFFF][_$a-zA-Z0-9\xA0-\uFFFF]*))/,v=/^\s*export\s*\*\s*from\s*(?:'([^']+)'|"([^"]+)")/;a.System||(a.System=p);var w;if(j){var x=document.getElementsByTagName("script");x=x[x.length-1],w=x.getAttribute("data-traceur-src")||x.src.substr(0,x.src.lastIndexOf("/")+1)+"traceur.js",document.onreadystatechange=function(){if("interactive"==document.readyState)for(var a=document.getElementsByTagName("script"),b=0;b<a.length;b++){var c=a[b];if("module"==c.type){var d=c.getAttribute("name"),e=c.getAttribute("src"),f=c.innerHTML;(d?p.define(d,f,{address:e}):p.module(f,{address:e})).then(function(){},function(a){nextTick(function(){throw a})})}}},x.getAttribute("data-init")&&window[x.getAttribute("data-init")]()}"object"==typeof exports&&(module.exports=p),a.System||(a.System=p),a.SystemPolyfill=p}("undefined"!=typeof global?global:this);
View
14 dist/traceur.js
7 additions, 7 deletions not shown
View
1,367 lib/es6-module-loader.js
@@ -1,1367 +0,0 @@
-/*
- * ES6 Module Loader Polyfill
- * https://github.com/ModuleLoader/es6-module-loader
- *
- * Based on the 2013-12-02 specification draft
- * System loader based on example implementation as of 2013-12-03
- *
- * Copyright (c) 2013 Guy Bedford, Luke Hoban, Addy Osmani
- * Licensed under the MIT license.
- *
- */
-
-/*
- ToDo
- - Traceur ModuleTransformer update for new system
- - getImports to use visitor pattern
- - Loader Iterator support
- - Tracking these and spec issues with 'NB' comments in this code
-*/
-(function () {
- (function() {
-
- var isBrowser = typeof window != 'undefined';
- var global = isBrowser ? window : this;
- var exports = isBrowser ? window : module.exports;
-
- var nextTick = isBrowser ? function(fn) { setTimeout(fn, 1); } : process.nextTick;
-
- /*
- *********************************************************************************************
-
- Simple Promises A+ Implementation
- Adapted from https://github.com/RubenVerborgh/promiscuous
- Copyright 2013 Ruben Verborgh
-
- *********************************************************************************************
- */
-
- var Promise = global.Promise;
- if (Promise) {
- // check if native promises have what we need
- if (Promise.all && Promise.resolve && Promise.reject) {
- Promise = global.Promise;
- var p = new Promise(function(r) {
- if (typeof r != 'function')
- Promise = null;
- });
- }
- else
- Promise = null;
- }
- // export the promises polyfill
- if (!Promise)
- global.Promise = Promise = (function(setImmediate, func, obj) {
- // Type checking utility function
- function is(type, item) { return (typeof item)[0] == type; }
-
- // Creates a promise, calling callback(resolve, reject), ignoring other parameters.
- function Promise(callback, handler) {
- // The `handler` variable points to the function that will
- // 1) handle a .then(resolved, rejected) call
- // 2) handle a resolve or reject call (if the first argument === `is`)
- // Before 2), `handler` holds a queue of callbacks.
- // After 2), `handler` is a finalized .then handler.
- handler = function pendingHandler(resolved, rejected, value, queue, then, i) {
- queue = pendingHandler.q;
-
- // Case 1) handle a .then(resolved, rejected) call
- if (resolved != is) {
- return Promise(function(resolve, reject) {
- queue.push({ p: this, r: resolve, j: reject, 1: resolved, 0: rejected });
- });
- }
-
- // Case 2) handle a resolve or reject call
- // (`resolved` === `is` acts as a sentinel)
- // The actual function signature is
- // .re[ject|solve](<is>, success, value)
-
- // Check if the value is a promise and try to obtain its `then` method
- if (value && (is(func, value) | is(obj, value))) {
- try { then = value.then; }
- catch (reason) { rejected = 0; value = reason; }
- }
- // If the value is a promise, take over its state
- if (is(func, then)) {
- function valueHandler(resolved) {
- return function(value) { then && (then = 0, pendingHandler(is, resolved, value)); };
- }
- try { then.call(value, valueHandler(1), rejected = valueHandler(0)); }
- catch (reason) { rejected(reason); }
- }
- // The value is not a promise; handle resolve/reject
- else {
- // Replace this handler with a finalized resolved/rejected handler
- handler = createFinalizedThen(callback, value, rejected);
- // Resolve/reject pending callbacks
- i = 0;
- while (i < queue.length) {
- then = queue[i++];
- // If no callback, just resolve/reject the promise
- if (!is(func, resolved = then[rejected]))
- (rejected ? then.r : then.j)(value);
- // Otherwise, resolve/reject the promise with the result of the callback
- else
- finalize(then.p, then.r, then.j, value, resolved);
- }
- }
- };
- // The queue of pending callbacks; garbage-collected when handler is resolved/rejected
- handler.q = [];
-
- // Create and return the promise (reusing the callback variable)
- callback.call(callback = { then: function (resolved, rejected) { return handler(resolved, rejected); },
- 'catch': function (rejected) { return handler(0, rejected); } },
- function(value) { handler(is, 1, value); },
- function(reason) { handler(is, 0, reason); });
- return callback;
- }
-
- // Creates a resolved or rejected .then function
- function createFinalizedThen(promise, value, success) {
- return function(resolved, rejected) {
- // If the resolved or rejected parameter is not a function, return the original promise
- if (!is(func, (resolved = success ? resolved : rejected)))
- return promise;
- // Otherwise, return a finalized promise, transforming the value with the function
- return Promise(function(resolve, reject) { finalize(this, resolve, reject, value, resolved); });
- };
- }
-
- // Finalizes the promise by resolving/rejecting it with the transformed value
- function finalize(promise, resolve, reject, value, transform) {
- setImmediate(function() {
- try {
- // Transform the value through and check whether it's a promise
- value = transform(value);
- transform = value && (is(obj, value) | is(func, value)) && value.then;
- // Return the result if it's not a promise
- if (!is(func, transform))
- resolve(value);
- // If it's a promise, make sure it's not circular
- else if (value == promise)
- reject(new TypeError());
- // Take over the promise's state
- else
- transform.call(value, resolve, reject);
- }
- catch (error) { reject(error); }
- });
- }
-
- // Export the main module
- Promise.resolve = function (value) { return Promise(function (resolve) { resolve(value) }); };
- Promise.reject = function (reason) { return Promise(function (resolve, reject) { reject(reason) }); };
- Promise.all = function(promises) {
- return new Promise(function(resolve, reject) {
- if (!promises.length)
- return setImmediate(resolve);
-
- var outputs = [];
- var resolved = 0;
- for (var i = 0, l = promises.length; i < l; i++) (function(i) {
- promises[i].then(function(resolvedVal) {
- outputs[i] = resolvedVal;
- resolved++;
- if (resolved == promises.length)
- resolve(outputs);
- }, reject);
- })(i);
- });
- }
- return Promise;
- })(nextTick, 'f', 'o');
-
-
- /*
- *********************************************************************************************
-
- Loader Polyfill
-
- - Implemented exactly to the 2013-12-02 Specification Draft -
- https://github.com/jorendorff/js-loaders/blob/e60d3651/specs/es6-modules-2013-12-02.pdf
- with the only exceptions as described here
-
- - Abstract functions have been combined where possible, and their associated functions
- commented
-
- - Declarative Module Support is entirely disabled, and an error will be thrown if
- the instantiate loader hook returns undefined
-
- - With this assumption, instead of Link, LinkDynamicModules is run directly
-
- - ES6 support is thus provided through the translate function of the System loader
-
- - EnsureEvaluated is removed, but may in future implement dynamic execution pending
- issue - https://github.com/jorendorff/js-loaders/issues/63
-
- - Realm implementation is entirely omitted. As such, Loader.global and Loader.realm
- accessors will throw errors, as well as Loader.eval
-
- - Loader module table iteration currently not yet implemented
-
- *********************************************************************************************
- */
-
- // Some Helpers
-
- // logs a linkset snapshot for debugging
- /* function snapshot(loader) {
- console.log('\n');
- for (var i = 0; i < loader._loads.length; i++) {
- var load = loader._loads[i];
- var linkSetLog = load.name + ' (' + load.status + '): ';
-
- for (var j = 0; j < load.linkSets.length; j++) {
- linkSetLog += '{'
- linkSetLog += logloads(load.linkSets[j].loads);
- linkSetLog += '} ';
- }
- console.log(linkSetLog);
- }
- console.log('\n');
- }
- function logloads(loads) {
- var log = '';
- for (var k = 0; k < loads.length; k++)
- log += loads[k].name + (k != loads.length - 1 ? ' ' : '');
- return log;
- } */
-
- function assert(name, expression) {
- if (!expression)
- console.log('Assertion Failed - ' + name);
- }
- function defineProperty(obj, prop, opt) {
- if (Object.defineProperty)
- Object.defineProperty(obj, prop, opt);
- else
- obj[prop] = opt.value || opt.get.call(obj);
- };
- function preventExtensions(obj) {
- if (Object.preventExtensions)
- Object.preventExtensions(obj);
- }
-
- // Define an IE-friendly shim good-enough for purposes
- var indexOf = Array.prototype.indexOf || function (item) {
- for (var i = 0, thisLen = this.length; i < thisLen; i++) {
- if (this[i] === item) {
- return i;
- }
- }
- return -1;
- };
-
- // Load Abstract Functions
-
- function createLoad(name) {
- return {
- status: 'loading',
- name: name,
- metadata: {},
- linkSets: []
- };
- }
-
- // promise for a load record, can be in registry, already loading, or not
- function requestLoad(loader, request, refererName, refererAddress) {
- return new Promise(function(resolve, reject) {
- // CallNormalize
- resolve(loader.normalize(request, refererName, refererAddress));
- })
-
- // GetOrCreateLoad
- .then(function(name) {
- var load;
- if (loader._modules[name]) {
- load = createLoad(name);
- load.status = 'linked';
- return load;
- }
-
- for (var i = 0, l = loader._loads.length; i < l; i++) {
- load = loader._loads[i];
- if (load.name == name) {
- assert('loading or loaded', load.status == 'loading' || load.status == 'loaded');
- return load;
- }
- }
-
- // CreateLoad
- load = createLoad(name);
- loader._loads.push(load);
-
- proceedToLocate(loader, load);
-
- return load;
- });
- }
- function proceedToLocate(loader, load) {
- proceedToFetch(loader, load,
- Promise.resolve()
- // CallLocate
- .then(function() {
- return loader.locate({ name: load.name, metadata: load.metadata });
- })
- );
- }
- function proceedToFetch(loader, load, p) {
- proceedToTranslate(loader, load,
- p
- // CallFetch
- .then(function(address) {
- if (load.status == 'failed') // NB https://github.com/jorendorff/js-loaders/issues/88
- return undefined;
- load.address = address;
- return loader.fetch({ name: load.name, metadata: load.metadata, address: address });
- })
- );
- }
- function proceedToTranslate(loader, load, p) {
- p
- // CallTranslate
- .then(function(source) {
- if (load.status == 'failed')
- return undefined;
- return loader.translate({ name: load.name, metadata: load.metadata, address: load.address, source: source })
- })
-
- // CallInstantiate
- .then(function(source) {
- if (load.status == 'failed')
- return undefined;
- load.source = source;
- return loader.instantiate({ name: load.name, metadata: load.metadata, address: load.address, source: source });
- })
-
- // InstantiateSucceeded
- .then(function(instantiateResult) {
- if (load.status == 'failed')
- return undefined;
-
- var depsList;
- if (instantiateResult === undefined)
- throw 'Declarative parsing is not implemented by the polyfill.';
-
- else if (typeof instantiateResult == 'object') {
- depsList = instantiateResult.deps || [];
- load.execute = instantiateResult.execute;
- load.kind = 'dynamic';
- }
- else
- throw TypeError('Invalid instantiate return value');
-
- // ProcessLoadDependencies
- load.dependencies = {};
- load.depsList = depsList;
- var loadPromises = [];
- for (var i = 0, l = depsList.length; i < l; i++) (function(request) {
- var p = requestLoad(loader, request, load.name, load.address);
-
- // AddDependencyLoad (load is parentLoad)
- p.then(function(depLoad) {
- assert('not already a dependency', !load.dependencies[request]);
- load.dependencies[request] = depLoad.name;
-
- if (depLoad.status != 'linked') {
- var linkSets = load.linkSets.concat([]);
- for (var i = 0, l = linkSets.length; i < l; i++)
- addLoadToLinkSet(linkSets[i], depLoad);
- }
- });
-
- loadPromises.push(p);
- })(depsList[i]);
-
- return Promise.all(loadPromises);
- })
-
- // LoadSucceeded
- .then(function() {
- assert('is loading', load.status == 'loading');
-
- load.status = 'loaded';
-
- // console.log('load succeeeded ' + load.name);
- // snapshot(loader);
-
- var linkSets = load.linkSets.concat([]);
- for (var i = 0, l = linkSets.length; i < l; i++)
- updateLinkSetOnLoad(linkSets[i], load);
- }
-
- // LoadFailed
- , function(exc) {
- assert('is loading on fail', load.status == 'loading');
- load.status = 'failed';
- load.exception = exc;
- for (var i = 0, l = load.linkSets.length; i < l; i++)
- linkSetFailed(load.linkSets[i], exc);
- assert('fail linkSets removed', load.linkSets.length == 0);
- });
- }
-
-
- // LinkSet Abstract Functions
- function createLinkSet(loader, startingLoad) {
- var resolve, reject, promise = new Promise(function(_resolve, _reject) { resolve = _resolve; reject = _reject; });
- var linkSet = {
- loader: loader,
- loads: [],
- done: promise,
- resolve: resolve,
- reject: reject,
- loadingCount: 0
- };
- addLoadToLinkSet(linkSet, startingLoad);
- return linkSet;
- }
- function addLoadToLinkSet(linkSet, load) {
- assert('loading or loaded on link set', load.status == 'loading' || load.status == 'loaded');
-
- for (var i = 0, l = linkSet.loads.length; i < l; i++)
- if (linkSet.loads[i] == load)
- return;
-
- linkSet.loads.push(load);
- load.linkSets.push(linkSet);
-
- if (load.status != 'loaded')
- linkSet.loadingCount++;
-
- var loader = linkSet.loader;
-
- for (var dep in load.dependencies) {
- var name = load.dependencies[dep];
-
- if (loader._modules[name])
- continue;
-
- for (var i = 0, l = loader._loads.length; i < l; i++)
- if (loader._loads[i].name == name) {
- addLoadToLinkSet(linkSet, loader._loads[i]);
- break;
- }
- }
- // console.log('add to linkset ' + load.name);
- // snapshot(linkSet.loader);
- }
- function updateLinkSetOnLoad(linkSet, load) {
- // NB https://github.com/jorendorff/js-loaders/issues/85
- // assert('no load when updated ' + load.name, indexOf.call(linkSet.loads, load) != -1);
- assert('loaded or linked', load.status == 'loaded' || load.status == 'linked');
-
- // console.log('update linkset on load ' + load.name);
- // snapshot(linkSet.loader);
-
- // see https://github.com/jorendorff/js-loaders/issues/80
- linkSet.loadingCount--;
- /* for (var i = 0; i < linkSet.loads.length; i++) {
- if (linkSet.loads[i].status == 'loading') {
- return;
- }
- } */
-
- if (linkSet.loadingCount > 0)
- return;
-
- var startingLoad = linkSet.loads[0];
- try {
- link(linkSet.loads, linkSet.loader);
- }
- catch(exc) {
- return linkSetFailed(linkSet, exc);
- }
-
- assert('loads cleared', linkSet.loads.length == 0);
- linkSet.resolve(startingLoad);
- }
- function linkSetFailed(linkSet, exc) {
- var loads = linkSet.loads.concat([]);
- for (var i = 0, l = loads.length; i < l; i++) {
- var load = loads[i];
- var linkIndex = indexOf.call(load.linkSets, linkSet);
- assert('link not present', linkIndex != -1);
- load.linkSets.splice(linkIndex, 1);
- if (load.linkSets.length == 0) {
- var globalLoadsIndex = indexOf.call(linkSet.loader._loads, load);
- if (globalLoadsIndex != -1)
- linkSet.loader._loads.splice(globalLoadsIndex, 1);
- }
- }
- linkSet.reject(exc);
- }
- function finishLoad(loader, load) {
- // if not anonymous, add to the module table
- if (load.name) {
- assert('load not in module table', !loader._modules[load.name]);
- loader._modules[load.name] = load.module;
- }
- var loadIndex = indexOf.call(loader._loads, load);
- if (loadIndex != -1)
- loader._loads.splice(loadIndex, 1);
- for (var i = 0, l = load.linkSets.length; i < l; i++) {
- loadIndex = indexOf.call(load.linkSets[i].loads, load);
- load.linkSets[i].loads.splice(loadIndex, 1);
- }
- load.linkSets = [];
- }
- function loadModule(loader, name, options) {
- return new Promise(asyncStartLoadPartwayThrough(loader, name, options && options.address ? 'fetch' : 'locate', undefined, options && options.address, undefined)).then(function(load) {
- return load;
- });
- }
- function asyncStartLoadPartwayThrough(loader, name, step, meta, address, source) {
- return function(resolve, reject) {
- if (loader._modules[name])
- throw new TypeError('Module "' + name + '" already exists in the module table');
- for (var i = 0, l = loader._loads.length; i < l; i++)
- if (loader._loads[i].name == name)
- throw new TypeError('Module "' + name + '" is already loading');
-
- var load = createLoad(name);
-
- if (meta)
- load.metadata = meta;
-
- var linkSet = createLinkSet(loader, load);
-
- loader._loads.push(load);
-
- // NB spec change as in https://github.com/jorendorff/js-loaders/issues/79
- linkSet.done.then(resolve, reject);
-
- if (step == 'locate')
- proceedToLocate(loader, load);
-
- else if (step == 'fetch')
- proceedToFetch(loader, load, Promise.resolve(address));
-
- else {
- assert('translate step', step == 'translate');
- load.address = address;
- proceedToTranslate(loader, load, Promise.resolve(source));
- }
- }
- }
- function evaluateLoadedModule(loader, load) {
- assert('is linked ' + load.name, load.status == 'linked');
-
- assert('is a module', load.module instanceof Module);
-
- // ensureEvaluated(load.module, [], loader);
-
- return load.module;
- }
-
- // Module Object
- function Module(obj) {
- if (typeof obj != 'object')
- throw new TypeError('Expected object');
-
- if (!(this instanceof Module))
- return new Module(obj);
-
- var self = this;
- for (var key in obj) {
- (function (key, value) {
- defineProperty(self, key, {
- configurable: false,
- enumerable: true,
- get: function () {
- return value;
- }
- });
- })(key, obj[key]);
- }
- preventExtensions(this);
- }
- // Module.prototype = null;
-
-
- // Linking
- // Link is directly LinkDynamicModules assuming all modules are dynamic
- function link(loads, loader) {
- // console.log('linking {' + logloads(loads) + '}');
-
- // continue until all linked
- // NB circular dependencies will stall this loop
- var loopCnt = 0;
- while (loads.length) {
- loopCnt++;
- // search through to find a load with all its dependencies linked
- search: for (var i = 0; i < loads.length; i++) {
- var load = loads[i];
- var depNames = [];
- for (var d in load.dependencies) {
- var depName = load.dependencies[d];
- // being in the module table means it is linked
- if (!loader._modules[depName])
- continue search;
- var index = load.depsList.indexOf(d);
- depNames[index] = depName;
- }
-
- // all dependencies linked now, so we can execute
- var module = load.execute.apply(null, depNames);
- if (!(module instanceof Module))
- throw new TypeError('Execution must define a Module instance');
- load.module = module;
- load.status = 'linked';
- finishLoad(loader, load);
- }
- if (loopCnt === 1000) {
- console.log('Circular Dependency Detected');
- return;
- }
- }
- // console.log('linked');
- }
-
- // Loader
- function Loader(options) {
- if (typeof options != 'object')
- throw new TypeError('Options must be an object');
-
- if (options.normalize)
- this.normalize = options.normalize;
- if (options.locate)
- this.locate = options.locate;
- if (options.fetch)
- this.fetch = options.fetch;
- if (options.translate)
- this.translate = options.translate;
- if (options.instantiate)
- this.instantiate = options.instantiate;
-
- defineProperty(this, 'global', {
- get: function() {
- throw new TypeError('global accessor not provided by polyfill');
- }
- });
- defineProperty(this, 'realm', {
- get: function() {
- throw new TypeError('Realms not implemented in polyfill');
- }
- });
-
- this._modules = {};
- this._loads = [];
- }
-
- // NB importPromises hacks ability to import a module twice without error - https://github.com/jorendorff/js-loaders/issues/60
- var importPromises = {};
- Loader.prototype = {
- define: function(name, source, options) {
- if (importPromises[name])
- throw new TypeError('Module is already loading.');
- importPromises[name] = new Promise(asyncStartLoadPartwayThrough(this, name, options && options.address ? 'fetch' : 'translate', options && options.meta || {}, options && options.address, source));
- return importPromises[name].then(function() { delete importPromises[name]; });
- },
- load: function(request, options) {
- if (this._modules[request])
- return Promise.resolve(this._modules[request]);
- if (importPromises[request])
- return importPromises[request];
- importPromises[request] = loadModule(this, request, options);
- return importPromises[request].then(function() { delete importPromises[request]; })
- },
- module: function(source, options) {
- var load = createLoad();
- load.address = options && options.address;
- var linkSet = createLinkSet(this, load);
- var sourcePromise = Promise.resolve(source);
- var p = linkSet.done.then(function() {
- evaluateLoadedModule(this, load);
- });
- proceedToTranslate(this, load, sourcePromise);
- return p;
- },
- 'import': function(name, options) {
- if (this._modules[name])
- return Promise.resolve(this._modules[name]);
- return (importPromises[name] || (importPromises[name] = loadModule(this, name, options)))
- .then(function(load) {
- delete importPromises[name];
- return evaluateLoadedModule(this, load);
- });
- },
- eval: function(source) {
- throw new TypeError('Eval not implemented in polyfill')
- },
- get: function(key) {
- // NB run ensure evaluted here when implemented
- return this._modules[key];
- },
- has: function(name) {
- return !!this._modules[name];
- },
- set: function(name, module) {
- if (!(module instanceof Module))
- throw new TypeError('Set must be a module');
- this._modules[name] = module;
- },
- 'delete': function(name) {
- return this._modules[name] ? delete this._modules[name] : false;
- },
- // NB implement iterations
- entries: function() {
- throw new TypeError('Iteration not yet implemented in the polyfill');
- },
- keys: function() {
- throw new TypeError('Iteration not yet implemented in the polyfill');
- },
- values: function() {
- throw new TypeError('Iteration not yet implemented in the polyfill');
- },
- normalize: function(name, refererName, refererAddress) {
- return name;
- },
- locate: function(load) {
- return load.name;
- },
- fetch: function(load) {
- throw new TypeError('Fetch not implemented');
- },
- translate: function(load) {
- return load.source;
- },
- instantiate: function(load) {
- }
- };
-
-
-
- /*
- *********************************************************************************************
-
- System Loader Implementation
-
- - Implemented to https://github.com/jorendorff/js-loaders/blob/master/browser-loader.js,
- except for Instantiate function
-
- - Instantiate function determines if ES6 module syntax is being used, if so parses with
- Traceur and returns a dynamic InstantiateResult for loading ES6 module syntax in ES5.
-
- - Custom loaders thus can be implemented by using this System.instantiate function as
- the fallback loading scenario, after other module format detections.
-
- - Traceur is loaded dynamically when module syntax is detected by a regex (with over-
- classification), either from require('traceur') on the server, or the
- 'data-traceur-src' property on the current script in the browser, or if not set,
- 'traceur.js' in the same URL path as the current script in the browser.
-
- - <script type="module"> supported, but <module> tag not
-
- *********************************************************************************************
- */
-
- // Helpers
- // Absolute URL parsing, from https://gist.github.com/Yaffle/1088850
- function parseURI(url) {
- var m = String(url).replace(/^\s+|\s+$/g, '').match(/^([^:\/?#]+:)?(\/\/(?:[^:@]*(?::[^:@]*)?@)?(([^:\/?#]*)(?::(\d*))?))?([^?#]*)(\?[^#]*)?(#[\s\S]*)?/);
- // authority = '//' + user + ':' + pass '@' + hostname + ':' port
- return (m ? {
- href : m[0] || '',
- protocol : m[1] || '',
- authority: m[2] || '',
- host : m[3] || '',
- hostname : m[4] || '',
- port : m[5] || '',
- pathname : m[6] || '',
- search : m[7] || '',
- hash : m[8] || ''
- } : null);
- }
- function toAbsoluteURL(base, href) {
- function removeDotSegments(input) {
- var output = [];
- input.replace(/^(\.\.?(\/|$))+/, '')
- .replace(/\/(\.(\/|$))+/g, '/')
- .replace(/\/\.\.$/, '/../')
- .replace(/\/?[^\/]*/g, function (p) {
- if (p === '/..')
- output.pop();
- else
- output.push(p);
- });
- return output.join('').replace(/^\//, input.charAt(0) === '/' ? '/' : '');
- }
-
- href = parseURI(href || '');
- base = parseURI(base || '');
-
- return !href || !base ? null : (href.protocol || base.protocol) +
- (href.protocol || href.authority ? href.authority : base.authority) +
- 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)) +
- (href.protocol || href.authority || href.pathname ? href.search : (href.search || base.search)) +
- href.hash;
- }
-
- var fetchTextFromURL;
- if (isBrowser) {
- fetchTextFromURL = function(url, fulfill, reject) {
- var xhr = new XMLHttpRequest();
- var sameDomain = true;
- if (!('withCredentials' in xhr)) {
- // check if same domain
- var domainCheck = /^(\w+:)?\/\/([^\/]+)/.exec(url);
- if (domainCheck) {
- sameDomain = domainCheck[2] === window.location.host;
- if (domainCheck[1])
- sameDomain &= domainCheck[1] === window.location.protocol;
- }
- }
- if (!sameDomain) {
- xhr = new XDomainRequest();
- xhr.onload = load;
- xhr.onerror = error;
- xhr.ontimeout = error;
- }
- function load() {
- fulfill(xhr.responseText);
- }
- function error() {
- reject(xhr.statusText + ': ' + url || 'XHR error');
- }
-
- xhr.onreadystatechange = function () {
- if (xhr.readyState === 4) {
- if (xhr.status === 200 || (xhr.status == 0 && xhr.responseText)) {
- load();
- } else {
- error();
- }
- }
- };
- xhr.open("GET", url, true);
- xhr.send(null);
- }
- }
- else {
- var fs = require('fs');
- fetchTextFromURL = function(url, fulfill, reject) {
- return fs.readFile(url, function(err, data) {
- if (err)
- return reject(err);
- else
- fulfill(data + '');
- });
- }
- }
-
- var System = new Loader({
- global: isBrowser ? window : global,
- strict: true,
- normalize: function(name, parentName, parentAddress) {
- if (typeof name != 'string')
- throw new TypeError('Module name must be a string');
-
- var segments = name.split('/');
-
- if (segments.length == 0)
- throw new TypeError('No module name provided');
-
- // current segment
- var i = 0;
- // is the module name relative
- var rel = false;
- // number of backtracking segments
- var dotdots = 0;
- if (segments[0] == '.') {
- i++;
- if (i == segments.length)
- throw new TypeError('Illegal module name "' + name + '"');
- rel = true;
- }
- else {
- while (segments[i] == '..') {
- i++;
- if (i == segments.length)
- throw new TypeError('Illegal module name "' + name + '"');
- }
- if (i)
- rel = true;
- dotdots = i;
- }
-
- for (var j = i; j < segments.length; j++) {
- var segment = segments[j];
- if (segment == '' || segment == '.' || segment == '..')
- throw new TypeError('Illegal module name"' + name + '"');
- }
-
- if (!rel)
- return name;
-
- // build the full module name
- var normalizedParts = [];
- var parentParts = (parentName || '').split('/');
- var normalizedLen = parentParts.length - 1 - dotdots;
-
- normalizedParts = normalizedParts.concat(parentParts.splice(0, parentParts.length - 1 - dotdots));
- normalizedParts = normalizedParts.concat(segments.splice(i));
-
- return normalizedParts.join('/');
- },
- locate: function(load) {
- var name = load.name;
-
- // NB no specification provided for System.paths, used ideas discussed in https://github.com/jorendorff/js-loaders/issues/25
-
- // most specific (longest) match wins
- var pathMatch = '', wildcard;
-
- // check to see if we have a paths entry
- for (var p in this.paths) {
- var pathParts = p.split('*');
- if (pathParts.length > 2)
- throw new TypeError('Only one wildcard in a path is permitted');
-
- // exact path match
- if (pathParts.length == 1) {
- if (name == p && p.length > pathMatch.length)
- pathMatch = p;
- }
-
- // wildcard path match
- else {
- if (name.substr(0, pathParts[0].length) == pathParts[0] && name.substr(name.length - pathParts[1].length) == pathParts[1]) {
- pathMatch = p;
- wildcard = name.substr(pathParts[0].length, name.length - pathParts[1].length - pathParts[0].length);
- }
- }
- }
-
- var outPath = this.paths[pathMatch];
- if (wildcard)
- outPath = outPath.replace('*', wildcard);
-
- return toAbsoluteURL(this.baseURL, outPath);
- },
- fetch: function(load) {
- var resolve, reject, promise = new Promise(function(_resolve, _reject) { resolve = _resolve; reject = _reject; });
- fetchTextFromURL(toAbsoluteURL(this.baseURL, load.address), function(source) {
- resolve(source);
- }, reject);
- return promise;
- },
- instantiate: function(load) {
-
- // allow empty source
- if (!load.source) {
- return {
- deps: [],
- execute: function() {
- return new global.Module({});
- }
- };
- }
-
- // normal eval (non-module code)
- // note that anonymous modules (load.name == undefined) are always
- // anonymous <module> tags, so we use Traceur for these
- if (!load.metadata.es6 && load.name && (load.metadata.es6 === false || !load.source.match(es6RegEx))) {
- return {
- deps: [],
- execute: function() {
- __eval(load.source, global, load.address, load.name);
-
- // when loading traceur, it overwrites the System
- // global. The only way to synchronously ensure it is
- // reverted in time not to cause issue is here
- if (load.name == 'traceur' && isBrowser) {
- global.traceur = global.System.get('../src/traceur.js');
- global.System = System;
- }
-
- // return an empty module
- return new Module({});
- }
- };
- }
-
- var match;
- var loader = this;
- // alias check is based on a "simple form" only
- // eg import * from 'jquery';
- if (match = load.source.match(aliasRegEx)) {
- return {
- deps: [match[1] || match[2]],
- execute: function(dep) {
- return loader._modules[dep];
- }
- };
- }
-
- // ES6 -> ES5 conversion
- load.address = load.address || 'anonymous-module-' + anonCnt++;
- // load traceur and the module transformer
- return getTraceur()
- .then(function(traceur) {
-
- traceur.options.sourceMaps = true;
- traceur.options.modules = 'parse';
- // traceur.options.blockBinding = true;
-
- var reporter = new traceur.util.ErrorReporter();
-
- reporter.reportMessageInternal = function(location, kind, format, args) {
- throw kind + '\n' + location;
- }
-
- var parser = new traceur.syntax.Parser(reporter, new traceur.syntax.SourceFile(load.address, load.source));
-
- var tree = parser.parseModule();
-
-
- var imports = getImports(tree);
-
- return {
- deps: imports,
- execute: function() {
-
- // write dependencies as unique globals
- // creating a map from the unnormalized import name to the unique global name
- var globalMap = {};
- for (var i = 0; i < arguments.length; i++) {
- var name = '__moduleDependency' + i;
- global[name] = System.get(arguments[i]);
- globalMap[imports[i]] = name;
- }
-
- // transform
- var transformer = new traceur.codegeneration.FromOptionsTransformer(reporter);
- transformer.append(function(tree) {
- return new traceur.codegeneration.ModuleLoaderTransformer(globalMap, '__exports').transformAny(tree);
- });
- tree = transformer.transform(tree);
-
- // convert back to a source string
- var sourceMapGenerator = new traceur.outputgeneration.SourceMapGenerator({ file: load.address });
- var options = { sourceMapGenerator: sourceMapGenerator };
-
- source = traceur.outputgeneration.TreeWriter.write(tree, options);
- if (isBrowser && window.btoa)
- source += '\n//# sourceMappingURL=data:application/json;base64,' + btoa(unescape(encodeURIComponent(options.sourceMap))) + '\n';
-
- global.__exports = {};
-
- __eval(source, global, load.address, load.name);
-
- var exports = global.__exports;
-
- delete global.__exports;
- for (var i = 0; i < arguments.length; i++)
- delete global['__moduleDependency' + i];
-
- return new Module(exports);
- }
- };
- });
- }
- });
-
- // count anonymous evals to have unique name
- var anonCnt = 1;
-
- if (isBrowser) {
- var href = window.location.href.split('#')[0].split('?')[0];
- System.baseURL = href.substring(0, href.lastIndexOf('\/') + 1);
- }
- else {
- System.baseURL = './';
- }
- System.paths = { '*': '*.js' };
-
-
- // ES6 to ES5 parsing functions
-
- // comprehensively overclassifying regex detectection for es6 module syntax
- var es6RegEx = /(?:^\s*|[}{\(\);,\n]\s*)(import\s+['"]|(import|module)\s+[^"'\(\)\n;]+\s+from\s+['"]|export\s+(\*|\{|default|function|var|const|let|[_$a-zA-Z\xA0-\uFFFF][_$a-zA-Z0-9\xA0-\uFFFF]*))/;
-
- // es6 module forwarding - allow detecting without Traceur
- var aliasRegEx = /^\s*export\s*\*\s*from\s*(?:'([^']+)'|"([^"]+)")/;
-
- // dynamically load traceur when needed
- // populates the traceur, reporter and moduleLoaderTransfomer variables
-
- // NB we need to queue getTraceur callbacks due to https://github.com/jorendorff/js-loaders/issues/60
- var traceur, traceurPromise;
- function getTraceur() {
- if (traceur)
- return Promise.resolve(traceur || (traceur = global.traceur));
-
- if (traceurPromise)
- return traceurPromise;
-
- return traceurPromise = (isBrowser ? exports.System.import : function(name, src, callback) {
- return Promise.resolve(require('traceur'));
- }).call(exports.System, 'traceur', { address: traceurSrc }).then(function(_traceur) {
- traceurPromise = null;
-
- if (isBrowser)
- _traceur = global.traceur;
-
- traceur = _traceur;
-
- traceur.codegeneration.ModuleLoaderTransformer = createModuleLoaderTransformer(
- traceur.codegeneration.ParseTreeFactory,
- traceur.codegeneration.ParseTreeTransformer
- );
-
- return traceur;
- });
- }
-
- // NB update to new transformation system
- function createModuleLoaderTransformer(ParseTreeFactory, ParseTreeTransformer) {
- var createAssignmentExpression = ParseTreeFactory.createAssignmentExpression;
- var createVariableDeclaration = ParseTreeFactory.createVariableDeclaration;
-
- var createCallExpression = ParseTreeFactory.createCallExpression;
-
- var createVariableDeclarationList = ParseTreeFactory.createVariableDeclarationList;
- var createStringLiteral = ParseTreeFactory.createStringLiteral;
- var createIdentifierExpression = ParseTreeFactory.createIdentifierExpression;
-
- var createMemberLookupExpression = ParseTreeFactory.createMemberLookupExpression;
-
- var createCommaExpression = ParseTreeFactory.createCommaExpression;
- var createVariableStatement = ParseTreeFactory.createVariableStatement;
-
- var createAssignmentStatement = ParseTreeFactory.createAssignmentStatement;
- var createExpressionStatement = ParseTreeFactory.createExpressionStatement;
-
-
- var self = this;
- var ModuleLoaderTransformer = function(globalMap, exportGlobal) {
- this.depMap = globalMap;
- this.exportGlobal = exportGlobal;
- }
- ModuleLoaderTransformer.prototype = Object.create(ParseTreeTransformer.prototype);
-
- // var VARIABLE = __moduleDependencyX['VALUE'], ...
- // var VARIABLE = __moduleDependencyX, ...
- ModuleLoaderTransformer.prototype.createModuleVariableDeclaration = function(moduleName, variables, values, location) {
- var self = this;
- var variableDeclarations = variables.map(function(variable, i) {
- return createVariableDeclaration(variable, self.createImportExpression(moduleName, values[i]));
- });
- var varList = createVariableDeclarationList('var', variableDeclarations);
- varList.location = location;
- return createVariableStatement(varList);
- }
-
- // __moduleDependencyX['VALUE']
- ModuleLoaderTransformer.prototype.createImportExpression = function(moduleName, value) {
- var expression = createIdentifierExpression(this.depMap[moduleName]);
- return value ? createMemberLookupExpression(expression, createStringLiteral(value)) : expression;
- }
-
- // __exports['EXPORT_NAME']
- ModuleLoaderTransformer.prototype.createExportExpression = function(exportName) {
- return createMemberLookupExpression(createIdentifierExpression(this.exportGlobal), createStringLiteral(exportName));
- }
-
- ModuleLoaderTransformer.prototype.transformImportDeclaration = function(tree) {
- var moduleName = tree.moduleSpecifier.token.processedValue;
-
- var variables = [];
- var values = [];
-
- // import 'jquery';
- if (!tree.importClause) {
- return;
- }
- // import $ from 'jquery';
- else if (tree.importClause && tree.importClause.binding) {
- variables.push(tree.importClause.binding.identifierToken);
- values.push('default');
- }
- // import { ... } from 'jquery';
- else if (tree.importClause) {
- var specifiers = tree.importClause.specifiers;
- for (var i = 0; i < specifiers.length; i++) {
- var specifier = specifiers[i];
- variables.push(specifier.rhs ? specifier.rhs.value : specifier.lhs.value);
- values.push(specifier.lhs.value);
- }
- }
- return this.createModuleVariableDeclaration(moduleName, variables, values, tree.location);
- }
- ModuleLoaderTransformer.prototype.transformModuleDeclaration = function(tree) {
- var moduleName = tree.expression.token.processedValue;
- return this.createModuleVariableDeclaration(moduleName, [tree.identifier], [null], tree.location);
- }
- ModuleLoaderTransformer.prototype.transformExportDeclaration = function(tree) {
- var declaration = tree.declaration;
-
- if (declaration.type == 'NAMED_EXPORT') {
- var moduleName = declaration.moduleSpecifier && declaration.moduleSpecifier.token.processedValue;
- // export {a as b, c as d}
- // export {a as b, c as d} from 'module'
- if (declaration.specifierSet.type != 'EXPORT_STAR') {
- var expressions = [];
- var specifiers = declaration.specifierSet.specifiers;
- for (var i = 0; i < specifiers.length; i++) {
- var specifier = specifiers[i];
- expressions.push(createAssignmentExpression(
- this.createExportExpression(specifier.rhs ? specifier.rhs.value : specifier.lhs.value),
- moduleName
- ? this.createImportExpression(moduleName, specifier.lhs.value)
- : createIdentifierExpression(specifier.lhs.value)
- ));
- }
- var commaExpression = createExpressionStatement(createCommaExpression(expressions));
- commaExpression.location = tree.location;
- return commaExpression;
- }
- else {
- var exportStarStatement = createAssignmentStatement(createIdentifierExpression(this.exportGlobal), this.createImportExpression(moduleName));
- exportStarStatement.location = tree.location;
- return exportStarStatement;
- }
- }
-
- // export var p = 4;
- else if (declaration.type == 'VARIABLE_STATEMENT') {
- // export var p = ...
- var varDeclaration = declaration.declarations.declarations[0];
- varDeclaration.initialiser = createAssignmentExpression(
- this.createExportExpression(varDeclaration.lvalue.identifierToken.value),
- this.transformAny(varDeclaration.initialiser)
- );
- return declaration;
- }
- // export function q() {}
- else if (declaration.type == 'FUNCTION_DECLARATION') {
- var varDeclaration = createVariableDeclaration(
- declaration.name.identifierToken.value,
- createAssignmentStatement(
- this.createExportExpression(declaration.name.identifierToken.value),
- this.transformAny(declaration)
- )
- );
- varDeclaration.location = tree.location;
- return createVariableDeclarationList('var', [varDeclaration]);
- }
- // export default ...
- else if (declaration.type == 'EXPORT_DEFAULT') {
- return createAssignmentStatement(
- this.createExportExpression('default'),
- this.transformAny(declaration.expression)
- );
- }
-
- return tree;
- }
- return ModuleLoaderTransformer;
- }
-
- // tree traversal, NB should use visitor pattern here
- function traverse(object, iterator, parent, parentProperty) {
- var key, child;
- if (iterator(object, parent, parentProperty) === false)
- return;
- for (key in object) {
- if (!object.hasOwnProperty(key))
- continue;
- if (key == 'location' || key == 'type')
- continue;
- child = object[key];
- if (typeof child == 'object' && child !== null)
- traverse(child, iterator, object, key);
- }
- }
-
- // given a syntax tree, return the import list
- function getImports(moduleTree) {
- var imports = [];
-
- function addImport(name) {
- if (indexOf.call(imports, name) == -1)
- imports.push(name);
- }
-
- traverse(moduleTree, function(node) {
- // import {} from 'foo';
- // export * from 'foo';
- // export { ... } from 'foo';
- // module x from 'foo';
- if (node.type == 'EXPORT_DECLARATION') {
- if (node.declaration.moduleSpecifier)
- addImport(node.declaration.moduleSpecifier.token.processedValue);
- }
- else if (node.type == 'IMPORT_DECLARATION')
- addImport(node.moduleSpecifier.token.processedValue);
- else if (node.type == 'MODULE_DECLARATION')
- addImport(node.expression.token.processedValue);
- });
- return imports;
- }
-
-
- // Export the Loader class
- exports.Loader = Loader;
- // Export the Module class
- exports.Module = Module;
- // Export the System object
- exports.System = System;
-
- var traceurSrc;
-
- // <script type="module"> support
- // allow a data-init function callback once loaded
- if (isBrowser) {
- var curScript = document.getElementsByTagName('script');
- curScript = curScript[curScript.length - 1];
-
- // set the path to traceur
- traceurSrc = curScript.getAttribute('data-traceur-src')
- || curScript.src.substr(0, curScript.src.lastIndexOf('/') + 1) + 'traceur.js';
-
- document.onreadystatechange = function() {
- if (document.readyState == 'interactive') {
- var scripts = document.getElementsByTagName('script');
-
- for (var i = 0; i < scripts.length; i++) {
- var script = scripts[i];
- if (script.type == 'module') {
- // <script type="module" name="" src=""> support
- var name = script.getAttribute('name');
- var address = script.getAttribute('src');
- var source = script.innerHTML;
-
- (name
- ? System.define(name, source, { address: address })
- : System.module(source, { address: address })
- ).then(function() {}, function(err) { nextTick(function() { throw err; }); });
- }
- }
- }
- }
-
- // run the data-init function on the script tag
- if (curScript.getAttribute('data-init'))
- window[curScript.getAttribute('data-init')]();
- }
-
- })();
-
- function __eval(__source, global, __sourceURL, __moduleName) {
- try {
- Function('global', 'var __moduleName = "' + (__moduleName || '').replace('"', '\"') + '"; with(global) { ' + __source + ' \n }'
- + (__sourceURL && !__source.match(/\/\/[@#] ?(sourceURL|sourceMappingURL)=([^\n]+)/)
- ? '\n//# sourceURL=' + __sourceURL : '')).call(global, global);
- }
- catch(e) {
- if (e.name == 'SyntaxError')
- e.message = 'Evaluating ' + __sourceURL + '\n\t' + e.message;
- throw e;
- }
- }
-
-})();
View
5 lib/index.js
@@ -0,0 +1,5 @@
+module.exports = {
+ Loader: require('./loader.js'),
+ Module: require('./module.js'),
+ System: require('./system.js')
+};
View
550 lib/loader.js
@@ -0,0 +1,550 @@
+/*
+*********************************************************************************************
+
+ Loader Polyfill
+
+ - Implemented exactly to the 2013-12-02 Specification Draft -
+ https://github.com/jorendorff/js-loaders/blob/e60d3651/specs/es6-modules-2013-12-02.pdf
+ with the only exceptions as described here
+
+ - Abstract functions have been combined where possible, and their associated functions
+ commented
+
+ - Declarative Module Support is entirely disabled, and an error will be thrown if
+ the instantiate loader hook returns undefined
+
+ - With this assumption, instead of Link, LinkDynamicModules is run directly
+
+ - ES6 support is thus provided through the translate function of the System loader
+
+ - EnsureEvaluated is removed, but may in future implement dynamic execution pending
+ issue - https://github.com/jorendorff/js-loaders/issues/63
+
+ - Realm implementation is entirely omitted. As such, Loader.global and Loader.realm
+ accessors will throw errors, as well as Loader.eval
+
+ - Loader module table iteration currently not yet implemented
+
+*********************************************************************************************
+*/
+
+// Some Helpers
+
+// logs a linkset snapshot for debugging
+/* function snapshot(loader) {
+ console.log('\n');
+ for (var i = 0; i < loader._loads.length; i++) {
+ var load = loader._loads[i];
+ var linkSetLog = load.name + ' (' + load.status + '): ';
+
+ for (var j = 0; j < load.linkSets.length; j++) {
+ linkSetLog += '{'
+ linkSetLog += logloads(load.linkSets[j].loads);
+ linkSetLog += '} ';
+ }
+ console.log(linkSetLog);
+ }
+ console.log('\n');
+}
+function logloads(loads) {
+ var log = '';
+ for (var k = 0; k < loads.length; k++)
+ log += loads[k].name + (k != loads.length - 1 ? ' ' : '');
+ return log;
+} */
+
+(function (global) {
+ var Module = global.Module || require('./module.js');
+ var Promise = global.Promise || require('./promise.js');
+
+ var defineProperty;
+ try {
+ if (!!Object.defineProperty({}, 'a', {})) {
+ defineProperty = Object.defineProperty;
+ }
+ } catch (e) {
+ defineProperty = function (obj, prop, opt) {
+ obj[prop] = opt.value || opt.get.call(obj);
+ }
+ }
+
+ function assert(name, expression) {
+ if (!expression)
+ console.log('Assertion Failed - ' + name);
+ }
+ function preventExtensions(obj) {
+ if (Object.preventExtensions)
+ Object.preventExtensions(obj);
+ }
+
+ // Define an IE-friendly shim good-enough for purposes
+ var indexOf = Array.prototype.indexOf || function (item) {
+ for (var i = 0, thisLen = this.length; i < thisLen; i++) {
+ if (this[i] === item) {
+ return i;
+ }
+ }
+ return -1;
+ };
+
+ // Load Abstract Functions
+
+ function createLoad(name) {
+ return {
+ status: 'loading',
+ name: name,
+ metadata: {},
+ linkSets: []
+ };
+ }
+
+ // promise for a load record, can be in registry, already loading, or not
+ function requestLoad(loader, request, refererName, refererAddress) {
+ return new Promise(function(resolve, reject) {
+ // CallNormalize
+ resolve(loader.normalize(request, refererName, refererAddress));
+ })
+
+ // GetOrCreateLoad
+ .then(function(name) {
+ var load;
+ if (loader._modules[name]) {
+ load = createLoad(name);
+ load.status = 'linked';
+ return load;
+ }
+
+ for (var i = 0, l = loader._loads.length; i < l; i++) {
+ load = loader._loads[i];
+ if (load.name == name) {
+ assert('loading or loaded', load.status == 'loading' || load.status == 'loaded');
+ return load;
+ }
+ }
+
+ // CreateLoad
+ load = createLoad(name);
+ loader._loads.push(load);
+
+ proceedToLocate(loader, load);
+
+ return load;
+ });
+ }
+ function proceedToLocate(loader, load) {
+ proceedToFetch(loader, load,
+ Promise.resolve()
+ // CallLocate
+ .then(function() {
+ return loader.locate({ name: load.name, metadata: load.metadata });
+ })
+ );
+ }
+ function proceedToFetch(loader, load, p) {
+ proceedToTranslate(loader, load,
+ p
+ // CallFetch
+ .then(function(address) {
+ if (load.status == 'failed') // NB https://github.com/jorendorff/js-loaders/issues/88
+ return undefined;
+ load.address = address;
+ return loader.fetch({ name: load.name, metadata: load.metadata, address: address });
+ })
+ );
+ }
+ function proceedToTranslate(loader, load, p) {
+ p
+ // CallTranslate
+ .then(function(source) {
+ if (load.status == 'failed')
+ return undefined;
+ return loader.translate({ name: load.name, metadata: load.metadata, address: load.address, source: source })
+ })
+
+ // CallInstantiate
+ .then(function(source) {
+ if (load.status == 'failed')
+ return undefined;
+ load.source = source;
+ return loader.instantiate({ name: load.name, metadata: load.metadata, address: load.address, source: source });
+ })
+
+ // InstantiateSucceeded
+ .then(function(instantiateResult) {
+ if (load.status == 'failed')
+ return undefined;
+
+ var depsList;
+ if (instantiateResult === undefined)
+ throw 'Declarative parsing is not implemented by the polyfill.';
+
+ else if (typeof instantiateResult == 'object') {
+ depsList = instantiateResult.deps || [];
+ load.execute = instantiateResult.execute;
+ load.kind = 'dynamic';
+ }
+ else
+ throw TypeError('Invalid instantiate return value');
+
+ // ProcessLoadDependencies
+ load.dependencies = {};
+ load.depsList = depsList;
+ var loadPromises = [];
+ for (var i = 0, l = depsList.length; i < l; i++) (function(request) {
+ var p = requestLoad(loader, request, load.name, load.address);
+
+ // AddDependencyLoad (load is parentLoad)
+ p.then(function(depLoad) {
+ assert('not already a dependency', !load.dependencies[request]);
+ load.dependencies[request] = depLoad.name;
+
+ if (depLoad.status != 'linked') {
+ var linkSets = load.linkSets.concat([]);
+ for (var i = 0, l = linkSets.length; i < l; i++)
+ addLoadToLinkSet(linkSets[i], depLoad);
+ }
+ });
+
+ loadPromises.push(p);
+ })(depsList[i]);
+
+ return Promise.all(loadPromises);
+ })
+
+ // LoadSucceeded
+ .then(function() {
+ assert('is loading', load.status == 'loading');
+
+ load.status = 'loaded';
+
+ // console.log('load succeeeded ' + load.name);
+ // snapshot(loader);
+
+ var linkSets = load.linkSets.concat([]);
+ for (var i = 0, l = linkSets.length; i < l; i++)
+ updateLinkSetOnLoad(linkSets[i], load);
+ }
+
+ // LoadFailed
+ , function(exc) {
+ assert('is loading on fail', load.status == 'loading');
+ load.status = 'failed';
+ load.exception = exc;
+ for (var i = 0, l = load.linkSets.length; i < l; i++)
+ linkSetFailed(load.linkSets[i], exc);
+ assert('fail linkSets removed', load.linkSets.length == 0);
+ });
+ }
+
+
+ // LinkSet Abstract Functions
+ function createLinkSet(loader, startingLoad) {
+ var resolve, reject, promise = new Promise(function(_resolve, _reject) { resolve = _resolve; reject = _reject; });
+ var linkSet = {
+ loader: loader,
+ loads: [],
+ done: promise,
+ resolve: resolve,
+ reject: reject,
+ loadingCount: 0
+ };
+ addLoadToLinkSet(linkSet, startingLoad);
+ return linkSet;
+ }
+ function addLoadToLinkSet(linkSet, load) {
+ assert('loading or loaded on link set', load.status == 'loading' || load.status == 'loaded');
+
+ for (var i = 0, l = linkSet.loads.length; i < l; i++)
+ if (linkSet.loads[i] == load)
+ return;
+
+ linkSet.loads.push(load);
+ load.linkSets.push(linkSet);
+
+ if (load.status != 'loaded')
+ linkSet.loadingCount++;
+
+ var loader = linkSet.loader;
+
+ for (var dep in load.dependencies) {
+ var name = load.dependencies[dep];
+
+ if (loader._modules[name])
+ continue;
+
+ for (var i = 0, l = loader._loads.length; i < l; i++)
+ if (loader._loads[i].name == name) {
+ addLoadToLinkSet(linkSet, loader._loads[i]);
+ break;
+ }
+ }
+ // console.log('add to linkset ' + load.name);
+ // snapshot(linkSet.loader);
+ }
+ function updateLinkSetOnLoad(linkSet, load) {
+ // NB https://github.com/jorendorff/js-loaders/issues/85
+ // assert('no load when updated ' + load.name, indexOf.call(linkSet.loads, load) != -1);
+ assert('loaded or linked', load.status == 'loaded' || load.status == 'linked');
+
+ // console.log('update linkset on load ' + load.name);
+ // snapshot(linkSet.loader);
+
+ // see https://github.com/jorendorff/js-loaders/issues/80
+ linkSet.loadingCount--;
+ /* for (var i = 0; i < linkSet.loads.length; i++) {
+ if (linkSet.loads[i].status == 'loading') {
+ return;
+ }
+ } */
+
+ if (linkSet.loadingCount > 0)
+ return;
+
+ var startingLoad = linkSet.loads[0];
+ try {
+ link(linkSet.loads, linkSet.loader);
+ }
+ catch(exc) {
+ return linkSetFailed(linkSet, exc);
+ }
+
+ assert('loads cleared', linkSet.loads.length == 0);
+ linkSet.resolve(startingLoad);
+ }
+ function linkSetFailed(linkSet, exc) {
+ var loads = linkSet.loads.concat([]);
+ for (var i = 0, l = loads.length; i < l; i++) {
+ var load = loads[i];
+ var linkIndex = indexOf.call(load.linkSets, linkSet);
+ assert('link not present', linkIndex != -1);
+ load.linkSets.splice(linkIndex, 1);
+ if (load.linkSets.length == 0) {
+ var globalLoadsIndex = indexOf.call(linkSet.loader._loads, load);
+ if (globalLoadsIndex != -1)
+ linkSet.loader._loads.splice(globalLoadsIndex, 1);
+ }
+ }
+ linkSet.reject(exc);
+ }
+ function finishLoad(loader, load) {
+ // if not anonymous, add to the module table
+ if (load.name) {
+ assert('load not in module table', !loader._modules[load.name]);
+ loader._modules[load.name] = load.module;
+ }
+ var loadIndex = indexOf.call(loader._loads, load);
+ if (loadIndex != -1)
+ loader._loads.splice(loadIndex, 1);
+ for (var i = 0, l = load.linkSets.length; i < l; i++) {
+ loadIndex = indexOf.call(load.linkSets[i].loads, load);
+ load.linkSets[i].loads.splice(loadIndex, 1);
+ }
+ load.linkSets = [];
+ }
+ function loadModule(loader, name, options) {
+ return new Promise(asyncStartLoadPartwayThrough(loader, name, options && options.address ? 'fetch' : 'locate', undefined, options && options.address, undefined)).then(function(load) {
+ return load;
+ });
+ }
+ function asyncStartLoadPartwayThrough(loader, name, step, meta, address, source) {
+ return function(resolve, reject) {
+ if (loader._modules[name])
+ throw new TypeError('Module "' + name + '" already exists in the module table');
+ for (var i = 0, l = loader._loads.length; i < l; i++)
+ if (loader._loads[i].name == name)
+ throw new TypeError('Module "' + name + '" is already loading');
+
+ var load = createLoad(name);
+
+ if (meta)
+ load.metadata = meta;
+
+ var linkSet = createLinkSet(loader, load);
+
+ loader._loads.push(load);
+
+ // NB spec change as in https://github.com/jorendorff/js-loaders/issues/79
+ linkSet.done.then(resolve, reject);
+
+ if (step == 'locate')
+ proceedToLocate(loader, load);
+
+ else if (step == 'fetch')
+ proceedToFetch(loader, load, Promise.resolve(address));
+
+ else {
+ assert('translate step', step == 'translate');
+ load.address = address;
+ proceedToTranslate(loader, load, Promise.resolve(source));
+ }
+ }
+ }
+ function evaluateLoadedModule(loader, load) {
+ assert('is linked ' + load.name, load.status == 'linked');
+
+ assert('is a module', load.module instanceof Module);
+
+ // ensureEvaluated(load.module, [], loader);
+
+ return load.module;
+ }
+
+ // Linking
+ // Link is directly LinkDynamicModules assuming all modules are dynamic
+ function link(loads, loader) {
+ // console.log('linking {' + logloads(loads) + '}');
+
+ // continue until all linked
+ // NB circular dependencies will stall this loop
+ var loopCnt = 0;
+ while (loads.length) {
+ loopCnt++;
+ // search through to find a load with all its dependencies linked
+ search: for (var i = 0; i < loads.length; i++) {
+ var load = loads[i];
+ var depNames = [];
+ for (var d in load.dependencies) {
+ var depName = load.dependencies[d];
+ // being in the module table means it is linked
+ if (!loader._modules[depName])
+ continue search;
+ var index = load.depsList.indexOf(d);
+ depNames[index] = depName;
+ }
+
+ // all dependencies linked now, so we can execute
+ var module = load.execute.apply(null, depNames);
+ if (!(module instanceof Module))
+ throw new TypeError('Execution must define a Module instance');
+ load.module = module;
+ load.status = 'linked';
+ finishLoad(loader, load);
+ }
+ if (loopCnt === 1000) {
+ console.log('Circular Dependency Detected');
+ return;
+ }
+ }
+ // console.log('linked');
+ }
+
+ // Loader
+ function Loader(options) {
+ if (typeof options != 'object')
+ throw new TypeError('Options must be an object');
+
+ if (options.normalize)
+ this.normalize = options.normalize;
+ if (options.locate)
+ this.locate = options.locate;
+ if (options.fetch)
+ this.fetch = options.fetch;
+ if (options.translate)
+ this.translate = options.translate;
+ if (options.instantiate)
+ this.instantiate = options.instantiate;
+
+ defineProperty(this, 'global', {
+ get: function() {
+ throw new TypeError('global accessor not provided by polyfill');
+ }
+ });
+ defineProperty(this, 'realm', {
+ get: function() {
+ throw new TypeError('Realms not implemented in polyfill');
+ }
+ });
+
+ this._modules = {};
+ this._loads = [];
+ }
+
+ // NB importPromises hacks ability to import a module twice without error - https://github.com/jorendorff/js-loaders/issues/60
+ var importPromises = {};
+ Loader.prototype = {
+ define: function(name, source, options) {
+ if (importPromises[name])
+ throw new TypeError('Module is already loading.');
+ importPromises[name] = new Promise(asyncStartLoadPartwayThrough(this, name, options && options.address ? 'fetch' : 'translate', options && options.meta || {}, options && options.address, source));
+ return importPromises[name].then(function() { delete importPromises[name]; });
+ },
+ load: function(request, options) {
+ if (this._modules[request])
+ return Promise.resolve(this._modules[request]);
+ if (importPromises[request])
+ return importPromises[request];
+ importPromises[request] = loadModule(this, request, options);
+ return importPromises[request].then(function() { delete importPromises[request]; })
+ },
+ module: function(source, options) {
+ var load = createLoad();
+ load.address = options && options.address;
+ var linkSet = createLinkSet(this, load);
+ var sourcePromise = Promise.resolve(source);
+ var p = linkSet.done.then(function() {
+ evaluateLoadedModule(this, load);
+ });
+ proceedToTranslate(this, load, sourcePromise);
+ return p;
+ },
+ 'import': function(name, options) {
+ if (this._modules[name])
+ return Promise.resolve(this._modules[name]);
+ return (importPromises[name] || (importPromises[name] = loadModule(this, name, options)))
+ .then(function(load) {
+ delete importPromises[name];
+ return evaluateLoadedModule(this, load);
+ });
+ },
+ eval: function(source) {
+ throw new TypeError('Eval not implemented in polyfill')
+ },
+ get: function(key) {
+ // NB run ensure evaluted here when implemented
+ return this._modules[key];
+ },
+ has: function(name) {
+ return !!this._modules[name];
+ },
+ set: function(name, module) {
+ if (!(module instanceof Module))
+ throw new TypeError('Set must be a module');
+ this._modules[name] = module;
+ },
+ 'delete': function(name) {
+ return this._modules[name] ? delete this._modules[name] : false;
+ },
+ // NB implement iterations
+ entries: function() {
+ throw new TypeError('Iteration not yet implemented in the polyfill');
+ },
+ keys: function() {
+ throw new TypeError('Iteration not yet implemented in the polyfill');
+ },
+ values: function() {
+ throw new TypeError('Iteration not yet implemented in the polyfill');
+ },
+ normalize: function(name, refererName, refererAddress) {
+ return name;
+ },
+ locate: function(load) {
+ return load.name;
+ },
+ fetch: function(load) {
+ throw new TypeError('Fetch not implemented');
+ },
+ translate: function(load) {
+ return load.source;
+ },
+ instantiate: function(load) {
+ }
+ };
+
+ if (typeof exports === 'object') {
+ module.exports = Loader;
+ }
+
+ global.Loader || (global.Loader = Loader);
+ global.LoaderPolyfill = Loader;
+
+})(typeof global !== 'undefined' ? global : this);
View
45 lib/module.js
@@ -0,0 +1,45 @@
+(function (global) {
+ var defineProperty;
+ try {
+ if (!!Object.defineProperty({}, 'a', {})) {
+ defineProperty = Object.defineProperty;
+ }
+ } catch (e) {
+ defineProperty = function (obj, prop, opt) {
+ obj[prop] = opt.value || opt.get.call(obj);
+ }
+ }
+
+ // Module Object
+ function Module(obj) {
+ if (typeof obj != 'object')
+ throw new TypeError('Expected object');
+
+ if (!(this instanceof Module))
+ return new Module(obj);
+
+ var self = this;
+ for (var key in obj) {
+ (function (key, value) {
+ defineProperty(self, key, {
+ configurable: false,
+ enumerable: true,
+ get: function () {
+ return value;
+ }
+ });
+ })(key, obj[key]);
+ }
+ if (Object.preventExtensions)
+ Object.preventExtensions(this);
+ }
+ // Module.prototype = null;
+
+ if (typeof exports === 'object') {
+ module.exports = Module;
+ }
+
+ global.Module || (global.Module = Module);
+ global.ModulePolyfill = Module;
+
+})(typeof global !== 'undefined' ? global : this);
View
149 lib/promise.js
@@ -0,0 +1,149 @@
+(function (global) {
+ var isBrowser = typeof window != 'undefined';
+ var nextTick = isBrowser ? function(fn) { setTimeout(fn, 1); } : process.nextTick;
+ var Promise = global.Promise;
+ if (Promise) {
+ // check if native promises have what we need
+ if (Promise.all && Promise.resolve && Promise.reject) {
+ Promise = global.Promise;
+ var p = new Promise(function(r) {
+ if (typeof r != 'function')
+ Promise = null;
+ });
+ }
+ else
+ Promise = null;
+ }
+ // export the promises polyfill
+ if (!Promise) {
+ Promise = (function(setImmediate, func, obj) {
+ // Type checking utility function
+ function is(type, item) { return (typeof item)[0] == type; }
+
+ // Creates a promise, calling callback(resolve, reject), ignoring other parameters.
+ function Promise(callback, handler) {
+ // The `handler` variable points to the function that will
+ // 1) handle a .then(resolved, rejected) call
+ // 2) handle a resolve or reject call (if the first argument === `is`)
+ // Before 2), `handler` holds a queue of callbacks.
+ // After 2), `handler` is a finalized .then handler.
+ handler = function pendingHandler(resolved, rejected, value, queue, then, i) {
+ queue = pendingHandler.q;
+
+ // Case 1) handle a .then(resolved, rejected) call
+ if (resolved != is) {
+ return Promise(function(resolve, reject) {
+ queue.push({ p: this, r: resolve, j: reject, 1: resolved, 0: rejected });
+ });
+ }
+
+ // Case 2) handle a resolve or reject call
+ // (`resolved` === `is` acts as a sentinel)
+ // The actual function signature is
+ // .re[ject|solve](<is>, success, value)
+
+ // Check if the value is a promise and try to obtain its `then` method
+ if (value && (is(func, value) | is(obj, value))) {
+ try { then = value.then; }
+ catch (reason) { rejected = 0; value = reason; }
+ }
+ // If the value is a promise, take over its state
+ if (is(func, then)) {
+ function valueHandler(resolved) {
+ return function(value) { then && (then = 0, pendingHandler(is, resolved, value)); };
+ }
+ try { then.call(value, valueHandler(1), rejected = valueHandler(0)); }
+ catch (reason) { rejected(reason); }
+ }
+ // The value is not a promise; handle resolve/reject
+ else {
+ // Replace this handler with a finalized resolved/rejected handler
+ handler = createFinalizedThen(callback, value, rejected);
+ // Resolve/reject pending callbacks
+ i = 0;
+ while (i < queue.length) {
+ then = queue[i++];
+ // If no callback, just resolve/reject the promise
+ if (!is(func, resolved = then[rejected]))
+ (rejected ? then.r : then.j)(value);
+ // Otherwise, resolve/reject the promise with the result of the callback
+ else
+ finalize(then.p, then.r, then.j, value, resolved);
+ }
+ }
+ };
+ // The queue of pending callbacks; garbage-collected when handler is resolved/rejected
+ handler.q = [];
+
+ // Create and return the promise (reusing the callback variable)
+ callback.call(callback = { then: function (resolved, rejected) { return handler(resolved, rejected); },
+ 'catch': function (rejected) { return handler(0, rejected); } },
+ function(value) { handler(is, 1, value); },
+ function(reason) { handler(is, 0, reason); });
+ return callback;
+ }
+
+ // Creates a resolved or rejected .then function
+ function createFinalizedThen(promise, value, success) {
+ return function(resolved, rejected) {
+ // If the resolved or rejected parameter is not a function, return the original promise
+ if (!is(func, (resolved = success ? resolved : rejected)))
+ return promise;
+ // Otherwise, return a finalized promise, transforming the value with the function
+ return Promise(function(resolve, reject) { finalize(this, resolve, reject, value, resolved); });
+ };
+ }
+
+ // Finalizes the promise by resolving/rejecting it with the transformed value
+ function finalize(promise, resolve, reject, value, transform) {
+ setImmediate(function() {
+ try {
+ // Transform the value through and check whether it's a promise
+ value = transform(value);
+ transform = value && (is(obj, value) | is(func, value)) && value.then;
+ // Return the result if it's not a promise
+ if (!is(func, transform))
+ resolve(value);
+ // If it's a promise, make sure it's not circular
+ else if (value == promise)
+ reject(new TypeError());
+ // Take over the promise's state
+ else
+ transform.call(value, resolve, reject);
+ }
+ catch (error) { reject(error); }
+ });
+ }
+
+ // Export the main module
+ Promise.resolve = function (value) { return Promise(function (resolve) { resolve(value) }); };
+ Promise.reject = function (reason) { return Promise(function (resolve, reject) { reject(reason) }); };
+ Promise.all = function(promises) {
+ return new Promise(function(resolve, reject) {
+ if (!promises.length)
+ return setImmediate(resolve);
+
+ var outputs = [];
+ var resolved = 0;
+ for (var i = 0, l = promises.length; i < l; i++) (function(i) {
+ promises[i].then(function(resolvedVal) {
+ outputs[i] = resolvedVal;
+ resolved++;
+ if (resolved == promises.length)
+ resolve(outputs);
+ }, reject);
+ })(i);
+ });
+ }
+ return Promise;
+ })(nextTick, 'f', 'o');
+ }
+
+ if (typeof exports === 'object') {
+ module.exports = Promise;
+ }
+
+ global.Promise || (global.Promise = Promise);
+ global.PromisePolyfill = Promise;
+
+})(typeof global !== 'undefined' ? global : this);
View
646 lib/system.js
@@ -0,0 +1,646 @@
+/*
+*********************************************************************************************
+
+ System Loader Implementation
+
+ - Implemented to https://github.com/jorendorff/js-loaders/blob/master/browser-loader.js,
+ except for Instantiate function
+
+ - Instantiate function determines if ES6 module syntax is being used, if so parses with
+ Traceur and returns a dynamic InstantiateResult for loading ES6 module syntax in ES5.
+
+ - Custom loaders thus can be implemented by using this System.instantiate function as
+ the fallback loading scenario, after other module format detections.
+
+ - Traceur is loaded dynamically when module syntax is detected by a regex (with over-
+ classification), either from require('traceur') on the server, or the
+ 'data-traceur-src' property on the current script in the browser, or if not set,
+ 'traceur.js' in the same URL path as the current script in the browser.
+
+ - <script type="module"> supported, but <module> tag not
+
+*********************************************************************************************
+*/
+
+(function (global) {
+ var isBrowser = typeof window != 'undefined';
+ var Module = global.Module || require('./module.js');
+ var Loader = global.Loader || require('./loader.js');
+ var Promise = global.Promise || require('./promise.js');
+
+ // Helpers
+ // Absolute URL parsing, from https://gist.github.com/Yaffle/1088850
+ function parseURI(url) {
+ var m = String(url).replace(/^\s+|\s+$/g, '').match(/^([^:\/?#]+:)?(\/\/(?:[^:@]*(?::[^:@]*)?@)?(([^:\/?#]*)(?::(\d*))?))?([^?#]*)(\?[^#]*)?(#[\s\S]*)?/);
+ // authority = '//' + user + ':' + pass '@' + hostname + ':' port
+ return (m ? {
+ href : m[0] || '',
+ protocol : m[1] || '',
+ authority: m[2] || '',
+ host : m[3] || '',
+ hostname : m[4] || '',
+ port : m[5] || '',
+ pathname : m[6] || '',
+ search : m[7] || '',
+ hash : m[8] || ''
+ } : null);
+ }
+ function toAbsoluteURL(base, href) {
+ function removeDotSegments(input) {
+ var output = [];
+ input.replace(/^(\.\.?(\/|$))+/, '')
+ .replace(/\/(\.(\/|$))+/g, '/')
+ .replace(/\/\.\.$/, '/../')
+ .replace(/\/?[^\/]*/g, function (p) {
+ if (p === '/..')
+ output.pop();
+ else
+ output.push(p);
+ });
+ return output.join('').replace(/^\//, input.charAt(0) === '/' ? '/' : '');
+ }
+
+ href = parseURI(href || '');
+ base = parseURI(base || '');
+
+ return !href || !base ? null : (href.protocol || base.protocol) +
+ (href.protocol || href.authority ? href.authority : base.authority) +