-
Notifications
You must be signed in to change notification settings - Fork 16
/
fondue.browser.js
12326 lines (10496 loc) · 453 KB
/
fondue.browser.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
(function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){
window.fondue = require("./");
},{"./":2}],2:[function(require,module,exports){
(function (__dirname){
/*
* Copyright (c) 2012 Massachusetts Institute of Technology, Adobe Systems
* Incorporated, and other contributors. All rights reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*
*/
var basename = require('path').basename;
var falafel = require('falafel');
var falafelMap = require('falafel-map');
var eselector = require('esprima-selector');
var helpers = require('falafel-helpers');
var fs = require('fs');
// adds keys from options to defaultOptions, overwriting on conflicts & returning defaultOptions
function mergeInto(options, defaultOptions) {
for (var key in options) {
if (options[key] !== undefined) {
defaultOptions[key] = options[key];
}
}
return defaultOptions;
}
// tiny templating library
// replaces {name} with vars.name
function template(s, vars) {
for (var p in vars) {
s = s.replace(new RegExp('{' + p + '}', 'g'), vars[p]);
}
return s;
}
function makeId(type, path, loc) {
return path + '-'
+ type + '-'
+ loc.start.line + '-'
+ loc.start.column + '-'
+ loc.end.line + '-'
+ loc.end.column;
};
function instrumentationPrefix(options) {
options = mergeInto(options, {
name: '__tracer',
nodejs: false,
maxInvocationsPerTick: 4096,
});
// the inline comments below are markers for building the browser version of
// fondue, where the file contents will be inlined as a string.
var tracerSource = "/*\nThe following code was inserted automatically by fondue to collect information\nabout the execution of all the JavaScript on this page or in this program.\n\nIf you're using Brackets, this is caused by the Theseus extension, which you\ncan disable by unchecking File > Enable Theseus.\n\nhttps://github.com/adobe-research/fondue\nhttps://github.com/adobe-research/theseus\n*/\n\n/*\n * Copyright (c) 2012 Massachusetts Institute of Technology, Adobe Systems\n * Incorporated, and other contributors. All rights reserved.\n *\n * Permission is hereby granted, free of charge, to any person obtaining a\n * copy of this software and associated documentation files (the \"Software\"),\n * to deal in the Software without restriction, including without limitation\n * the rights to use, copy, modify, merge, publish, distribute, sublicense,\n * and/or sell copies of the Software, and to permit persons to whom the\n * Software is furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\n * DEALINGS IN THE SOFTWARE.\n *\n */\n\n/*\nThe source of source-map is included below on the line beginning with \"var sourceMap\",\nand its license is as follows:\n\nCopyright (c) 2009-2011, Mozilla Foundation and contributors\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions are met:\n\n* Redistributions of source code must retain the above copyright notice, this\n list of conditions and the following disclaimer.\n\n* Redistributions in binary form must reproduce the above copyright notice,\n this list of conditions and the following disclaimer in the documentation\n and/or other materials provided with the distribution.\n\n* Neither the names of the Mozilla Foundation nor the names of project\n contributors may be used to endorse or promote products derived from this\n software without specific prior written permission.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND\nANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\nWARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\nDISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE\nFOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\nDAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\nSERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\nCAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\nOR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\nOF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n*/\n\nif (typeof {name} === 'undefined') {\n{name} = new (function () {\n\tvar sourceMap = (function () {function define(e,t,n){if(typeof e!=\"string\")throw new TypeError(\"Expected string, got: \"+e);arguments.length==2&&(n=t);if(e in define.modules)throw new Error(\"Module already defined: \"+e);define.modules[e]=n}function Domain(){this.modules={},this._currentModule=null}define.modules={},function(){function e(e){var t=e.split(\"/\"),n=1;while(n<t.length)t[n]===\"..\"?t.splice(n-1,1):t[n]===\".\"?t.splice(n,1):n++;return t.join(\"/\")}function t(e,t){return e=e.trim(),t=t.trim(),/^\\//.test(t)?t:e.replace(/\\/*$/,\"/\")+t}function n(e){var t=e.split(\"/\");return t.pop(),t.join(\"/\")}Domain.prototype.require=function(e,t){if(Array.isArray(e)){var n=e.map(function(e){return this.lookup(e)},this);return t&&t.apply(null,n),undefined}return this.lookup(e)},Domain.prototype.lookup=function(r){/^\\./.test(r)&&(r=e(t(n(this._currentModule),r)));if(r in this.modules){var i=this.modules[r];return i}if(r in define.modules){var i=define.modules[r];if(typeof i==\"function\"){var s={},o=this._currentModule;this._currentModule=r,i(this.require.bind(this),s,{id:r,uri:\"\"}),this._currentModule=o,i=s}return this.modules[r]=i,i}throw new Error(\"Module not defined: \"+r)}}(),define.Domain=Domain,define.globalDomain=new Domain;var require=define.globalDomain.require.bind(define.globalDomain);define(\"source-map/source-map-generator\",[\"require\",\"exports\",\"module\",\"source-map/base64-vlq\",\"source-map/util\",\"source-map/array-set\"],function(e,t,n){function o(e){this._file=i.getArg(e,\"file\"),this._sourceRoot=i.getArg(e,\"sourceRoot\",null),this._sources=new s,this._names=new s,this._mappings=[],this._sourcesContents=null}function u(e,t){var n=(e&&e.line)-(t&&t.line);return n?n:(e&&e.column)-(t&&t.column)}function a(e,t){return e=e||\"\",t=t||\"\",(e>t)-(e<t)}function f(e,t){return u(e.generated,t.generated)||u(e.original,t.original)||a(e.source,t.source)||a(e.name,t.name)}var r=e(\"./base64-vlq\"),i=e(\"./util\"),s=e(\"./array-set\").ArraySet;o.prototype._version=3,o.fromSourceMap=function(t){var n=t.sourceRoot,r=new o({file:t.file,sourceRoot:n});return t.eachMapping(function(e){var t={generated:{line:e.generatedLine,column:e.generatedColumn}};e.source&&(t.source=e.source,n&&(t.source=i.relative(n,t.source)),t.original={line:e.originalLine,column:e.originalColumn},e.name&&(t.name=e.name)),r.addMapping(t)}),t.sources.forEach(function(e){var n=t.sourceContentFor(e);n&&r.setSourceContent(e,n)}),r},o.prototype.addMapping=function(t){var n=i.getArg(t,\"generated\"),r=i.getArg(t,\"original\",null),s=i.getArg(t,\"source\",null),o=i.getArg(t,\"name\",null);this._validateMapping(n,r,s,o),s&&!this._sources.has(s)&&this._sources.add(s),o&&!this._names.has(o)&&this._names.add(o),this._mappings.push({generated:n,original:r,source:s,name:o})},o.prototype.setSourceContent=function(t,n){var r=t;this._sourceRoot&&(r=i.relative(this._sourceRoot,r)),n!==null?(this._sourcesContents||(this._sourcesContents={}),this._sourcesContents[i.toSetString(r)]=n):(delete this._sourcesContents[i.toSetString(r)],Object.keys(this._sourcesContents).length===0&&(this._sourcesContents=null))},o.prototype.applySourceMap=function(t,n){n||(n=t.file);var r=this._sourceRoot;r&&(n=i.relative(r,n));var o=new s,u=new s;this._mappings.forEach(function(e){if(e.source===n&&e.original){var s=t.originalPositionFor({line:e.original.line,column:e.original.column});s.source!==null&&(r?e.source=i.relative(r,s.source):e.source=s.source,e.original.line=s.line,e.original.column=s.column,s.name!==null&&e.name!==null&&(e.name=s.name))}var a=e.source;a&&!o.has(a)&&o.add(a);var f=e.name;f&&!u.has(f)&&u.add(f)},this),this._sources=o,this._names=u,t.sources.forEach(function(e){var n=t.sourceContentFor(e);n&&(r&&(e=i.relative(r,e)),this.setSourceContent(e,n))},this)},o.prototype._validateMapping=function(t,n,r,i){if(t&&\"line\"in t&&\"column\"in t&&t.line>0&&t.column>=0&&!n&&!r&&!i)return;if(t&&\"line\"in t&&\"column\"in t&&n&&\"line\"in n&&\"column\"in n&&t.line>0&&t.column>=0&&n.line>0&&n.column>=0&&r)return;throw new Error(\"Invalid mapping.\")},o.prototype._serializeMappings=function(){var t=0,n=1,i=0,s=0,o=0,u=0,a=\"\",l;this._mappings.sort(f);for(var c=0,h=this._mappings.length;c<h;c++){l=this._mappings[c];if(l.generated.line!==n){t=0;while(l.generated.line!==n)a+=\";\",n++}else if(c>0){if(!f(l,this._mappings[c-1]))continue;a+=\",\"}a+=r.encode(l.generated.column-t),t=l.generated.column,l.source&&l.original&&(a+=r.encode(this._sources.indexOf(l.source)-u),u=this._sources.indexOf(l.source),a+=r.encode(l.original.line-1-s),s=l.original.line-1,a+=r.encode(l.original.column-i),i=l.original.column,l.name&&(a+=r.encode(this._names.indexOf(l.name)-o),o=this._names.indexOf(l.name)))}return a},o.prototype.toJSON=function(){var t={version:this._version,file:this._file,sources:this._sources.toArray(),names:this._names.toArray(),mappings:this._serializeMappings()};return this._sourceRoot&&(t.sourceRoot=this._sourceRoot),this._sourcesContents&&(t.sourcesContent=t.sources.map(function(e){return t.sourceRoot&&(e=i.relative(t.sourceRoot,e)),Object.prototype.hasOwnProperty.call(this._sourcesContents,i.toSetString(e))?this._sourcesContents[i.toSetString(e)]:null},this)),t},o.prototype.toString=function(){return JSON.stringify(this)},t.SourceMapGenerator=o}),define(\"source-map/base64-vlq\",[\"require\",\"exports\",\"module\",\"source-map/base64\"],function(e,t,n){function a(e){return e<0?(-e<<1)+1:(e<<1)+0}function f(e){var t=(e&1)===1,n=e>>1;return t?-n:n}var r=e(\"./base64\"),i=5,s=1<<i,o=s-1,u=s;t.encode=function(t){var n=\"\",s,f=a(t);do s=f&o,f>>>=i,f>0&&(s|=u),n+=r.encode(s);while(f>0);return n},t.decode=function(t){var n=0,s=t.length,a=0,l=0,c,h;do{if(n>=s)throw new Error(\"Expected more digits in base 64 VLQ value.\");h=r.decode(t.charAt(n++)),c=!!(h&u),h&=o,a+=h<<l,l+=i}while(c);return{value:f(a),rest:t.slice(n)}}}),define(\"source-map/base64\",[\"require\",\"exports\",\"module\"],function(e,t,n){var r={},i={};\"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/\".split(\"\").forEach(function(e,t){r[e]=t,i[t]=e}),t.encode=function(t){if(t in i)return i[t];throw new TypeError(\"Must be between 0 and 63: \"+t)},t.decode=function(t){if(t in r)return r[t];throw new TypeError(\"Not a valid base 64 digit: \"+t)}}),define(\"source-map/util\",[\"require\",\"exports\",\"module\"],function(e,t,n){function r(e,t,n){if(t in e)return e[t];if(arguments.length===3)return n;throw new Error('\"'+t+'\" is a required argument.')}function s(e){var t=e.match(i);return t?{scheme:t[1],auth:t[3],host:t[4],port:t[6],path:t[7]}:null}function o(e){var t=e.scheme+\"://\";return e.auth&&(t+=e.auth+\"@\"),e.host&&(t+=e.host),e.port&&(t+=\":\"+e.port),e.path&&(t+=e.path),t}function u(e,t){var n;return t.match(i)?t:t.charAt(0)===\"/\"&&(n=s(e))?(n.path=t,o(n)):e.replace(/\\/$/,\"\")+\"/\"+t}function a(e){return\"$\"+e}function f(e){return e.substr(1)}function l(e,t){e=e.replace(/\\/$/,\"\");var n=s(e);return t.charAt(0)==\"/\"&&n&&n.path==\"/\"?t.slice(1):t.indexOf(e+\"/\")===0?t.substr(e.length+1):t}t.getArg=r;var i=/([\\w+\\-.]+):\\/\\/((\\w+:\\w+)@)?([\\w.]+)?(:(\\d+))?(\\S+)?/;t.urlParse=s,t.urlGenerate=o,t.join=u,t.toSetString=a,t.fromSetString=f,t.relative=l}),define(\"source-map/array-set\",[\"require\",\"exports\",\"module\",\"source-map/util\"],function(e,t,n){function i(){this._array=[],this._set={}}var r=e(\"./util\");i.fromArray=function(t){var n=new i;for(var r=0,s=t.length;r<s;r++)n.add(t[r]);return n},i.prototype.add=function(t){if(this.has(t))return;var n=this._array.length;this._array.push(t),this._set[r.toSetString(t)]=n},i.prototype.has=function(t){return Object.prototype.hasOwnProperty.call(this._set,r.toSetString(t))},i.prototype.indexOf=function(t){if(this.has(t))return this._set[r.toSetString(t)];throw new Error('\"'+t+'\" is not in the set.')},i.prototype.at=function(t){if(t>=0&&t<this._array.length)return this._array[t];throw new Error(\"No element indexed by \"+t)},i.prototype.toArray=function(){return this._array.slice()},t.ArraySet=i}),define(\"source-map/source-map-consumer\",[\"require\",\"exports\",\"module\",\"source-map/util\",\"source-map/binary-search\",\"source-map/array-set\",\"source-map/base64-vlq\"],function(e,t,n){function u(e){var t=e;typeof e==\"string\"&&(t=JSON.parse(e.replace(/^\\)\\]\\}'/,\"\")));var n=r.getArg(t,\"version\"),i=r.getArg(t,\"sources\"),o=r.getArg(t,\"names\"),u=r.getArg(t,\"sourceRoot\",null),a=r.getArg(t,\"sourcesContent\",null),f=r.getArg(t,\"mappings\"),l=r.getArg(t,\"file\",null);if(n!==this._version)throw new Error(\"Unsupported version: \"+n);this._names=s.fromArray(o),this._sources=s.fromArray(i),this.sourceRoot=u,this.sourcesContent=a,this.file=l,this._generatedMappings=[],this._originalMappings=[],this._parseMappings(f,u)}var r=e(\"./util\"),i=e(\"./binary-search\"),s=e(\"./array-set\").ArraySet,o=e(\"./base64-vlq\");u.prototype._version=3,Object.defineProperty(u.prototype,\"sources\",{get:function(){return this._sources.toArray().map(function(e){return this.sourceRoot?r.join(this.sourceRoot,e):e},this)}}),u.prototype._parseMappings=function(t,n){var r=1,i=0,s=0,u=0,a=0,f=0,l=/^[,;]/,c=t,h,p;while(c.length>0)if(c.charAt(0)===\";\")r++,c=c.slice(1),i=0;else if(c.charAt(0)===\",\")c=c.slice(1);else{h={},h.generatedLine=r,p=o.decode(c),h.generatedColumn=i+p.value,i=h.generatedColumn,c=p.rest;if(c.length>0&&!l.test(c.charAt(0))){p=o.decode(c),h.source=this._sources.at(a+p.value),a+=p.value,c=p.rest;if(c.length===0||l.test(c.charAt(0)))throw new Error(\"Found a source, but no line and column\");p=o.decode(c),h.originalLine=s+p.value,s=h.originalLine,h.originalLine+=1,c=p.rest;if(c.length===0||l.test(c.charAt(0)))throw new Error(\"Found a source and line, but no column\");p=o.decode(c),h.originalColumn=u+p.value,u=h.originalColumn,c=p.rest,c.length>0&&!l.test(c.charAt(0))&&(p=o.decode(c),h.name=this._names.at(f+p.value),f+=p.value,c=p.rest)}this._generatedMappings.push(h),typeof h.originalLine==\"number\"&&this._originalMappings.push(h)}this._originalMappings.sort(this._compareOriginalPositions)},u.prototype._compareOriginalPositions=function(t,n){if(t.source>n.source)return 1;if(t.source<n.source)return-1;var r=t.originalLine-n.originalLine;return r===0?t.originalColumn-n.originalColumn:r},u.prototype._compareGeneratedPositions=function(t,n){var r=t.generatedLine-n.generatedLine;return r===0?t.generatedColumn-n.generatedColumn:r},u.prototype._findMapping=function(t,n,r,s,o){if(t[r]<=0)throw new TypeError(\"Line must be greater than or equal to 1, got \"+t[r]);if(t[s]<0)throw new TypeError(\"Column must be greater than or equal to 0, got \"+t[s]);return i.search(t,n,o)},u.prototype.originalPositionFor=function(t){var n={generatedLine:r.getArg(t,\"line\"),generatedColumn:r.getArg(t,\"column\")},i=this._findMapping(n,this._generatedMappings,\"generatedLine\",\"generatedColumn\",this._compareGeneratedPositions);if(i){var s=r.getArg(i,\"source\",null);return s&&this.sourceRoot&&(s=r.join(this.sourceRoot,s)),{source:s,line:r.getArg(i,\"originalLine\",null),column:r.getArg(i,\"originalColumn\",null),name:r.getArg(i,\"name\",null)}}return{source:null,line:null,column:null,name:null}},u.prototype.sourceContentFor=function(t){if(!this.sourcesContent)return null;this.sourceRoot&&(t=r.relative(this.sourceRoot,t));if(this._sources.has(t))return this.sourcesContent[this._sources.indexOf(t)];var n;if(this.sourceRoot&&(n=r.urlParse(this.sourceRoot))){var i=t.replace(/^file:\\/\\//,\"\");if(n.scheme==\"file\"&&this._sources.has(i))return this.sourcesContent[this._sources.indexOf(i)];if((!n.path||n.path==\"/\")&&this._sources.has(\"/\"+t))return this.sourcesContent[this._sources.indexOf(\"/\"+t)]}throw new Error('\"'+t+'\" is not in the SourceMap.')},u.prototype.generatedPositionFor=function(t){var n={source:r.getArg(t,\"source\"),originalLine:r.getArg(t,\"line\"),originalColumn:r.getArg(t,\"column\")};this.sourceRoot&&(n.source=r.relative(this.sourceRoot,n.source));var i=this._findMapping(n,this._originalMappings,\"originalLine\",\"originalColumn\",this._compareOriginalPositions);return i?{line:r.getArg(i,\"generatedLine\",null),column:r.getArg(i,\"generatedColumn\",null)}:{line:null,column:null}},u.GENERATED_ORDER=1,u.ORIGINAL_ORDER=2,u.prototype.eachMapping=function(t,n,i){var s=n||null,o=i||u.GENERATED_ORDER,a;switch(o){case u.GENERATED_ORDER:a=this._generatedMappings;break;case u.ORIGINAL_ORDER:a=this._originalMappings;break;default:throw new Error(\"Unknown order of iteration.\")}var f=this.sourceRoot;a.map(function(e){var t=e.source;return t&&f&&(t=r.join(f,t)),{source:t,generatedLine:e.generatedLine,generatedColumn:e.generatedColumn,originalLine:e.originalLine,originalColumn:e.originalColumn,name:e.name}}).forEach(t,s)},t.SourceMapConsumer=u}),define(\"source-map/binary-search\",[\"require\",\"exports\",\"module\"],function(e,t,n){function r(e,t,n,i,s){var o=Math.floor((t-e)/2)+e,u=s(n,i[o]);return u===0?i[o]:u>0?t-o>1?r(o,t,n,i,s):i[o]:o-e>1?r(e,o,n,i,s):e<0?null:i[e]}t.search=function(t,n,i){return n.length>0?r(-1,n.length,t,n,i):null}}),define(\"source-map/source-node\",[\"require\",\"exports\",\"module\",\"source-map/source-map-generator\",\"source-map/util\"],function(e,t,n){function s(e,t,n,r,i){this.children=[],this.sourceContents={},this.line=e===undefined?null:e,this.column=t===undefined?null:t,this.source=n===undefined?null:n,this.name=i===undefined?null:i,r!=null&&this.add(r)}var r=e(\"./source-map-generator\").SourceMapGenerator,i=e(\"./util\");s.fromStringWithSourceMap=function(t,n){function f(e,t){e===null||e.source===undefined?r.add(t):r.add(new s(e.originalLine,e.originalColumn,e.source,t,e.name))}var r=new s,i=t.split(\"\\n\"),o=1,u=0,a=null;return n.eachMapping(function(e){if(a===null){while(o<e.generatedLine)r.add(i.shift()+\"\\n\"),o++;if(u<e.generatedColumn){var t=i[0];r.add(t.substr(0,e.generatedColumn)),i[0]=t.substr(e.generatedColumn),u=e.generatedColumn}}else if(o<e.generatedLine){var n=\"\";do n+=i.shift()+\"\\n\",o++,u=0;while(o<e.generatedLine);if(u<e.generatedColumn){var t=i[0];n+=t.substr(0,e.generatedColumn),i[0]=t.substr(e.generatedColumn),u=e.generatedColumn}f(a,n)}else{var t=i[0],n=t.substr(0,e.generatedColumn-u);i[0]=t.substr(e.generatedColumn-u),u=e.generatedColumn,f(a,n)}a=e},this),f(a,i.join(\"\\n\")),n.sources.forEach(function(e){var t=n.sourceContentFor(e);t&&r.setSourceContent(e,t)}),r},s.prototype.add=function(t){if(Array.isArray(t))t.forEach(function(e){this.add(e)},this);else{if(!(t instanceof s||typeof t==\"string\"))throw new TypeError(\"Expected a SourceNode, string, or an array of SourceNodes and strings. Got \"+t);t&&this.children.push(t)}return this},s.prototype.prepend=function(t){if(Array.isArray(t))for(var n=t.length-1;n>=0;n--)this.prepend(t[n]);else{if(!(t instanceof s||typeof t==\"string\"))throw new TypeError(\"Expected a SourceNode, string, or an array of SourceNodes and strings. Got \"+t);this.children.unshift(t)}return this},s.prototype.walk=function(t){this.children.forEach(function(e){e instanceof s?e.walk(t):e!==\"\"&&t(e,{source:this.source,line:this.line,column:this.column,name:this.name})},this)},s.prototype.join=function(t){var n,r,i=this.children.length;if(i>0){n=[];for(r=0;r<i-1;r++)n.push(this.children[r]),n.push(t);n.push(this.children[r]),this.children=n}return this},s.prototype.replaceRight=function(t,n){var r=this.children[this.children.length-1];return r instanceof s?r.replaceRight(t,n):typeof r==\"string\"?this.children[this.children.length-1]=r.replace(t,n):this.children.push(\"\".replace(t,n)),this},s.prototype.setSourceContent=function(t,n){this.sourceContents[i.toSetString(t)]=n},s.prototype.walkSourceContents=function(t){this.children.forEach(function(e){e instanceof s&&e.walkSourceContents(t)},this),Object.keys(this.sourceContents).forEach(function(e){t(i.fromSetString(e),this.sourceContents[e])},this)},s.prototype.toString=function(){var t=\"\";return this.walk(function(e){t+=e}),t},s.prototype.toStringWithSourceMap=function(t){var n={code:\"\",line:1,column:0},i=new r(t),s=!1;return this.walk(function(e,t){n.code+=e,t.source!==null&&t.line!==null&&t.column!==null?(i.addMapping({source:t.source,original:{line:t.line,column:t.column},generated:{line:n.line,column:n.column},name:t.name}),s=!0):s&&(i.addMapping({generated:{line:n.line,column:n.column}}),s=!1),e.split(\"\").forEach(function(e){e===\"\\n\"?(n.line++,n.column=0):n.column++})}),this.walkSourceContents(function(e,t){i.setSourceContent(e,t)}),{code:n.code,map:i}},t.SourceNode=s});return {SourceMapConsumer:require(\"source-map/source-map-consumer\").SourceMapConsumer,SourceMapGenerator:require(\"source-map/source-map-generator\").SourceMapGenerator,SourceNode:require(\"source-map/source-node\").SourceNode}})();\n\n\tvar TRACER_ID = String(Math.random());\n\n\tvar globalThis = undefined;\n\n\tvar nodes = []; // objects describing functions, branches, call sites, etc\n\tvar nodeById = {}; // id(string) -> node\n\tvar invocationStack = [];\n\tvar invocationById = {}; // id(string) -> invocation\n\tvar invocationsByNodeId = {}; // id(string) -> array of invocations\n\tvar exceptionsByNodeId = {}; // nodeId -> array of { exception: ..., invocationId: ... }\n\tvar uncaughtExceptionsByNodeId = {}; // nodeId -> array of { exception: ..., invocationId: ... }\n\tvar nodeHitCounts = {}; // { query-handle: { nodeId: hit-count } }\n\tvar exceptionCounts = {}; // { query-handle: { nodeId: exception-count } }\n\tvar logEntries = {}; // { query-handle: [invocation id] }\n\tvar anonFuncParentInvocation, lastException, lastExceptionThrownFromInvocation; // yucky globals track state between trace* calls\n\tvar nextInvocationId = 0;\n\tvar _hitQueries = [];\n\tvar _exceptionQueries = [];\n\tvar _logQueries = [];\n\tvar _fileCallGraph = [];\n\tvar _sourceMaps = {};\n\n\tvar _connected = false;\n\n\t// epochs\n\tvar _lastEpochID = 0;\n\tvar _lastEmitterID = 0;\n\tvar _epochsById = []; // int -> epoch (only epochs that end up as part of the call graph are saved)\n\tvar _epochsByName = {}; // string -> [epoch] (only epochs that end up as part of the call graph are saved)\n\tvar _topLevelEpochsByName = {}; // string -> [epoch]\n\tvar _epochStack = [];\n\tvar _epochInvocationDepth = []; // stack of how deep into the invocation stack of each epoch we are\n\tvar _topLevelInvocationsByEventName = {};\n\n\t// bail\n\tvar _bailedTick = false;\n\tvar _invocationsThisTick = 0;\n\tvar _invocationStackSize = 0;\n\tvar _explainedBails = false;\n\n\tfunction _resetTrace() {\n\t\tconsole.log(\"[fondue] resetting trace data...\");\n\n\t\tinvocationStack = [];\n\t\tinvocationById = {}; // id(string) -> invocation\n\t\tinvocationsByNodeId = {}; // id(string) -> array of invocations\n\t\texceptionsByNodeId = {}; // nodeId -> array of { exception: ..., invocationId: ... }\n\t\tuncaughtExceptionsByNodeId = {}; // nodeId -> array of { exception: ..., invocationId: ... }\n\t\tnodeHitCounts = {}; // { query-handle: { nodeId: hit-count } }\n\t\texceptionCounts = {}; // { query-handle: { nodeId: exception-count } }\n\t\tlogEntries = {}; // { query-handle: [invocation id] }\n\t\tanonFuncParentInvocation = undefined, lastException = undefined, lastExceptionThrownFromInvocation = undefined; // yucky globals track state between trace* calls\n\t\t_hitQueries = [];\n\t\t_exceptionQueries = [];\n\t\t_logQueries = [];\n\t\t_fileCallGraph = [];\n\n\t\t// epochs\n\t\t_epochsById = []; // int -> epoch (only epochs that end up as part of the call graph are saved)\n\t\t_epochsByName = {}; // string -> [epoch] (only epochs that end up as part of the call graph are saved)\n\t\t_topLevelEpochsByName = {}; // string -> [epoch]\n\t\t_epochStack = [];\n\t\t_epochInvocationDepth = []; // stack of how deep into the invocation stack of each epoch we are\n\t\t_topLevelInvocationsByEventName = {};\n\n\t\t// bail\n\t\t_bailedTick = false;\n\t\t_invocationsThisTick = 0;\n\t\t_invocationStackSize = 0;\n\t\t_explainedBails = false;\n\n\t\tnodeTracker.reset();\n\t\tepochTracker.reset();\n\t\tfileCallGraphTracker.reset();\n\t}\n\n\t/*\n\tFetching data from fondue happens by requesting a handle for the data you\n\twant, then calling another function to get the latest data from that handle.\n\tTypically, the first call to that function returns all the historical data\n\tand subsequent calls return the changes since the last call.\n\n\tThe bookkeeping was the same in all the cases. Now this 'base class' handles\n\tit. Just make a new instance and override backfill() and updateSingle().\n\t*/\n\tfunction Tracker(handlePrefix) {\n\t\tthis.lastHandleID = 0;\n\t\tthis.handlePrefix = handlePrefix;\n\t\tthis.queries = {}; // handle -> query\n\t\tthis.data = {}; // handle -> data\n\t}\n\tTracker.prototype = {\n\t\ttrack: function (query) {\n\t\t\tvar handleID = ++this.lastHandleID;\n\t\t\tvar handle = this.handlePrefix + '-' + handleID;\n\t\t\tthis.queries[handle] = query;\n\t\t\tthis.data[handle] = this.backfill(query);\n\t\t\treturn handle;\n\t\t},\n\t\tuntrack: function (handle) {\n\t\t\tthis._checkHandle(handle);\n\n\t\t\tdelete this.queries[handle];\n\t\t\tdelete this.data[handle];\n\t\t},\n\t\t/** return the data to be returned from the first call to delta() */\n\t\tbackfill: function (query) {\n\t\t\t// override this\n\t\t\treturn {};\n\t\t},\n\t\tupdate: function () {\n\t\t\tfor (var handle in this.data) {\n\t\t\t\tvar data = this.data[handle];\n\t\t\t\tvar args = [data].concat(Array.prototype.slice.apply(arguments));\n\t\t\t\tthis.data[handle] = this.updateSingle.apply(this, args);\n\t\t\t}\n\t\t},\n\t\t/**\n\t\tdata: the previous data for this query\n\t\targuments passed to update() will be passed after the data argument.\n\t\t*/\n\t\tupdateSingle: function (data, extraData1, extraData2) {\n\t\t\t// override this\n\t\t\tdata['foo'] = 'bar';\n\t\t\treturn data;\n\t\t},\n\t\tdelta: function (handle) {\n\t\t\tthis._checkHandle(handle);\n\n\t\t\tvar result = this.data[handle];\n\t\t\tthis.data[handle] = this.emptyData(handle);\n\t\t\treturn result;\n\t\t},\n\t\t/** after a call to delta(), the data for a handle is reset to this */\n\t\temptyData: function (handle) {\n\t\t\treturn {};\n\t\t},\n\t\treset: function () {\n\t\t\tthis.queries = {}; // handle -> query\n\t\t\tthis.data = {}; // handle -> data\n\t\t},\n\t\t_checkHandle: function (handle) {\n\t\t\tif (!(handle in this.queries)) {\n\t\t\t\tthrow new Error(\"unrecognized query\");\n\t\t\t}\n\t\t},\n\t}\n\n\tvar nodeTracker = new Tracker('node');\n\tnodeTracker.emptyData = function () {\n\t\treturn [];\n\t};\n\tnodeTracker.backfill = function () {\n\t\treturn nodes.slice();\n\t};\n\tnodeTracker.updateSingle = function (data, newNodes) {\n\t\tdata.push.apply(data, newNodes);\n\t\treturn data;\n\t};\n\n\tvar epochTracker = new Tracker('epoch');\n\tepochTracker.backfill = function () {\n\t\tvar data = {};\n\t\tfor (var epochName in _topLevelEpochsByName) {\n\t\t\tdata[epochName] = { hits: _topLevelEpochsByName[epochName].length };\n\t\t}\n\t\treturn data;\n\t};\n\tepochTracker.updateSingle = function (data, epoch) {\n\t\tif (!(epoch.eventName in data)) {\n\t\t\tdata[epoch.eventName] = { hits: 0 };\n\t\t}\n\t\tdata[epoch.eventName].hits++;\n\t\treturn data;\n\t};\n\n\tvar fileCallGraphTracker = new Tracker('file-call-graph');\n\tfileCallGraphTracker.emptyData = function () {\n\t\treturn [];\n\t};\n\tfileCallGraphTracker.backfill = function () {\n\t\treturn _fileCallGraph.slice();\n\t};\n\tfileCallGraphTracker.updateSingle = function (data, item) {\n\t\tdata.push(item);\n\t\treturn data;\n\t};\n\n\tfunction _addSpecialNodes() {\n\t\tvar node = {\n\t\t\tpath: \"[built-in]\",\n\t\t\tstart: { line: 0, column: 0 },\n\t\t\tend: { line: 0, column: 0 },\n\t\t\tid: \"log\",\n\t\t\ttype: \"function\",\n\t\t\tchildrenIds: [],\n\t\t\tparentId: undefined,\n\t\t\tname: \"[log]\",\n\t\t\tparams: []\n\t\t};\n\t\tnodes.push(node);\n\t\tnodeById[node.id] = node;\n\t}\n\t_addSpecialNodes();\n\n\n\t// helpers\n\n\t// adds keys from options to defaultOptions, overwriting on conflicts & returning defaultOptions\n\tfunction mergeInto(options, defaultOptions) {\n\t\tfor (var key in options) {\n\t\t\tdefaultOptions[key] = options[key];\n\t\t}\n\t\treturn defaultOptions;\n\t}\n\n\t/**\n\t * calls callback with (item, index, collect) where collect is a function\n\t * whose argument should be one of the strings to be de-duped.\n\t * returns an array where each string appears only once.\n\t */\n\tfunction dedup(collection, callback) {\n\t\tvar o = {};\n\t\tvar collect = function (str) {\n\t\t\to[str] = true;\n\t\t};\n\t\tfor (var i in collection) {\n\t\t\tcallback(collect, collection[i], i);\n\t\t}\n\t\tvar arr = [];\n\t\tfor (var str in o) {\n\t\t\tarr.push(str);\n\t\t}\n\t\treturn arr;\n\t};\n\n\tfunction count(collection, callback) {\n\t\tvar o = {};\n\t\tvar collect = function (str) {\n\t\t\tif (str in o) {\n\t\t\t\to[str]++;\n\t\t\t} else {\n\t\t\t\to[str] = 1;\n\t\t\t}\n\t\t};\n\t\tfor (var i in collection) {\n\t\t\tcallback(collect, collection[i], i);\n\t\t}\n\t\treturn o;\n\t};\n\n\tfunction flattenmap(collection, callback) {\n\t\tvar arr = [];\n\t\tvar collect = function (o) {\n\t\t\tarr.push(o);\n\t\t};\n\t\tfor (var i in collection) {\n\t\t\tcallback(collect, collection[i], i, collection);\n\t\t}\n\t\treturn arr;\n\t};\n\n\t/**\n\t * behaves like de-dup, but collect takes a second, 'value' argument.\n\t * returns an object whose keys are the first arguments to collect,\n\t * and values are arrays of all the values passed with that key\n\t */\n\tfunction cluster(collection, callback) {\n\t\tvar o = {};\n\t\tvar collect = function (key, value) {\n\t\t\tif (key in o) {\n\t\t\t\to[key].push(value);\n\t\t\t} else {\n\t\t\t\to[key] = [value];\n\t\t\t}\n\t\t};\n\t\tfor (var i in collection) {\n\t\t\tcallback(collect, collection[i], i);\n\t\t}\n\t\treturn o;\n\t};\n\n\t/**\n\t * returns a version of an object that's safe to JSON,\n\t * and is very conservative\n\t *\n\t * undefined -> { type: 'undefined', value: undefined }\n\t * null -> { type: 'undefined', value: null }\n\t * true -> { type: 'boolean', value: true }\n\t * 4 -> { type: 'number', value: 4 }\n\t * \"foo\" -> { type: 'string', value: \"foo\" }\n\t * (function () { }) -> { type: 'object' }\n\t * { a: \"b\" } -> { type: 'object' }\n\t */\n\tfunction marshalForTransmission(val, maxDepth) {\n\t\tif (maxDepth === undefined) {\n\t\t\tmaxDepth = 1;\n\t\t}\n\n\t\tvar o = { type: typeof(val) };\n\t\tif ([\"undefined\", \"boolean\", \"number\", \"string\"].indexOf(o.type) !== -1 || val === null) {\n\t\t\tif (typeof(val) === \"undefined\" && val !== undefined) {\n\t\t\t\t// special case: document.all claims to be undefined http://stackoverflow.com/questions/10350142/why-is-document-all-falsy\n\t\t\t\to.type = \"object\";\n\t\t\t\to.preview = \"\" + val;\n\t\t\t} else if (val === null) {\n\t\t\t\to.type = \"null\";\n\t\t\t\to.preview = \"null\";\n\t\t\t} else {\n\t\t\t\to.value = val;\n\t\t\t}\n\t\t} else if (o.type === \"object\") {\n\t\t\tvar newDepth = maxDepth - 1;\n\n\t\t\tif (val instanceof Array) {\n\t\t\t\tvar len = val.length;\n\t\t\t\tif (val.__theseusTruncated && val.__theseusTruncated.length) {\n\t\t\t\t\tlen += val.__theseusTruncated.length;\n\t\t\t\t}\n\t\t\t\to.preview = \"[Array:\" + len + \"]\";\n\t\t\t\tnewDepth = maxDepth - 0.5; // count for half\n\t\t\t} else if (typeof(Buffer) === \"function\" && (val instanceof Buffer)) {\n\t\t\t\tvar len = val.length;\n\t\t\t\tif (val.__theseusTruncated && val.__theseusTruncated.length) {\n\t\t\t\t\tlen += val.__theseusTruncated.length;\n\t\t\t\t}\n\t\t\t\to.preview = \"[Buffer:\" + len + \"]\";\n\t\t\t} else {\n\t\t\t\ttry { o.preview = String(val) } catch (e) { o.preview = \"[Object]\" }\n\t\t\t}\n\n\t\t\tif (maxDepth > 0) {\n\t\t\t\to.ownProperties = {};\n\t\t\t\tfor (var key in val) {\n\t\t\t\t\tif (val.hasOwnProperty(key) && !/^__theseus/.test(key)) {\n\t\t\t\t\t\to.ownProperties[key] = marshalForTransmission(val[key], newDepth);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (\"__theseusTruncated\" in val) {\n\t\t\t\to.truncated = {};\n\t\t\t\tif (\"length\" in val.__theseusTruncated) {\n\t\t\t\t\to.truncated.length = {\n\t\t\t\t\t\tamount: val.__theseusTruncated.length,\n\t\t\t\t\t};\n\t\t\t\t}\n\t\t\t\tif (\"keys\" in val.__theseusTruncated) {\n\t\t\t\t\to.truncated.keys = {\n\t\t\t\t\t\tamount: val.__theseusTruncated.keys,\n\t\t\t\t\t};\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn o;\n\t}\n\n\tfunction scrapeObject(object, depth) {\n\t\tvar MAX_BUFFER_LENGTH = 32;\n\t\tvar MAX_TOTAL_SIZE = 512;\n\n\t\t/**\n\t\tIt's everyone's favorite game: bin packing!\n\n\t\tThere's a big bin: total memory\n\t\tThere's a smaller bin: the memory used by this scraped object\n\t\tThere's smaller bins: the memory used by each child of this scraped object\n\n\t\tOur job is to copy as much useful information we can without overflowing\n\t\tthe big bin (total memory). For now, we pretend that bin is bottomless.\n\n\t\tSo our job is really to copy as much useful information as we can into\n\t\tthe MAX_TOTAL_SIZE \"bytes\" allocated to this scraped object. We do this\n\t\tby performing a deep copy, and any time we encounter an object that's\n\t\tsufficiently large to put us over the limit, we store a reference to it\n\t\tinstead of copying it.\n\n\t\tIn this function, the \"size\" of a copy is approximated by summing the\n\t\tlengths of all strings, the lengths of all keys, and the count of\n\t\tobjects of any other type, ignoring the overhead of array/object storage.\n\t\t**/\n\n\t\t// returns array: [approx size of copy, copy]\n\t\tvar scrape = function (o, depth) {\n\t\t\tif (typeof(o) === \"string\") return [o.length, o]; // don't worry about retaining strings > MAX_TOTAL_SIZE, for now\n\n\t\t\tif (depth <= 0) return [1, o]; // XXX: even if there's a ton there, count it as 1\n\t\t\tif (o === null || typeof(o) !== \"object\") return [1, o];\n\n\t\t\t// return only the first MAX_BUFFER_LENGTH bytes of a Buffer\n\t\t\tif (typeof(Buffer) === \"function\" && (o instanceof Buffer)) {\n\t\t\t\tvar len = Math.min(o.length, MAX_BUFFER_LENGTH);\n\t\t\t\tvar o2 = new Buffer(len);\n\t\t\t\tif (o.length > MAX_BUFFER_LENGTH) {\n\t\t\t\t\to2.__theseusTruncated = { length: o.length - MAX_BUFFER_LENGTH };\n\t\t\t\t}\n\t\t\t\ttry { o.copy(o2, 0, 0, len); } catch (e) { }\n\t\t\t\treturn [len, o2];\n\t\t\t}\n\n\t\t\ttry {\n\t\t\t\tvar size = 0;\n\t\t\t\tvar o2 = (o instanceof Array) ? [] : {};\n\t\t\t\tfor (var key in o) {\n\t\t\t\t\tif ((o.__lookupGetter__ instanceof Function) && o.__lookupGetter__(key))\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\tif (!(o.hasOwnProperty instanceof Function) || !o.hasOwnProperty(key))\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\tvar scraped = scrape(o[key], depth - 1);\n\t\t\t\t\tvar childSize = key.length + scraped[0];\n\t\t\t\t\tif (size + childSize <= MAX_TOTAL_SIZE) {\n\t\t\t\t\t\tsize += childSize;\n\t\t\t\t\t\to2[key] = scraped[1];\n\t\t\t\t\t} else {\n\t\t\t\t\t\t// XXX: if it's an array and this is a numeric key, count it as truncating the length instead\n\t\t\t\t\t\tif (!(\"__theseusTruncated\" in o2)) {\n\t\t\t\t\t\t\to2.__theseusTruncated = { keys: 0 };\n\t\t\t\t\t\t}\n\t\t\t\t\t\to2.__theseusTruncated.keys++;\n\t\t\t\t\t\to2[key] = o[key];\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\treturn [size, o2];\n\t\t\t} catch (e) {\n\t\t\t\tconsole.log(\"[fondue] couldn't scrape\", o, e);\n\t\t\t\treturn [1, o];\n\t\t\t}\n\t\t};\n\n\t\treturn scrape(object, 1)[1];\n\t}\n\n\tfunction Invocation(info, type) {\n\t\tthis.tick = nextInvocationId++;\n\t\tthis.id = TRACER_ID + \"-\" + this.tick;\n\t\tthis.timestamp = new Date().getTime();\n\t\tthis.type = type;\n\t\tthis.f = nodeById[info.nodeId];\n\t\tthis.childLinks = [];\n\t\tthis.parentLinks = [];\n\t\tthis.returnValue = undefined;\n\t\tthis.exception = undefined;\n\t\tthis.topLevelInvocationId = undefined;\n\t\tthis.epochID = undefined;\n\t\tthis.epochDepth = undefined;\n\t\tthis.arguments = info.arguments ? info.arguments.map(function (a) { return scrapeObject(a) }) : undefined;\n\t\tthis.this = (info.this && info.this !== globalThis) ? scrapeObject(info.this) : undefined;\n\n\t\tinvocationById[this.id] = this;\n\t}\n\tInvocation.prototype.equalToInfo = function (info) {\n\t\treturn this.f.id === info.nodeId;\n\t};\n\tInvocation.prototype.linkToChild = function (child, linkType) {\n\t\tthis.childLinks.push(new InvocationLink(child.id, linkType));\n\t\tchild.parentLinks.push(new InvocationLink(this.id, linkType));\n\t\tif (['call', 'branch-enter'].indexOf(linkType) !== -1) {\n\t\t\tchild.topLevelInvocationId = this.topLevelInvocationId;\n\t\t}\n\t};\n\tInvocation.prototype.getChildren = function (linkFilter) {\n\t\tvar links = this.childLinks;\n\t\tif (linkFilter) {\n\t\t\tlinks = links.filter(linkFilter);\n\t\t}\n\t\treturn links.map(function (link) { return invocationById[link.id]; });\n\t};\n\tInvocation.prototype.getParents = function () {\n\t\treturn this.parentLinks.map(function (link) { return invocationById[link.id]; });\n\t};\n\tInvocation.prototype.getParentLinks = function () {\n\t\treturn this.parentLinks;\n\t};\n\t/**\n\tcalls iter(invocation) for all children in sub-graph; if iter returns true,\n\ttreats that invocation as a leaf and continues\n\t**/\n\tInvocation.prototype.walk = function (iter) {\n\t\tthis.getChildren().forEach(function (child) {\n\t\t\tif (iter(child) !== true) {\n\t\t\t\tchild.walk(iter);\n\t\t\t}\n\t\t});\n\t};\n\n\tfunction InvocationLink(destId, type) {\n\t\tthis.id = destId;\n\t\tthis.type = type;\n\t}\n\n\tfunction Epoch(id, emitterID, eventName) {\n\t\tthis.id = id;\n\t\tthis.emitterID = emitterID;\n\t\tthis.eventName = eventName;\n\t}\n\n\tfunction nextEpoch(emitterID, eventName) {\n\t\tvar epochID = ++_lastEpochID;\n\t\tvar epoch = new Epoch(epochID, emitterID, eventName);\n\t\treturn epoch;\n\t}\n\n\tfunction hit(invocation) {\n\t\tvar id = invocation.f.id;\n\t\tfor (var handle in nodeHitCounts) {\n\t\t\tvar hits = nodeHitCounts[handle];\n\t\t\thits[id] = (hits[id] || 0) + 1;\n\t\t}\n\n\t\t// if this is console.log, we'll want the call site in a moment\n\t\tvar callSite;\n\t\tif (invocation.f.id === \"log\") {\n\t\t\tcallSite = invocation.getParents().filter(function (inv) { return inv.type === \"callsite\" })[0];\n\t\t}\n\n\t\t// add this invocation to all the relevant log queries\n\t\tfor (var handle in _logQueries) {\n\t\t\tvar query = _logQueries[handle];\n\t\t\tif (query.logs && invocation.f.id === \"log\") {\n\t\t\t\tif (callSite) {\n\t\t\t\t\taddLogEntry(handle, callSite.id);\n\t\t\t\t} else {\n\t\t\t\t\tconsole.log(\"no call site! I needed one!\", invocation.getParents());\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (query.ids && query.ids.indexOf(id) !== -1) {\n\t\t\t\taddLogEntry(handle, invocation.id);\n\t\t\t}\n\t\t}\n\t}\n\n\tfunction calculateHitCounts() {\n\t\tvar hits = {};\n\t\tnodes.forEach(function (n) {\n\t\t\tif (n.id in invocationsByNodeId) {\n\t\t\t\thits[n.id] = invocationsByNodeId[n.id].length;\n\t\t\t}\n\t\t});\n\t\treturn hits;\n\t}\n\n\tfunction calculateExceptionCounts() {\n\t\tvar counts = {};\n\t\tnodes.forEach(function (n) {\n\t\t\tif (n.id in exceptionsByNodeId) {\n\t\t\t\tcounts[n.id] = exceptionsByNodeId[n.id].length;\n\t\t\t}\n\t\t});\n\t\treturn counts;\n\t}\n\n\t/** return ordered list of invocation ids for the given log query */\n\tfunction backlog(query) {\n\t\tvar seenIds = {};\n\t\tvar ids = [];\n\n\t\tfunction addIfUnseen(id) {\n\t\t\tif (!(id in seenIds)) {\n\t\t\t\tids.push(id);\n\t\t\t\tseenIds[id] = true;\n\t\t\t}\n\t\t}\n\n\t\tvar getId = function (invocation) { return invocation.id };\n\n\t\tif (query.ids) {\n\t\t\tquery.ids.forEach(function (nodeId) {\n\t\t\t\tvar invocations = (invocationsByNodeId[nodeId] || []);\n\t\t\t\tinvocations.map(getId).forEach(addIfUnseen);\n\n\t\t\t\t// add logs that are called directly from this function\n\t\t\t\tinvocations.forEach(function (invocation) {\n\t\t\t\t\tinvocation.walk(function (child) {\n\t\t\t\t\t\tvar isFunction = child.type === \"function\";\n\t\t\t\t\t\tif (isFunction && child.f.id === \"log\") {\n\t\t\t\t\t\t\tvar callSite = child.getParents().filter(function (inv) { return inv.type === \"callsite\" })[0];\n\t\t\t\t\t\t\tif (callSite) {\n\t\t\t\t\t\t\t\taddIfUnseen(callSite.id);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\treturn isFunction;\n\t\t\t\t\t})\n\t\t\t\t});\n\t\t\t});\n\t\t}\n\n\t\tif (query.eventNames) {\n\t\t\tquery.eventNames.forEach(function (name) {\n\t\t\t\t(_topLevelInvocationsByEventName[name] || []).map(getId).forEach(addIfUnseen);\n\t\t\t});\n\t\t}\n\n\t\tif (query.exceptions) {\n\t\t\tfor (var nodeId in uncaughtExceptionsByNodeId) {\n\t\t\t\tuncaughtExceptionsByNodeId[nodeId].map(function (o) { return o.invocationId }).forEach(addIfUnseen);\n\t\t\t}\n\t\t}\n\n\t\tif (query.logs) {\n\t\t\t(invocationsByNodeId[\"log\"] || []).forEach(function (invocation) {\n\t\t\t\tvar callSite = invocation.getParents().filter(function (inv) { return inv.type === \"callsite\" })[0];\n\t\t\t\tif (callSite) {\n\t\t\t\t\taddIfUnseen(callSite.id);\n\t\t\t\t}\n\t\t\t});\n\t\t}\n\n\t\tids = ids.sort(function (a, b) { return invocationById[a].tick - invocationById[b].tick });\n\t\treturn { entries: ids, seenIds: seenIds };\n\t}\n\n\tfunction addLogEntry(handle, invocationId) {\n\t\tif (!(invocationId in logEntries[handle].seenIds)) {\n\t\t\tlogEntries[handle].entries.push(invocationId);\n\t\t\tlogEntries[handle].seenIds[invocationId] = true;\n\t\t}\n\t}\n\n\n\t// instrumentation\n\n\tfunction bailThisTick(fromNode) {\n\t\t_bailedTick = true;\n\t\tinvocationStack = [];\n\t\t_epochStack = [];\n\t\t_epochInvocationDepth = [];\n\t\tanonFuncParentInvocation = undefined;\n\t\tlastException = undefined;\n\t\tlastExceptionThrownFromInvocation = undefined;\n\n\t\tif (fromNode) {\n\t\t\tconsole.log(\"[fondue] bailing from \" + (fromNode.name ? (fromNode.name + \" at \") : \"\") + fromNode.path + \" line \" + fromNode.start.line + \", character \" + fromNode.start.column);\n\t\t} else {\n\t\t\tconsole.log(\"[fondue] bailing! trace collection will resume next tick\");\n\t\t}\n\t\tif (!_explainedBails) {\n\t\t\tconsole.log(\"[fondue] (fondue is set to automatically bail after {maxInvocationsPerTick} invocations within a single tick. If you are using node-theseus, you can use the --theseus-max-invocations-per-tick=XXX option to raise the limit, but it will require more memory)\");\n\t\t\t_explainedBails = true;\n\t\t}\n\t}\n\n\tfunction endBail() {\n\t\t_bailedTick = false;\n\t\t_invocationsThisTick = 0;\n\n\t\tconsole.log('[fondue] resuming trace collection after bailed tick');\n\t}\n\n\tfunction pushNewInvocation(info, type) {\n\t\tif (_bailedTick) {\n\t\t\t_invocationStackSize++;\n\t\t\treturn;\n\t\t}\n\n\t\tvar invocation = new Invocation(info, type);\n\t\tpushInvocation(invocation);\n\t\treturn invocation;\n\t}\n\n\tfunction pushInvocation(invocation) {\n\t\t_invocationStackSize++;\n\n\t\tif (_bailedTick) return;\n\n\t\t_invocationsThisTick++;\n\t\tif (_invocationsThisTick === {maxInvocationsPerTick}) {\n\t\t\tbailThisTick(invocation.f);\n\t\t\treturn;\n\t\t}\n\n\t\t// associate with epoch, if there is one\n\t\tif (_epochStack.length > 0) {\n\t\t\tvar epoch = _epochStack[_epochStack.length - 1];\n\t\t\tvar depth = _epochInvocationDepth[_epochInvocationDepth.length - 1];\n\t\t\tinvocation.epochID = epoch.id;\n\t\t\tinvocation.epochDepth = depth;\n\n\t\t\t_epochInvocationDepth[_epochInvocationDepth.length - 1]++;\n\n\t\t\t// hang on to the epoch now that it's part of the call graph\n\t\t\t_epochsById[epoch.id] = epoch;\n\n\t\t\tif (!(epoch.eventName in _epochsByName)) {\n\t\t\t\t_epochsByName[epoch.eventName] = [];\n\t\t\t}\n\t\t\t_epochsByName[epoch.eventName].push(epoch);\n\n\t\t\tif (depth === 0) {\n\t\t\t\tepochTracker.update(epoch);\n\n\t\t\t\tif (!(epoch.eventName in _topLevelEpochsByName)) {\n\t\t\t\t\t_topLevelEpochsByName[epoch.eventName] = [];\n\t\t\t\t\t_topLevelInvocationsByEventName[epoch.eventName] = [];\n\t\t\t\t}\n\t\t\t\t_topLevelEpochsByName[epoch.eventName].push(epoch);\n\t\t\t\t_topLevelInvocationsByEventName[epoch.eventName].push(invocation);\n\n\t\t\t\tfor (var handle in _logQueries) {\n\t\t\t\t\tvar query = _logQueries[handle];\n\t\t\t\t\tif (query.eventNames && query.eventNames.indexOf(epoch.eventName) !== -1) {\n\t\t\t\t\t\taddLogEntry(handle, invocation.id);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t// add to invocationsByNodeId\n\t\tif (!invocationsByNodeId[invocation.f.id]) {\n\t\t\tinvocationsByNodeId[invocation.f.id] = [];\n\t\t}\n\t\tinvocationsByNodeId[invocation.f.id].push(invocation);\n\n\t\t// associate with caller, if there is one; otherwise, save as a top-level invocation\n\t\tvar top = invocationStack[invocationStack.length - 1];\n\t\tif (top) {\n\t\t\ttop.linkToChild(invocation, 'call');\n\t\t} else {\n\t\t\tinvocation.topLevelInvocationId = invocation.id;\n\t\t}\n\n\t\t// associate with the invocation where this anonymous function was created\n\t\tif (anonFuncParentInvocation) {\n\t\t\tanonFuncParentInvocation.linkToChild(invocation, 'async');\n\t\t\tanonFuncParentInvocation = undefined;\n\t\t}\n\n\t\t// update hit counts\n\t\thit(invocation);\n\n\t\tinvocationStack.push(invocation);\n\t}\n\n\tfunction popInvocation(info) {\n\t\t_invocationStackSize--;\n\t\tif (_bailedTick && _invocationStackSize === 0) {\n\t\t\tendBail();\n\t\t\treturn;\n\t\t}\n\n\t\tif (_bailedTick) return;\n\n\t\tvar top = invocationStack.pop();\n\n\t\t// if the tick was bailed or something, there might not be an invocation\n\t\tif (top) {\n\t\t\ttop.endTimestamp = new Date().getTime();\n\t\t\ttop.duration = top.endTimestamp - top.timestamp;\n\n\t\t\t// if there was an exception before, but this function didn't throw\n\t\t\t// it as well, then it must have been caught.\n\t\t\t// only functions track exceptions.\n\t\t\tif (top.type === 'function' && lastException !== undefined && top.exception !== lastException) {\n\t\t\t\t// traceExceptionThrown sets lastException, but this is where we clear it\n\t\t\t\tif (top.exception === undefined) {\n\t\t\t\t\tlastException = undefined;\n\t\t\t\t\tlastExceptionThrownFromInvocation = undefined;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tif (invocationStack.length === 0) {\n\t\t\t// check for uncaught exceptions\n\t\t\tif (lastException !== undefined && lastExceptionThrownFromInvocation !== undefined) {\n\t\t\t\tvar id = lastExceptionThrownFromInvocation.f.id;\n\n\t\t\t\tif (!uncaughtExceptionsByNodeId[id]) {\n\t\t\t\t\tuncaughtExceptionsByNodeId[id] = [];\n\t\t\t\t}\n\t\t\t\tuncaughtExceptionsByNodeId[id].push({ exception: lastException, invocationId: lastExceptionThrownFromInvocation.id });\n\n\t\t\t\tfor (var handle in _logQueries) {\n\t\t\t\t\tif (_logQueries[handle].exceptions) {\n\t\t\t\t\t\t// BUG: we're adding this at the end of the tick, which\n\t\t\t\t\t\t// means it's technically out-of-order relative to\n\t\t\t\t\t\t// the other log entries in this tick.\n\t\t\t\t\t\taddLogEntry(handle, lastExceptionThrownFromInvocation.id);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t_invocationsThisTick = 0;\n\t\t\tlastException = undefined;\n\t\t\tlastExceptionThrownFromInvocation = undefined;\n\n\t\t\t// make the file call graph for this tick\n\n\t\t\t// if the tick was bailed or something, there might not be an invocation\n\t\t\tif (top) {\n\t\t\t\tfunction makeSubgraph(invocation, node) {\n\t\t\t\t\tif (!node) {\n\t\t\t\t\t\tnode = { path: invocation.f.path, nodeId: invocation.f.id, eventNames: [], children: [] };\n\t\t\t\t\t} else if (node.path !== invocation.f.path) {\n\t\t\t\t\t\tvar parent = node;\n\t\t\t\t\t\tnode = { path: invocation.f.path, nodeId: invocation.f.id, eventNames: [], children: [] };\n\t\t\t\t\t\tparent.children.push(node);\n\t\t\t\t\t}\n\t\t\t\t\tif (invocation.epochID) {\n\t\t\t\t\t\tvar epoch = _epochsById[invocation.epochID];\n\t\t\t\t\t\tif (epoch.eventName !== undefined && node.eventNames.indexOf(epoch.eventName) === -1) {\n\t\t\t\t\t\t\tnode.eventNames.push(epoch.eventName);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tinvocation.getChildren(function (link) { return link.type === \"call\" }).forEach(function (child) {\n\t\t\t\t\t\tmakeSubgraph(child, node);\n\t\t\t\t\t});\n\t\t\t\t\treturn node;\n\t\t\t\t}\n\n\t\t\t\tvar item = makeSubgraph(top);\n\t\t\t\t_fileCallGraph.push(item);\n\t\t\t\tfileCallGraphTracker.update(item);\n\t\t\t}\n\t\t}\n\n\t\tif (_epochStack.length > 0) {\n\t\t\t_epochInvocationDepth[_epochInvocationDepth.length - 1]--;\n\t\t}\n\t}\n\n\t/**\n\t * called from the top of every script processed by the rewriter\n\t */\n\tthis.add = function (path, options) {\n\t\tnodes.push.apply(nodes, options.nodes);\n\t\toptions.nodes.forEach(function (n) { nodeById[n.id] = n; });\n\n\t\tnodeTracker.update(options.nodes);\n\n\t\t_sendNodes(options.nodes);\n\t};\n\n\tthis.addSourceMap = function (path, mapJSON) {\n\t\t_sourceMaps[path] = _sourceMaps[path + \".fondue\"] = new sourceMap.SourceMapConsumer(mapJSON);\n\t};\n\n\tthis.traceFileEntry = function (info) {\n\t\tpushNewInvocation(info, 'toplevel');\n\t};\n\n\tthis.traceFileExit = function (info) {\n\t\tpopInvocation(info);\n\t};\n\n\tthis.setGlobal = function (gthis) {\n\t\tglobalThis = gthis;\n\t}\n\n\t/**\n\t * the rewriter wraps every anonymous function in a call to traceFunCreate.\n\t * a new function is returned that's associated with the parent invocation.\n\t */\n\tthis.traceFunCreate = function (f, src) {\n\t\tvar creatorInvocation = invocationStack[invocationStack.length - 1];\n\t\tvar creatorInvocationId = creatorInvocation ? creatorInvocation.id : undefined;\n\t\tvar newF;\n\n\t\t// Some code changes its behavior depending on the arity of the callback.\n\t\t// Therefore, we construct a replacement function that has the same arity.\n\t\t// The most direct route seems to be to use eval() (as opposed to\n\t\t// new Function()), so that creatorInvocation can be accessed from the\n\t\t// closure.\n\n\t\tvar arglist = '';\n\t\tfor (var i = 0; i < f.length; i++) {\n\t\t\targlist += (i > 0 ? ', ' : '') + 'v' + i;\n\t\t}\n\n\t\tvar sharedBody = 'return f.apply(this, arguments);';\n\n\t\tif (creatorInvocation) {\n\t\t\t// traceEnter checks anonFuncParentInvocation and creates\n\t\t\t// an edge in the graph from the creator to the new invocation.\n\t\t\t// Look up by ID instead of using creatorInvocation directly in case\n\t\t\t// the trace has been cleared and the original invocation no longer\n\t\t\t// exists.\n\t\t\tvar asyncBody = 'anonFuncParentInvocation = invocationById[creatorInvocationId];';\n\t\t\tvar newSrc = '(function (' + arglist + ') { ' + asyncBody + sharedBody + '})';\n\t\t\tnewF = eval(newSrc);\n\t\t} else {\n\t\t\tvar newSrc = '(function (' + arglist + ') { ' + sharedBody + '})';\n\t\t\tnewF = eval(newSrc);\n\t\t}\n\t\tnewF.toString = function () { return src };\n\t\treturn newF;\n\t};\n\n\t/** helper for traceFunCall below */\n\tvar _traceLogCall = function (info) {\n\t\tvar queryMatchesInvocation = function (handle, invocation) {\n\t\t\tvar query = _logQueries[handle];\n\t\t\tvar epoch = _epochsById[invocation.epochID];\n\t\t\tif (query.logs && invocation.f.id === \"log\") {\n\t\t\t\treturn true;\n\t\t\t} else if (query.exceptions && invocation.exception) {\n\t\t\t\treturn true;\n\t\t\t} else if (query.ids && query.ids.indexOf(invocation.f.id) !== -1) {\n\t\t\t\treturn true;\n\t\t\t} else if (query.eventNames && epoch && query.eventNames.indexOf(epoch.eventName) !== -1) {\n\t\t\t\treturn true;\n\t\t\t}\n\t\t\treturn false;\n\t\t};\n\t\tvar matchingQueryHandles = function (invocation) {\n\t\t\treturn Object.keys(_logQueries).filter(function (handle) {\n\t\t\t\treturn queryMatchesInvocation(handle, invocation);\n\t\t\t});\n\t\t};\n\n\t\treturn function () {\n\t\t\tconsole.log.apply(console, arguments);\n\n\t\t\tvar callerInvocation = invocationStack[invocationStack.length - 1];\n\n\t\t\tinfo.arguments = Array.prototype.slice.apply(arguments); // XXX: mutating info may not be okay, but we want the arguments\n\n\t\t\tvar callSiteInvocation = pushNewInvocation(info, 'callsite');\n\t\t\tpushNewInvocation({ nodeId: \"log\", arguments: info.arguments }, 'function');\n\t\t\tpopInvocation();\n\t\t\tpopInvocation();\n\n\t\t\t// if called directly from an invocation that's in the query, add\n\t\t\t// this log statement invocation as well\n\t\t\t// (callSiteInvocation might be falsy if this tick was bailed)\n\t\t\tif (callerInvocation && callSiteInvocation) {\n\t\t\t\tmatchingQueryHandles(callerInvocation).forEach(function (handle) {\n\t\t\t\t\taddLogEntry(handle, callSiteInvocation.id);\n\t\t\t\t});\n\t\t\t}\n\t\t}\n\t};\n\n\t/**\n\t * the rewriter wraps the callee portion of every function call with a call\n\t * to traceFunCall like this:\n\t *\n\t * a.b('foo') -> (traceFunCall({ this: a, property: 'b', nodeId: '...', vars: {}))('foo')\n\t * b('foo') -> (traceFunCall({ func: b, nodeId: '...', vars: {}))('foo')\n\t */\n\tthis.traceFunCall = function (info) {\n\t\tvar customThis = false, fthis, func;\n\n\t\tif ('func' in info) {\n\t\t\tfunc = info.func;\n\t\t} else {\n\t\t\tcustomThis = true;\n\t\t\tfthis = info.this;\n\t\t\tfunc = fthis[info.property];\n\t\t}\n\n\t\t// if it doesn't look like a function, it's faster not to wrap it with\n\t\t// all of the cruft below\n\t\tif (!func) {\n\t\t\treturn func;\n\t\t}\n\n\t\tvar logFunctions = [console.log, console.info, console.warn, console.error, console.trace];\n\t\tif (typeof console !== 'undefined' && logFunctions.indexOf(func) !== -1) {\n\t\t\treturn _traceLogCall(info);\n\t\t}\n\n\t\treturn function () {\n\t\t\tinfo.arguments = Array.prototype.slice.apply(arguments); // XXX: mutating info may not be okay, but we want the arguments\n\t\t\tvar invocation = pushNewInvocation(info, 'callsite');\n\n\t\t\ttry {\n\t\t\t\t// this used to be func.apply(t, arguments), but not all functions\n\t\t\t\t// have apply. so we apply Function.apply instead.\n\t\t\t\tvar t = customThis ? fthis : this;\n\t\t\t\treturn Function.apply.apply(func, [t].concat(arguments));\n\t\t\t} finally {\n\t\t\t\tpopInvocation();\n\t\t\t}\n\t\t}\n\t};\n\n\t/**\n\t * the rewriter calls traceEnter from just before the try clause it wraps\n\t * function bodies in. info is an object like:\n\t *\n\t * {\n\t * start: { line: ..., column: ... },\n\t * end: { line: ..., column: ... },\n\t * vars: { a: a, b: b, ... }\n\t * }\n\t */\n\tthis.traceEnter = function (info) {\n\t\tpushNewInvocation(info, 'function');\n\t};\n\n\t/**\n\t * the rewriter calls traceExit from the finally clause it wraps function\n\t * bodies in. info is an object like:\n\t *\n\t * {\n\t * start: { line: ..., column: ... },\n\t * end: { line: ..., column: ... }\n\t * }\n\t *\n\t * in the future, traceExit will be passed an object with all the\n\t * local variables of the instrumented function.\n\t */\n\tthis.traceExit = function (info) {\n\t\tpopInvocation(info);\n\t};\n\n\tthis.traceReturnValue = function (value) {\n\t\tif (_bailedTick) return value;\n\n\t\tvar top = invocationStack[invocationStack.length - 1];\n\t\tif (!top) {\n\t\t\tthrow new Error('value returned with nothing on the stack');\n\t\t}\n\t\ttop.returnValue = scrapeObject(value);\n\t\treturn value;\n\t}\n\n\t/**\n\t * the rewriter calls traceExceptionThrown from the catch clause it wraps\n\t * function bodies in. info is an object like:\n\t *\n\t * {\n\t * start: { line: ..., column: ... },\n\t * end: { line: ..., column: ... }\n\t * }\n\t */\n\tthis.traceExceptionThrown = function (info, exception) {\n\t\tif (_bailedTick) return;\n\n\t\tlastException = exception;\n\n\t\tvar parsedStack;\n\t\tif (exception.stack) {\n\t\t\tvar mapFrame = function (frame) {\n\t\t\t\tif (frame.path in _sourceMaps) {\n\t\t\t\t\tvar pos = _sourceMaps[frame.path].originalPositionFor({ line: frame.line, column: frame.column });\n\t\t\t\t\tframe.path = pos.source;\n\t\t\t\t\tframe.line = pos.line;\n\t\t\t\t\tframe.column = pos.column;\n\t\t\t\t}\n\t\t\t\treturn frame;\n\t\t\t};\n\n\t\t\tvar shouldIgnoreFrame = function (frame) {\n\t\t\t\treturn /node-theseus\\.js/.test(frame.path) || /^Module\\.(load|_compile)$/.test(frame.at);\n\t\t\t};\n\n\t\t\tparsedStack = [];\n\t\t\tvar match, match2,\n\t\t\t\twholeMatchRegexp = /\\n at ([^(]+) \\((.*):(\\d+):(\\d+)\\)/g; // TODO: match lines without column numbers\n\t\t\t\tpartialMatchRegexp = /at ([^(]+) \\((.*):(\\d+):(\\d+)\\)/g;\n\t\t\twhile (match = wholeMatchRegexp.exec(exception.stack)) {\n\t\t\t\tvar frame = mapFrame({\n\t\t\t\t\tat: match[1],\n\t\t\t\t\tpath: match[2],\n\t\t\t\t\tline: parseInt(match[3]),\n\t\t\t\t\tcolumn: parseInt(match[4]),\n\t\t\t\t});\n\t\t\t\tif (/^eval at /.test(match[2]) && (match2 = partialMatchRegexp.exec(match[2]))) {\n\t\t\t\t\tframe.evalFrame = mapFrame({\n\t\t\t\t\t\tat: match2[1],\n\t\t\t\t\t\tpath: match2[2],\n\t\t\t\t\t\tline: parseInt(match2[3]),\n\t\t\t\t\t\tcolumn: parseInt(match2[4]),\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t\tif (!shouldIgnoreFrame(frame) && (!frame.evalFrame || !shouldIgnoreFrame(frame.evalFrame))) {\n\t\t\t\t\tparsedStack.push(frame);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tvar top = invocationStack[invocationStack.length - 1];\n\t\tif (!top || !top.equalToInfo(info)) {\n\t\t\tthrow new Error('exception thrown from a non-matching enter');\n\t\t}\n\t\ttop.exception = exception;\n\t\ttop.rawStack = exception.stack;\n\t\tif (parsedStack) top.exceptionStack = parsedStack;\n\n\t\tif (lastExceptionThrownFromInvocation === undefined) {\n\t\t\tlastExceptionThrownFromInvocation = top;\n\t\t}\n\n\t\tvar id = top.f.id;\n\t\tif (!exceptionsByNodeId[id]) {\n\t\t\texceptionsByNodeId[id] = [];\n\t\t}\n\t\texceptionsByNodeId[id].push({ exception: exception, invocationId: top.id });\n\n\t\tfor (var handle in exceptionCounts) {\n\t\t\tvar hits = exceptionCounts[handle];\n\t\t\thits[id] = (hits[id] || 0) + 1;\n\t\t}\n\t};\n\n\t/** cease collecting trace information until the next tick **/\n\tthis.bailThisTick = bailThisTick;\n\n\tthis.pushEpoch = function (epoch) {\n\t\t_epochStack.push(epoch);\n\t\t_epochInvocationDepth.push(0);\n\t};\n\n\tthis.popEpoch = function () {\n\t\t_epochStack.pop();\n\t\t_epochInvocationDepth.pop();\n\t}\n\n\tif ({nodejs}) {\n\t\t// override EventEmitter.emit() to automatically begin epochs when events are thrown\n\t\tvar EventEmitter = require('events').EventEmitter;\n\t\tvar oldEmit = EventEmitter.prototype.emit;\n\t\tEventEmitter.prototype.emit = function (ev) {\n\t\t\t// give this emitter an identifier if it doesn't already have one\n\t\t\tif (!this._emitterID) {\n\t\t\t\tthis._emitterID = ++_lastEmitterID;\n\t\t\t}\n\n\t\t\t// start an epoch & emit the event\n\t\t\tvar epoch = nextEpoch(this._emitterID, ev);\n\t\t\t{name}.pushEpoch(epoch);\n\t\t\ttry {\n\t\t\t\treturn oldEmit.apply(this, arguments);\n\t\t\t} finally {\n\t\t\t\t{name}.popEpoch();\n\t\t\t}\n\t\t};\n\t}\n\n\tthis.augmentjQuery = function ($) {\n\t\tvar trigger = $.event.trigger, triggerHandler = $.event.triggerHandler;\n\t\tvar core_hasOwn = {}.hasOwnProperty;\n\t\t$.event.trigger = function (event) {\n\t\t\tvar type = core_hasOwn.call(event, \"type\") ? event.type : event;\n\t\t\tvar epoch = nextEpoch(-1 /* emitterID */, type);\n\n\t\t\t{name}.pushEpoch(epoch);\n\t\t\ttry {\n\t\t\t\treturn trigger.apply($.event, arguments);\n\t\t\t} finally {\n\t\t\t\t{name}.popEpoch();\n\t\t\t}\n\t\t};\n\t\t$.event.triggerHandler = function (event) {\n\t\t\tvar type = core_hasOwn.call(event, \"type\") ? event.type : event;\n\t\t\tvar epoch = nextEpoch(-1 /* emitterID */, type);\n\n\t\t\t{name}.pushEpoch(epoch);\n\t\t\ttry {\n\t\t\t\treturn triggerHandler.apply($.event, arguments);\n\t\t\t} finally {\n\t\t\t\t{name}.popEpoch();\n\t\t\t}\n\t\t};\n\t};\n\n\n\t// remote prebuggin' (from Brackets)\n\n\tvar _sendNodes = function (nodes) {\n\t\tif (_connected) {\n\t\t\t_sendBracketsMessage('scripts-added', JSON.stringify({ nodes: nodes }));\n\t\t}\n\t};\n\n\tfunction _sendBracketsMessage(name, value) {\n\t\tvar key = \"data-{name}-\" + name;\n\t\tdocument.body.setAttribute(key, value);\n\t\twindow.setTimeout(function () { document.body.removeAttribute(key); });\n\t}\n\n\tthis.version = function () {\n\t\treturn {version};\n\t};\n\n\t// deprecated\n\tthis.connect = function () {\n\t\tif (typeof console !== 'undefined') console.log(\"Opening the Developer Console will break the connection with Brackets!\");\n\t\t_connected = true;\n\t\t_sendNodes(nodes);\n\t\treturn this;\n\t};\n\n\tthis.resetTrace = _resetTrace;\n\n\t// accessors\n\n\t// this is mostly here for unit tests, and not necessary or encouraged\n\t// use trackNodes instead\n\tthis.nodes = function () {\n\t\treturn nodes;\n\t};\n\n\tthis.trackNodes = function () {\n\t\treturn nodeTracker.track();\n\t};\n\n\tthis.untrackNodes = function (handle) {\n\t\treturn nodeTracker.untrack(handle);\n\t};\n\n\tthis.newNodes = function (handle) {\n\t\treturn nodeTracker.delta(handle);\n\t};\n\n\tthis.trackHits = function () {\n\t\tvar handle = _hitQueries.push(true) - 1;\n\t\tnodeHitCounts[handle] = calculateHitCounts();\n\t\treturn handle;\n\t};\n\n\tthis.trackExceptions = function () {\n\t\tvar handle = _exceptionQueries.push(true) - 1;\n\t\texceptionCounts[handle] = calculateExceptionCounts();\n\t\treturn handle;\n\t};\n\n\tthis.trackLogs = function (query) {\n\t\tvar handle = _logQueries.push(query) - 1;\n\t\tlogEntries[handle] = backlog(query);\n\t\treturn handle;\n\t};\n\n\tthis.trackEpochs = function () {\n\t\treturn epochTracker.track();\n\t};\n\n\tthis.untrackEpochs = function (handle) {\n\t\treturn epochTracker.untrack(handle);\n\t};\n\n\tthis.trackFileCallGraph = function () {\n\t\treturn fileCallGraphTracker.track();\n\t};\n\n\tthis.untrackFileCallGraph = function (handle) {\n\t\treturn fileCallGraphTracker.untrack(handle);\n\t};\n\n\tthis.fileCallGraphDelta = function (handle) {\n\t\treturn fileCallGraphTracker.delta(handle);\n\t};\n\n\tthis.hitCountDeltas = function (handle) {\n\t\tif (!(handle in _hitQueries)) {\n\t\t\tthrow new Error(\"unrecognized query\");\n\t\t}\n\t\tvar result = nodeHitCounts[handle];\n\t\tnodeHitCounts[handle] = {};\n\t\treturn result;\n\t};\n\n\tthis.newExceptions = function (handle) {\n\t\tif (!(handle in _exceptionQueries)) {\n\t\t\tthrow new Error(\"unrecognized query\");\n\t\t}\n\t\tvar result = exceptionCounts[handle];\n\t\texceptionCounts[handle] = {};\n\t\treturn { counts: result };\n\t};\n\n\tthis.epochDelta = function (handle) {\n\t\treturn epochTracker.delta(handle);\n\t};\n\n\t// okay, the second argument is kind of a hack\n\tfunction makeLogEntry(invocation, parents) {\n\t\tparents = (parents || []);\n\t\tvar entry = {\n\t\t\ttimestamp: invocation.timestamp,\n\t\t\ttick: invocation.tick,\n\t\t\tinvocationId: invocation.id,\n\t\t\ttopLevelInvocationId: invocation.topLevelInvocationId,\n\t\t\tnodeId: invocation.f.id,\n\t\t};\n\t\tif (invocation.epochID !== undefined) {\n\t\t\tvar epoch = _epochsById[invocation.epochID];\n\t\t\tentry.epoch = {\n\t\t\t\tid: epoch.id,\n\t\t\t\temitterID: epoch.emitterID,\n\t\t\t\teventName: epoch.eventName,\n\t\t\t};\n\t\t\tentry.epochDepth = invocation.epochDepth;\n\t\t}\n\t\tif (invocation.returnValue !== undefined) {\n\t\t\tentry.returnValue = marshalForTransmission(invocation.returnValue);\n\t\t}\n\t\tif (invocation.exception !== undefined) {\n\t\t\tentry.exception = marshalForTransmission(invocation.exception);\n\t\t}\n\t\tif (invocation.f.params || invocation.arguments) {\n\t\t\tentry.arguments = [];\n\t\t\tvar params = invocation.f.params || [];\n\t\t\tfor (var i = 0; i < params.length; i++) {\n\t\t\t\tvar param = params[i];\n\t\t\t\tentry.arguments.push({\n\t\t\t\t\tname: param.name,\n\t\t\t\t\tvalue: marshalForTransmission(invocation.arguments[i]),\n\t\t\t\t});\n\t\t\t}\n\t\t\tfor (var i = params.length; i < invocation.arguments.length; i++) {\n\t\t\t\tentry.arguments.push({\n\t\t\t\t\tvalue: marshalForTransmission(invocation.arguments[i]),\n\t\t\t\t});\n\t\t\t}\n\t\t}\n\t\tif (invocation.this !== undefined) {\n\t\t\tentry.this = marshalForTransmission(invocation.this);\n\t\t}\n\t\tif (parents.length > 0) {\n\t\t\tentry.parents = parents;\n\t\t}\n\t\treturn entry;\n\t}\n\n\tthis.logCount = function (handle) {\n\t\tif (!(handle in _logQueries)) {\n\t\t\tthrow new Error(\"unrecognized query\");\n\t\t}\n\n\t\treturn logEntries[handle].entries.length;\n\t};\n\n\tthis.logDelta = function (handle, maxResults) {\n\t\tif (!(handle in _logQueries)) {\n\t\t\tthrow new Error(\"unrecognized query\");\n\t\t}\n\n\t\tmaxResults = maxResults || 10;\n\n\t\tvar ids = logEntries[handle].entries.splice(0, maxResults);\n\t\tvar results = ids.map(function (invocationId, i) {\n\t\t\tvar invocation = invocationById[invocationId];\n\t\t\treturn makeLogEntry(invocation, findParentsInQuery(invocation, _logQueries[handle]));\n\t\t});\n\n\t\treturn results;\n\t};\n\n\tthis.backtrace = function (options) {\n\t\toptions = mergeInto(options, {\n\t\t\trange: [0, 10],\n\t\t});\n\n\t\tvar invocation = invocationById[options.invocationId];\n\t\tif (!invocation) {\n\t\t\tthrow new Error(\"invocation not found\");\n\t\t}\n\n\t\tvar stack = [];\n\t\tif (options.range[0] <= 0) {\n\t\t\tstack.push(invocation);\n\t\t}\n\n\t\tfunction search(invocation, depth) {\n\t\t\t// stop if we're too deep\n\t\t\tif (depth+1 >= options.range[1]) {\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tvar callers = findCallers(invocation);\n\t\t\tvar directCallers = callers.filter(function (c) { return c.type === \"call\" })\n\t\t\tvar caller = directCallers[0];\n\n\t\t\tif (caller) {\n\t\t\t\tvar parent = invocationById[caller.invocationId];\n\t\t\t\tif (options.range[0] <= depth+1) {\n\t\t\t\t\tstack.push(parent);\n\t\t\t\t}\n\t\t\t\tsearch(parent, depth + 1);\n\t\t\t}\n\t\t}\n\t\tsearch(invocation, 0);\n\t\tvar results = stack.map(function (invocation) {\n\t\t\treturn makeLogEntry(invocation);\n\t\t});\n\t\treturn results;\n\t};\n\n\tfunction findParentsInQuery(invocation, query) {\n\t\tif (!query.ids || query.ids.length === 0) {\n\t\t\treturn [];\n\t\t}\n\n\t\tvar matches = {}; // invocation id -> link\n\t\tvar seen = {}; // invocation id -> true\n\t\tvar types = ['async', 'call', 'branch-enter']; // in priority order\n\t\tfunction promoteType(type, newType) {\n\t\t\tif (types.indexOf(type) === -1 || types.indexOf(newType) === -1) {\n\t\t\t\tthrow new Exception(\"invocation link type not known\")\n\t\t\t}\n\t\t\tif (types.indexOf(newType) < types.indexOf(type)) {\n\t\t\t\treturn newType;\n\t\t\t}\n\t\t\treturn type;\n\t\t}\n\t\tfunction search(link, type) {\n\t\t\tif (link.id in seen) {\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tseen[link.id] = true;\n\n\t\t\tvar targetInvocation = invocationById[link.id];\n\t\t\tif (query.ids.indexOf(targetInvocation.f.id) !== -1) { // if the called function is in the query\n\t\t\t\tif (link.id in matches) { // if we've already found this one\n\t\t\t\t\tif (link.type === 'call' && matches[link.id].type === 'async') { // if we found an async one before but this one is synchronous\n\t\t\t\t\t\t// overwrite the previous match\n\t\t\t\t\t\tmatches[link.id] = {\n\t\t\t\t\t\t\tinvocationId: link.id,\n\t\t\t\t\t\t\ttype: type,\n\t\t\t\t\t\t\tinbetween: []\n\t\t\t\t\t\t};\n\t\t\t\t\t}\n\t\t\t\t} else { // if we haven't found this link before, store it\n\t\t\t\t\tmatches[link.id] = {\n\t\t\t\t\t\tinvocationId: link.id,\n\t\t\t\t\t\ttype: type,\n\t\t\t\t\t\tinbetween: []\n\t\t\t\t\t};\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\ttargetInvocation.getParentLinks().forEach(function (link) { search(link, promoteType(type, link.type)); });\n\t\t\t}\n\t\t}\n\t\tinvocation.getParentLinks().forEach(function (link) { search(link, link.type); });\n\n\t\t// convert matches to an array\n\t\tvar matchesArr = [];\n\t\tfor (var id in matches) {\n\t\t\tmatchesArr.push(matches[id]);\n\t\t}\n\t\treturn matchesArr;\n\t}\n\n\tfunction findCallers(invocation) {\n\t\tvar matches = {}; // invocation id -> link\n\t\tvar seen = {}; // invocation id -> true\n\t\tvar types = ['async', 'call', 'branch-enter']; // in priority order\n\t\tfunction promoteType(type, newType) {\n\t\t\tif (types.indexOf(type) === -1 || types.indexOf(newType) === -1) {\n\t\t\t\tthrow new Exception(\"invocation link type not known\")\n\t\t\t}\n\t\t\tif (types.indexOf(newType) < types.indexOf(type)) {\n\t\t\t\treturn newType;\n\t\t\t}\n\t\t\treturn type;\n\t\t}\n\t\tfunction search(link, type) {\n\t\t\tif (link.id in seen) {\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tseen[link.id] = true;\n\n\t\t\tif (invocationById[link.id].f.type === \"function\") {\n\t\t\t\tif (link.id in matches) {\n\t\t\t\t\tif (link.type === 'call' && matches[link.id].type === 'async') {\n\t\t\t\t\t\tmatches[link.id] = {\n\t\t\t\t\t\t\tinvocationId: link.id,\n\t\t\t\t\t\t\ttype: type,\n\t\t\t\t\t\t};\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\tmatches[link.id] = {\n\t\t\t\t\t\tinvocationId: link.id,\n\t\t\t\t\t\ttype: type,\n\t\t\t\t\t};\n\t\t\t\t}\n\t\t\t\treturn; // search no more down this path\n\t\t\t}\n\t\t\tinvocationById[link.id].getParentLinks().forEach(function (link) { search(link, promoteType(type, link.type)); });\n\t\t}\n\t\tinvocation.getParentLinks().forEach(function (link) { search(link, link.type); });\n\n\t\t// convert matches to an array\n\t\tvar matchesArr = [];\n\t\tfor (var id in matches) {\n\t\t\tmatchesArr.push(matches[id]);\n\t\t}\n\t\treturn matchesArr;\n\t}\n\n\tthis.Array = Array;\n});\n}\n(function () { {name}.setGlobal(this); })();\n";
return template(tracerSource, {
name: options.name,
version: JSON.stringify(require('./package.json').version),
nodejs: options.nodejs,
maxInvocationsPerTick: options.maxInvocationsPerTick,
});
}
// uses the surrounding code to generate a reasonable name for a function
function concoctFunctionName(node) {
var name = undefined;
if (node.type === 'FunctionDeclaration') {
// function xxx() { }
// -> "xxx"
name = node.id.name;
} else if (node.type === 'FunctionExpression') {
if (node.id) {
// (function xxx() { })
// -> "xxx"
name = node.id.name;
} else if (node.parent.type === 'VariableDeclarator') {
// var xxx = function () { }
// -> "xxx"
name = node.parent.id.name;
} else if (node.parent.type === 'AssignmentExpression') {
var left = node.parent.left;
if (left.type === 'MemberExpression' && !left.computed) {
if (left.object.type === 'MemberExpression' && !left.object.computed) {
if (left.object.property.type === 'Identifier' && left.object.property.name === 'prototype') {
// yyy.prototype.xxx = function () { }
// -> "yyy.xxx"
name = left.object.object.name + '.' + left.property.name;
}
}
}
} else if (node.parent.type === 'CallExpression') {
// look, I know this is a regexp, I'm just sick of parsing ASTs
if (/\.on$/.test(node.parent.callee.source())) {
var args = node.parent.arguments;
if (args[0].type === 'Literal' && typeof args[0].value === 'string') {
// .on('event', function () { })
// -> "('event' handler)"
name = "('" + args[0].value + "' handler)";
}
} else if (node.parent.callee.type === 'Identifier') {
if (['setTimeout', 'setInterval'].indexOf(node.parent.callee.name) !== -1) {
// setTimeout(function () { }, xxx)
// setInterval(function () { }, xxx)
// -> "timer handler"
name = 'timer handler';
if (node.parent.arguments[1] && node.parent.arguments[1].type === 'Literal' && typeof node.parent.arguments[1].value === 'number') {
// setTimeout(function () { }, 100)
// setInterval(function () { }, 1500)
// -> "timer handler (100ms)"
// -> "timer handler (1.5s)"
if (node.parent.arguments[1].value < 1000) {
name += ' (' + node.parent.arguments[1].value + 'ms)';
} else {
name += ' (' + (node.parent.arguments[1].value / 1000) + 's)';
}
}
name = '(' + name + ')';
} else {
// xxx(function () { })
// -> "('xxx' callback)"
name = "('" + node.parent.callee.source() + "' callback)";
}
} else if (node.parent.callee.type === 'MemberExpression') {
if (node.parent.callee.property.type === 'Identifier') {
// xxx.yyy(..., function () { }, ...)
// -> "('yyy' callback)"
name = "('" + node.parent.callee.property.name + "' callback)";
}
}
} else if (node.parent.type === 'Property') {
// { xxx: function () { } }
// -> "xxx"
name = node.parent.key.name || node.parent.key.value;
if (name !== undefined) {
if (node.parent.parent.type === 'ObjectExpression') {
var obj = node.parent.parent;
if (obj.parent.type === 'VariableDeclarator') {
// var yyy = { xxx: function () { } }
// -> "yyy.xxx"
name = obj.parent.id.name + '.' + name;
} else if(obj.parent.type === 'AssignmentExpression') {
var left = obj.parent.left;
if (left.type === 'MemberExpression' && !left.computed) {
if (left.object.type === 'Identifier' && left.property.name === 'prototype') {
// yyy.prototype = { xxx: function () { } }
// -> "yyy.xxx"
name = left.object.name + '.' + name;
}
}
}
}
}
}
}
return name;
}
function traceFilter(src, options) {
options = mergeInto(options, {
path: '<anonymous>',
prefix: '',
tracer_name: '__tracer',
source_map: false,
throw_parse_errors: false,
});
try {
var nodes = [];
var functionSources = {};
// some code looks at the source code for callback functions and does
// different things depending on what it finds. since fondue wraps all
// anonymous functions, we need to capture the original source code for
// the functions so that we can return it from the wrapper function's
// toString.
falafel(src, { loc: true }, eselector.tester([
{
selector: '.function',
callback: function (node) {
var id = makeId('function', options.path, node.loc);
functionSources[id] = node.source();
},
}
]));
// instrument the source code
var instrumentedSrc = falafel(src, { loc: true }, helpers.wrap(eselector.tester([
{
selector: 'program',
callback: function (node) {
var id = makeId('toplevel', options.path, node.loc);
nodes.push({
path: options.path,
start: node.loc.start,
end: node.loc.end,
id: id,
type: 'toplevel',
name: '(' + basename(options.path) + ' toplevel)',
});
traceFileEntry(node, id);
}
},
{
selector: '.function > block',
callback: function (node) {
var id = makeId('function', options.path, node.parent.loc);
var params = node.parent.params.map(function (param) {
return { name: param.name, start: param.loc.start, end: param.loc.end };
});
nodes.push({
path: options.path,
start: node.parent.loc.start,
end: node.parent.loc.end,
id: id,
type: 'function',
name: concoctFunctionName(node.parent),
params: params,
});
traceEntry(node, id, [
'arguments: ' + options.tracer_name + '.Array.prototype.slice.apply(arguments)',
'this: this',
]);
},
},
{
selector: 'expression.function',
callback: function (node) {
if (node.parent.type !== 'Property' || node.parent.kind === 'init') {
var id = makeId('function', options.path, node.loc);
node.wrap(options.tracer_name + '.traceFunCreate(', ', ' + JSON.stringify(functionSources[id]) + ')')
}
},
},
{
selector: '.call',
callback: function (node) {
var id = makeId('callsite', options.path, node.loc);
var nameLoc = (node.callee.type === 'MemberExpression') ? node.callee.property.loc : node.callee.loc;
nodes.push({
path: options.path,
start: node.loc.start,
end: node.loc.end,
id: id,
type: 'callsite',
name: node.callee.source(),
nameStart: nameLoc.start,
nameEnd: nameLoc.end,
});
if (node.callee.source() !== 'require') {
if (node.callee.type === 'MemberExpression') {
if (node.callee.computed) {
node.callee.update(' ', options.tracer_name, '.traceFunCall({ this: ', node.callee.object.source(), ', property: ', node.callee.property.source(), ', nodeId: ', JSON.stringify(id), ' })');
} else {
node.callee.update(' ', options.tracer_name, '.traceFunCall({ this: ', node.callee.object.source(), ', property: "', node.callee.property.source(), '", nodeId: ', JSON.stringify(id), ' })');
}
} else {
node.callee.wrap(options.tracer_name + '.traceFunCall({ func: ', ', nodeId: ' + JSON.stringify(id) + '})');
}
}
},
},
])));
var prologue = options.prefix;
prologue += template("/*\nThe following code has been modified by fondue to collect information about its\nexecution.\n\nhttps://github.com/adobe-research/fondue\n*/\n\nif (typeof {name} === 'undefined') {\n\t{name} = {};\n\tvar methods = [\"add\", \"addSourceMap\", \"traceFileEntry\", \"traceFileExit\", \"setGlobal\", \"traceFunCreate\", \"traceEnter\", \"traceExit\", \"traceReturnValue\", \"traceExceptionThrown\", \"bailThisTick\", \"pushEpoch\", \"popEpoch\", \"augmentjQuery\", \"version\", \"connect\", \"nodes\", \"trackNodes\", \"untrackNodes\", \"newNodes\", \"trackHits\", \"trackExceptions\", \"trackLogs\", \"trackEpochs\", \"untrackEpochs\", \"trackFileCallGraph\", \"untrackFileCallGraph\", \"fileCallGraphDelta\", \"hitCountDeltas\", \"newExceptions\", \"epochDelta\", \"logCount\", \"logDelta\", \"backtrace\"];\n\tfor (var i = 0; i < methods.length; i++) {\n\t\t{name}[methods[i]] = function () { return arguments[0] };\n\t}\n\n\t{name}.traceFunCall = function (info) {\n\t\tvar customThis = false, fthis, func;\n\n\t\tif ('func' in info) {\n\t\t\tfunc = info.func;\n\t\t} else {\n\t\t\tcustomThis = true;\n\t\t\tfthis = info.this;\n\t\t\tfunc = fthis[info.property];\n\t\t}\n\n\t\treturn function () {\n\t\t\treturn func.apply(customThis ? fthis : this, arguments);\n\t\t};\n\t};\n\n\t{name}.Array = Array;\n}\n", { name: options.tracer_name });
if (options.source_map) prologue += '/*mapshere*/';
prologue += options.tracer_name + '.add(' + JSON.stringify(options.path) + ', { nodes: ' + JSON.stringify(nodes) + ' });\n\n';
return {
map: function () { return '' },
toString: function () { return prologue + instrumentedSrc },
};
function traceEntry(node, nodeId, args) {
args = ['nodeId: ' + JSON.stringify(nodeId)].concat(args || []);
node.before(options.tracer_name + '.traceEnter({' + args.join(',') + '});');
node.after(options.tracer_name + '.traceExit(' + JSON.stringify({ nodeId: nodeId }) + ');',
options.tracer_name + '.traceExceptionThrown(' + JSON.stringify({ nodeId: nodeId }) + ', __e);throw __e;');
}
function traceFileEntry(node, nodeId, args) {
args = ['nodeId: ' + JSON.stringify(nodeId)].concat(args || []);
node.before(options.tracer_name + '.traceFileEntry({' + args.join(',') + '});');
node.after(options.tracer_name + '.traceFileExit(' + JSON.stringify({ nodeId: nodeId }) + ');', true);
}
} catch (e) {
if (options.throw_parse_errors) {
throw e;
} else {
console.error('exception during parsing', options.path, e.stack);
return options.prefix + src;
}
}
}
/**
* options:
* path (<anonymous>): path of the source being instrumented
* (should be unique if multiple instrumented files are to be run together)
* include_prefix (true): include the instrumentation thunk
* tracer_name (__tracer): name for the global tracer object
* nodejs (false): true to enable Node.js-specific functionality
* maxInvocationsPerTick (4096): stop collecting trace information for a tick
* with more than this many invocations
* throw_parse_errors (false): if false, parse exceptions are caught and the
* original source code is returned.
**/
function instrument(src, options) {
options = mergeInto(options, {
include_prefix: true,
tracer_name: '__tracer',
});
var prefix = '', shebang = '', output, m;
if (m = /^(#![^\n]+)\n/.exec(src)) {
shebang = m[1];
src = src.slice(shebang.length);
}
if (options.include_prefix) {
prefix += instrumentationPrefix({
name: options.tracer_name,
nodejs: options.nodejs,
maxInvocationsPerTick: options.maxInvocationsPerTick,
});
}
if (src.indexOf("/*theseus" + " instrument: false */") !== -1) {
output = shebang + prefix + src;
} else {
var m = traceFilter(src, {
prefix: prefix,
path: options.path,
tracer_name: options.tracer_name,
sourceFilename: options.sourceFilename,
generatedFilename: options.generatedFilename,
throw_parse_errors: options.throw_parse_errors,
});
var oldToString = m.toString;
m.toString = function () {
return shebang + oldToString();
}
return m;
}
return output;
}
module.exports = {
instrument: instrument,
instrumentationPrefix: instrumentationPrefix,
};
}).call(this,"/")
},{"./package.json":19,"esprima-selector":3,"falafel":17,"falafel-helpers":4,"falafel-map":5,"fs":20,"path":25}],3:[function(require,module,exports){
// returns true if selector matches the given esprima node
// example selectors:
// *
// statement.return
// expression.identifier
// program declaration.function > block
// statement.return > expression
// expression.literal, expression.identifier
function test(selectorString, node) {
// TODO: complain about syntax errors
var alternates = selectorString.split(",");
return alternates.some(function (selectorString) {
var selector = splitSelector(selectorString + '>');
return matchUpward(selector, node);
});
}
// accepts an array of objects that look like this:
// { selector: "statement.return", callback: function (node) { } }
// returns a function that takes a node and calls the callbacks that have matching selectors.
// useful as a falafel callback.
function tester(selectors) {
return function (node) {
var self = this, args = Array.prototype.slice.apply(arguments);
selectors.forEach(function (s) {
if (test(s.selector, node)) {
s.callback.apply(self, args);
}
});
};
}
function splitSelector(selectorString) {
var regexp = /([\.a-z]+)(?:\s*(>))?/ig;
var m, pieces = [];
while (m = regexp.exec(selectorString)) {
var selector = {};
var namePieces = m[1].split('.');
if (namePieces[0].length > 0) selector.name = namePieces[0];
if (namePieces.length > 1) selector.classes = namePieces.slice(1);
if (m[2]) {
selector.directDescendant = true;
}
pieces.push(selector);
}
return pieces;
}
function matchUpward(selector, node) {
if (selector.length === 0) {
return true;
}
if (!node) {
return false;
}
var last = selector[selector.length - 1];
var tag = nodeTag(node);
if (tag && isMatch(tag, last)) {
return matchUpward(selector.slice(0, selector.length - 1), node.parent);
} else if (!last.directDescendant) {
return matchUpward(selector, node.parent);
} else {
return false;
}
}
function nodeTag(node) {
if (node.type === 'Identifier') {
var exprTag = { name: 'expression', classes: ['identifier'] };
switch (node.parent.type) {
case 'VariableDeclarator': if (node.parent.init === node) return decorate(exprTag); break;
case 'AssignmentExpression': if (node.parent.right === node) return decorate(exprTag); break;
case 'MemberExpression': if ((node.parent.object === node) || (node.parent.computed && node.parent.property === node)) return decorate(exprTag); break;
case 'Property': if (node.parent.value === node) return decorate(exprTag); break;
case 'ArrayExpression': return decorate(exprTag);
case 'CallExpression': return decorate(exprTag);
case 'BinaryExpression': return decorate(exprTag);
case 'ConditionalExpression': return decorate(exprTag);
case 'ReturnStatement': return decorate(exprTag);
case 'UnaryExpression': return decorate(exprTag);
case 'NewExpression': return decorate(exprTag);
case 'LogicalExpression': return decorate(exprTag);
case 'UpdateExpression': return decorate(exprTag);
case 'SequenceExpression': return decorate(exprTag);
case 'CatchClause': return decorate(exprTag);
case 'ExpressionStatement': return decorate(exprTag);
case 'IfStatement': return decorate(exprTag);
case 'SwitchStatement': return decorate(exprTag);
case 'ForStatement': return decorate(exprTag);
case 'ForInStatement': return decorate(exprTag);
case 'WhileStatement': return decorate(exprTag);
case 'DoWhileStatement': return decorate(exprTag);
case 'ThrowStatement': return decorate(exprTag);
case 'FunctionDeclaration': break;
case 'FunctionExpression': break;
case 'LabeledStatement': break;
case 'BreakStatement': break;
default: throw new Error('unrecognized identifier parent ' + node.parent.type);
}
return undefined;
} else if (node.type === 'Literal') {
return decorate({ name: 'expression', classes: ['literal'] });
} else if (node.type === 'ThisExpression') {
return decorate({ name: 'expression', classes: ['this'] });
} else if (node.type === 'CallExpression') {
return decorate({ name: 'expression', classes: ['call'] });
} else if (node.type === 'UnaryExpression') {
return decorate({ name: 'expression', classes: ['unary'] });
} else if (node.type === 'UpdateExpression') {
return decorate({ name: 'expression', classes: ['update'] });
} else if (node.type === 'BinaryExpression') {
return decorate({ name: 'expression', classes: ['binary'] });
} else if (node.type === 'ArrayExpression') {
return decorate({ name: 'expression', classes: ['array'] });
} else if (node.type === 'AssignmentExpression') {
return decorate({ name: 'expression', classes: ['assignment'] });
} else if (node.type === 'MemberExpression') {
return decorate({ name: 'expression', classes: ['member'] });
} else if (node.type === 'LogicalExpression') {
return decorate({ name: 'expression', classes: ['logical'] });
} else if (node.type === 'ConditionalExpression') {
return decorate({ name: 'expression', classes: ['ternary'] });
} else if (node.type === 'SequenceExpression') {
return decorate({ name: 'expression', classes: ['comma'] });
} else if (node.type === 'ObjectExpression') {
return decorate({ name: 'expression', classes: ['object'] });
} else if (node.type === 'NewExpression') {
return decorate({ name: 'expression', classes: ['new'] });
} else if (node.type === 'FunctionExpression') {
return decorate({ name: 'expression', classes: ['function'] });
} else if (node.type === 'ReturnStatement') {
return decorate({ name: 'statement', classes: ['return'] });
} else if (node.type === 'BreakStatement') {
return decorate({ name: 'statement', classes: ['break'] });
} else if (node.type === 'ContinueStatement') {
return decorate({ name: 'statement', classes: ['break'] });
} else if (node.type === 'LabeledStatement') {
return decorate({ name: 'statement', classes: ['label'] });
} else if (node.type === 'ExpressionStatement') {
return decorate({ name: 'statement', classes: ['expression'] });
} else if (node.type === 'IfStatement') {
return decorate({ name: 'statement', classes: ['if'] });
} else if (node.type === 'WhileStatement') {
return decorate({ name: 'statement', classes: ['while'] });
} else if (node.type === 'DoWhileStatement') {
return decorate({ name: 'statement', classes: ['do-while'] });
} else if (node.type === 'ThrowStatement') {
return decorate({ name: 'statement', classes: ['throw'] });
} else if (node.type === 'TryStatement') {
return decorate({ name: 'statement', classes: ['try'] });
} else if (node.type === 'CatchClause') {
return decorate({ name: 'clause', classes: ['catch'] });
} else if (node.type === 'ForStatement') {
return decorate({ name: 'statement', classes: ['for'] });
} else if (node.type === 'ForInStatement') {
return decorate({ name: 'statement', classes: ['forin'] });
} else if (node.type === 'SwitchStatement') {
return decorate({ name: 'statement', classes: ['switch'] });
} else if (node.type === 'BlockStatement') {
return decorate({ name: 'block', classes: [] });
} else if (node.type === 'EmptyStatement') {
return undefined;
} else if (node.type === 'VariableDeclaration') {
return decorate({ name: 'declaration', classes: ['variable'] });
} else if (node.type === 'FunctionDeclaration') {
return decorate({ name: 'declaration', classes: ['function'] });
} else if (node.type === 'VariableDeclarator') {
return decorate({ name: 'declarator', classes: [] });
} else if (node.type === 'Property') {
return decorate({ name: 'property', classes: [] });
} else if (node.type === 'SwitchCase') {
return decorate({ name: 'switch-case', classes: [] });
} else if (node.type === 'Program') {
return decorate({ name: 'program', classes: [] });
}
// console.error(node);
// console.error(node.source());
throw new Error('tag not found for ' + node.type);
function decorate(tag) {
if (node.parent) {
if (node.parent.type === 'IfStatement') {
if (node.parent.consequent === node) {
tag.classes.push('branch', 'consequent');
} else if (node.parent.alternate === node) {
tag.classes.push('branch', 'alternate');
}
}
}
return tag;
}
}
function isMatch(tag, selector) {
if (('name' in selector) && selector.name !== '*' && tag.name !== selector.name) {
return false;
}
if (('classes' in selector)) {
for (var i in selector.classes) {
if (tag.classes.indexOf(selector.classes[i]) === -1) {
return false;
}
}
}
return true;
}
module.exports = test;
module.exports.tester = tester;
module.exports.nodeTag = nodeTag;
},{}],4:[function(require,module,exports){
var eselector = require('esprima-selector');
// decorates the given esprima node with tag-specific helpers.
// statements and the like get:
// node.before(src) - inserts src before the node
// node.after(src) - inserts src after the node
// node.wrap(beforeSrc, afterSrc) - wraps the node
//
// expressions just get:
// node.wrap(beforeSrc, afterSrc) - wraps the node (be sure to match parentheses)
//
// blocks get:
// node.before(src) - inserts src before everything in the block
// node.after(src, useFinally) - inserts src after everything in the block; if useFinally is true, the block is wrapped with try-block with src in the finally clause
module.exports = function (node, options) {
options = (options || {});
var primitives = options.falafelMap ? falafelMapPrimitives : falafelPrimitives;
var w = eselector.nodeTag(node);
if (w) {
node.update = newUpdate(node);
if (['statement', 'declaration', 'program', 'block'].indexOf(w.name) !== -1) {
node.before = before;
node.after = after;
node.wrap = beforeAfterWrap;
} else if (w.name === "expression") {
node.wrap = parensWrap;
} else if (['switch-case'].indexOf(w.name) !== -1) {
// TODO
} else if (['declarator', 'property', 'clause'].indexOf(w.name) !== -1) {
// skip
} else {
throw new Error('unrecognized node ' + w.name + ' (' + node.type + ')');
}
}
return node;
function before(src) {
rawWrap.call(this, primitives.sequence('{', src), '}');
}
function after(src, catchSrc) {
if (catchSrc === true) {
rawWrap.call(this, '{ try {', primitives.sequence('} finally {', src, '} }'));
} else if (catchSrc) {
rawWrap.call(this, '{ try {', primitives.sequence('} catch (__e) {', catchSrc, '} finally {', src, '} }'));
} else {
rawWrap.call(this, '{', primitives.sequence(src, '}'));
}
}
function beforeAfterWrap(beforeSrc, afterSrc, useFinally) {
this.before(beforeSrc);
this.after(afterSrc, useFinally);
}
function parensWrap(beforeSrc, afterSrc) {
this.update('(', beforeSrc, primitives.source(this), afterSrc, ')');
}
function rawWrap(beforeSrc, afterSrc) {
this.update(beforeSrc, primitives.source(this), afterSrc);
}
function newUpdate(node) {
var oldUpdate = node.update;
return function () {
var seq = primitives.sequence.apply(this, arguments);
return oldUpdate.call(this, seq);
};
}
}
// returns a version of f where the node argument has been wrapped with the function above
module.exports.wrap = function (f, options) {
return function (node) {
return f(module.exports(node, options));
};
};
var falafelPrimitives = {
sequence: function () { return Array.prototype.join.call(arguments, '') },
source: function (node) { return node.source() },
};
var falafelMapPrimitives = {
sequence: function () { return Array.prototype.slice.call(arguments) },
source: function (node) { return node.sourceNodes() },
};
},{"esprima-selector":3}],5:[function(require,module,exports){
(function (Buffer){
var parse = require('esprima').parse;
var SourceNode = require("source-map").SourceNode;
var objectKeys = Object.keys || function (obj) {
var keys = [];
for (var key in obj) keys.push(key);
return keys;
};
var forEach = function (xs, fn) {
if (xs.forEach) return xs.forEach(fn);
for (var i = 0; i < xs.length; i++) {
fn.call(xs, xs[i], i, xs);
}
};
var isArray = Array.isArray || function (xs) {
return Object.prototype.toString.call(xs) === '[object Array]';
};
var base64 = function (str) {
return new Buffer(str).toString('base64');
}
module.exports = function (src, opts, fn) {
if (typeof opts === 'function') {
fn = opts;
opts = {};
}
if (typeof src === 'object') {
opts = src;
src = opts.source;
delete opts.source;
}
src = src === undefined ? opts.source : src;
opts.range = true;
opts.loc = true;
if (typeof src !== 'string') src = String(src);
var ast = parse(src, opts);
var result = {
chunks : src.split(''),
map : function () {
var root = new SourceNode(null, null, null, result.chunks);
root.setSourceContent(opts.sourceFilename || "in.js", src);
var sm = root.toStringWithSourceMap({ file: opts.generatedFilename || "out.js" });
return sm.map.toString();
},
toString : function () {
var root = new SourceNode(null, null, null, result.chunks);
root.setSourceContent(opts.sourceFilename || "in.js", src);
var sm = root.toStringWithSourceMap({ file: opts.generatedFilename || "out.js" });
return sm.code + "\n//@ sourceMappingURL=data:application/json;base64," + base64(sm.map.toString()) + "\n";
},
inspect : function () { return result.toString() }
};
var index = 0;
(function walk (node, parent) {
insertHelpers(node, parent, result.chunks, opts);
forEach(objectKeys(node), function (key) {
if (key === 'parent') return;
var child = node[key];
if (isArray(child)) {
forEach(child, function (c) {
if (c && typeof c.type === 'string') {
walk(c, node);
}
});
}
else if (child && typeof child.type === 'string') {
insertHelpers(child, node, result.chunks, opts);
walk(child, node);
}
});
fn(node);
})(ast, undefined);
return result;
};
function insertHelpers (node, parent, chunks, opts) {
if (!node.range) return;
node.parent = parent;
node.source = function () {
return chunks.slice(
node.range[0], node.range[1]
).join('');
};
node.sourceNodes = function () {
return chunks.slice(
node.range[0], node.range[1]
);
};
if (node.update && typeof node.update === 'object') {
var prev = node.update;
forEach(objectKeys(prev), function (key) {
update[key] = prev[key];
});
node.update = update;
}
else {
node.update = update;
}
function update () {
chunks[node.range[0]] = new SourceNode(
node.loc.start.line,
node.loc.start.column,
opts.sourceFilename || "in.js",
Array.prototype.slice.apply(arguments));
for (var i = node.range[0] + 1; i < node.range[1]; i++) {
chunks[i] = '';
}
};
node.replace = function (sourceNode) {
chunks[node.range[0]] = sourceNode;
for (var i = node.range[0] + 1; i < node.range[1]; i++) {
chunks[i] = '';
}
};
node.prepend = function () {
var prevNode = new SourceNode(null, null, null, node.sourceNodes());
prevNode.prepend(new SourceNode(null, null, null, Array.prototype.slice.apply(arguments)));
node.replace(prevNode);
};
node.append = function () {
var prevNode = new SourceNode(null, null, null, node.sourceNodes());
prevNode.add(new SourceNode(null, null, null, Array.prototype.slice.apply(arguments)));
node.replace(prevNode);
};
}
}).call(this,require("buffer").Buffer)
},{"buffer":21,"esprima":6,"source-map":7}],6:[function(require,module,exports){
/*
Copyright (C) 2012 Ariya Hidayat <ariya.hidayat@gmail.com>
Copyright (C) 2012 Mathias Bynens <mathias@qiwi.be>
Copyright (C) 2012 Joost-Wim Boekesteijn <joost-wim@boekesteijn.nl>
Copyright (C) 2012 Kris Kowal <kris.kowal@cixar.com>
Copyright (C) 2012 Yusuke Suzuki <utatane.tea@gmail.com>
Copyright (C) 2012 Arpad Borsos <arpad.borsos@googlemail.com>
Copyright (C) 2011 Ariya Hidayat <ariya.hidayat@gmail.com>
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/*jslint bitwise:true plusplus:true */
/*global esprima:true, define:true, exports:true, window: true,
throwError: true, generateStatement: true, peek: true,
parseAssignmentExpression: true, parseBlock: true, parseExpression: true,
parseFunctionDeclaration: true, parseFunctionExpression: true,
parseFunctionSourceElements: true, parseVariableIdentifier: true,
parseLeftHandSideExpression: true,
parseStatement: true, parseSourceElement: true */
(function (root, factory) {
'use strict';
// Universal Module Definition (UMD) to support AMD, CommonJS/Node.js,
// Rhino, and plain browser loading.
if (typeof define === 'function' && define.amd) {
define(['exports'], factory);
} else if (typeof exports !== 'undefined') {
factory(exports);
} else {
factory((root.esprima = {}));
}
}(this, function (exports) {
'use strict';
var Token,
TokenName,
Syntax,
PropertyKind,
Messages,
Regex,
SyntaxTreeDelegate,
source,
strict,
index,
lineNumber,
lineStart,
length,
delegate,
lookahead,
state,
extra;
Token = {
BooleanLiteral: 1,
EOF: 2,
Identifier: 3,
Keyword: 4,
NullLiteral: 5,
NumericLiteral: 6,
Punctuator: 7,
StringLiteral: 8
};
TokenName = {};
TokenName[Token.BooleanLiteral] = 'Boolean';
TokenName[Token.EOF] = '<end>';
TokenName[Token.Identifier] = 'Identifier';
TokenName[Token.Keyword] = 'Keyword';
TokenName[Token.NullLiteral] = 'Null';
TokenName[Token.NumericLiteral] = 'Numeric';
TokenName[Token.Punctuator] = 'Punctuator';
TokenName[Token.StringLiteral] = 'String';
Syntax = {
AssignmentExpression: 'AssignmentExpression',
ArrayExpression: 'ArrayExpression',
BlockStatement: 'BlockStatement',
BinaryExpression: 'BinaryExpression',
BreakStatement: 'BreakStatement',
CallExpression: 'CallExpression',
CatchClause: 'CatchClause',
ConditionalExpression: 'ConditionalExpression',
ContinueStatement: 'ContinueStatement',
DoWhileStatement: 'DoWhileStatement',
DebuggerStatement: 'DebuggerStatement',
EmptyStatement: 'EmptyStatement',
ExpressionStatement: 'ExpressionStatement',
ForStatement: 'ForStatement',
ForInStatement: 'ForInStatement',
FunctionDeclaration: 'FunctionDeclaration',
FunctionExpression: 'FunctionExpression',
Identifier: 'Identifier',
IfStatement: 'IfStatement',
Literal: 'Literal',
LabeledStatement: 'LabeledStatement',
LogicalExpression: 'LogicalExpression',
MemberExpression: 'MemberExpression',
NewExpression: 'NewExpression',
ObjectExpression: 'ObjectExpression',
Program: 'Program',
Property: 'Property',
ReturnStatement: 'ReturnStatement',
SequenceExpression: 'SequenceExpression',
SwitchStatement: 'SwitchStatement',
SwitchCase: 'SwitchCase',
ThisExpression: 'ThisExpression',
ThrowStatement: 'ThrowStatement',
TryStatement: 'TryStatement',
UnaryExpression: 'UnaryExpression',
UpdateExpression: 'UpdateExpression',
VariableDeclaration: 'VariableDeclaration',
VariableDeclarator: 'VariableDeclarator',
WhileStatement: 'WhileStatement',
WithStatement: 'WithStatement'
};
PropertyKind = {
Data: 1,
Get: 2,
Set: 4
};
// Error messages should be identical to V8.
Messages = {
UnexpectedToken: 'Unexpected token %0',
UnexpectedNumber: 'Unexpected number',
UnexpectedString: 'Unexpected string',
UnexpectedIdentifier: 'Unexpected identifier',
UnexpectedReserved: 'Unexpected reserved word',
UnexpectedEOS: 'Unexpected end of input',
NewlineAfterThrow: 'Illegal newline after throw',
InvalidRegExp: 'Invalid regular expression',
UnterminatedRegExp: 'Invalid regular expression: missing /',
InvalidLHSInAssignment: 'Invalid left-hand side in assignment',
InvalidLHSInForIn: 'Invalid left-hand side in for-in',
MultipleDefaultsInSwitch: 'More than one default clause in switch statement',
NoCatchOrFinally: 'Missing catch or finally after try',
UnknownLabel: 'Undefined label \'%0\'',
Redeclaration: '%0 \'%1\' has already been declared',
IllegalContinue: 'Illegal continue statement',
IllegalBreak: 'Illegal break statement',
IllegalReturn: 'Illegal return statement',
StrictModeWith: 'Strict mode code may not include a with statement',
StrictCatchVariable: 'Catch variable may not be eval or arguments in strict mode',
StrictVarName: 'Variable name may not be eval or arguments in strict mode',
StrictParamName: 'Parameter name eval or arguments is not allowed in strict mode',
StrictParamDupe: 'Strict mode function may not have duplicate parameter names',