1 // <script type="text/javascript">
2 XObject = imports.XObject.XObject;
3 File = imports.File.File;
5 TextStream = imports.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;
24 Packer = imports['JSDOC/Packer.js'].Packer;
27 files : [ "/location/of/file1.js", "/location/of/file2.js", ... ],
28 target : "/tmp/output.js",
29 debugTarget : "/tmp/output.debug.js", // merged file without compression.
30 translateJSON: "/tmp/translate.json",
35 "/location/of/temp_batch_dir",
36 "/location/of/output-compacted-file.js",
37 "/location/of/output-debug-merged-file.js"
42 * Notes for improving compacting:
43 * if you add a jsdoc comment
50 * directly before an eval statement, it will compress all the code around the eval,
51 * and not rename the variables 'avarname'
53 * Dont try running this on a merged uncompressed large file - it's used to be horrifically slow. not sure about now..
54 * Best to use lot's of small classes, and use it to merge, as it will cache the compaction
58 * Notes for translation
59 * - translation relies on you using double quotes for strings if they need translating
60 * - single quoted strings are ignored.
62 * Generation of indexFiles
63 * - translateIndex = the indexfile
70 Packer = function(cfg)
73 XObject.extend(this, cfg);
75 if (this.srcfiles && this.srcfiles.length) {
76 this.srcfiles.forEach(function(f) {
77 _this.loadSourceFile(f);
88 this.files.forEach(function(f) {
89 version = Math.max(File.mtime(f), version);
91 var dirname = GLib.path_get_dirname(this.files[0]);
92 var outname = GLib.path_get_basename(this.files[0]);
93 this.target = dirname + '/compiled/' + outname + '-' + version + '.js';
95 this.translateJSON = dirname + '/compiled/_translation_.js';
100 this.timer = new Date() * 1;
107 * @prop srcfiles {String} file containing a list of files/or classes to use.
112 * @prop files {Array} list of files to compress (must be full path)
116 * @cfg {String} target to write files to - must be full path.
120 * @cfg {Boolean} autoBuild - turn on autobuild feature (puts files in compiled directory,
121 * and enables translation toolkit.
125 * @prop debugTarget {String} target to write files debug version to (uncompacted)- must be full path.
127 debugTarget : '', // merged file without compression.
129 * @prop tmpDir {String} (optional) where to put the temporary files.
130 * if you set this, then files will not be cleaned up
134 translateJSON : '', // json based list of strings in all files.
137 * @prop cleanup {Boolean} (optional) clean up temp files after done -
138 * Defaults to false if you set tmpDir, otherwise true.
143 * @prop prefix {String} (optional) prefix of directory to be stripped of when
144 * Calculating md5 of filename
147 out : '', // if no target is specified - then this will contain the result
150 * load a dependancy list -f option
151 * @param {String} srcfile sourcefile to parse
155 loadSourceFile : function(srcfile)
157 var lines = File.read(srcfile).split("\n");
159 lines.forEach(function(f) {
161 if (/^\s*\//.test(f) || !/[a-z]+/i.test(f)) { // skip comments..
164 if (/\.js$/.test(f)) {
165 _this.files.push( f);
170 //println("ADD"+ f.replace(/\./g, '/'));
171 var add = f.replace(/\./g, '/').replace(/\s+/g,'')+'.js';
172 if (_this.files.indexOf(f) > -1) {
175 _this.files.push( add );
181 packAll : function() // do the packing (run from constructor)
184 //this.transOrigFile= bpath + '/../lang.en.js'; // needs better naming...
185 //File.write(this.transfile, "");
187 File.write(this.target, "");
190 if (this.debugTarget) {
191 File.write(this.debugTarget, "");
194 for(var i=0; i < this.files.length; i++) {
195 var file = this.files[i];
197 print("reading " +file );
198 if (!File.isFile(file)) {
199 print("SKIP (is not a file) " + file);
203 if (this.debugTarget) {
204 File.append(this.debugTarget, File.read(file));
206 // it's a good idea to check with 0 compression to see if the code can parse!!
209 //File.append(dout, str +"\n");
213 var minfile = this.tmpDir + '/' +file.replace(/\//g, '.');
216 // let's see if we have a min file already?
217 // this might happen if tmpDir is set ..
218 if (true && File.exists(minfile)) {
219 var mt = File.mtime(minfile);
220 var ot = File.mtime(file);
221 print("compare : " + mt + "=>" + ot);
225 // then the min'files time is > than original..
226 var str = File.read(minfile);
227 print("using MIN FILE "+ minfile);
229 File.append(outpath, str + "\n");
238 print("COMPRESSING ");
239 //var codeComp = pack(str, 10, 0, 0);
240 if (File.exists(minfile)) {
241 File.remove(minfile);
243 var str = File.read(file);
244 var str = this.pack(str, file, minfile);
246 File.write(minfile, str);
252 if (this.translateJSON) {
255 print("MERGING LANGUAGE");
256 var out = "if (typeof(_T) == 'undefined') { _T={};}\n"
258 File.write(this.target, out);
265 File.write(this.translateJSON, "");
266 for(var i=0; i < this.files.length; i++) {
267 var file = this.files[i];
268 var transfile= this.tmpDir + '/' +file.replace(/\//g, '.') +'.lang.trans';
269 var transmd5 = this.tmpDir + '/' +file.replace(/\//g, '.') +'.lang';
270 if (File.exists(transmd5)) {
271 var str = File.read(transmd5);
274 File.append(this.target, str + "\n");
276 this.out += str + "\n";
281 File.remove(transmd5);
284 if (File.exists(transfile)) {
285 var str = File.read(transfile);
287 File.append(this.translateJSON, str);
290 File.remove(transfile);
298 print("MERGING SOURCE");
300 for(var i=0; i < this.files.length; i++) {
301 var file = this.files[i];
302 var minfile = this.tmpDir + '/' + file.replace(/\//g, '.');
305 if (!File.exists(minfile)) {
308 var str = File.read(minfile);
309 print("using MIN FILE "+ minfile);
312 File.append(this.target, str + "\n");
314 this.out += str + "\n";
319 File.remove(minfile);
329 * Core packing routine for a file
331 * @param str - str source text..
332 * @param fn - filename (for reference?)
333 * @param minfile - min file location...
337 pack : function (str,fn,minfile)
340 var tr = new TokenReader( {
345 collapseWhite : false
347 this.timerPrint("START" + fn);
349 // we can load translation map here...
351 var toks = tr.tokenize(new TextStream(str)); // dont merge xxx + . + yyyy etc.
353 // at this point we can write a language file...
354 if (this.translateJSON) {
356 this.writeTranslateFile(fn, minfile, toks);
359 this.activeFile = fn;
361 // and replace if we are generating a different language..
363 this.timerPrint("Tokenized");
364 //var ts = new TokenStream(toks);
365 //print(JSON.stringify(toks, null,4 )); Seed.quit();
366 var ts = new Collapse(toks);
367 // print(JSON.stringify(ts.tokens, null,4 )); Seed.quit();
369 var sp = new ScopeParser(ts);
370 this.timerPrint("Converted to Parser");
372 sp.buildSymbolTree();
373 this.timerPrint("Built Sym tree");
374 sp.mungeSymboltree();
375 this.timerPrint("Munged Sym tree");
376 print(sp.warnings.join("\n"));
379 //var out = CompressWhite(new TokenStream(toks), this, true); // do not kill whitespace..
380 var out = CompressWhite(new TokenStream(toks), this, false);
381 this.timerPrint("Compressed");
388 timerPrint: function (str) {
389 var ntime = new Date() * 1;
390 var tdif = ntime -this.timer;
392 print('['+tdif+']'+str);
397 * Translation concept...
398 * -> replace text strings with _T....
399 * -> this file will need inserting at the start of the application....
400 * -> we need to generate 2 files,
401 * -> a reference used to do the translation, and the _T file..
405 writeTranslateFile : function(fn, minfile, toks)
410 toks.forEach(function (t) {
411 if (t.type == 'STRN' && t.name == 'DOUBLE_QUOTE') {
412 var sval = t.data.substring(1,t.data.length-1);
413 var ffn = fn.substring(_this.prefix.length);
414 map[sval] = _this.md5(ffn + '-' + sval);
418 var transfile = minfile + '.lang.trans';
419 var transmd5 = minfile + '.lang';
420 print("writeTranslateFile " + transfile);
423 if (File.exists(transfile)) {
424 File.remove(transfile);
426 if (File.exists(transmd5)) {
427 File.remove(transmd5);
429 for(v in map) { i++; break };
431 return; // no strings in file...
433 var ffn = fn.substring(this.prefix.length);
436 File.write(transfile, "\n'" + ffn + "' : {");
440 File.write(transmd5, '');
442 File.append(transfile, l + "\n\t \"" + v + '" : "' + v + '"');
444 // strings are raw... - as the where encoded to start with!!!
445 File.append(transmd5, '_T["' + this.md5(ffn + '-' + v) + '"]="'+v+"\";\n");
447 File.append(transfile, "\n},"); // always one trailing..
451 md5 : function (string)
454 return GLib.compute_checksum_for_string(GLib.ChecksumType.MD5, string, string.length);
457 stringHandler : function(tok)
459 //print("STRING HANDLER");
460 // callback when outputing compressed file,
462 if (!this.translateJSON) {
463 // print("TURNED OFF");
466 if (tok.name == 'SINGLE_QUOTE') {
470 var sval = data.substring(1,data.length-1);
471 // we do not clean up... quoting here!??!!?!?!?!?
474 // blank with tabs or spaces..
475 //if (!sval.replace(new RegExp("(\\\\n|\\\\t| )+",'g'), '').length) {
476 // return tok.outData;
479 var sval = tok.data.substring(1,data.length-1);
480 var fn = this.activeFile.substring(this.prefix.length);
483 return '_T["' + this.md5(fn + '-' + sval) + '"]';