/*!# @license webfan (C) Till Wehowski, Webfan.de - All rights reserved. !*/
define([ 'webfan/es6-compiler', 'webfan/bootcache!amd-loader','webfan/bootcache!lit', 'feature!vm'], function(traceur, amdL, Lit, vm) {
console.log('es6Compiler traceur ', traceur);
let URL = global.URL || global.webkitURL;
let requestFileSystem = global.requestFileSystem || global.webkitRequestFileSystem;
let resolveLocalFileSystemURL = global.resolveLocalFileSystemURL || global.webkitResolveLocalFileSystemURL;
navigator.temporaryStorage = navigator.temporaryStorage || navigator.webkitTemporaryStorage;
navigator.persistentStorage = navigator.persistentStorage || navigator.webkitPersistentStorage;
let BlobBuilder = global.BlobBuilder || global.MozBlobBuilder || global.WebKitBlobBuilder;
requirejs.config({
map: {
'webfan/bootcache': {
'*': 'frdlcjs'
}
}
});
var CACHE_LIMIT_LOCAL_STORAGE = 24 * 60 * 60 * 1000;
var ext = 'js';
var cjsRequireRegExp = /\s*require\s*\(\s*["']([^'"\s]+)["']\s*\)/g;
var amdLoader = clone(amdL);
var plugin = amdLoader('frdlcjs', ext, ['js'], function(name, source, req, callback, errback, config) {
function parse_require_calls(Source){
var d = [];
var lit = clone(Lit);
// alert(JSON.stringify(lit));
lit.opts.identify_number_literals = true;
lit.opts.identify_simple_literals = true;
lit.opts.overlook_html_comment_markers = true;
var ast = lit.lex(Source);
var i = 0,
t = false,
tok = false,
Toks = [];
var _regex = /([^\n\,;!?\s{}=]+)/i;
var requiredUrls = [],
defineCalls = [],
reqUrl = false,
requireCall = false,
defineCall = false;
for (i = 0; i < ast.length - 1; i++) {
Toks = [];
tok = ast[i];
if (0 === tok.type) {
t = tok.val.split(_regex);
t.forEach( function(t, i) {
if ('' !== t && ' ' !== t)
Toks.push(t);
});
if('require(' === Toks[Toks.length - 1]) {
if (2 === ast[i + 1].type) {
reqUrl = ast[i + 1].val.substr(1, ast[i + 1].val.length - 2);
if (')' === ast[i + 2].val.substr(0, 1) || ',' === ast[i + 2].val.substr(0, 1)) {
requireCall = {
returnTok: Toks[Toks.length - 2],
url: reqUrl,
AstPosition : i + 1
};
requiredUrls.push(requireCall);
}
}
}else if('define(' === tok.val.substr(0, 'define('.length)){
//Toks[Toks.length - 1]){
//if (0 === ast[i + 1].type) {
defineCall = {
token : tok
};
defineCalls.push(defineCall);
// }
}
}
}
// alert(JSON.stringify(ast));
// alert(JSON.stringify(defineCalls));
// alert(JSON.stringify(requiredUrls));
var CompilerConfig = {
es6 : true,
defaultPlugin : 'frdlcjs',
defineWrap : true
};
var comment_lines = [];
var compiler_comments_directives = [];
ast.forEach( function(a, i) {
if(1!==parseInt(a.type))return;
// alert(JSON.stringify(a.val.split(/[\r\n]/)));
a.val.split(/[\r\n\t]+/) .forEach( function(c, j) {
comment_lines.push(c);
if(false!==strpos(c, '@')){
//alert(c);
c.replace(/@\s?([(){}.-_\w^@><]+)\s?:?([().-_><@\s\w]+)/, function(match, _type, _value, pos, all){
var Com = {
type : _type.trim(),
value : _value.trim()
};
// alert(JSON.stringify(Com));
compiler_comments_directives.push(Com);
return match;
});
}
});
});
compiler_comments_directives.forEach( function(d, i) {
if('no' === d.value.toLowerCase()
|| 'false' === d.value.toLowerCase()
|| 0 === parseInt(d.value)
){
d.value=false;
}else if('yes' === d.value.toLowerCase()
|| 'true' === d.value.toLowerCase()
|| 1 === parseInt(d.value)
){
d.value=true;
}
var p = explode('.', d.type);
if(p.length === 5
&& 'frdl' === p[0]
&& 'Frdlweb' === p[1]
&& 'js' === p[2]
&& 'Compiler' === p[3]
){
CompilerConfig[p[4]] = d.value;
}
});
if(false!==CompilerConfig.defaultPlugin) {
requiredUrls.forEach( function(r, i) {
var tok = CompilerConfig.defaultPlugin + '!';
if(tok!==r.url.substr(0, tok.length)){
var nUrl =tok + r.url;
// requiredUrls[i].url = 'frdlcjs!'+ r.url;
ast[parseInt(r.AstPosition)].val=str_replace(requiredUrls[i].url, nUrl, ast[parseInt(r.AstPosition)].val);
// alert(JSON.stringify(ast[parseInt(r.AstPosition)]));
}
});
}
// alert(JSON.stringify(ast));
Source = lit.generate(ast);
// source = 'define(function(require, exports, module){'+source+'});';
// source = 'define(function(require, exports, module) { var define=undefined;' + source + ' \n//# sourceURL=' + req.toUrl(name) + '\n });';
if((true=== CompilerConfig.defineWrap && 0===defineCalls.length && false!==strpos('exports', Source) )
){
Source = 'define("'+name+'", ["require", "exports", "module"], function( require,exports, module){\n'+Source+' \n//# sourceURL=' + req.toUrl(name) + '\n});';
console.log('No dedfine call ', Source, CompilerConfig, defineCalls, strpos('exports', Source) );
}else{
// Source = '{' + Source + '}';
Source=Source+' \n//# sourceURL=' + req.toUrl(name)+ '\n';
}
if(true!== !!CompilerConfig.es6){
var source =Source;
}else{//if(true!== !!CompilerConfig.es6)
var url = req.toUrl(name) + '.js';
var project = new traceur.semantics.symbols.Project(url);
// traceur.options = config.traceur;
traceur.options = clone(traceur.options);
traceur.options.sourceMaps = false;
// traceur.options.sourceMaps = true;
traceur.options.debug = true;
var reporter = new traceur.util.ErrorReporter();
reporter.reportMessageInternal = function(location, kind, format, args) {
errback(location + '\n ' + format + '\n ' + args + '\n');
}
try{
var source =Source;
var sourceFile = new traceur.syntax.SourceFile(name, source);
project.addFile(sourceFile);
var res = traceur.codegeneration.Compiler.compile(reporter, project, false);
// console.log('res compiled : ', res);
var options;
if (true === traceur.options.sourceMaps) {
var config = {file: 'traceured.js'};
var sourceMapGenerator = new traceur.outputgeneration.SourceMapGenerator(config);
options = {sourceMapGenerator: sourceMapGenerator};
}
source = traceur.outputgeneration.ProjectWriter.write(res, options);
if (true === traceur.options.sourceMaps) {
var sourceMap = JSON.parse(options.sourceMap);
//sourceMap.sourcesContent = [null, null, null, null];
// nb make this work
// source += '\n//@ sourceMappingURL=data:application/json;base64,' + frdl.base64_encode(JSON.stringify(options.sourceMap));
source += '\n//@ sourceMappingURL=data:application/json;base64,' +base64_encode(JSON.stringify(options.sourceMap));
// console.log('sourceMap: ', sourceMap);
}
}catch(err){
console.warn('Error transpiling from es6 : '+ name +' '+err);
var source = Source;
}
}
return {
source : source,
requiredUrls : requiredUrls,
countDefineCalls : defineCalls.length
};
}//if(true!== !!CompilerConfig.es6){}else{ }
function runIt(c, runItCallback){
function compile(s){
var _url = req.toUrl(name);
if(false===strpos(_url, '.js') && false===strpos(_url, '.css') && false===strpos(_url, '.html') && false===strpos(_url, '.xml')){
_url += '.js';
}
var parsed = false, mime = localStorage.getItem(_url+'#mime');
if(null !== mime){
mime = explode(';', mime)[0].trim();
}
// alert(mime);
if(null === mime || false !== strpos(mime, 'script') ){
parsed = parse_require_calls(s);
}else if(false !== strpos(mime, 'css') ){
alert('@ToDo : require->parse text/css ('+name+')');
}else if(false !== strpos(mime, 'html') ){
alert('@ToDo : require->parse text/html ('+name+')');
}else{
parsed = {
source : s
};
}
return parsed.source;
}
var r = runItCallback( c );
return r;
}//runIt
req.exec = require.exec /**/= function (js) {
function compile_after(code){
code = parse_require_calls(code).source;
return code;
}
var script = vm.createScript(js, {
filename : name,
compile : compile_after
});
var context = vm.createContext({
});
if('undefined'!==typeof frdl){
context.frdl=frdl;
if('undefined'!==typeof frdl.webfan){
context.webfan=frdl.webfan;
}
}
try{
return script.runInNewContext(context);
}catch(err){
console.error(err , script.code);
}
};
runIt(source, callback);
});
var _fetch = clone(amdLoader.fetch);
let hasLocalStorage = (function(){
var supported = false;
try{
supported = window && ("localStorage" in window) && ("getItem" in localStorage);
}catch(e){}
return supported;
})();
plugin.fetch = amdLoader.fetch = function(url, callback, errback) {
var path = url;
var cb = function(code){
if(
// 1===0 &&
'undefined'!==typeof frdl && 'undefined'!==typeof frdl.fs && 'function'===typeof frdl.fs.writeFile
&& true === frdl.fs.polyfill.check()
&& true === frdl.fs.polyfill.ready
){
frdl.fs.writeFile(path, base64_encode(code), console.warn);
frdl.fs.writeFile(path + '#meta', new Date().getTime(), console.warn);
}
try {
if('undefined'===typeof frdl || 'undefined'===typeof frdl.fs || 'function'!==typeof frdl.fs.writeFile
|| true !== frdl.fs.polyfill.check()
|| true !== frdl.fs.polyfill.ready
|| 16 > localStorage.length
){
localStorage.setItem(path, base64_encode(code));
localStorage.setItem(path + '#meta', new Date().getTime());
}
} catch(e) {
if(!!console)console.warn(e);
}
callback(code);
};
if (hasLocalStorage) {
var cached = localStorage.getItem(url);
var lt = localStorage.getItem(url + '#meta');
if (cached !== null && null !== lt && (CACHE_LIMIT_LOCAL_STORAGE>(new Date().getTime()-parseInt(lt)))) {
callback(base64_decode(cached));
return;
}
}
if ('undefined'!==typeof frdl && 'undefined'!==typeof frdl.fs && 'function'===typeof frdl.fs.readFile
&& true === frdl.fs.polyfill.check()
&& true === frdl.fs.polyfill.ready
) {
frdl.fs.readFile(url, function(e,cached){
if(e){
return _fetch(url, cb, errback);
return;
}
frdl.fs.readFile(url + '#meta', function(e_meta,d_meta){
if(e_meta){
return _fetch(url, cb, errback);
return;
}
if ('string'===typeof cached && 'string'===typeof d_meta && (CACHE_LIMIT_LOCAL_STORAGE>(new Date().getTime()-parseInt(d_meta)))) {
callback(base64_decode(cached));
return;
}
_fetch(url, cb, errback);
});
});
return;
} else{
_fetch(url, cb, errback);
}
};
function extend(from, to) {
if (from === null || typeof from !== 'object')
return from;
if (from.constructor !== Object && from.constructor !== Array)
return from;
if (from.constructor === Date || from.constructor === RegExp || from.constructor === Function || from.constructor === String || from.constructor === Number || from.constructor === Boolean)
return new from.constructor(from);
to = to || new from.constructor();
var name;
for (name in from) {
to[name] = typeof to[name] === 'undefined' ? extend(from[name], null) : to[name];
}
return to;
};
function clone(obj) {
var clone = extend(obj);
return clone;
};
function base64_encode(data) {
var b64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
var o1, o2, o3, h1, h2, h3, h4, bits, i = 0,
ac = 0,
enc = "",
tmp_arr = [];
if (!data) {
return data;
}
do {
o1 = data.charCodeAt(i++);
o2 = data.charCodeAt(i++);
o3 = data.charCodeAt(i++);
bits = o1 << 16 | o2 << 8 | o3;
h1 = bits >> 18 & 0x3f;
h2 = bits >> 12 & 0x3f;
h3 = bits >> 6 & 0x3f;
h4 = bits & 0x3f;
tmp_arr[ac++] = b64.charAt(h1) + b64.charAt(h2) + b64.charAt(h3) + b64.charAt(h4);
} while (i < data.length);
enc = tmp_arr.join('');
var r = data.length % 3;
return (r ? enc.slice(0, r - 3) : enc) + '==='.slice(r || 3);
}
function base64_decode(data) {
var b64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
var o1, o2, o3, h1, h2, h3, h4, bits, i = 0,
ac = 0,
dec = "",
tmp_arr = [];
if (!data) {
return data;
}
data += '';
do {
h1 = b64.indexOf(data.charAt(i++));
h2 = b64.indexOf(data.charAt(i++));
h3 = b64.indexOf(data.charAt(i++));
h4 = b64.indexOf(data.charAt(i++));
bits = h1 << 18 | h2 << 12 | h3 << 6 | h4;
o1 = bits >> 16 & 0xff;
o2 = bits >> 8 & 0xff;
o3 = bits & 0xff;
if (h3 == 64) {
tmp_arr[ac++] = String.fromCharCode(o1);
} else if (h4 == 64) {
tmp_arr[ac++] = String.fromCharCode(o1, o2);
} else {
tmp_arr[ac++] = String.fromCharCode(o1, o2, o3);
}
} while (i < data.length);
dec = tmp_arr.join('');
return dec;
}
function base64_detect(str) {
var base64Detect = new RegExp("^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=|[A-Za-z0-9+/]{4})$");
if (base64Detect.test(str)) {
return true;
} else {
return false;
}
}
function getFunctionBody(func){
return func.toString().trim().match(new RegExp("^function\s*\w*\s*\([\w\s,]*\)\s*{([\w\W]*?)}$"))[1];
}
function createJavascriptObjectURL(func){
var functionBody = getFunctionBody(func);
return URL.createObjectURL(new Blob([functionBody], {
type: "text/javascript"
}));
}
function strpos(haystack, needle, offset) {
var i = (haystack + '').indexOf(needle, (offset || 0));
return i === -1 ? false : i;
}
function str_replace(search, replace, subject) {
if ('string' !== typeof subject)
return '';
try {
return subject.split(search).join(replace);
} catch (err) {
console.error(err);
return '';
}
}
function explode(delimiter, string, limit) {
if (arguments.length < 2 || typeof delimiter === 'undefined' || typeof string === 'undefined')
return null;
if (delimiter === '' || delimiter === false || delimiter === null)
return false;
if (typeof delimiter === 'function' || typeof delimiter === 'object' || typeof string === 'function' || typeof string === 'object') {
return [0];
}
if (delimiter === true)
delimiter = '1';
delimiter += '';
string += '';
var s = string.split(delimiter);
if (typeof limit === 'undefined')
return s;
if (limit === 0)
limit = 1;
if (limit > 0) {
if (limit >= s.length)
return s;
return s.slice(0, limit - 1).concat([s.slice(limit - 1).join(delimiter)]);
}
if (-limit >= s.length)
return [];
s.splice(s.length + limit);
return s;
}
return plugin;
});
|