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 = this.module ? this.module : 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 * @cfg {String} srcfiles file containing a list of files/or classes to use.
116 * @cfg {Array} files 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 * @cfg {String} module used with autoBuild to force a file name
133 * @cfg {String} debugTargettarget to write files debug version to (uncompacted)- must be full path.
135 debugTarget : '', // merged file without compression.
137 * @cfg {String} tmpDir (optional) where to put the temporary files.
138 * if you set this, then files will not be cleaned up
142 translateJSON : '', // json based list of strings in all files.
145 * @cfg {Boolean} cleanup (optional) clean up temp files after done -
146 * Defaults to false if you set tmpDir, otherwise true.
151 * @cfg {String} prefix (optional) prefix of directory to be stripped of when
152 * Calculating md5 of filename
155 out : '', // if no target is specified - then this will contain the result
158 * load a dependancy list -f option
159 * @param {String} srcfile sourcefile to parse
163 loadSourceFile : function(srcfile)
165 var lines = File.read(srcfile).split("\n");
167 lines.forEach(function(f) {
169 if (/^\s*\//.test(f) || !/[a-z]+/i.test(f)) { // skip comments..
172 if (/\.js$/.test(f)) {
173 _this.files.push( f);
178 //println("ADD"+ f.replace(/\./g, '/'));
179 var add = f.replace(/\./g, '/').replace(/\s+/g,'')+'.js';
180 if (_this.files.indexOf(f) > -1) {
183 _this.files.push( add );
189 packAll : function() // do the packing (run from constructor)
192 //this.transOrigFile= bpath + '/../lang.en.js'; // needs better naming...
193 //File.write(this.transfile, "");
195 File.write(this.target, "");
198 if (this.debugTarget) {
199 File.write(this.debugTarget, "");
202 for(var i=0; i < this.files.length; i++) {
203 var file = this.files[i];
205 print("reading " +file );
206 if (!File.isFile(file)) {
207 print("SKIP (is not a file) " + file);
211 if (this.debugTarget) {
212 File.append(this.debugTarget, File.read(file));
214 // it's a good idea to check with 0 compression to see if the code can parse!!
217 //File.append(dout, str +"\n");
221 var minfile = this.tmpDir + '/' +file.replace(/\//g, '.');
224 // let's see if we have a min file already?
225 // this might happen if tmpDir is set ..
226 if (true && File.exists(minfile)) {
227 var mt = File.mtime(minfile);
228 var ot = File.mtime(file);
229 print("compare : " + mt + "=>" + ot);
233 // then the min'files time is > than original..
234 var str = File.read(minfile);
235 print("using MIN FILE "+ minfile);
237 File.append(outpath, str + "\n");
246 print("COMPRESSING ");
247 //var codeComp = pack(str, 10, 0, 0);
248 if (File.exists(minfile)) {
249 File.remove(minfile);
251 var str = File.read(file);
252 var str = this.pack(str, file, minfile);
254 File.write(minfile, str);
260 if (this.translateJSON) {
263 print("MERGING LANGUAGE");
264 var out = "if (typeof(_T) == 'undefined') { _T={};}\n"
266 File.write(this.target, out);
273 File.write(this.translateJSON, "");
274 for(var i=0; i < this.files.length; i++) {
275 var file = this.files[i];
276 var transfile= this.tmpDir + '/' +file.replace(/\//g, '.') +'.lang.trans';
277 var transmd5 = this.tmpDir + '/' +file.replace(/\//g, '.') +'.lang';
278 if (File.exists(transmd5)) {
279 var str = File.read(transmd5);
282 File.append(this.target, str + "\n");
284 this.out += str + "\n";
289 File.remove(transmd5);
292 if (File.exists(transfile)) {
293 var str = File.read(transfile);
295 File.append(this.translateJSON, str);
298 File.remove(transfile);
306 print("MERGING SOURCE");
308 for(var i=0; i < this.files.length; i++) {
309 var file = this.files[i];
310 var minfile = this.tmpDir + '/' + file.replace(/\//g, '.');
313 if (!File.exists(minfile)) {
316 var str = File.read(minfile);
317 print("using MIN FILE "+ minfile);
320 File.append(this.target, str + "\n");
322 this.out += str + "\n";
327 File.remove(minfile);
337 * Core packing routine for a file
339 * @param str - str source text..
340 * @param fn - filename (for reference?)
341 * @param minfile - min file location...
345 pack : function (str,fn,minfile)
348 var tr = new TokenReader( {
353 collapseWhite : false
355 this.timerPrint("START" + fn);
357 // we can load translation map here...
359 var toks = tr.tokenize(new TextStream(str)); // dont merge xxx + . + yyyy etc.
361 // at this point we can write a language file...
362 if (this.translateJSON) {
364 this.writeTranslateFile(fn, minfile, toks);
367 this.activeFile = fn;
369 // and replace if we are generating a different language..
371 this.timerPrint("Tokenized");
372 //var ts = new TokenStream(toks);
373 //print(JSON.stringify(toks, null,4 )); Seed.quit();
374 var ts = new Collapse(toks);
375 // print(JSON.stringify(ts.tokens, null,4 )); Seed.quit();
377 var sp = new ScopeParser(ts);
378 this.timerPrint("Converted to Parser");
380 sp.buildSymbolTree();
381 this.timerPrint("Built Sym tree");
382 sp.mungeSymboltree();
383 this.timerPrint("Munged Sym tree");
384 print(sp.warnings.join("\n"));
387 //var out = CompressWhite(new TokenStream(toks), this, true); // do not kill whitespace..
388 var out = CompressWhite(new TokenStream(toks), this, false);
389 this.timerPrint("Compressed");
396 timerPrint: function (str) {
397 var ntime = new Date() * 1;
398 var tdif = ntime -this.timer;
400 print('['+tdif+']'+str);
405 * Translation concept...
406 * -> replace text strings with _T....
407 * -> this file will need inserting at the start of the application....
408 * -> we need to generate 2 files,
409 * -> a reference used to do the translation, and the _T file..
413 writeTranslateFile : function(fn, minfile, toks)
418 toks.forEach(function (t) {
419 if (t.type == 'STRN' && t.name == 'DOUBLE_QUOTE') {
420 var sval = t.data.substring(1,t.data.length-1);
421 var ffn = fn.substring(_this.prefix.length);
422 map[sval] = _this.md5(ffn + '-' + sval);
426 var transfile = minfile + '.lang.trans';
427 var transmd5 = minfile + '.lang';
428 print("writeTranslateFile " + transfile);
431 if (File.exists(transfile)) {
432 File.remove(transfile);
434 if (File.exists(transmd5)) {
435 File.remove(transmd5);
437 for(v in map) { i++; break };
439 return; // no strings in file...
441 var ffn = fn.substring(this.prefix.length);
444 File.write(transfile, "\n'" + ffn + "' : {");
448 File.write(transmd5, '');
453 File.append(transfile, l + "\n\t" + JSON.stringify(v) + " : " + JSON.stringify(v));
455 // strings are raw... - as the where encoded to start with!!!
456 File.append(transmd5, '_T["' + this.md5(ffn + '-' + v) + '"]='+JSON.stringify(v)+";\n");
458 File.append(transfile, "\n},"); // always one trailing..
462 md5 : function (string)
465 return GLib.compute_checksum_for_string(GLib.ChecksumType.MD5, string, string.length);
468 stringHandler : function(tok)
470 //print("STRING HANDLER");
471 // callback when outputing compressed file,
473 if (!this.translateJSON) {
474 // print("TURNED OFF");
477 if (tok.name == 'SINGLE_QUOTE') {
481 var sval = data.substring(1,data.length-1);
482 // we do not clean up... quoting here!??!!?!?!?!?
485 // blank with tabs or spaces..
486 //if (!sval.replace(new RegExp("(\\\\n|\\\\t| )+",'g'), '').length) {
487 // return tok.outData;
490 var sval = tok.data.substring(1,data.length-1);
491 var fn = this.activeFile.substring(this.prefix.length);
494 return '_T["' + this.md5(fn + '-' + sval) + '"]';