1 // <script type="text/javascript">
2 XObject = imports.XObject.XObject;
3 File = imports.File.File;
5 TextStream = imports.JSDOC.TextStream.TextStream ;
6 TokenReader = imports.TokenReader.TokenReader;
7 ScopeParser = imports.ScopeParser.ScopeParser;
8 TokenStream = imports.TokenStream.TokenStream;
9 CompressWhite = imports.CompressWhite.CompressWhite;
10 Collapse = imports.Collapse.Collapse;
12 GLib = imports.gi.GLib;
26 Packer = imports['JSDOC/Packer.js'].Packer;
29 files : [ "/location/of/file1.js", "/location/of/file2.js", ... ],
30 target : "/tmp/output.js",
31 debugTarget : "/tmp/output.debug.js", // merged file without compression.
32 debugTranslateTarget : "/tmp/output.translate.js", // merged with translation
34 translateJSON: "/tmp/translate.json",
39 "/location/of/temp_batch_dir",
40 "/location/of/output-compacted-file.js",
41 "/location/of/output-debug-merged-file.js"
46 * Notes for improving compacting:
47 * if you add a jsdoc comment
54 * directly before an eval statement, it will compress all the code around the eval,
55 * and not rename the variables 'avarname'
57 * Dont try running this on a merged uncompressed large file - it's used to be horrifically slow. not sure about now..
58 * Best to use lot's of small classes, and use it to merge, as it will cache the compaction
62 * Notes for translation
63 * - translation relies on you using double quotes for strings if they need translating
64 * - single quoted strings are ignored.
66 * Generation of indexFiles
67 * - translateIndex = the indexfile
74 Packer = function(cfg)
77 XObject.extend(this, cfg);
79 if (this.srcfiles && this.srcfiles.length) {
80 this.srcfiles.forEach(function(f) {
81 _this.loadSourceFile(f);
93 function dateString(d){
94 function pad(n){return n<10 ? '0'+n : n}
95 return d.getFullYear() +
106 this.files.forEach(function(f) {
107 version = Math.max(File.mtime(f), version);
109 var version = dateString(new Date(version));
111 var dirname = GLib.path_get_dirname(this.files[0]);
112 var outname = this.module ? this.module : GLib.path_get_basename(dirname);
113 this.target = dirname + '/compiled/' + outname + '-' + version + '.js';
114 if (File.exists(this.target)) {
115 print("Target file already exists: " + this.target);
118 this.prefix = dirname +'/';
119 this.translateJSON = dirname + '/compiled/_translation_.js';
123 print(this.translateJSON);
124 this.timer = new Date() * 1;
135 * @cfg {String} srcfiles file containing a list of files/or classes to use.
140 * @cfg {Array} files list of files to compress (must be full path)
144 * @cfg {String} target to write files to - must be full path.
148 * @cfg {Boolean} autoBuild - turn on autobuild feature (puts files in compiled directory,
149 * and enables translation toolkit.
153 * @cfg {String} module used with autoBuild to force a file name
157 * @cfg {String} debugTarget target to write files debug version to (uncompacted)- must be full path.
159 debugTarget : '', // merged file without compression.
161 * @cfg {String} debugTranslateTarget target to write files debug version
162 * to (uncompacted) but with translation- must be full path.
165 debugTranslateTarget : '',
168 * @cfg {String} tmpDir (optional) where to put the temporary files.
169 * if you set this, then files will not be cleaned up
173 * json based list of strings in all files.
179 * @cfg {Boolean} cleanup (optional) clean up temp files after done -
180 * Defaults to false if you set tmpDir, otherwise true.
184 * @cfg {Boolean} keepWhite (optional) do not remove white space in output.
185 * usefull for debugging compressed files.
191 * @cfg {String} prefix (optional) prefix of directory to be stripped of when
192 * Calculating md5 of filename
195 out : '', // if no target is specified - then this will contain the result
198 * load a dependancy list -f option
199 * @param {String} srcfile sourcefile to parse
203 loadSourceFile : function(srcfile)
205 var lines = File.read(srcfile).split("\n");
207 lines.forEach(function(f) {
209 if (/^\s*\//.test(f) || !/[a-z]+/i.test(f)) { // skip comments..
212 if (/\.js$/.test(f)) {
213 _this.files.push( f);
218 //println("ADD"+ f.replace(/\./g, '/'));
219 var add = f.replace(/\./g, '/').replace(/\s+/g,'')+'.js';
220 if (_this.files.indexOf(f) > -1) {
223 _this.files.push( add );
229 packAll : function() // do the packing (run from constructor)
232 //this.transOrigFile= bpath + '/../lang.en.js'; // needs better naming...
233 //File.write(this.transfile, "");
235 File.write(this.target, "");
238 if (this.debugTarget) {
239 File.write(this.debugTarget, "");
241 if (this.debugTranslateTarget) {
242 File.write(this.debugTarget, "");
245 for(var i=0; i < this.files.length; i++) {
246 var file = this.files[i];
248 print("reading " +file );
249 if (!File.isFile(file)) {
250 print("SKIP (is not a file) " + file);
256 if (this.debugTarget) {
257 File.append(this.debugTarget, File.read(file));
259 // it's a good idea to check with 0 compression to see if the code can parse!!
262 //File.append(dout, str +"\n");
266 var minfile = this.tmpDir + '/' +file.replace(/\//g, '.');
269 // let's see if we have a min file already?
270 // this might happen if tmpDir is set ..
271 if (true && File.exists(minfile)) {
272 var mt = File.mtime(minfile);
273 var ot = File.mtime(file);
274 print("compare : " + mt + "=>" + ot);
282 print("COMPRESSING ");
283 //var codeComp = pack(str, 10, 0, 0);
284 if (File.exists(minfile)) {
285 File.remove(minfile);
287 var str = File.read(file);
288 var str = this.pack(str, file, minfile);
295 // if we are translating, write the translations strings at the top
298 if (this.translateJSON) {
301 print("MERGING LANGUAGE");
302 var out = "if (typeof(_T) == 'undefined') { _T={};}\n"
304 File.write(this.target, out);
309 File.write(this.translateJSON, "");
310 for(var i=0; i < this.files.length; i++) {
311 var file = this.files[i];
312 var transfile= this.tmpDir + '/' +file.replace(/\//g, '.') +'.lang.trans';
313 var transmd5 = this.tmpDir + '/' +file.replace(/\//g, '.') +'.lang';
314 if (File.exists(transmd5)) {
315 var str = File.read(transmd5);
318 File.append(this.target, str + "\n");
320 this.out += str + "\n";
325 File.remove(transmd5);
328 if (File.exists(transfile)) {
329 var str = File.read(transfile);
331 File.append(this.translateJSON, str);
334 File.remove(transfile);
342 print("MERGING SOURCE");
344 for(var i=0; i < this.files.length; i++) {
345 var file = this.files[i];
346 var minfile = this.tmpDir + '/' + file.replace(/\//g, '.');
349 if (!File.exists(minfile)) {
352 var str = File.read(minfile);
353 print("using MIN FILE "+ minfile);
356 File.append(this.target, str + "\n");
358 this.out += str + "\n";
363 File.remove(minfile);
367 print("Output file: " + this.target);
368 if (this.debugTarget) print("Output debug file: " + this.debugTarget);
375 * Core packing routine for a file
377 * @param str - str source text..
378 * @param fn - filename (for reference?)
379 * @param minfile - min file location...
383 pack : function (str,fn,minfile)
386 var tr = new TokenReader( {
391 collapseWhite : false,
394 this.timerPrint("START" + fn);
396 // we can load translation map here...
398 var toks = tr.tokenize(new TextStream(str)); // dont merge xxx + . + yyyy etc.
400 // at this point we can write a language file...
401 if (this.translateJSON) {
403 this.writeTranslateFile(fn, minfile, toks);
406 this.activeFile = fn;
408 // and replace if we are generating a different language..
410 this.timerPrint("Tokenized");
411 //var ts = new TokenStream(toks);
412 //print(JSON.stringify(toks, null,4 )); Seed.quit();
413 var ts = new Collapse(toks);
414 // print(JSON.stringify(ts.tokens, null,4 )); Seed.quit();
416 var sp = new ScopeParser(ts);
417 this.timerPrint("Converted to Parser");
419 sp.buildSymbolTree();
420 this.timerPrint("Built Sym tree");
421 sp.mungeSymboltree();
422 this.timerPrint("Munged Sym tree");
423 print(sp.warnings.join("\n"));
424 this.timerPrint("Compressed");
426 var out = CompressWhite(new TokenStream(toks), this, this.keepWhite); // do not kill whitespace..
429 this.timerPrint("Compressed");
432 File.write(minfile, out);
441 timerPrint: function (str) {
442 var ntime = new Date() * 1;
443 var tdif = ntime -this.timer;
445 print('['+tdif+']'+str);
450 * Translation concept...
451 * -> replace text strings with _T....
452 * -> this file will need inserting at the start of the application....
453 * -> we need to generate 2 files,
454 * -> a reference used to do the translation, and the _T file..
457 * We store the trsum on the token...
461 writeTranslateFile : function(fn, minfile, toks)
464 var map = {}; // 'string=> md5sum'
469 var tokfind = function (j,dir) {
471 if ((dir < 0) && (j < 0)) {
474 if ((dir > 0) && (j >= toks.length)) {
478 if (toks[j].type != 'WHIT') {
487 for (var i=0;i<toks.length;i++) {
490 if (t.type != 'STRN') {
493 if (t.name != 'DOUBLE_QUOTE') {
497 last = tokfind(i,-1);
498 next = tokfind(i,+1);
500 // we have to ignore key values on objects
503 // last == '{' or ',' and
507 next.type == 'PUNC' &&
510 last.type == 'PUNC' &&
511 (last.data == ',' || last.data == '{')
513 continue; // found object key... - we can not translate these
516 var sval = t.data.substring(1,t.data.length-1);
517 var ffn = fn.substring(_this.prefix.length);
519 t.trsum = _this.md5(ffn + '-' + sval);
527 var transfile = minfile + '.lang.trans';
528 var transmd5 = minfile + '.lang';
529 print("writeTranslateFile " + transfile);
532 if (File.exists(transfile)) {
533 File.remove(transfile);
535 if (File.exists(transmd5)) {
536 File.remove(transmd5);
538 for(v in map) { i++; break };
540 return; // no strings in file...
542 var ffn = fn.substring(this.prefix.length);
545 File.write(transfile, "\n'" + ffn + "' : {");
549 File.write(transmd5, '');
554 File.append(transfile, l + "\n\t\"" + v + "\" : \"" + v +"\"");
556 // strings are raw... - as the where encoded to start with!!!
557 // so we should not need to encode them again.. - just wrap with "
558 File.append(transmd5, '_T["' + this.md5(ffn + '-' + v) + '"]="'+v+"\";\n");
560 File.append(transfile, "\n},"); // always one trailing..
564 md5 : function (string)
567 return GLib.compute_checksum_for_string(GLib.ChecksumType.MD5, string, string.length);
570 stringHandler : function(tok)
572 //print("STRING HANDLER");
573 // callback when outputing compressed file,
575 if (!this.translateJSON) {
576 // print("TURNED OFF");
579 if (tok.name == 'SINGLE_QUOTE') {
583 if (typeof(tok.trsum) == 'undefined') {
587 return '_T["' + tok.trsum + '"]';
589 var sval = data.substring(1,data.length-1);
590 // we do not clean up... quoting here!??!!?!?!?!?
593 // blank with tabs or spaces..
594 //if (!sval.replace(new RegExp("(\\\\n|\\\\t| )+",'g'), '').length) {
595 // return tok.outData;
598 var sval = tok.data.substring(1,data.length-1);
599 var fn = this.activeFile.substring(this.prefix.length);
602 return '_T["' + this.md5(fn + '-' + sval) + '"]';