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;
25 Packer = imports['JSDOC/Packer.js'].Packer;
28 files : [ "/location/of/file1.js", "/location/of/file2.js", ... ],
29 target : "/tmp/output.js",
30 debugTarget : "/tmp/output.debug.js", // merged file without compression.
31 debugTranslateTarget : "/tmp/output.translate.js", // merged with translation
32 translateJSON: "/tmp/translate.json",
37 "/location/of/temp_batch_dir",
38 "/location/of/output-compacted-file.js",
39 "/location/of/output-debug-merged-file.js"
44 * Notes for improving compacting:
45 * if you add a jsdoc comment
52 * directly before an eval statement, it will compress all the code around the eval,
53 * and not rename the variables 'avarname'
55 * Dont try running this on a merged uncompressed large file - it's used to be horrifically slow. not sure about now..
56 * Best to use lot's of small classes, and use it to merge, as it will cache the compaction
60 * Notes for translation
61 * - translation relies on you using double quotes for strings if they need translating
62 * - single quoted strings are ignored.
64 * Generation of indexFiles
65 * - translateIndex = the indexfile
72 Packer = function(cfg)
75 XObject.extend(this, cfg);
77 if (this.srcfiles && this.srcfiles.length) {
78 this.srcfiles.forEach(function(f) {
79 _this.loadSourceFile(f);
91 function dateString(d){
92 function pad(n){return n<10 ? '0'+n : n}
93 return d.getFullYear() +
104 this.files.forEach(function(f) {
105 version = Math.max(File.mtime(f), version);
107 var version = dateString(new Date(version));
109 var dirname = GLib.path_get_dirname(this.files[0]);
110 var outname = this.module ? this.module : GLib.path_get_basename(dirname);
111 this.target = dirname + '/compiled/' + outname + '-' + version + '.js';
112 if (File.exists(this.target)) {
113 print("Target file already exists: " + this.target);
116 this.prefix = dirname +'/';
117 this.translateJSON = dirname + '/compiled/_translation_.js';
121 print(this.translateJSON);
122 this.timer = new Date() * 1;
131 * @cfg {String} srcfiles file containing a list of files/or classes to use.
136 * @cfg {Array} files list of files to compress (must be full path)
140 * @cfg {String} target to write files to - must be full path.
144 * @cfg {Boolean} autoBuild - turn on autobuild feature (puts files in compiled directory,
145 * and enables translation toolkit.
149 * @cfg {String} module used with autoBuild to force a file name
153 * @cfg {String} debugTargettarget to write files debug version to (uncompacted)- must be full path.
155 debugTarget : '', // merged file without compression.
157 * @cfg {String} tmpDir (optional) where to put the temporary files.
158 * if you set this, then files will not be cleaned up
162 translateJSON : '', // json based list of strings in all files.
165 * @cfg {Boolean} cleanup (optional) clean up temp files after done -
166 * Defaults to false if you set tmpDir, otherwise true.
170 * @cfg {Boolean} keepWhite (optional) do not remove white space in output.
171 * usefull for debugging compressed files.
177 * @cfg {String} prefix (optional) prefix of directory to be stripped of when
178 * Calculating md5 of filename
181 out : '', // if no target is specified - then this will contain the result
184 * load a dependancy list -f option
185 * @param {String} srcfile sourcefile to parse
189 loadSourceFile : function(srcfile)
191 var lines = File.read(srcfile).split("\n");
193 lines.forEach(function(f) {
195 if (/^\s*\//.test(f) || !/[a-z]+/i.test(f)) { // skip comments..
198 if (/\.js$/.test(f)) {
199 _this.files.push( f);
204 //println("ADD"+ f.replace(/\./g, '/'));
205 var add = f.replace(/\./g, '/').replace(/\s+/g,'')+'.js';
206 if (_this.files.indexOf(f) > -1) {
209 _this.files.push( add );
215 packAll : function() // do the packing (run from constructor)
218 //this.transOrigFile= bpath + '/../lang.en.js'; // needs better naming...
219 //File.write(this.transfile, "");
221 File.write(this.target, "");
224 if (this.debugTarget) {
225 File.write(this.debugTarget, "");
228 for(var i=0; i < this.files.length; i++) {
229 var file = this.files[i];
231 print("reading " +file );
232 if (!File.isFile(file)) {
233 print("SKIP (is not a file) " + file);
239 if (this.debugTarget) {
240 File.append(this.debugTarget, File.read(file));
242 // it's a good idea to check with 0 compression to see if the code can parse!!
245 //File.append(dout, str +"\n");
249 var minfile = this.tmpDir + '/' +file.replace(/\//g, '.');
252 // let's see if we have a min file already?
253 // this might happen if tmpDir is set ..
254 if (true && File.exists(minfile)) {
255 var mt = File.mtime(minfile);
256 var ot = File.mtime(file);
257 print("compare : " + mt + "=>" + ot);
265 print("COMPRESSING ");
266 //var codeComp = pack(str, 10, 0, 0);
267 if (File.exists(minfile)) {
268 File.remove(minfile);
270 var str = File.read(file);
271 var str = this.pack(str, file, minfile);
273 File.write(minfile, str);
279 if (this.translateJSON) {
282 print("MERGING LANGUAGE");
283 var out = "if (typeof(_T) == 'undefined') { _T={};}\n"
285 File.write(this.target, out);
292 File.write(this.translateJSON, "");
293 for(var i=0; i < this.files.length; i++) {
294 var file = this.files[i];
295 var transfile= this.tmpDir + '/' +file.replace(/\//g, '.') +'.lang.trans';
296 var transmd5 = this.tmpDir + '/' +file.replace(/\//g, '.') +'.lang';
297 if (File.exists(transmd5)) {
298 var str = File.read(transmd5);
301 File.append(this.target, str + "\n");
303 this.out += str + "\n";
308 File.remove(transmd5);
311 if (File.exists(transfile)) {
312 var str = File.read(transfile);
314 File.append(this.translateJSON, str);
317 File.remove(transfile);
325 print("MERGING SOURCE");
327 for(var i=0; i < this.files.length; i++) {
328 var file = this.files[i];
329 var minfile = this.tmpDir + '/' + file.replace(/\//g, '.');
332 if (!File.exists(minfile)) {
335 var str = File.read(minfile);
336 print("using MIN FILE "+ minfile);
339 File.append(this.target, str + "\n");
341 this.out += str + "\n";
346 File.remove(minfile);
350 print("Output file: " + this.target);
351 if (this.debugTarget) print("Output debug file: " + this.debugTarget);
358 * Core packing routine for a file
360 * @param str - str source text..
361 * @param fn - filename (for reference?)
362 * @param minfile - min file location...
366 pack : function (str,fn,minfile)
369 var tr = new TokenReader( {
374 collapseWhite : false,
377 this.timerPrint("START" + fn);
379 // we can load translation map here...
381 var toks = tr.tokenize(new TextStream(str)); // dont merge xxx + . + yyyy etc.
383 // at this point we can write a language file...
384 if (this.translateJSON) {
386 this.writeTranslateFile(fn, minfile, toks);
389 this.activeFile = fn;
391 // and replace if we are generating a different language..
393 this.timerPrint("Tokenized");
394 //var ts = new TokenStream(toks);
395 //print(JSON.stringify(toks, null,4 )); Seed.quit();
396 var ts = new Collapse(toks);
397 // print(JSON.stringify(ts.tokens, null,4 )); Seed.quit();
399 var sp = new ScopeParser(ts);
400 this.timerPrint("Converted to Parser");
402 sp.buildSymbolTree();
403 this.timerPrint("Built Sym tree");
404 sp.mungeSymboltree();
405 this.timerPrint("Munged Sym tree");
406 print(sp.warnings.join("\n"));
409 var out = CompressWhite(new TokenStream(toks), this, this.keepWhite); // do not kill whitespace..
412 this.timerPrint("Compressed");
419 timerPrint: function (str) {
420 var ntime = new Date() * 1;
421 var tdif = ntime -this.timer;
423 print('['+tdif+']'+str);
428 * Translation concept...
429 * -> replace text strings with _T....
430 * -> this file will need inserting at the start of the application....
431 * -> we need to generate 2 files,
432 * -> a reference used to do the translation, and the _T file..
436 writeTranslateFile : function(fn, minfile, toks)
441 toks.forEach(function (t) {
442 if (t.type == 'STRN' && t.name == 'DOUBLE_QUOTE') {
443 var sval = t.data.substring(1,t.data.length-1);
444 var ffn = fn.substring(_this.prefix.length);
445 map[sval] = _this.md5(ffn + '-' + sval);
449 var transfile = minfile + '.lang.trans';
450 var transmd5 = minfile + '.lang';
451 print("writeTranslateFile " + transfile);
454 if (File.exists(transfile)) {
455 File.remove(transfile);
457 if (File.exists(transmd5)) {
458 File.remove(transmd5);
460 for(v in map) { i++; break };
462 return; // no strings in file...
464 var ffn = fn.substring(this.prefix.length);
467 File.write(transfile, "\n'" + ffn + "' : {");
471 File.write(transmd5, '');
476 File.append(transfile, l + "\n\t" + JSON.stringify(v) + " : " + JSON.stringify(v));
478 // strings are raw... - as the where encoded to start with!!!
479 File.append(transmd5, '_T["' + this.md5(ffn + '-' + v) + '"]='+JSON.stringify(v)+";\n");
481 File.append(transfile, "\n},"); // always one trailing..
485 md5 : function (string)
488 return GLib.compute_checksum_for_string(GLib.ChecksumType.MD5, string, string.length);
491 stringHandler : function(tok)
493 //print("STRING HANDLER");
494 // callback when outputing compressed file,
496 if (!this.translateJSON) {
497 // print("TURNED OFF");
500 if (tok.name == 'SINGLE_QUOTE') {
504 var sval = data.substring(1,data.length-1);
505 // we do not clean up... quoting here!??!!?!?!?!?
508 // blank with tabs or spaces..
509 //if (!sval.replace(new RegExp("(\\\\n|\\\\t| )+",'g'), '').length) {
510 // return tok.outData;
513 var sval = tok.data.substring(1,data.length-1);
514 var fn = this.activeFile.substring(this.prefix.length);
517 return '_T["' + this.md5(fn + '-' + sval) + '"]';