-
Notifications
You must be signed in to change notification settings - Fork 10
/
tracegl.js
13559 lines (11982 loc) · 366 KB
/
tracegl.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env node
define('/trace/trace_server',function(require){
if(process.version.indexOf('v0.6') != -1 || process.version.indexOf('v0.4') != -1){
console.log("Node version too old, try 0.8 or 0.10")
process.exit(-1)
return
}
var path = require('path')
var fs = require('fs')
var url = require('url')
var zlib = require('zlib')
var http = require('http')
var https = require('https')
var crypto = require('crypto')
var instrument = require('./instrument')
var childproc = require('child_process')
var ssl_pub = require('../core/sign_pub')
// the nodejs loader
if(process.argv[2] && process.argv[2].indexOf('-l')==0) return nodeLoader()
function nodeLoader(){
var filter = makeFilter(process.argv[2].slice(2))
var m = require('module').Module.prototype;
var oldCompile = m._compile;
var did = 1
m._compile = function(content, filename){
if(filter.active && filter(filename))
return oldCompile.call(this, content, filename)
// lets instrument
var t = instrument(filename, content, did)
did = t.id
// send the dictionary out
var m = {dict:1, src:t.input, f:filename, d:t.d}
if(process.send) process.send(m)
else process.stderr.write('\x1f'+JSON.stringify(m)+'\x17')
return oldCompile.call(this, t.output, filename)
}
process.argv.splice(1,2) // remove leading arguments
// clear require cache
for(var k in define.require.cache) delete define.require.cache[k]
var file = path.resolve(process.argv[1])
define.require(file);
}
var fn = require('../core/fn')
var ssl = require('../core/io_ssl')
var ioServer = require('../core/io_server')
function out() {
for (var v = Array.prototype.slice.call(arguments), i = 0, c = out.colors; i < v.length; i++) {
v[i] = String(v[i]).replace(/~(\w*)~/g, function(m, a) {
return "\033[" + (c[a] || 0) + "m";
}) + "\033[0m";
process.stderr.write(v[i]);
}
}
out.colors = {
bl:"30",bo:"1",r:"0;31",g:"0;32",y:"0;33",b:"0;34",m:"0;35",c:"0;36",
w:"0;37",br:"1;31",bg:"1;32",by:"1;33",bb:"1;34",bm:"1;35",bc:"1;36",bw:"1;37"
}
function makeFilter(fspec){
if(typeof fspec == 'string') fspec = JSON.parse(fspec)
var _do = init(fspec._do)
var _no = init(fspec._no)
function init(a){
var d = []
for(var i = 0;i<a.length;i++){
if(a[i].charAt(0)==':') d[i] = a[i].slice(1)
else d[i] = new RegExp(a[i].slice(1),"i")
}
return d
}
function match(d, f){
if(!d.length) return 0
for(var i = 0;i<d.length;i++){
if(typeof d[i] == 'string'){
if(f.indexOf(d[i]) != -1) return 2
} else if(f.match(d[i])) return 2
}
return 1
}
function f(file){
if(match(_do, file) == 1) return true
if(match(_no, file) == 2) return true
return false
}
f.active = _do.length || _no.length
f.stringify = function(){
return JSON.stringify(fspec)
}
return f
}
out('~~[trace.GL] ~bc~See~w~ your code. This product has a commercial license.\n')
function loadSettings(file){
if(!fs.existsSync(file)) return
try{
var data = fs.readFileSync(file).toString().replace(/\/\*[\s|S]?\*\//g,'').replace(/\/\/.*?\n/g,'')
define.settings = JSON.parse(data)
define.settingsData = data
define.settingsFile = file
}
catch(e){
console.log("Error reading settings file ("+file+") ",e)
}
}
if(!loadSettings(path.resolve(process.cwd(),"tracegl.json")) &&
!loadSettings("~/tracegl.json") &&
!loadSettings(path.resolve(path.dirname(__filename),"tracegl.json")) &&
!define.settings)
loadSettings(path.resolve(path.dirname(__filename),"tracegl.json"))
function update(){
// call the server for an update
if(typeof sig64 == 'undefined') return
out('~~[trace.GL] ~w~Checking for update...')
var s = sig64.split('=')
var sig = s[0]
var req = https.request("https://trace.gl/update/" + s[1] + "/" + encodeURIComponent(sig+'='), function(res){
var code = ''
res.on('error', function(){
out("~br~Error fetching update!")
})
res.on('data', function(d){
code += d.toString()
})
res.on('end', function(){
var end = '(define.mkreq("/trace/trace_server"))'
if(code.lastIndexOf(end) == code.length - end.length){
// check signature
var newsig
var data = code.replace(/var sig64=\"(.*?=).*?\"\n/g,function(m,a){newsig = a;return "var sig64=\"\"\n"})
var verify = crypto.createVerify('sha1')
verify.update(data)
if(!verify.verify(ssl_pub, newsig, 'base64')){
return out("~br~Warning signature invalid, please contact [email protected].")
} else {
// write to new file next to our main file
var mainfile = process.mainModule.filename
var jsfile = path.basename(mainfile)
var dirname = path.dirname(mainfile)
var newfile = dirname + '/tracegl.js.' + encodeURIComponent(newsig).slice(0, 10)
var oldfile = dirname + '/tracegl.js.old.' + encodeURIComponent(sig).slice(0, 10)
fs.writeFile(newfile, code, function(err){
if(err) return out("~br~Error writing update " + err)
if(jsfile == 'trace_server.js') return out("~br~Not an updateable process ")
// rename swap old and new file
try{
fs.renameSync(mainfile, oldfile)
fs.renameSync(newfile, mainfile)
out("~bg~traceGL updated, please restart application.\n")
} catch(e){
return out("~br~Update rename failed, might need manual recovery")
}
// only swap if we are named tracegl.js
})
}
} else {
if(code.indexOf("There was a problem with your invoice")!= -1){
out('Your license is invalid, please buy copy at http://trace.gl or contact [email protected].\n')
} else {
out('up to date.\n')
}
}
})
})
req.on('error', function(e){ })
req.end()
}
// argument parse variables
function processArgs(arg){
var sender // send messages to ui or zip
var uiport = 2000
var tgtport = 2080
var fspec = {_no:[], _do:[]}
function usage(err){
out('~br~'+err+'\n')
out('~w~Usage:\n')
out('~w~node tracegl ~c~[flag] ~g~target ~y~[args]\n')
out(' ~g~../path/to/wwwroot ~w~Trace browser js via static fileserver\n')
out(' ~g~http://proxytarget:port ~w~Trace browser js via proxy\n')
out(' ~g~nodefile.js ~y~[args] ~w~Trace Node.js process\n')
out(' ~g~trace.gz ~w~Play back trace.gz file\n')
out(' ~c~-gz[:trace.gz] ~w~Record trace to gzip file. No trace UI started\n')
out(' ~c~-do[/:]match ~w~Only trace filenames containing match. Filters -do set first, then -no\n')
out(' ~c~-no[/:]match ~w~Ignore filenames containing match. Replace : with / for a regexp, use double escaped \\\\ \n')
out(' ~c~-nolib ~w~Short for -no/jquery.* -no:require.js -no/node\\\\_modules \n')
out(' ~c~-noup ~w~Don\'t update traceGL automatically\n')
out(' ~c~-ui:port ~w~Set trace UI port. default: 2000\n')
out(' ~c~-tgt:port ~w~Set browser JS port. default: 2080\n')
out('~w~node tracegl.js ~r~[commmand]\n')
out(' ~r~-settings ~w~write a .tracegl settings template in the current dir\n')
out(' ~r~-update ~w~do an explicit update of traceGL (normally in background)\n')
return
}
var noup
// process arguments
for(var i = 2;i<arg.length;i++){
var a = arg[i]
if(a.charAt(0) == '-'){
var d = a.indexOf(':')
var b
if(d!=-1) b = a.slice(d+1)
if(a.indexOf('-gz') == 0){
if(d!=-1) sender = gzSender(a.slice(d+1))
else sender = gzSender('trace.gz')
} else if(a.indexOf('-install') == 0){
} else if(a.indexOf('-ui') == 0){
if(d==-1) return usage("No port specified")
uiport = parseInt(b)
} else if(a.indexOf('-tgt') == 0){
if(d==-1) return usage("No port specified")
tgtport = parseInt(b)
} else if(a.indexOf('-no') == 0){
if(a == '-noup'){
noup = true
} else
if(a == '-nolib'){
fspec._no.push("/jquery.*")
fspec._no.push(":require.js")
fspec._no.push("/node\\_modules")
} else {
fspec._no.push(a.slice(3))
}
} else if(a.indexOf('-do') == 0){
fspec._do.push(a.slice(3))
} else if(a.indexOf('-settings') == 0){
if(fs.existsSync('.tracegl')){
return out('~r~ERROR: ~~ .tracegl file already exists, remove before creating a new template\n')
}
fs.writeFileSync(".tracegl", define.settingsData)
return out('~g~OK: ~~ .tracegl file written in current directory, open it in an editor to modify settings\n')
} else if(a.indexOf('-update') == 0){
return update()
}else return usage("Invalid argument "+a)
} else {
if(!sender) sender = uiSender(uiport)
var f = makeFilter(fspec)
// always run update in the background
if(!noup) update()
// execute the right mode
if(a.match(/\.gz$/i)) return gzPlaybackMode(f, a, sender)
if(a.match(/\.js$/i)) return nodeJSMode(f, a, arg.slice(i+1), sender)
if(a.match(/^https?/)) return proxyMode(f, tgtport, a, sender)
return browserJSMode(f, tgtport, path.resolve(process.cwd(), a), sender)
break
}
}
usage("Error, no target specified")
}
return processArgs(process.argv)
// create a file finder
function fileFinder(root){
var scanHash
function scan(dir, done) {
fs.readdir(dir, function(err, list) {
if (err) return done(err)
var i = 0
function next() {
var file = list[i++]
if (!file) return done()
file = dir + '/' + file
fs.stat(file, function(err, stat) {
if (stat && stat.isDirectory()) scan(file, next)
else {
var f = file.toLowerCase().split('/')
while(f.length){
scanHash[f.join('/')] = file
f.shift()
}
next()
}
})
}
next()
})
}
return function(file, found){
// open a file in the editor
fs.stat(file, function(err, stat){
if(!err) return found(null, file)
var sp = file.split('/')
resolve()
function resolve(){
if(sp.length == 0){ // not found the fast way
function find(){
var f = file.toLowerCase().split('/')
while(f.length){
var sf = scanHash[f.join('/')]
if(sf) return found(null, sf)
f.shift()
}
return found("Could not match "+file+" to anything in "+root)
}
if(!scanHash){
console.log("Building file find search db from "+root+" ..")
scanHash = {}
scan(root, find)
}
else find()
} else {
var sf = path.resolve(root, sp.join('/'))
fs.stat(sf, function(err, stat){
if(!err) return found(null, sf)
sp.shift()
resolve()
})
}
}
})
}
}
function openEditor(file, line){
var ed
var s = define.settings
if(!s.editors ||
!(ed = s.editors[process.platform]))
return console.log("No editor settings available for your platform")
// lets try all editors
for(var k in ed){
if(fs.existsSync(ed[k].bin)){
// execute editor
var rep = {file:file, line:line}
var args = ed[k].args
var narg = []
for(var i = 0;i<args.length;i++){
narg[i] = args[i].replace(/\$(\w+)/g,function(m,a){
if(!a in rep) console.log("Opening editor: argument not supported "+a)
return rep[a]
})
}
console.log('Opening '+file+' line '+line+' with '+k)
var child = childproc.spawn(ed[k].bin, narg,{
detached:true,
stdio:[process.stdin,process.stdout,process.stderr]
})
return
}
}
}
// send data to UI
function uiSender(port){
ui = ioServer()
ui.main = "./trace/trace_client"
ui.pass = fn.sha1hex("p4ssw0rd")
if(require.absolute)
ui.packaged = require.absolute('./trace_client')
else
ui.packaged = 1
ui.favicon = "R0lGODlhEAAQAPcAAAAAAAMBAAIAAwIDAQICAgEBBAIABAIABQIBBAAGAAAGAQAHAAAHAQEHAAEHAQIFAQMFAQIEAgIGAAIGAQMFBAQCAwYBAgYDAwYDBQcDBAQEAAQFAwUEAgUFAgUGAAQGAgUGAgYFAgYFAwYGAQcGAwQEBAUEBAUEBQUFBAYEBAYEBQYGBgAIAAAJAAEIAQEJAQIIAAULAQQLAgcJAQcJAgcKAAgEAwsGAg4FBggJAgsKCAsLDAARAAASAAATAAtvCgV0BwN9BQZ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OcAwMfgkNfgoQbw8TbgwWbBEVbB0YbRIYbhEYbxEYbxMQfAwScRAVcxEWcRMVchQVdRIVdhUWdhYWdhcRexEVehIWehEWfBIWfBYYdBMZdROrrK2uq6y/v8G9v8S9v8e/vMe+v8S+vsa+vsm5wce8wMO/wMC/wMO/wcW+wMe9x8K+xMLCv8DBvcXAv8XEv8XAwcLCwMHDw8HDw8LAw8XDw8TBxMPBxsHCxMPCxsfExcDExMTGxsfExcjHxcjFxszDysPEyMnIxcbj/+T8/Pz9/v7MzMwAAAAAAAAAAAAAAAAAAAAH04B4AIOEhYV5FFtZi4yNi1wfImsAM4OVlJYAcB8raBI+LCk5Jic7Kig9ImcWFXQzP0VGNU5NNkdFSDNiFhlvGEEKDEIPDkMNCUQbbR0iUQwzDHd3DM/R03IiF1vP0zPd33UfHm4z3uV35+dQHiBk0tTQ79VqHiFPBEsxL0kwMUwwMJQMKMPBQxoXMxaQkEGCBA0SJXC0iBNBg5kZQMrxKHejnI4ZdipM+IKp5KVKbCCEGONFS5cqUqhcCTPFCpY5YCrg0SBAAIKfCAoYODA0wAg8gQAAOw=="
ui.listen(port, "0.0.0.0")
out("~~[trace.GL]~w~ WebGL trace UI: http://localhost:2000\n")
var dict = []
var queue = []
var joined = false
var finder = fileFinder(process.cwd())
// set a filewatch on settings
if(define.settingsFile)
fs.exists(define.settingsFile, function(exists){
if(exists){
fs.watch(define.settingsFile, function(){
loadSettings(define.settingsFile)
ui.send({settings:define.settings})
console.log("Reloading settings file "+define.settingsFile)
})
}
})
// incoming channel data
ui.data = function(m, c){
if(m.t == 'join'){
for(var i = 0;i<dict.length;i++) c.send(dict[i])
for(var i = 0;i<queue.length;i++) c.send(queue[i])
joined = true
} else if(m.t == 'open'){
finder(m.file, function(err, file){
if(err) return console.log(err)
openEditor(file, m.line)
})
// next up is just eating off
}
else console.log('unused message',m)
}
// outgoing data channel
var lgc = 0
return function(m){
// verify ordering
if(!m.dict){
if(!lgc) lgc = m.g
else{
if(lgc + 1 != m.g){
console.log("Message order error", lgc, m.g)
}
lgc = m.g
}
if(joined && m.d == 1) queue = [] // clear the queue at depth 1
queue.push(m)
} else { // keep dictionaries for join
dict.push(m)
}
// keep all messages with depth 0
if(joined) ui.send(m)
}
}
// send data to zip
function gzSender(file){
// pipe writer into gzip into file
var gz = zlib.createGzip()
var fstr = fs.createWriteStream(file)
fstr.on('error', function(err){
console.log("Error writing "+file+" "+err)
})
gz.on('error', function(err){
console.log("Error zipping "+file+" "+err)
})
gz.pipe(fstr)
var buf = []
var total = 0
function flush(){
if(buf.length){
gz.write(buf.join(''))
buf = []
total = 0
}
}
var terminated = false
process.on('SIGINT', function() {
terminated = true
console.log('got sigint, flushing gz')
process.stdin.resume()
flush()
// wait for the drain, then end and exit
gz.flush(function(){
fstr.end(function(){
console.log("end!")
process.exit(0)
})
})
});
process.on('exit', function(){
console.log('exit!')
//gz.end()
})
return function(m){
if(!terminated){
// we should buffer atleast a megabyte
var data = '\x1f'+JSON.stringify(m)+'\x17'
buf.push(data)
total += data.length
if(total > 1024*1024) flush()
}
}
}
// app server
function browserJSMode(filter, port, root, sender){
// start the target server
var tgt = ioServer()
tgt.root = root
tgt.listen(port, "0.0.0.0")
//appHttp.watcher = define.watcher()
out("~~[trace.GL]~w~ Serving browser JS: http://localhost:2080\n")
// incoming message, forward to sender
tgt.data = function(m, c){
sender(m)
}
var fileCache= {}
var did = 1 // count instrument offset id
tgt.fileChange = function(f){
// lets flush everything
fileCache = {}
did = 1
// send reload message to UI
sender({reload:1})
}
tgt.process = function(file, data, type){
if(type != "application/javascript") return data
if(filter.active && filter(file)) return data
// cache
if(fileCache[file]) return fileCache[file].output
// lets use trace
var t = fileCache[file] = instrument(file, data.toString('utf8'), did)
did = t.id
// send to UI
sender({dict:1, f:file, src:t.input, d:t.d})
return t.output
}
}
function streamParser(dataCb, sideCb){
var last = ""
return function(d){
var data = last + d.toString();
last = "";
data = data.replace(/\x1f(.*?)\x17/g, function(x, m){
try{
dataCb(JSON.parse(m))
} catch(e){
fn('error in '+e,m)
}
return ''
})
if(data.indexOf('\x1f')!= -1) last = data;
else if(data.length && sideCb) sideCb(data)
}
}
// node server
function nodeJSMode(filter, file, args, sender){
// we start up ourselves with -l
var cp = require('child_process')
args.unshift(file)
args.unshift('-l' + filter.stringify())
args.unshift(process.argv[1])
var stdio = [process.stdin, process.stdout,'pipe']
//if(process.version.indexOf('v0.8') != -1) stdio.push('ipc')
var child = cp.spawn(process.execPath, args, {
stdio: stdio
})
// stderr datapath
var sp = streamParser(sender, function(d){
process.stderr.write(d)
})
if(child.stderr) child.stderr.on('data',sp)
// ipc datapath
child.on('message', function(m){
sender(m)
})
}
function proxyMode(filter, port, proxy, sender){
// start the target server
var tgt = ioServer()
tgt.root = root
tgt.proxy = url.parse(proxy)
tgt.listen(port, "0.0.0.0")
//appHttp.watcher = define.watcher()
out("~~[trace.GL]~w~ Proxying browser JS: http://localhost:2080\n")
// incoming message, forward to sender
tgt.data = function(m, c){
sender(m)
}
var fileCache= {}
var did = 1 // count instrument offset id
tgt.process = function(file, data, type){
if(type != "application/javascript") return data
if(filter.active && filter(file)) return data
// cache
if(fileCache[file]) return fileCache[file].output
// lets use trace
var t = fileCache[file] = instrument(file, data.toString('utf8'), did)
did = t.id
// send to UI
sender({dict:1, f:file, src:t.input, d:t.d})
// dump the last 100 chars
return t.output
}
}
function gzPlaybackMode(filter, file, sender){
// just output the gz file to sender
var rs = fs.createReadStream(file)
var gz = zlib.createGunzip()
process.stdout.write("Loading gzipped trace .")
rs.pipe(gz)
var sp = streamParser(function(m){
if(m.g%1000 == 0) process.stdout.write(".")
sender(m)
})
gz.on('data', sp)
gz.on('end', function(){
process.stdout.write("Complete!\n")
})
}
})
function define(id,fac){
//PACKSTART
// | returns path of file
function path(p){ //
if(!p) return ''
p = p.replace(/\.\//g, '')
var b = p.match(/([\s\S]*)\/[^\/]*$/)
return b ? b[1] : ''
}
// | normalizes relative path r against base b
function norm(r, b){
b = b.split(/\//)
r = r.replace(/\.\.\//g,function(){ b.pop(); return ''}).replace(/\.\//g, '')
var v = b.join('/')+ '/' + r
if(v.charAt(0)!='/') v = '/'+v
return v
}
//PACKEND
//PACKSTART
function def(id, fac){
if(!fac) fac = id, id = null
def.factory[id || '_'] = fac
}
def.module = {}
def.factory = {}
def.urls = {}
def.tags = {}
function req(id, base){
if(!base) base = ''
if(typeof require !== "undefined" && id.charAt(0) != '.') return require(id)
id = norm(id, base)
var c = def.module[id]
if(c) return c.exports
var f = def.factory[id]
if(!f) throw new Error('module not available '+id + ' in base' + base)
var m = {exports:{}}
var localreq = def.mkreq(id)
var ret = f(localreq, m.exports, m)
if(ret) m.exports = ret
def.module[id] = m
return m.exports
}
def.mkreq = function(base){
function localreq(i){
return def.req(i, path(base))
}
localreq.reload = function(i, cb){
var id = norm(i, base)
script(id, 'reload', function(){
delete def.module[id] // cause reexecution of module
cb( req(i, base) )
})
}
localreq.absolute = function(i){
return norm(i, path(base))
}
return localreq
}
def.req = req
def.outer = define
if(typeof require !== 'undefined') def.require = require
def.path = path
def.norm = norm
define = def
def(id, fac)
//PACKEND
}
var sig64="Y6O4kYtjgOIfE8fug8bpcN4mS9SArGBSUYe0M3Jjzgo55CbQGDjskHk76kAkaDheOIfxwkEa6+/ij/OzWWLC0U7OuS7MM8mNwmx9Cimqjgl+nIVKQmqoYzzRmlOuTxihmhkOtu5nUo1Fb+UaAEWxKku4gtvxpOucPGCVfv16Uc8=btc080aa2860b7b6e65f9de8c0f"
// | Function, utility lib|_____________________/
// |
// | (c) Code.GL 2013
// \____________________________________________/
define('/core/fn',function(){
if(console.log.bind)
var fn = console.log.bind(console)
else
var fn = function(){
var s = ''
for(var i = 0;i<arguments.length;i++) s+= (s?', ':'')+arguments[i]
console.log(s)
}
fn.list = list
fn.stack = stack
fn.ps = ps
fn.wait = wait
fn.repeat = repeat
fn.events = events
fn.dt = dt
fn.mt = mt
fn.sha1hex = sha1hex
fn.rndhex = rndhex
fn.tr = tr
fn.dump = dump
fn.walk = walk
fn.min = min
fn.max = max
fn.clamp = clamp
fn.nextpow2 = nextpow2
fn.named = named
// | named arguments
// \____________________________________________/
function named(a, f){
var t = typeof a[0]
if(t == 'function' || t== 'object') return t
if(!f) f = named.caller
if(!f._c) f._c = f.toString()
if(!f._n) f._n = f._c.match(/function.*?\((.*?)\)/)[1].split(',')
var n = f._n
if(a.length > n.length) throw new Error("Argument list mismatch, "+a.length+" instead of "+n.length)
var g = {}
for(var i = 0, j = a.length;i<j;i++) g[n[i]] = a[i]
return g
}
// | left right linked list
// \____________________________________________/
function list(l, r){
// var u // unique id/
// var f // free slot
var b // begin
var e // end
function li(){
return li.fn.apply(0, arguments)
}
li.fn = function(a){
if(arguments.length > 1){
var rm = {}
for(var i = 0, j = arguments.length; i<j; i++) li.add(rm[i] = arguments[i])
return function(){
for(var i in rm) li.rm(rm[i])
rm = null
}
}
li.add(a)
return function(){
if(a) li.rm(a)
a = null
}
}
var ln = 0
li.len = 0
li.add = add
li.rm = rm
li.clear = function(){
var n = b
while(n){
var m = n[r]
delete n[r]
delete n[l]
n = m
}
b = e = undefined
li.len = ln = 0
}
li.drop = function(){
b = e = undefined
li.len = ln = 0
}
//| add an item to the list
function add(i){
if(arguments.length > 1){
for(var i = 0, j = arguments.length; i<j; i++) add(arguments[i])
return ln
}
// already in list
if( l in i || r in i || b == i) return ln
if(!e) b = e = i
else e[r] = i, i[l] = e, e = i
li.len = ++ln
if(ln == 1 && li.fill) li.fill()
return ln
}
//| add a sorted item scanning from the end
li.sorted = function(i, s){
if( l in i || r in i || b == i) return ln
var a = e
while(a){
if(a[s] <= i[s]){ // insert after a
if(a[r]) a[r][l] = i, i[r] = a[r]
else e = i
i[l] = a
a[r] = i
break
}
a = a[l]
}
if(!a){ // add beginning
if(!e) e = i
if(b) i[r] = b, b[l] = i
b = i
}
li.len = ++ln
if(ln == 1 && li.fill) li.fill()
return ln
}
//| remove item from the list
function rm(i){
if(arguments.length > 1){
for(var i = 0, j = arguments.length; i<j; i++) rm(arguments[i])
return ln
}
var t = 0
if(b == i) b = i[r], t++
if(e == i) e = i[l], t++
if(i[r]){
if(i[l]) i[r][l] = i[l]
else delete i[r][l]
t++
}
if(i[l]){
if(i[r]) i[l][r] = i[r]
else delete i[l][r]
t++
}
if(!t) return
delete i[r]
delete i[l]
//if(!e && f) freeid()
li.len = --ln
if(!ln && li.empty) li.empty()
return ln
}
//| run all items in the list
li.run = function(){
var n = b, t, v
while(n) v = n.apply(null, arguments), t = v !== undefined ? v : t, n = n[r]
return t
}
//| iterate over all items
li.each = function(c){
var n = b
var j = 0
var t
while(n) {
var x = n[r]
v = c(n, li, j)
if(v !== undefined) t = v
n = x, j++
}
return t
}
//| check if item is in the list
li.has = function(i){
return l in i || r in i || b == i
}
li.first = function(){
return b
}
li.last = function(){
return e
}
return li
}
// | apply event pattern to object
// \____________________________________________/
function events(o){
o.on = function(e, f){
var l = this.$l || (this.$l = {})
var a = l[e]
if(!a) l[e] = f
else{
if(Array.isArray(a)) a.push(event)
else l[e] = [l[e], f]
}
}
o.off = function(e, f){
var l = this.$l || (this.$l = {})
if(!l) return
var a = l[e]
if(!a) return
if(Array.isArray(a)){
for(var i = 0;i<a.length;i++){
if(a[i] == f) a.splice(i,1), i--
}
}
else if (l[e] == f) delete l[e]
}
o.clear = function(e, f){
var l = this.$l
if(!l) return
delete l[e]
}
o.emit = function(e){
var l = this.$l
if(!l) return
var a = l[e]
if(!a) return
if(arguments.length>1){
var arg = Array.prototype.slice.call(arguments, 1)
if(typeof a == 'function') a.apply(null, arg)
else for(var i = 0;i<a.length;i++) a[i].apply(null, arg)
} else {
if(typeof a == 'function') a()
else for(var i = 0;i<a.length;i++) a[i]()
}
}
}
// | simple fixed integer stack
// \____________________________________________/
function stack(){
function st(){
return st.fn.apply(null, arguments)
}
st.fn = function(a){
if(arguments.length > 1){
var rm = {}
for(var i = 0, j = arguments.length; i<j; i++) rm[push(arguments[i])] = 1
return function(){
for(var i in rm) st.rm(i)
rm = null
}
} else {
var i = push(a)
return function(){