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(dirname);
93 this.target = dirname + '/compiled/' + outname + '-' + version + '.js';
94 if (File.exists(this.target)) {
95 print("Target file already exists");
98 this.prefix = dirname +'/';
99 this.translateJSON = dirname + '/compiled/_translation_.js';
104 this.timer = new Date() * 1;
111 * @prop srcfiles {String} file containing a list of files/or classes to use.
116 * @prop files {Array} list of files to compress (must be full path)
120 * @cfg {String} target to write files to - must be full path.
124 * @cfg {Boolean} autoBuild - turn on autobuild feature (puts files in compiled directory,
125 * and enables translation toolkit.
129 * @prop debugTarget {String} target to write files debug version to (uncompacted)- must be full path.
131 debugTarget : '', // merged file without compression.
133 * @prop tmpDir {String} (optional) where to put the temporary files.
134 * if you set this, then files will not be cleaned up
138 translateJSON : '', // json based list of strings in all files.
141 * @prop cleanup {Boolean} (optional) clean up temp files after done -
142 * Defaults to false if you set tmpDir, otherwise true.
147 * @prop prefix {String} (optional) prefix of directory to be stripped of when
148 * Calculating md5 of filename
151 out : '', // if no target is specified - then this will contain the result
154 * load a dependancy list -f option
155 * @param {String} srcfile sourcefile to parse
159 loadSourceFile : function(srcfile)
161 var lines = File.read(srcfile).split("\n");
163 lines.forEach(function(f) {
165 if (/^\s*\//.test(f) || !/[a-z]+/i.test(f)) { // skip comments..
168 if (/\.js$/.test(f)) {
169 _this.files.push( f);
174 //println("ADD"+ f.replace(/\./g, '/'));
175 var add = f.replace(/\./g, '/').replace(/\s+/g,'')+'.js';
176 if (_this.files.indexOf(f) > -1) {
179 _this.files.push( add );
185 packAll : function() // do the packing (run from constructor)
188 //this.transOrigFile= bpath + '/../lang.en.js'; // needs better naming...
189 //File.write(this.transfile, "");
191 File.write(this.target, "");
194 if (this.debugTarget) {
195 File.write(this.debugTarget, "");
198 for(var i=0; i < this.files.length; i++) {
199 var file = this.files[i];
201 print("reading " +file );
202 if (!File.isFile(file)) {
203 print("SKIP (is not a file) " + file);
207 if (this.debugTarget) {
208 File.append(this.debugTarget, File.read(file));
210 // it's a good idea to check with 0 compression to see if the code can parse!!
213 //File.append(dout, str +"\n");
217 var minfile = this.tmpDir + '/' +file.replace(/\//g, '.');
220 // let's see if we have a min file already?
221 // this might happen if tmpDir is set ..
222 if (true && File.exists(minfile)) {
223 var mt = File.mtime(minfile);
224 var ot = File.mtime(file);
225 print("compare : " + mt + "=>" + ot);
229 // then the min'files time is > than original..
230 var str = File.read(minfile);
231 print("using MIN FILE "+ minfile);
233 File.append(outpath, str + "\n");
242 print("COMPRESSING ");
243 //var codeComp = pack(str, 10, 0, 0);
244 if (File.exists(minfile)) {
245 File.remove(minfile);
247 var str = File.read(file);
248 var str = this.pack(str, file, minfile);
250 File.write(minfile, str);
256 if (this.translateJSON) {
259 print("MERGING LANGUAGE");
260 var out = "if (typeof(_T) == 'undefined') { _T={};}\n"
262 File.write(this.target, out);
269 File.write(this.translateJSON, "");
270 for(var i=0; i < this.files.length; i++) {
271 var file = this.files[i];
272 var transfile= this.tmpDir + '/' +file.replace(/\//g, '.') +'.lang.trans';
273 var transmd5 = this.tmpDir + '/' +file.replace(/\//g, '.') +'.lang';
274 if (File.exists(transmd5)) {
275 var str = File.read(transmd5);
278 File.append(this.target, str + "\n");
280 this.out += str + "\n";
285 File.remove(transmd5);
288 if (File.exists(transfile)) {
289 var str = File.read(transfile);
291 File.append(this.translateJSON, str);
294 File.remove(transfile);
302 print("MERGING SOURCE");
304 for(var i=0; i < this.files.length; i++) {
305 var file = this.files[i];
306 var minfile = this.tmpDir + '/' + file.replace(/\//g, '.');
309 if (!File.exists(minfile)) {
312 var str = File.read(minfile);
313 print("using MIN FILE "+ minfile);
316 File.append(this.target, str + "\n");
318 this.out += str + "\n";
323 File.remove(minfile);
333 * Core packing routine for a file
335 * @param str - str source text..
336 * @param fn - filename (for reference?)
337 * @param minfile - min file location...
341 pack : function (str,fn,minfile)
344 var tr = new TokenReader( {
349 collapseWhite : false
351 this.timerPrint("START" + fn);
353 // we can load translation map here...
355 var toks = tr.tokenize(new TextStream(str)); // dont merge xxx + . + yyyy etc.
357 // at this point we can write a language file...
358 if (this.translateJSON) {
360 this.writeTranslateFile(fn, minfile, toks);
363 this.activeFile = fn;
365 // and replace if we are generating a different language..
367 this.timerPrint("Tokenized");
368 //var ts = new TokenStream(toks);
369 //print(JSON.stringify(toks, null,4 )); Seed.quit();
370 var ts = new Collapse(toks);
371 // print(JSON.stringify(ts.tokens, null,4 )); Seed.quit();
373 var sp = new ScopeParser(ts);
374 this.timerPrint("Converted to Parser");
376 sp.buildSymbolTree();
377 this.timerPrint("Built Sym tree");
378 sp.mungeSymboltree();
379 this.timerPrint("Munged Sym tree");
380 print(sp.warnings.join("\n"));
383 //var out = CompressWhite(new TokenStream(toks), this, true); // do not kill whitespace..
384 var out = CompressWhite(new TokenStream(toks), this, false);
385 this.timerPrint("Compressed");
392 timerPrint: function (str) {
393 var ntime = new Date() * 1;
394 var tdif = ntime -this.timer;
396 print('['+tdif+']'+str);
401 * Translation concept...
402 * -> replace text strings with _T....
403 * -> this file will need inserting at the start of the application....
404 * -> we need to generate 2 files,
405 * -> a reference used to do the translation, and the _T file..
409 writeTranslateFile : function(fn, minfile, toks)
414 toks.forEach(function (t) {
415 if (t.type == 'STRN' && t.name == 'DOUBLE_QUOTE') {
416 var sval = t.data.substring(1,t.data.length-1);
417 var ffn = fn.substring(_this.prefix.length);
418 map[sval] = _this.md5(ffn + '-' + sval);
422 var transfile = minfile + '.lang.trans';
423 var transmd5 = minfile + '.lang';
424 print("writeTranslateFile " + transfile);
427 if (File.exists(transfile)) {
428 File.remove(transfile);
430 if (File.exists(transmd5)) {
431 File.remove(transmd5);
433 for(v in map) { i++; break };
435 return; // no strings in file...
437 var ffn = fn.substring(this.prefix.length);
440 File.write(transfile, "\n'" + ffn + "' : {");
444 File.write(transmd5, '');
446 File.append(transfile, l + "\n\t \"" + v + '" : "' + v + '"');
448 // strings are raw... - as the where encoded to start with!!!
449 File.append(transmd5, '_T["' + this.md5(ffn + '-' + v) + '"]="'+v+"\";\n");
451 File.append(transfile, "\n},"); // always one trailing..
455 md5 : function (string)
458 return GLib.compute_checksum_for_string(GLib.ChecksumType.MD5, string, string.length);
461 stringHandler : function(tok)
463 //print("STRING HANDLER");
464 // callback when outputing compressed file,
466 if (!this.translateJSON) {
467 // print("TURNED OFF");
470 if (tok.name == 'SINGLE_QUOTE') {
474 var sval = data.substring(1,data.length-1);
475 // we do not clean up... quoting here!??!!?!?!?!?
478 // blank with tabs or spaces..
479 //if (!sval.replace(new RegExp("(\\\\n|\\\\t| )+",'g'), '').length) {
480 // return tok.outData;
483 var sval = tok.data.substring(1,data.length-1);
484 var fn = this.activeFile.substring(this.prefix.length);
487 return '_T["' + this.md5(fn + '-' + sval) + '"]';