├── .gitignore
├── .npmignore
├── .travis.yml
├── LICENSE.md
├── README.md
├── amd-test
├── index.html
├── require.js
└── script.coffee
├── browser-source-map-support.js
├── browser-test
├── index.html
├── script.coffee
├── script.js
└── script.js.map
├── browserify-test
├── index.html
└── script.coffee
├── build.js
├── header-test
├── index.html
├── script.coffee
└── server.js
├── package-lock.json
├── package.json
├── register-hook-require.js
├── register.js
├── source-map-support.js
├── test.js
└── webpack-test
├── index.html
├── script.js
└── webpack.config.js
/.gitignore:
--------------------------------------------------------------------------------
1 | node_modules/
2 | amd-test/browser-source-map-support.js
3 | amd-test/script.js
4 | amd-test/script.js.map
5 | browserify-test/compiled.js
6 | browserify-test/script.js
7 | browserify-test/script.js.map
8 | header-test/script.js
9 | header-test/script.js.map
10 | webpack-test/compiled.js
11 |
--------------------------------------------------------------------------------
/.npmignore:
--------------------------------------------------------------------------------
1 | amd-test/
2 | browser-test/
3 | browserify-test/
4 | header-test/
5 | webpack-test/
6 | .npmignore
7 | .travis.yml
8 | build.js
9 | test.js
10 |
--------------------------------------------------------------------------------
/.travis.yml:
--------------------------------------------------------------------------------
1 | language: node_js
2 | node_js:
3 | - 10
4 | - 9
5 | - '8'
6 | - '7'
7 | - '6'
8 | - '4'
9 | - '0.12'
10 | - '0.10'
11 |
--------------------------------------------------------------------------------
/LICENSE.md:
--------------------------------------------------------------------------------
1 | The MIT License (MIT)
2 |
3 | Copyright (c) 2014 Evan Wallace
4 |
5 | Permission is hereby granted, free of charge, to any person obtaining a copy
6 | of this software and associated documentation files (the "Software"), to deal
7 | in the Software without restriction, including without limitation the rights
8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9 | copies of the Software, and to permit persons to whom the Software is
10 | furnished to do so, subject to the following conditions:
11 |
12 | The above copyright notice and this permission notice shall be included in all
13 | copies or substantial portions of the Software.
14 |
15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21 | SOFTWARE.
22 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # Source Map Support
2 | [](https://travis-ci.org/evanw/node-source-map-support)
3 |
4 | This module provides source map support for stack traces in node via the [V8 stack trace API](https://github.com/v8/v8/wiki/Stack-Trace-API). It uses the [source-map](https://github.com/mozilla/source-map) module to replace the paths and line numbers of source-mapped files with their original paths and line numbers. The output mimics node's stack trace format with the goal of making every compile-to-JS language more of a first-class citizen. Source maps are completely general (not specific to any one language) so you can use source maps with multiple compile-to-JS languages in the same node process.
5 |
6 | ## Installation and Usage
7 |
8 | #### Node support
9 |
10 | ##### Node >=12.12.0
11 |
12 | This package is no longer required as [Node 12.12.0 introduced the `--enable-source-maps` flag.](https://nodejs.org/docs/latest-v16.x/api/cli.html#--enable-source-maps) (unless you're using the [`vm`](https://nodejs.org/api/vm.html) module, as `--enable-source-maps` does not work with `vm.runInThisContext`).
13 |
14 | ##### Node <12.12.0
15 |
16 | ```
17 | $ npm install source-map-support
18 | ```
19 |
20 | Source maps can be generated using libraries such as [source-map-index-generator](https://github.com/twolfson/source-map-index-generator). Once you have a valid source map, place a source mapping comment somewhere in the file (usually done automatically or with an option by your transpiler):
21 |
22 | ```
23 | //# sourceMappingURL=path/to/source.map
24 | ```
25 |
26 | If multiple sourceMappingURL comments exist in one file, the last sourceMappingURL comment will be
27 | respected (e.g. if a file mentions the comment in code, or went through multiple transpilers).
28 | The path should either be absolute or relative to the compiled file.
29 |
30 | From here you have two options.
31 |
32 | ##### CLI Usage
33 |
34 | ```bash
35 | node -r source-map-support/register compiled.js
36 | ```
37 |
38 | ##### Programmatic Usage
39 |
40 | Put the following line at the top of the compiled file.
41 |
42 | ```js
43 | require('source-map-support').install();
44 | ```
45 |
46 | It is also possible to install the source map support directly by
47 | requiring the `register` module which can be handy with ES6:
48 |
49 | ```js
50 | import 'source-map-support/register'
51 |
52 | // Instead of:
53 | import sourceMapSupport from 'source-map-support'
54 | sourceMapSupport.install()
55 | ```
56 | Note: if you're using babel-register, it includes source-map-support already.
57 |
58 | It is also very useful with Mocha:
59 |
60 | ```
61 | $ mocha --require source-map-support/register tests/
62 | ```
63 |
64 | #### Browser support
65 |
66 | This library also works in Chrome. While the DevTools console already supports source maps, the V8 engine doesn't and `Error.prototype.stack` will be incorrect without this library. Everything will just work if you deploy your source files using [browserify](http://browserify.org/). Just make sure to pass the `--debug` flag to the browserify command so your source maps are included in the bundled code.
67 |
68 | This library also works if you use another build process or just include the source files directly. In this case, include the file `browser-source-map-support.js` in your page and call `sourceMapSupport.install()`. It contains the whole library already bundled for the browser using browserify.
69 |
70 | ```html
71 |
72 |
73 | ```
74 |
75 | This library also works if you use AMD (Asynchronous Module Definition), which is used in tools like [RequireJS](http://requirejs.org/). Just list `browser-source-map-support` as a dependency:
76 |
77 | ```html
78 |
83 | ```
84 |
85 | ## Options
86 |
87 | This module installs two things: a change to the `stack` property on `Error` objects and a handler for uncaught exceptions that mimics node's default exception handler (the handler can be seen in the demos below). You may want to disable the handler if you have your own uncaught exception handler. This can be done by passing an argument to the installer:
88 |
89 | ```js
90 | require('source-map-support').install({
91 | handleUncaughtExceptions: false
92 | });
93 | ```
94 |
95 | This module loads source maps from the filesystem by default. You can provide alternate loading behavior through a callback as shown below. For example, [Meteor](https://github.com/meteor) keeps all source maps cached in memory to avoid disk access.
96 |
97 | ```js
98 | require('source-map-support').install({
99 | retrieveSourceMap: function(source) {
100 | if (source === 'compiled.js') {
101 | return {
102 | url: 'original.js',
103 | map: fs.readFileSync('compiled.js.map', 'utf8')
104 | };
105 | }
106 | return null;
107 | }
108 | });
109 | ```
110 |
111 | The module will by default assume a browser environment if XMLHttpRequest and window are defined. If either of these do not exist it will instead assume a node environment.
112 | In some rare cases, e.g. when running a browser emulation and where both variables are also set, you can explictly specify the environment to be either 'browser' or 'node'.
113 |
114 | ```js
115 | require('source-map-support').install({
116 | environment: 'node'
117 | });
118 | ```
119 |
120 | To support files with inline source maps, the `hookRequire` options can be specified, which will monitor all source files for inline source maps.
121 |
122 |
123 | ```js
124 | require('source-map-support').install({
125 | hookRequire: true
126 | });
127 | ```
128 |
129 | This monkey patches the `require` module loading chain, so is not enabled by default and is not recommended for any sort of production usage.
130 |
131 | ## Demos
132 |
133 | #### Basic Demo
134 |
135 | original.js:
136 |
137 | ```js
138 | throw new Error('test'); // This is the original code
139 | ```
140 |
141 | compiled.js:
142 |
143 | ```js
144 | require('source-map-support').install();
145 |
146 | throw new Error('test'); // This is the compiled code
147 | // The next line defines the sourceMapping.
148 | //# sourceMappingURL=compiled.js.map
149 | ```
150 |
151 | compiled.js.map:
152 |
153 | ```json
154 | {
155 | "version": 3,
156 | "file": "compiled.js",
157 | "sources": ["original.js"],
158 | "names": [],
159 | "mappings": ";;AAAA,MAAM,IAAI"
160 | }
161 | ```
162 |
163 | Run compiled.js using node (notice how the stack trace uses original.js instead of compiled.js):
164 |
165 | ```
166 | $ node compiled.js
167 |
168 | original.js:1
169 | throw new Error('test'); // This is the original code
170 | ^
171 | Error: test
172 | at Object. (original.js:1:7)
173 | at Module._compile (module.js:456:26)
174 | at Object.Module._extensions..js (module.js:474:10)
175 | at Module.load (module.js:356:32)
176 | at Function.Module._load (module.js:312:12)
177 | at Function.Module.runMain (module.js:497:10)
178 | at startup (node.js:119:16)
179 | at node.js:901:3
180 | ```
181 |
182 | #### TypeScript Demo
183 |
184 | demo.ts:
185 |
186 | ```typescript
187 | declare function require(name: string);
188 | require('source-map-support').install();
189 | class Foo {
190 | constructor() { this.bar(); }
191 | bar() { throw new Error('this is a demo'); }
192 | }
193 | new Foo();
194 | ```
195 |
196 | Compile and run the file using the TypeScript compiler from the terminal:
197 |
198 | ```
199 | $ npm install source-map-support typescript
200 | $ node_modules/typescript/bin/tsc -sourcemap demo.ts
201 | $ node demo.js
202 |
203 | demo.ts:5
204 | bar() { throw new Error('this is a demo'); }
205 | ^
206 | Error: this is a demo
207 | at Foo.bar (demo.ts:5:17)
208 | at new Foo (demo.ts:4:24)
209 | at Object. (demo.ts:7:1)
210 | at Module._compile (module.js:456:26)
211 | at Object.Module._extensions..js (module.js:474:10)
212 | at Module.load (module.js:356:32)
213 | at Function.Module._load (module.js:312:12)
214 | at Function.Module.runMain (module.js:497:10)
215 | at startup (node.js:119:16)
216 | at node.js:901:3
217 | ```
218 |
219 | There is also the option to use `-r source-map-support/register` with typescript, without the need add the `require('source-map-support').install()` in the code base:
220 |
221 | ```
222 | $ npm install source-map-support typescript
223 | $ node_modules/typescript/bin/tsc -sourcemap demo.ts
224 | $ node -r source-map-support/register demo.js
225 |
226 | demo.ts:5
227 | bar() { throw new Error('this is a demo'); }
228 | ^
229 | Error: this is a demo
230 | at Foo.bar (demo.ts:5:17)
231 | at new Foo (demo.ts:4:24)
232 | at Object. (demo.ts:7:1)
233 | at Module._compile (module.js:456:26)
234 | at Object.Module._extensions..js (module.js:474:10)
235 | at Module.load (module.js:356:32)
236 | at Function.Module._load (module.js:312:12)
237 | at Function.Module.runMain (module.js:497:10)
238 | at startup (node.js:119:16)
239 | at node.js:901:3
240 | ```
241 |
242 | #### CoffeeScript Demo
243 |
244 | demo.coffee:
245 |
246 | ```coffee
247 | require('source-map-support').install()
248 | foo = ->
249 | bar = -> throw new Error 'this is a demo'
250 | bar()
251 | foo()
252 | ```
253 |
254 | Compile and run the file using the CoffeeScript compiler from the terminal:
255 |
256 | ```sh
257 | $ npm install source-map-support coffeescript
258 | $ node_modules/.bin/coffee --map --compile demo.coffee
259 | $ node demo.js
260 |
261 | demo.coffee:3
262 | bar = -> throw new Error 'this is a demo'
263 | ^
264 | Error: this is a demo
265 | at bar (demo.coffee:3:22)
266 | at foo (demo.coffee:4:3)
267 | at Object. (demo.coffee:5:1)
268 | at Object. (demo.coffee:1:1)
269 | at Module._compile (module.js:456:26)
270 | at Object.Module._extensions..js (module.js:474:10)
271 | at Module.load (module.js:356:32)
272 | at Function.Module._load (module.js:312:12)
273 | at Function.Module.runMain (module.js:497:10)
274 | at startup (node.js:119:16)
275 | ```
276 |
277 | ## Tests
278 |
279 | This repo contains both automated tests for node and manual tests for the browser. The automated tests can be run using mocha (type `mocha` in the root directory). To run the manual tests:
280 |
281 | * Build the tests using `build.js`
282 | * Launch the HTTP server (`npm run serve-tests`) and visit
283 | * http://127.0.0.1:1336/amd-test
284 | * http://127.0.0.1:1336/browser-test
285 | * http://127.0.0.1:1336/browserify-test - **Currently not working** due to a bug with browserify (see [pull request #66](https://github.com/evanw/node-source-map-support/pull/66) for details).
286 | * For `header-test`, run `server.js` inside that directory and visit http://127.0.0.1:1337/
287 |
288 | ## License
289 |
290 | This code is available under the [MIT license](http://opensource.org/licenses/MIT).
291 |
--------------------------------------------------------------------------------
/amd-test/index.html:
--------------------------------------------------------------------------------
1 |
2 | Make sure to run build.js.
3 | This test should say either "Test failed" or "Test passed":
4 |
5 |
6 |
7 |
--------------------------------------------------------------------------------
/amd-test/require.js:
--------------------------------------------------------------------------------
1 | /*
2 | RequireJS 2.1.9 Copyright (c) 2010-2012, The Dojo Foundation All Rights Reserved.
3 | Available via the MIT or new BSD license.
4 | see: http://github.com/jrburke/requirejs for details
5 | */
6 | var requirejs,require,define;
7 | (function(Z){function H(b){return"[object Function]"===L.call(b)}function I(b){return"[object Array]"===L.call(b)}function y(b,c){if(b){var e;for(e=0;ethis.depCount&&!this.defined){if(H(m)){if(this.events.error&&this.map.isDefine||j.onError!==aa)try{d=i.execCb(c,m,b,d)}catch(e){a=e}else d=i.execCb(c,m,b,d);this.map.isDefine&&((b=this.module)&&void 0!==b.exports&&b.exports!==
19 | this.exports?d=b.exports:void 0===d&&this.usingExports&&(d=this.exports));if(a)return a.requireMap=this.map,a.requireModules=this.map.isDefine?[this.map.id]:null,a.requireType=this.map.isDefine?"define":"require",v(this.error=a)}else d=m;this.exports=d;if(this.map.isDefine&&!this.ignore&&(r[c]=d,j.onResourceLoad))j.onResourceLoad(i,this.map,this.depMaps);x(c);this.defined=!0}this.defining=!1;this.defined&&!this.defineEmitted&&(this.defineEmitted=!0,this.emit("defined",this.exports),this.defineEmitComplete=
20 | !0)}}else this.fetch()}},callPlugin:function(){var a=this.map,b=a.id,e=n(a.prefix);this.depMaps.push(e);s(e,"defined",u(this,function(d){var m,e;e=this.map.name;var g=this.map.parentMap?this.map.parentMap.name:null,h=i.makeRequire(a.parentMap,{enableBuildCallback:!0});if(this.map.unnormalized){if(d.normalize&&(e=d.normalize(e,function(a){return c(a,g,!0)})||""),d=n(a.prefix+"!"+e,this.map.parentMap),s(d,"defined",u(this,function(a){this.init([],function(){return a},null,{enabled:!0,ignore:!0})})),
21 | e=l(p,d.id)){this.depMaps.push(d);if(this.events.error)e.on("error",u(this,function(a){this.emit("error",a)}));e.enable()}}else m=u(this,function(a){this.init([],function(){return a},null,{enabled:!0})}),m.error=u(this,function(a){this.inited=!0;this.error=a;a.requireModules=[b];F(p,function(a){0===a.map.id.indexOf(b+"_unnormalized")&&x(a.map.id)});v(a)}),m.fromText=u(this,function(d,c){var e=a.name,g=n(e),B=O;c&&(d=c);B&&(O=!1);q(g);t(k.config,b)&&(k.config[e]=k.config[b]);try{j.exec(d)}catch(ca){return v(A("fromtexteval",
22 | "fromText eval for "+b+" failed: "+ca,ca,[b]))}B&&(O=!0);this.depMaps.push(g);i.completeLoad(e);h([e],m)}),d.load(a.name,h,m,k)}));i.enable(e,this);this.pluginMaps[e.id]=e},enable:function(){T[this.map.id]=this;this.enabling=this.enabled=!0;y(this.depMaps,u(this,function(a,b){var c,d;if("string"===typeof a){a=n(a,this.map.isDefine?this.map:this.map.parentMap,!1,!this.skipMap);this.depMaps[b]=a;if(c=l(N,a.id)){this.depExports[b]=c(this);return}this.depCount+=1;s(a,"defined",u(this,function(a){this.defineDep(b,
23 | a);this.check()}));this.errback&&s(a,"error",u(this,this.errback))}c=a.id;d=p[c];!t(N,c)&&(d&&!d.enabled)&&i.enable(a,this)}));F(this.pluginMaps,u(this,function(a){var b=l(p,a.id);b&&!b.enabled&&i.enable(a,this)}));this.enabling=!1;this.check()},on:function(a,b){var c=this.events[a];c||(c=this.events[a]=[]);c.push(b)},emit:function(a,b){y(this.events[a],function(a){a(b)});"error"===a&&delete this.events[a]}};i={config:k,contextName:b,registry:p,defined:r,urlFetched:S,defQueue:G,Module:X,makeModuleMap:n,
24 | nextTick:j.nextTick,onError:v,configure:function(a){a.baseUrl&&"/"!==a.baseUrl.charAt(a.baseUrl.length-1)&&(a.baseUrl+="/");var b=k.pkgs,c=k.shim,d={paths:!0,config:!0,map:!0};F(a,function(a,b){d[b]?"map"===b?(k.map||(k.map={}),Q(k[b],a,!0,!0)):Q(k[b],a,!0):k[b]=a});a.shim&&(F(a.shim,function(a,b){I(a)&&(a={deps:a});if((a.exports||a.init)&&!a.exportsFn)a.exportsFn=i.makeShimExports(a);c[b]=a}),k.shim=c);a.packages&&(y(a.packages,function(a){a="string"===typeof a?{name:a}:a;b[a.name]={name:a.name,
25 | location:a.location||a.name,main:(a.main||"main").replace(ja,"").replace(ea,"")}}),k.pkgs=b);F(p,function(a,b){!a.inited&&!a.map.unnormalized&&(a.map=n(b))});if(a.deps||a.callback)i.require(a.deps||[],a.callback)},makeShimExports:function(a){return function(){var b;a.init&&(b=a.init.apply(Z,arguments));return b||a.exports&&ba(a.exports)}},makeRequire:function(a,f){function h(d,c,e){var g,k;f.enableBuildCallback&&(c&&H(c))&&(c.__requireJsBuild=!0);if("string"===typeof d){if(H(c))return v(A("requireargs",
26 | "Invalid require call"),e);if(a&&t(N,d))return N[d](p[a.id]);if(j.get)return j.get(i,d,a,h);g=n(d,a,!1,!0);g=g.id;return!t(r,g)?v(A("notloaded",'Module name "'+g+'" has not been loaded yet for context: '+b+(a?"":". Use require([])"))):r[g]}K();i.nextTick(function(){K();k=q(n(null,a));k.skipMap=f.skipMap;k.init(d,c,e,{enabled:!0});C()});return h}f=f||{};Q(h,{isBrowser:z,toUrl:function(b){var f,e=b.lastIndexOf("."),g=b.split("/")[0];if(-1!==e&&(!("."===g||".."===g)||1h.attachEvent.toString().indexOf("[native code"))&&!W?(O=!0,h.attachEvent("onreadystatechange",b.onScriptLoad)):(h.addEventListener("load",b.onScriptLoad,!1),h.addEventListener("error",
34 | b.onScriptError,!1)),h.src=e,K=h,C?x.insertBefore(h,C):x.appendChild(h),K=null,h;if(da)try{importScripts(e),b.completeLoad(c)}catch(l){b.onError(A("importscripts","importScripts failed for "+c+" at "+e,l,[c]))}};z&&!s.skipDataMain&&M(document.getElementsByTagName("script"),function(b){x||(x=b.parentNode);if(J=b.getAttribute("data-main"))return q=J,s.baseUrl||(D=q.split("/"),q=D.pop(),fa=D.length?D.join("/")+"/":"./",s.baseUrl=fa),q=q.replace(ea,""),j.jsExtRegExp.test(q)&&(q=J),s.deps=s.deps?s.deps.concat(q):
35 | [q],!0});define=function(b,c,e){var h,j;"string"!==typeof b&&(e=c,c=b,b=null);I(c)||(e=c,c=null);!c&&H(e)&&(c=[],e.length&&(e.toString().replace(la,"").replace(ma,function(b,e){c.push(e)}),c=(1===e.length?["require"]:["require","exports","module"]).concat(c)));if(O){if(!(h=K))P&&"interactive"===P.readyState||M(document.getElementsByTagName("script"),function(b){if("interactive"===b.readyState)return P=b}),h=P;h&&(b||(b=h.getAttribute("data-requiremodule")),j=E[h.getAttribute("data-requirecontext")])}(j?
36 | j.defQueue:R).push([b,c,e])};define.amd={jQuery:!0};j.exec=function(b){return eval(b)};j(s)}})(this);
37 |
--------------------------------------------------------------------------------
/amd-test/script.coffee:
--------------------------------------------------------------------------------
1 | define ['browser-source-map-support'], (sourceMapSupport) ->
2 | sourceMapSupport.install()
3 |
4 | foo = -> throw new Error 'foo'
5 |
6 | try
7 | foo()
8 | catch e
9 | if /\bscript\.coffee\b/.test e.stack
10 | document.body.appendChild document.createTextNode 'Test passed'
11 | else
12 | document.body.appendChild document.createTextNode 'Test failed'
13 | console.log e.stack
14 |
--------------------------------------------------------------------------------
/browser-source-map-support.js:
--------------------------------------------------------------------------------
1 | /*
2 | * Support for source maps in V8 stack traces
3 | * https://github.com/evanw/node-source-map-support
4 | */
5 | /*
6 | The buffer module from node.js, for the browser.
7 |
8 | @author Feross Aboukhadijeh
9 | license MIT
10 | */
11 | (this.define||function(R,U){this.sourceMapSupport=U()})("browser-source-map-support",function(R){(function e(C,J,A){function p(f,c){if(!J[f]){if(!C[f]){var l="function"==typeof require&&require;if(!c&&l)return l(f,!0);if(t)return t(f,!0);throw Error("Cannot find module '"+f+"'");}l=J[f]={exports:{}};C[f][0].call(l.exports,function(q){var r=C[f][1][q];return p(r?r:q)},l,l.exports,e,C,J,A)}return J[f].exports}for(var t="function"==typeof require&&require,m=0;mm)return-1;if(58>m)return m-48+52;if(91>m)return m-65;if(123>m)return m-97+26}var t="undefined"!==typeof Uint8Array?Uint8Array:Array;e.toByteArray=function(m){function f(d){q[k++]=d}if(0>16);f((u&65280)>>8);f(u&255)}2===l?(u=p(m.charAt(c))<<2|p(m.charAt(c+1))>>4,f(u&255)):1===l&&(u=p(m.charAt(c))<<10|p(m.charAt(c+1))<<4|p(m.charAt(c+2))>>2,f(u>>8&255),f(u&255));return q};e.fromByteArray=function(m){var f=m.length%3,c="",l;var q=0;for(l=m.length-f;q>
14 | 18&63)+"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".charAt(r>>12&63)+"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".charAt(r>>6&63)+"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".charAt(r&63);c+=r}switch(f){case 1:r=m[m.length-1];c+="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".charAt(r>>2);c+="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".charAt(r<<4&63);c+="==";break;case 2:r=(m[m.length-2]<<8)+
15 | m[m.length-1],c+="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".charAt(r>>10),c+="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".charAt(r>>4&63),c+="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".charAt(r<<2&63),c+="="}return c}})("undefined"===typeof A?this.base64js={}:A)},{}],3:[function(C,J,A){},{}],4:[function(C,J,A){(function(e){var p=Object.prototype.toString,t="function"===typeof e.alloc&&"function"===typeof e.allocUnsafe&&"function"===
16 | typeof e.from;J.exports=function(m,f,c){if("number"===typeof m)throw new TypeError('"value" argument must not be a number');if("ArrayBuffer"===p.call(m).slice(8,-1)){f>>>=0;var l=m.byteLength-f;if(0>l)throw new RangeError("'offset' is out of bounds");if(void 0===c)c=l;else if(c>>>=0,c>l)throw new RangeError("'length' is out of bounds");return t?e.from(m.slice(f,f+c)):new e(new Uint8Array(m.slice(f,f+c)))}if("string"===typeof m){c=f;if("string"!==typeof c||""===c)c="utf8";if(!e.isEncoding(c))throw new TypeError('"encoding" must be a valid string encoding');
17 | return t?e.from(m,c):new e(m,c)}return t?e.from(m):new e(m)}}).call(this,C("buffer").Buffer)},{buffer:5}],5:[function(C,J,A){function e(a,b,h){if(!(this instanceof e))return new e(a,b,h);var w=typeof a;if("number"===w)var y=0>>0:0;else if("string"===w){if("base64"===b)for(a=(a.trim?a.trim():a.replace(/^\s+|\s+$/g,"")).replace(L,"");0!==a.length%4;)a+="=";y=e.byteLength(a,b)}else if("object"===w&&null!==a)"Buffer"===a.type&&z(a.data)&&(a=a.data),y=0<+a.length?Math.floor(+a.length):0;else throw new TypeError("must start with number, buffer, array or string");
18 | if(this.length>G)throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+G.toString(16)+" bytes");if(e.TYPED_ARRAY_SUPPORT)var I=e._augment(new Uint8Array(y));else I=this,I.length=y,I._isBuffer=!0;if(e.TYPED_ARRAY_SUPPORT&&"number"===typeof a.byteLength)I._set(a);else{var K=a;if(z(K)||e.isBuffer(K)||K&&"object"===typeof K&&"number"===typeof K.length)if(e.isBuffer(a))for(b=0;ba)throw new RangeError("offset is not uint");if(a+b>h)throw new RangeError("Trying to access beyond buffer length");}function m(a,b,h,w,y,I){if(!e.isBuffer(a))throw new TypeError("buffer must be a Buffer instance");if(b>y||ba.length)throw new TypeError("index out of range");
20 | }function f(a,b,h,w){0>b&&(b=65535+b+1);for(var y=0,I=Math.min(a.length-h,2);y>>8*(w?y:1-y)}function c(a,b,h,w){0>b&&(b=4294967295+b+1);for(var y=0,I=Math.min(a.length-h,4);y>>8*(w?y:3-y)&255}function l(a,b,h,w,y,I){if(b>y||ba.length)throw new TypeError("index out of range");}function q(a,b,h,w,y){y||l(a,b,h,4,3.4028234663852886E38,-3.4028234663852886E38);v.write(a,b,h,w,23,4);return h+4}function r(a,
21 | b,h,w,y){y||l(a,b,h,8,1.7976931348623157E308,-1.7976931348623157E308);v.write(a,b,h,w,52,8);return h+8}function k(a){for(var b=[],h=0;h=w)b.push(w);else{var y=h;55296<=w&&57343>=w&&h++;w=encodeURIComponent(a.slice(y,h+1)).substr(1).split("%");for(y=0;y=b.length||y>=a.length);y++)b[y+
22 | h]=a[y];return y}function g(a){try{return decodeURIComponent(a)}catch(b){return String.fromCharCode(65533)}}var n=C("base64-js"),v=C("ieee754"),z=C("is-array");A.Buffer=e;A.SlowBuffer=e;A.INSPECT_MAX_BYTES=50;e.poolSize=8192;var G=1073741823;e.TYPED_ARRAY_SUPPORT=function(){try{var a=new ArrayBuffer(0),b=new Uint8Array(a);b.foo=function(){return 42};return 42===b.foo()&&"function"===typeof b.subarray&&0===(new Uint8Array(1)).subarray(1,1).byteLength}catch(h){return!1}}();e.isBuffer=function(a){return!(null==
23 | a||!a._isBuffer)};e.compare=function(a,b){if(!e.isBuffer(a)||!e.isBuffer(b))throw new TypeError("Arguments must be Buffers");for(var h=a.length,w=b.length,y=0,I=Math.min(h,w);y>>1;break;case "utf8":case "utf-8":h=k(a).length;break;case "base64":h=n.toByteArray(a).length;
25 | break;default:h=a.length}return h};e.prototype.length=void 0;e.prototype.parent=void 0;e.prototype.toString=function(a,b,h){var w=!1;b>>>=0;h=void 0===h||Infinity===h?this.length:h>>>0;a||(a="utf8");0>b&&(b=0);h>this.length&&(h=this.length);if(h<=b)return"";for(;;)switch(a){case "hex":a=b;b=h;h=this.length;if(!a||0>a)a=0;if(!b||0>b||b>h)b=h;w="";for(h=a;hw?"0"+w.toString(16):w.toString(16),w=a+w;return w;case "utf8":case "utf-8":w=a="";for(h=Math.min(this.length,h);b=
26 | this[b]?(a+=g(w)+String.fromCharCode(this[b]),w=""):w+="%"+this[b].toString(16);return a+g(w);case "ascii":return p(this,b,h);case "binary":return p(this,b,h);case "base64":return b=0===b&&h===this.length?n.fromByteArray(this):n.fromByteArray(this.slice(b,h)),b;case "ucs2":case "ucs-2":case "utf16le":case "utf-16le":b=this.slice(b,h);h="";for(a=0;ab&&(a+=" ... "));return""};e.prototype.compare=function(a){if(!e.isBuffer(a))throw new TypeError("Argument must be a Buffer");return e.compare(this,a)};e.prototype.get=function(a){console.log(".get() is deprecated. Access using array indexes instead.");
28 | return this.readUInt8(a)};e.prototype.set=function(a,b){console.log(".set() is deprecated. Access using array indexes instead.");return this.writeUInt8(a,b)};e.prototype.write=function(a,b,h,w){if(isFinite(b))isFinite(h)||(w=h,h=void 0);else{var y=w;w=b;b=h;h=y}b=Number(b)||0;y=this.length-b;h?(h=Number(h),h>y&&(h=y)):h=y;w=String(w||"utf8").toLowerCase();switch(w){case "hex":b=Number(b)||0;w=this.length-b;h?(h=Number(h),h>w&&(h=w)):h=w;w=a.length;if(0!==w%2)throw Error("Invalid hex string");h>w/
29 | 2&&(h=w/2);for(w=0;w>8;K%=256;y.push(K);y.push(w)}a=d(y,this,b,h,2);break;default:throw new TypeError("Unknown encoding: "+
30 | w);}return a};e.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};e.prototype.slice=function(a,b){var h=this.length;a=~~a;b=void 0===b?h:~~b;0>a?(a+=h,0>a&&(a=0)):a>h&&(a=h);0>b?(b+=h,0>b&&(b=0)):b>h&&(b=h);b>>=0;h||m(this,a,b,1,255,0);e.TYPED_ARRAY_SUPPORT||(a=Math.floor(a));this[b]=a;return b+1};e.prototype.writeUInt16LE=function(a,
34 | b,h){a=+a;b>>>=0;h||m(this,a,b,2,65535,0);e.TYPED_ARRAY_SUPPORT?(this[b]=a,this[b+1]=a>>>8):f(this,a,b,!0);return b+2};e.prototype.writeUInt16BE=function(a,b,h){a=+a;b>>>=0;h||m(this,a,b,2,65535,0);e.TYPED_ARRAY_SUPPORT?(this[b]=a>>>8,this[b+1]=a):f(this,a,b,!1);return b+2};e.prototype.writeUInt32LE=function(a,b,h){a=+a;b>>>=0;h||m(this,a,b,4,4294967295,0);e.TYPED_ARRAY_SUPPORT?(this[b+3]=a>>>24,this[b+2]=a>>>16,this[b+1]=a>>>8,this[b]=a):c(this,a,b,!0);return b+4};e.prototype.writeUInt32BE=function(a,
35 | b,h){a=+a;b>>>=0;h||m(this,a,b,4,4294967295,0);e.TYPED_ARRAY_SUPPORT?(this[b]=a>>>24,this[b+1]=a>>>16,this[b+2]=a>>>8,this[b+3]=a):c(this,a,b,!1);return b+4};e.prototype.writeInt8=function(a,b,h){a=+a;b>>>=0;h||m(this,a,b,1,127,-128);e.TYPED_ARRAY_SUPPORT||(a=Math.floor(a));0>a&&(a=255+a+1);this[b]=a;return b+1};e.prototype.writeInt16LE=function(a,b,h){a=+a;b>>>=0;h||m(this,a,b,2,32767,-32768);e.TYPED_ARRAY_SUPPORT?(this[b]=a,this[b+1]=a>>>8):f(this,a,b,!0);return b+2};e.prototype.writeInt16BE=function(a,
36 | b,h){a=+a;b>>>=0;h||m(this,a,b,2,32767,-32768);e.TYPED_ARRAY_SUPPORT?(this[b]=a>>>8,this[b+1]=a):f(this,a,b,!1);return b+2};e.prototype.writeInt32LE=function(a,b,h){a=+a;b>>>=0;h||m(this,a,b,4,2147483647,-2147483648);e.TYPED_ARRAY_SUPPORT?(this[b]=a,this[b+1]=a>>>8,this[b+2]=a>>>16,this[b+3]=a>>>24):c(this,a,b,!0);return b+4};e.prototype.writeInt32BE=function(a,b,h){a=+a;b>>>=0;h||m(this,a,b,4,2147483647,-2147483648);0>a&&(a=4294967295+a+1);e.TYPED_ARRAY_SUPPORT?(this[b]=a>>>24,this[b+1]=a>>>16,this[b+
37 | 2]=a>>>8,this[b+3]=a):c(this,a,b,!1);return b+4};e.prototype.writeFloatLE=function(a,b,h){return q(this,a,b,!0,h)};e.prototype.writeFloatBE=function(a,b,h){return q(this,a,b,!1,h)};e.prototype.writeDoubleLE=function(a,b,h){return r(this,a,b,!0,h)};e.prototype.writeDoubleBE=function(a,b,h){return r(this,a,b,!1,h)};e.prototype.copy=function(a,b,h,w){h||(h=0);w||0===w||(w=this.length);b||(b=0);if(w!==h&&0!==a.length&&0!==this.length){if(wb||b>=a.length)throw new TypeError("targetStart out of bounds");
38 | if(0>h||h>=this.length)throw new TypeError("sourceStart out of bounds");if(0>w||w>this.length)throw new TypeError("sourceEnd out of bounds");w>this.length&&(w=this.length);a.length-bw||!e.TYPED_ARRAY_SUPPORT)for(var y=0;yb||b>=this.length)throw new TypeError("start out of bounds");
39 | if(0>h||h>this.length)throw new TypeError("end out of bounds");if("number"===typeof a)for(;b>1,r=-7;f=t?f-1:0;var k=t?-1:1,u=e[p+f];f+=k;t=u&(1<<-r)-1;u>>=-r;for(r+=c;0>=-r;for(r+=m;0>1,u=23===f?Math.pow(2,-24)-Math.pow(2,-77):0;c=m?0:c-1;var d=m?1:-1,g=0>p||0===p&&0>1/p?1:0;p=Math.abs(p);isNaN(p)||Infinity===p?(p=isNaN(p)?1:0,m=r):(m=Math.floor(Math.log(p)/Math.LN2),1>p*(l=Math.pow(2,-m))&&(m--,l*=2),p=1<=m+k?p+u/l:p+u*Math.pow(2,1-k),2<=p*l&&(m++,l/=2),m+k>=r?(p=0,m=r):1<=m+k?(p=(p*l-1)*Math.pow(2,f),m+=k):(p=p*Math.pow(2,k-1)*Math.pow(2,f),m=0));for(;8<=f;e[t+c]=p&255,c+=
44 | d,p/=256,f-=8);m=m<z?[]:n.slice(v,z-v+1)}c=A.resolve(c).substr(1);l=A.resolve(l).substr(1);
47 | for(var r=q(c.split("/")),k=q(l.split("/")),u=Math.min(r.length,k.length),d=u,g=0;gl&&(l=c.length+l);return c.substr(l,q)}}).call(this,C("g5I+bs"))},{"g5I+bs":9}],9:[function(C,J,A){function e(){}C=J.exports={};C.nextTick=function(){if("undefined"!==typeof window&&window.setImmediate)return function(t){return window.setImmediate(t)};if("undefined"!==typeof window&&window.postMessage&&window.addEventListener){var p=[];window.addEventListener("message",function(t){var m=t.source;m!==window&&null!==
49 | m||"process-tick"!==t.data||(t.stopPropagation(),0p?(-p<<1)+1:p<<1;do p=m&31,m>>>=5,0=f)throw Error("Expected more digits in base 64 VLQ value.");var q=e.decode(p.charCodeAt(t++));if(-1===q)throw Error("Invalid base64 digit: "+p.charAt(t-1));var r=!!(q&32);q&=31;c+=q<>1;m.value=1===(c&1)?-p:p;m.rest=t}},{"./base64":12}],12:[function(C,
53 | J,A){var e="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".split("");A.encode=function(p){if(0<=p&&p=p?p-65:97<=p&&122>=p?p-97+26:48<=p&&57>=p?p-48+52:43==p?62:47==p?63:-1}},{}],13:[function(C,J,A){function e(p,t,m,f,c,l){var q=Math.floor((t-p)/2)+p,r=c(m,f[q],!0);return 0===r?q:0p?-1:p}A.GREATEST_LOWER_BOUND=1;A.LEAST_UPPER_BOUND=2;A.search=function(p,t,m,f){if(0===t.length)return-1;p=e(-1,t.length,p,t,m,f||A.GREATEST_LOWER_BOUND);if(0>p)return-1;for(;0<=p-1&&0===m(t[p],t[p-1],!0);)--p;return p}},{}],14:[function(C,J,A){function e(){this._array=[];this._sorted=!0;this._last={generatedLine:-1,generatedColumn:0}}var p=C("./util");e.prototype.unsortedForEach=function(t,m){this._array.forEach(t,m)};e.prototype.add=function(t){var m=this._last,f=m.generatedLine,
55 | c=t.generatedLine,l=m.generatedColumn,q=t.generatedColumn;c>f||c==f&&q>=l||0>=p.compareByGeneratedPositionsInflated(m,t)?this._last=t:this._sorted=!1;this._array.push(t)};e.prototype.toArray=function(){this._sorted||(this._array.sort(p.compareByGeneratedPositionsInflated),this._sorted=!0);return this._array};A.MappingList=e},{"./util":19}],15:[function(C,J,A){function e(t,m,f){var c=t[m];t[m]=t[f];t[f]=c}function p(t,m,f,c){if(f=m(t[r],q)&&(l+=1,e(t,l,r));e(t,l+1,r);l+=1;p(t,m,f,l-1);p(t,m,l+1,c)}}A.quickSort=function(t,m){p(t,m,0,t.length-1)}},{}],16:[function(C,J,A){function e(k,u){var d=k;"string"===typeof k&&(d=f.parseSourceMapInput(k));return null!=d.sections?new m(d,u):new p(d,u)}function p(k,u){var d=k;"string"===typeof k&&(d=f.parseSourceMapInput(k));var g=f.getArg(d,"version"),n=f.getArg(d,"sources"),v=f.getArg(d,"names",[]),z=f.getArg(d,"sourceRoot",null),G=f.getArg(d,"sourcesContent",null),D=f.getArg(d,
57 | "mappings");d=f.getArg(d,"file",null);if(g!=this._version)throw Error("Unsupported version: "+g);z&&(z=f.normalize(z));n=n.map(String).map(f.normalize).map(function(L){return z&&f.isAbsolute(z)&&f.isAbsolute(L)?f.relative(z,L):L});this._names=l.fromArray(v.map(String),!0);this._sources=l.fromArray(n,!0);this.sourceRoot=z;this.sourcesContent=G;this._mappings=D;this._sourceMapURL=u;this.file=d}function t(){this.generatedColumn=this.generatedLine=0;this.name=this.originalColumn=this.originalLine=this.source=
58 | null}function m(k,u){var d=k;"string"===typeof k&&(d=f.parseSourceMapInput(k));var g=f.getArg(d,"version");d=f.getArg(d,"sections");if(g!=this._version)throw Error("Unsupported version: "+g);this._sources=new l;this._names=new l;var n={line:-1,column:0};this._sections=d.map(function(v){if(v.url)throw Error("Support for url field in sections not implemented.");var z=f.getArg(v,"offset"),G=f.getArg(z,"line"),D=f.getArg(z,"column");if(G=k[d])throw new TypeError("Line must be greater than or equal to 1, got "+
68 | k[d]);if(0>k[g])throw new TypeError("Column must be greater than or equal to 0, got "+k[g]);return c.search(k,u,n,v)};p.prototype.computeColumnSpans=function(){for(var k=0;k=this._sources.size()&&!this.sourcesContent.some(function(k){return null==k}):!1};p.prototype.sourceContentFor=function(k,u){if(!this.sourcesContent)return null;var d=k;null!=this.sourceRoot&&(d=f.relative(this.sourceRoot,d));if(this._sources.has(d))return this.sourcesContent[this._sources.indexOf(d)];
71 | var g=this.sources,n;for(n=0;n
97 | g||95!==d.charCodeAt(g-1)||95!==d.charCodeAt(g-2)||111!==d.charCodeAt(g-3)||116!==d.charCodeAt(g-4)||111!==d.charCodeAt(g-5)||114!==d.charCodeAt(g-6)||112!==d.charCodeAt(g-7)||95!==d.charCodeAt(g-8)||95!==d.charCodeAt(g-9))return!1;for(g-=10;0<=g;g--)if(36!==d.charCodeAt(g))return!1;return!0}function r(d,g){return d===g?0:null===d?1:null===g?-1:d>g?1:-1}A.getArg=function(d,g,n){if(g in d)return d[g];if(3===arguments.length)return n;throw Error('"'+g+'" is a required argument.');};var k=/^(?:([\w+\-.]+):)?\/\/(?:(\w+:\w+)@)?([\w.-]*)(?::(\d+))?(.*)$/,
98 | u=/^data:.+,.+$/;A.urlParse=e;A.urlGenerate=p;A.normalize=t;A.join=m;A.isAbsolute=function(d){return"/"===d.charAt(0)||k.test(d)};A.relative=function(d,g){""===d&&(d=".");d=d.replace(/\/$/,"");for(var n=0;0!==g.indexOf(d+"/");){var v=d.lastIndexOf("/");if(0>v)return g;d=d.slice(0,v);if(d.match(/^([^\/]+:\/)?\/*$/))return g;++n}return Array(n+1).join("../")+g.substr(d.length+1)};C=!("__proto__"in Object.create(null));A.toSetString=C?f:c;A.fromSetString=C?f:l;A.compareByOriginalPositions=function(d,
99 | g,n){var v=r(d.source,g.source);if(0!==v)return v;v=d.originalLine-g.originalLine;if(0!==v)return v;v=d.originalColumn-g.originalColumn;if(0!==v||n)return v;v=d.generatedColumn-g.generatedColumn;if(0!==v)return v;v=d.generatedLine-g.generatedLine;return 0!==v?v:r(d.name,g.name)};A.compareByGeneratedPositionsDeflated=function(d,g,n){var v=d.generatedLine-g.generatedLine;if(0!==v)return v;v=d.generatedColumn-g.generatedColumn;if(0!==v||n)return v;v=r(d.source,g.source);if(0!==v)return v;v=d.originalLine-
100 | g.originalLine;if(0!==v)return v;v=d.originalColumn-g.originalColumn;return 0!==v?v:r(d.name,g.name)};A.compareByGeneratedPositionsInflated=function(d,g){var n=d.generatedLine-g.generatedLine;if(0!==n)return n;n=d.generatedColumn-g.generatedColumn;if(0!==n)return n;n=r(d.source,g.source);if(0!==n)return n;n=d.originalLine-g.originalLine;if(0!==n)return n;n=d.originalColumn-g.originalColumn;return 0!==n?n:r(d.name,g.name)};A.parseSourceMapInput=function(d){return JSON.parse(d.replace(/^\)]}'[^\n]*\n/,
101 | ""))};A.computeSourceURL=function(d,g,n){g=g||"";d&&("/"!==d[d.length-1]&&"/"!==g[0]&&(d+="/"),g=d+g);if(n){d=e(n);if(!d)throw Error("sourceMapURL could not be parsed");d.path&&(n=d.path.lastIndexOf("/"),0<=n&&(d.path=d.path.substring(0,n+1)));g=m(p(d),g)}return t(g)}},{}],20:[function(C,J,A){A.SourceMapGenerator=C("./lib/source-map-generator").SourceMapGenerator;A.SourceMapConsumer=C("./lib/source-map-consumer").SourceMapConsumer;A.SourceNode=C("./lib/source-node").SourceNode},{"./lib/source-map-consumer":16,
102 | "./lib/source-map-generator":17,"./lib/source-node":18}],21:[function(C,J,A){(function(e){function p(){return"browser"===a?!0:"node"===a?!1:"undefined"!==typeof window&&"function"===typeof XMLHttpRequest&&!(window.require&&window.module&&window.process&&"renderer"===window.process.type)}function t(x){return function(B){for(var F=0;F";B=this.getLineNumber();null!=B&&(x+=":"+B,(B=
105 | this.getColumnNumber())&&(x+=":"+B))}B="";var F=this.getFunctionName(),E=!0,H=this.isConstructor();if(this.isToplevel()||H)H?B+="new "+(F||""):F?B+=F:(B+=x,E=!1);else{H=this.getTypeName();"[object Object]"===H&&(H="null");var M=this.getMethodName();F?(H&&0!=F.indexOf(H)&&(B+=H+"."),B+=F,M&&F.indexOf("."+M)!=F.length-M.length-1&&(B+=" [as "+M+"]")):B+=H+"."+(M||"")}E&&(B+=" ("+x+")");return B}function q(x){var B={};Object.getOwnPropertyNames(Object.getPrototypeOf(x)).forEach(function(F){B[F]=
106 | /^(?:is|get)/.test(F)?function(){return x[F].call(x)}:x[F]});B.toString=l;return B}function r(x,B){void 0===B&&(B={nextPosition:null,curPosition:null});if(x.isNative())return B.curPosition=null,x;var F=x.getFileName()||x.getScriptNameOrSourceURL();if(F){var E=x.getLineNumber(),H=x.getColumnNumber()-1,M=/^v(10\.1[6-9]|10\.[2-9][0-9]|10\.[0-9]{3,}|1[2-9]\d*|[2-9]\d|\d{3,}|11\.11)/,S=M.test;var V="object"===typeof e&&null!==e?e.version:"";M=S.call(M,V)?0:62;1===E&&H>M&&!p()&&!x.isEval()&&(H-=M);var O=
107 | f({source:F,line:E,column:H});B.curPosition=O;x=q(x);var T=x.getFunctionName;x.getFunctionName=function(){return null==B.nextPosition?T():B.nextPosition.name||T()};x.getFileName=function(){return O.source};x.getLineNumber=function(){return O.line};x.getColumnNumber=function(){return O.column+1};x.getScriptNameOrSourceURL=function(){return O.source};return x}var Q=x.isEval()&&x.getEvalOrigin();Q&&(Q=c(Q),x=q(x),x.getEvalOrigin=function(){return Q});return x}function k(x,B){L&&(b={},h={});for(var F=
108 | (x.name||"Error")+": "+(x.message||""),E={nextPosition:null,curPosition:null},H=[],M=B.length-1;0<=M;M--)H.push("\n at "+r(B[M],E)),E.nextPosition=E.curPosition;E.curPosition=E.nextPosition=null;return F+H.reverse().join("")}function u(x){var B=/\n at [^(]+ \((.*):(\d+):(\d+)\)/.exec(x.stack);if(B){x=B[1];var F=+B[2];B=+B[3];var E=b[x];if(!E&&v&&v.existsSync(x))try{E=v.readFileSync(x,"utf8")}catch(H){E=""}if(E&&(E=E.split(/(?:\r\n|\r|\n)/)[F-1]))return x+":"+F+"\n"+E+"\n"+Array(B).join(" ")+
109 | "^"}return null}function d(){var x=e.emit;e.emit=function(B){if("uncaughtException"===B){var F=arguments[1]&&arguments[1].stack,E=0
2 | Make sure to run build.js.
3 | This test should say either "Test failed" or "Test passed":
4 |
5 |
6 |
7 |
--------------------------------------------------------------------------------
/browser-test/script.coffee:
--------------------------------------------------------------------------------
1 | sourceMapSupport.install()
2 |
3 | foo = -> throw new Error 'foo'
4 |
5 | try
6 | foo()
7 | catch e
8 | if /\bscript\.coffee\b/.test e.stack
9 | document.body.appendChild document.createTextNode 'Test passed'
10 | else
11 | document.body.appendChild document.createTextNode 'Test failed'
12 | console.log e.stack
13 |
--------------------------------------------------------------------------------
/browser-test/script.js:
--------------------------------------------------------------------------------
1 | // Generated by CoffeeScript 1.12.7
2 | (function() {
3 | var e, foo;
4 |
5 | sourceMapSupport.install();
6 |
7 | foo = function() {
8 | throw new Error('foo');
9 | };
10 |
11 | try {
12 | foo();
13 | } catch (error) {
14 | e = error;
15 | if (/\bscript\.coffee\b/.test(e.stack)) {
16 | document.body.appendChild(document.createTextNode('Test passed'));
17 | } else {
18 | document.body.appendChild(document.createTextNode('Test failed'));
19 | console.log(e.stack);
20 | }
21 | }
22 |
23 | }).call(this);
24 |
25 | //# sourceMappingURL=script.js.map
26 |
--------------------------------------------------------------------------------
/browser-test/script.js.map:
--------------------------------------------------------------------------------
1 | {
2 | "version": 3,
3 | "file": "script.js",
4 | "sourceRoot": "..",
5 | "sources": [
6 | "browser-test/script.coffee"
7 | ],
8 | "names": [],
9 | "mappings": ";AAAA;AAAA,MAAA;;EAAA,gBAAgB,CAAC,OAAjB,CAAA;;EAEA,GAAA,GAAM,SAAA;AAAG,UAAM,IAAI,KAAJ,CAAU,KAAV;EAAT;;AAEN;IACE,GAAA,CAAA,EADF;GAAA,aAAA;IAEM;IACJ,IAAG,oBAAoB,CAAC,IAArB,CAA0B,CAAC,CAAC,KAA5B,CAAH;MACE,QAAQ,CAAC,IAAI,CAAC,WAAd,CAA0B,QAAQ,CAAC,cAAT,CAAwB,aAAxB,CAA1B,EADF;KAAA,MAAA;MAGE,QAAQ,CAAC,IAAI,CAAC,WAAd,CAA0B,QAAQ,CAAC,cAAT,CAAwB,aAAxB,CAA1B;MACA,OAAO,CAAC,GAAR,CAAY,CAAC,CAAC,KAAd,EAJF;KAHF;;AAJA"
10 | }
--------------------------------------------------------------------------------
/browserify-test/index.html:
--------------------------------------------------------------------------------
1 |
2 | Make sure to run build.js.
3 | This test should say either "Test failed" or "Test passed":
4 |
5 |
6 |
--------------------------------------------------------------------------------
/browserify-test/script.coffee:
--------------------------------------------------------------------------------
1 | (require '../source-map-support').install()
2 |
3 | foo = -> throw new Error 'foo'
4 |
5 | try
6 | foo()
7 | catch e
8 | if /\bscript\.coffee\b/.test e.stack
9 | document.body.appendChild document.createTextNode 'Test passed'
10 | else
11 | document.body.appendChild document.createTextNode 'Test failed'
12 | console.log e.stack
13 |
--------------------------------------------------------------------------------
/build.js:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env node
2 |
3 | const fs = require('node:fs');
4 | const path = require('node:path');
5 | const child_process = require('node:child_process');
6 | const https = require('node:https');
7 | const { text } = require('node:stream/consumers');
8 |
9 | const browserify = path.resolve(path.join('node_modules', '.bin', 'browserify'));
10 | const webpack = path.resolve(path.join('node_modules', '.bin', 'webpack'));
11 | const coffee = path.resolve(path.join('node_modules', '.bin', 'coffee'));
12 |
13 | function run(command, callback) {
14 | console.log(command);
15 | child_process.exec(command, { maxBuffer: 25 * 1024 * 1024 }, callback);
16 | }
17 |
18 | // Use browserify to package up source-map-support.js
19 | fs.writeFileSync('.temp.js', 'sourceMapSupport = require("./source-map-support");');
20 |
21 | run(browserify + ' .temp.js', (error, stdout) => {
22 | if (error) throw error;
23 |
24 | // Wrap the code so it works both as a normal
6 |
7 |
--------------------------------------------------------------------------------
/header-test/script.coffee:
--------------------------------------------------------------------------------
1 | sourceMapSupport.install()
2 |
3 | foo = -> throw new Error 'foo'
4 |
5 | try
6 | foo()
7 | catch e
8 | if /\bscript\.coffee\b/.test e.stack
9 | document.body.appendChild document.createTextNode 'Test passed'
10 | else
11 | document.body.appendChild document.createTextNode 'Test failed'
12 | console.log e.stack
13 |
--------------------------------------------------------------------------------
/header-test/server.js:
--------------------------------------------------------------------------------
1 | var fs = require('fs');
2 | var http = require('http');
3 |
4 | http.createServer(function(req, res) {
5 | switch (req.url) {
6 | case '/':
7 | case '/index.html': {
8 | res.writeHead(200, { 'Content-Type': 'text/html' });
9 | res.end(fs.readFileSync('index.html', 'utf8'));
10 | break;
11 | }
12 |
13 | case '/browser-source-map-support.js': {
14 | res.writeHead(200, { 'Content-Type': 'text/javascript' });
15 | res.end(fs.readFileSync('../browser-source-map-support.js', 'utf8'));
16 | break;
17 | }
18 |
19 | case '/script.js': {
20 | res.writeHead(200, { 'Content-Type': 'text/javascript', 'SourceMap': 'script-source-map.map' });
21 | res.end(fs.readFileSync('script.js', 'utf8'));
22 | break;
23 | }
24 |
25 | case '/script-source-map.map': {
26 | res.writeHead(200, { 'Content-Type': 'application/json' });
27 | res.end(fs.readFileSync('script.map', 'utf8'));
28 | break;
29 | }
30 |
31 | case '/header-test/script.coffee': {
32 | res.writeHead(200, { 'Content-Type': 'text/x-coffeescript' });
33 | res.end(fs.readFileSync('script.coffee', 'utf8'));
34 | break;
35 | }
36 |
37 | default: {
38 | res.writeHead(404, { 'Content-Type': 'text/html' });
39 | res.end('404 not found');
40 | break;
41 | }
42 | }
43 | }).listen(1337, '127.0.0.1');
44 |
45 | console.log('Server running at http://127.0.0.1:1337/');
46 |
--------------------------------------------------------------------------------
/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "source-map-support",
3 | "description": "Fixes stack traces for files with source maps",
4 | "version": "0.5.21",
5 | "main": "./source-map-support.js",
6 | "scripts": {
7 | "build": "node build.js",
8 | "serve-tests": "http-server -p 1336",
9 | "prepublish": "npm run build",
10 | "test": "mocha"
11 | },
12 | "dependencies": {
13 | "buffer-from": "^1.0.0",
14 | "source-map": "^0.6.0"
15 | },
16 | "devDependencies": {
17 | "browserify": "^4.2.3",
18 | "coffeescript": "^1.12.7",
19 | "http-server": "^0.11.1",
20 | "mocha": "^3.5.3",
21 | "webpack": "^1.15.0"
22 | },
23 | "repository": {
24 | "type": "git",
25 | "url": "https://github.com/evanw/node-source-map-support"
26 | },
27 | "bugs": {
28 | "url": "https://github.com/evanw/node-source-map-support/issues"
29 | },
30 | "license": "MIT"
31 | }
32 |
--------------------------------------------------------------------------------
/register-hook-require.js:
--------------------------------------------------------------------------------
1 | require('./').install({hookRequire: true});
2 |
--------------------------------------------------------------------------------
/register.js:
--------------------------------------------------------------------------------
1 | require('./').install();
2 |
--------------------------------------------------------------------------------
/source-map-support.js:
--------------------------------------------------------------------------------
1 | var SourceMapConsumer = require('source-map').SourceMapConsumer;
2 | var path = require('path');
3 |
4 | var fs;
5 | try {
6 | fs = require('fs');
7 | if (!fs.existsSync || !fs.readFileSync) {
8 | // fs doesn't have all methods we need
9 | fs = null;
10 | }
11 | } catch (err) {
12 | /* nop */
13 | }
14 |
15 | var bufferFrom = require('buffer-from');
16 |
17 | /**
18 | * Requires a module which is protected against bundler minification.
19 | *
20 | * @param {NodeModule} mod
21 | * @param {string} request
22 | */
23 | function dynamicRequire(mod, request) {
24 | return mod.require(request);
25 | }
26 |
27 | // Only install once if called multiple times
28 | var errorFormatterInstalled = false;
29 | var uncaughtShimInstalled = false;
30 |
31 | // If true, the caches are reset before a stack trace formatting operation
32 | var emptyCacheBetweenOperations = false;
33 |
34 | // Supports {browser, node, auto}
35 | var environment = "auto";
36 |
37 | // Maps a file path to a string containing the file contents
38 | var fileContentsCache = {};
39 |
40 | // Maps a file path to a source map for that file
41 | var sourceMapCache = {};
42 |
43 | // Regex for detecting source maps
44 | var reSourceMap = /^data:application\/json[^,]+base64,/;
45 |
46 | // Priority list of retrieve handlers
47 | var retrieveFileHandlers = [];
48 | var retrieveMapHandlers = [];
49 |
50 | function isInBrowser() {
51 | if (environment === "browser")
52 | return true;
53 | if (environment === "node")
54 | return false;
55 | return ((typeof window !== 'undefined') && (typeof XMLHttpRequest === 'function') && !(window.require && window.module && window.process && window.process.type === "renderer"));
56 | }
57 |
58 | function hasGlobalProcessEventEmitter() {
59 | return ((typeof process === 'object') && (process !== null) && (typeof process.on === 'function'));
60 | }
61 |
62 | function globalProcessVersion() {
63 | if ((typeof process === 'object') && (process !== null)) {
64 | return process.version;
65 | } else {
66 | return '';
67 | }
68 | }
69 |
70 | function globalProcessStderr() {
71 | if ((typeof process === 'object') && (process !== null)) {
72 | return process.stderr;
73 | }
74 | }
75 |
76 | function globalProcessExit(code) {
77 | if ((typeof process === 'object') && (process !== null) && (typeof process.exit === 'function')) {
78 | return process.exit(code);
79 | }
80 | }
81 |
82 | function handlerExec(list) {
83 | return function(arg) {
84 | for (var i = 0; i < list.length; i++) {
85 | var ret = list[i](arg);
86 | if (ret) {
87 | return ret;
88 | }
89 | }
90 | return null;
91 | };
92 | }
93 |
94 | var retrieveFile = handlerExec(retrieveFileHandlers);
95 |
96 | retrieveFileHandlers.push(function(path) {
97 | // Trim the path to make sure there is no extra whitespace.
98 | path = path.trim();
99 | if (/^file:/.test(path)) {
100 | // existsSync/readFileSync can't handle file protocol, but once stripped, it works
101 | path = path.replace(/file:\/\/\/(\w:)?/, function(protocol, drive) {
102 | return drive ?
103 | '' : // file:///C:/dir/file -> C:/dir/file
104 | '/'; // file:///root-dir/file -> /root-dir/file
105 | });
106 | }
107 | if (path in fileContentsCache) {
108 | return fileContentsCache[path];
109 | }
110 |
111 | var contents = '';
112 | try {
113 | if (!fs) {
114 | // Use SJAX if we are in the browser
115 | var xhr = new XMLHttpRequest();
116 | xhr.open('GET', path, /** async */ false);
117 | xhr.send(null);
118 | if (xhr.readyState === 4 && xhr.status === 200) {
119 | contents = xhr.responseText;
120 | }
121 | } else if (fs.existsSync(path)) {
122 | // Otherwise, use the filesystem
123 | contents = fs.readFileSync(path, 'utf8');
124 | }
125 | } catch (er) {
126 | /* ignore any errors */
127 | }
128 |
129 | return fileContentsCache[path] = contents;
130 | });
131 |
132 | // Support URLs relative to a directory, but be careful about a protocol prefix
133 | // in case we are in the browser (i.e. directories may start with "http://" or "file:///")
134 | function supportRelativeURL(file, url) {
135 | if (!file) return url;
136 | var dir = path.dirname(file);
137 | var match = /^\w+:\/\/[^\/]*/.exec(dir);
138 | var protocol = match ? match[0] : '';
139 | var startPath = dir.slice(protocol.length);
140 | if (protocol && /^\/\w\:/.test(startPath)) {
141 | // handle file:///C:/ paths
142 | protocol += '/';
143 | return protocol + path.resolve(dir.slice(protocol.length), url).replace(/\\/g, '/');
144 | }
145 | return protocol + path.resolve(dir.slice(protocol.length), url);
146 | }
147 |
148 | function retrieveSourceMapURL(source) {
149 | var fileData;
150 |
151 | if (isInBrowser()) {
152 | try {
153 | var xhr = new XMLHttpRequest();
154 | xhr.open('GET', source, false);
155 | xhr.send(null);
156 | fileData = xhr.readyState === 4 ? xhr.responseText : null;
157 |
158 | // Support providing a sourceMappingURL via the SourceMap header
159 | var sourceMapHeader = xhr.getResponseHeader("SourceMap") ||
160 | xhr.getResponseHeader("X-SourceMap");
161 | if (sourceMapHeader) {
162 | return sourceMapHeader;
163 | }
164 | } catch (e) {
165 | }
166 | }
167 |
168 | // Get the URL of the source map
169 | fileData = retrieveFile(source);
170 | var re = /(?:\/\/[@#][\s]*sourceMappingURL=([^\s'"]+)[\s]*$)|(?:\/\*[@#][\s]*sourceMappingURL=([^\s*'"]+)[\s]*(?:\*\/)[\s]*$)/mg;
171 | // Keep executing the search to find the *last* sourceMappingURL to avoid
172 | // picking up sourceMappingURLs from comments, strings, etc.
173 | var lastMatch, match;
174 | while (match = re.exec(fileData)) lastMatch = match;
175 | if (!lastMatch) return null;
176 | return lastMatch[1];
177 | };
178 |
179 | // Can be overridden by the retrieveSourceMap option to install. Takes a
180 | // generated source filename; returns a {map, optional url} object, or null if
181 | // there is no source map. The map field may be either a string or the parsed
182 | // JSON object (ie, it must be a valid argument to the SourceMapConsumer
183 | // constructor).
184 | var retrieveSourceMap = handlerExec(retrieveMapHandlers);
185 | retrieveMapHandlers.push(function(source) {
186 | var sourceMappingURL = retrieveSourceMapURL(source);
187 | if (!sourceMappingURL) return null;
188 |
189 | // Read the contents of the source map
190 | var sourceMapData;
191 | if (reSourceMap.test(sourceMappingURL)) {
192 | // Support source map URL as a data url
193 | var rawData = sourceMappingURL.slice(sourceMappingURL.indexOf(',') + 1);
194 | sourceMapData = bufferFrom(rawData, "base64").toString();
195 | sourceMappingURL = source;
196 | } else {
197 | // Support source map URLs relative to the source URL
198 | sourceMappingURL = supportRelativeURL(source, sourceMappingURL);
199 | sourceMapData = retrieveFile(sourceMappingURL);
200 | }
201 |
202 | if (!sourceMapData) {
203 | return null;
204 | }
205 |
206 | return {
207 | url: sourceMappingURL,
208 | map: sourceMapData
209 | };
210 | });
211 |
212 | function mapSourcePosition(position) {
213 | var sourceMap = sourceMapCache[position.source];
214 | if (!sourceMap) {
215 | // Call the (overrideable) retrieveSourceMap function to get the source map.
216 | var urlAndMap = retrieveSourceMap(position.source);
217 | if (urlAndMap) {
218 | sourceMap = sourceMapCache[position.source] = {
219 | url: urlAndMap.url,
220 | map: new SourceMapConsumer(urlAndMap.map)
221 | };
222 |
223 | // Load all sources stored inline with the source map into the file cache
224 | // to pretend like they are already loaded. They may not exist on disk.
225 | if (sourceMap.map.sourcesContent) {
226 | sourceMap.map.sources.forEach(function(source, i) {
227 | var contents = sourceMap.map.sourcesContent[i];
228 | if (contents) {
229 | var url = supportRelativeURL(sourceMap.url, source);
230 | fileContentsCache[url] = contents;
231 | }
232 | });
233 | }
234 | } else {
235 | sourceMap = sourceMapCache[position.source] = {
236 | url: null,
237 | map: null
238 | };
239 | }
240 | }
241 |
242 | // Resolve the source URL relative to the URL of the source map
243 | if (sourceMap && sourceMap.map && typeof sourceMap.map.originalPositionFor === 'function') {
244 | var originalPosition = sourceMap.map.originalPositionFor(position);
245 |
246 | // Only return the original position if a matching line was found. If no
247 | // matching line is found then we return position instead, which will cause
248 | // the stack trace to print the path and line for the compiled file. It is
249 | // better to give a precise location in the compiled file than a vague
250 | // location in the original file.
251 | if (originalPosition.source !== null) {
252 | originalPosition.source = supportRelativeURL(
253 | sourceMap.url, originalPosition.source);
254 | return originalPosition;
255 | }
256 | }
257 |
258 | return position;
259 | }
260 |
261 | // Parses code generated by FormatEvalOrigin(), a function inside V8:
262 | // https://code.google.com/p/v8/source/browse/trunk/src/messages.js
263 | function mapEvalOrigin(origin) {
264 | // Most eval() calls are in this format
265 | var match = /^eval at ([^(]+) \((.+):(\d+):(\d+)\)$/.exec(origin);
266 | if (match) {
267 | var position = mapSourcePosition({
268 | source: match[2],
269 | line: +match[3],
270 | column: match[4] - 1
271 | });
272 | return 'eval at ' + match[1] + ' (' + position.source + ':' +
273 | position.line + ':' + (position.column + 1) + ')';
274 | }
275 |
276 | // Parse nested eval() calls using recursion
277 | match = /^eval at ([^(]+) \((.+)\)$/.exec(origin);
278 | if (match) {
279 | return 'eval at ' + match[1] + ' (' + mapEvalOrigin(match[2]) + ')';
280 | }
281 |
282 | // Make sure we still return useful information if we didn't find anything
283 | return origin;
284 | }
285 |
286 | // This is copied almost verbatim from the V8 source code at
287 | // https://code.google.com/p/v8/source/browse/trunk/src/messages.js. The
288 | // implementation of wrapCallSite() used to just forward to the actual source
289 | // code of CallSite.prototype.toString but unfortunately a new release of V8
290 | // did something to the prototype chain and broke the shim. The only fix I
291 | // could find was copy/paste.
292 | function CallSiteToString() {
293 | var fileName;
294 | var fileLocation = "";
295 | if (this.isNative()) {
296 | fileLocation = "native";
297 | } else {
298 | fileName = this.getScriptNameOrSourceURL();
299 | if (!fileName && this.isEval()) {
300 | fileLocation = this.getEvalOrigin();
301 | fileLocation += ", "; // Expecting source position to follow.
302 | }
303 |
304 | if (fileName) {
305 | fileLocation += fileName;
306 | } else {
307 | // Source code does not originate from a file and is not native, but we
308 | // can still get the source position inside the source string, e.g. in
309 | // an eval string.
310 | fileLocation += "";
311 | }
312 | var lineNumber = this.getLineNumber();
313 | if (lineNumber != null) {
314 | fileLocation += ":" + lineNumber;
315 | var columnNumber = this.getColumnNumber();
316 | if (columnNumber) {
317 | fileLocation += ":" + columnNumber;
318 | }
319 | }
320 | }
321 |
322 | var line = "";
323 | var functionName = this.getFunctionName();
324 | var addSuffix = true;
325 | var isConstructor = this.isConstructor();
326 | var isMethodCall = !(this.isToplevel() || isConstructor);
327 | if (isMethodCall) {
328 | var typeName = this.getTypeName();
329 | // Fixes shim to be backward compatable with Node v0 to v4
330 | if (typeName === "[object Object]") {
331 | typeName = "null";
332 | }
333 | var methodName = this.getMethodName();
334 | if (functionName) {
335 | if (typeName && functionName.indexOf(typeName) != 0) {
336 | line += typeName + ".";
337 | }
338 | line += functionName;
339 | if (methodName && functionName.indexOf("." + methodName) != functionName.length - methodName.length - 1) {
340 | line += " [as " + methodName + "]";
341 | }
342 | } else {
343 | line += typeName + "." + (methodName || "");
344 | }
345 | } else if (isConstructor) {
346 | line += "new " + (functionName || "");
347 | } else if (functionName) {
348 | line += functionName;
349 | } else {
350 | line += fileLocation;
351 | addSuffix = false;
352 | }
353 | if (addSuffix) {
354 | line += " (" + fileLocation + ")";
355 | }
356 | return line;
357 | }
358 |
359 | function cloneCallSite(frame) {
360 | var object = {};
361 | Object.getOwnPropertyNames(Object.getPrototypeOf(frame)).forEach(function(name) {
362 | object[name] = /^(?:is|get)/.test(name) ? function() { return frame[name].call(frame); } : frame[name];
363 | });
364 | object.toString = CallSiteToString;
365 | return object;
366 | }
367 |
368 | function wrapCallSite(frame, state) {
369 | // provides interface backward compatibility
370 | if (state === undefined) {
371 | state = { nextPosition: null, curPosition: null }
372 | }
373 | if(frame.isNative()) {
374 | state.curPosition = null;
375 | return frame;
376 | }
377 |
378 | // Most call sites will return the source file from getFileName(), but code
379 | // passed to eval() ending in "//# sourceURL=..." will return the source file
380 | // from getScriptNameOrSourceURL() instead
381 | var source = frame.getFileName() || frame.getScriptNameOrSourceURL();
382 | if (source) {
383 | var line = frame.getLineNumber();
384 | var column = frame.getColumnNumber() - 1;
385 |
386 | // Fix position in Node where some (internal) code is prepended.
387 | // See https://github.com/evanw/node-source-map-support/issues/36
388 | // Header removed in node at ^10.16 || >=11.11.0
389 | // v11 is not an LTS candidate, we can just test the one version with it.
390 | // Test node versions for: 10.16-19, 10.20+, 12-19, 20-99, 100+, or 11.11
391 | var noHeader = /^v(10\.1[6-9]|10\.[2-9][0-9]|10\.[0-9]{3,}|1[2-9]\d*|[2-9]\d|\d{3,}|11\.11)/;
392 | var headerLength = noHeader.test(globalProcessVersion()) ? 0 : 62;
393 | if (line === 1 && column > headerLength && !isInBrowser() && !frame.isEval()) {
394 | column -= headerLength;
395 | }
396 |
397 | var position = mapSourcePosition({
398 | source: source,
399 | line: line,
400 | column: column
401 | });
402 | state.curPosition = position;
403 | frame = cloneCallSite(frame);
404 | var originalFunctionName = frame.getFunctionName;
405 | frame.getFunctionName = function() {
406 | if (state.nextPosition == null) {
407 | return originalFunctionName();
408 | }
409 | return state.nextPosition.name || originalFunctionName();
410 | };
411 | frame.getFileName = function() { return position.source; };
412 | frame.getLineNumber = function() { return position.line; };
413 | frame.getColumnNumber = function() { return position.column + 1; };
414 | frame.getScriptNameOrSourceURL = function() { return position.source; };
415 | return frame;
416 | }
417 |
418 | // Code called using eval() needs special handling
419 | var origin = frame.isEval() && frame.getEvalOrigin();
420 | if (origin) {
421 | origin = mapEvalOrigin(origin);
422 | frame = cloneCallSite(frame);
423 | frame.getEvalOrigin = function() { return origin; };
424 | return frame;
425 | }
426 |
427 | // If we get here then we were unable to change the source position
428 | return frame;
429 | }
430 |
431 | // This function is part of the V8 stack trace API, for more info see:
432 | // https://v8.dev/docs/stack-trace-api
433 | function prepareStackTrace(error, stack) {
434 | if (emptyCacheBetweenOperations) {
435 | fileContentsCache = {};
436 | sourceMapCache = {};
437 | }
438 |
439 | var name = error.name || 'Error';
440 | var message = error.message || '';
441 | var errorString = name + ": " + message;
442 |
443 | var state = { nextPosition: null, curPosition: null };
444 | var processedStack = [];
445 | for (var i = stack.length - 1; i >= 0; i--) {
446 | processedStack.push('\n at ' + wrapCallSite(stack[i], state));
447 | state.nextPosition = state.curPosition;
448 | }
449 | state.curPosition = state.nextPosition = null;
450 | return errorString + processedStack.reverse().join('');
451 | }
452 |
453 | // Generate position and snippet of original source with pointer
454 | function getErrorSource(error) {
455 | var match = /\n at [^(]+ \((.*):(\d+):(\d+)\)/.exec(error.stack);
456 | if (match) {
457 | var source = match[1];
458 | var line = +match[2];
459 | var column = +match[3];
460 |
461 | // Support the inline sourceContents inside the source map
462 | var contents = fileContentsCache[source];
463 |
464 | // Support files on disk
465 | if (!contents && fs && fs.existsSync(source)) {
466 | try {
467 | contents = fs.readFileSync(source, 'utf8');
468 | } catch (er) {
469 | contents = '';
470 | }
471 | }
472 |
473 | // Format the line from the original source code like node does
474 | if (contents) {
475 | var code = contents.split(/(?:\r\n|\r|\n)/)[line - 1];
476 | if (code) {
477 | return source + ':' + line + '\n' + code + '\n' +
478 | new Array(column).join(' ') + '^';
479 | }
480 | }
481 | }
482 | return null;
483 | }
484 |
485 | function printErrorAndExit (error) {
486 | var source = getErrorSource(error);
487 |
488 | // Ensure error is printed synchronously and not truncated
489 | var stderr = globalProcessStderr();
490 | if (stderr && stderr._handle && stderr._handle.setBlocking) {
491 | stderr._handle.setBlocking(true);
492 | }
493 |
494 | if (source) {
495 | console.error();
496 | console.error(source);
497 | }
498 |
499 | console.error(error.stack);
500 | globalProcessExit(1);
501 | }
502 |
503 | function shimEmitUncaughtException () {
504 | var origEmit = process.emit;
505 |
506 | process.emit = function (type) {
507 | if (type === 'uncaughtException') {
508 | var hasStack = (arguments[1] && arguments[1].stack);
509 | var hasListeners = (this.listeners(type).length > 0);
510 |
511 | if (hasStack && !hasListeners) {
512 | return printErrorAndExit(arguments[1]);
513 | }
514 | }
515 |
516 | return origEmit.apply(this, arguments);
517 | };
518 | }
519 |
520 | var originalRetrieveFileHandlers = retrieveFileHandlers.slice(0);
521 | var originalRetrieveMapHandlers = retrieveMapHandlers.slice(0);
522 |
523 | exports.wrapCallSite = wrapCallSite;
524 | exports.getErrorSource = getErrorSource;
525 | exports.mapSourcePosition = mapSourcePosition;
526 | exports.retrieveSourceMap = retrieveSourceMap;
527 |
528 | exports.install = function(options) {
529 | options = options || {};
530 |
531 | if (options.environment) {
532 | environment = options.environment;
533 | if (["node", "browser", "auto"].indexOf(environment) === -1) {
534 | throw new Error("environment " + environment + " was unknown. Available options are {auto, browser, node}")
535 | }
536 | }
537 |
538 | // Allow sources to be found by methods other than reading the files
539 | // directly from disk.
540 | if (options.retrieveFile) {
541 | if (options.overrideRetrieveFile) {
542 | retrieveFileHandlers.length = 0;
543 | }
544 |
545 | retrieveFileHandlers.unshift(options.retrieveFile);
546 | }
547 |
548 | // Allow source maps to be found by methods other than reading the files
549 | // directly from disk.
550 | if (options.retrieveSourceMap) {
551 | if (options.overrideRetrieveSourceMap) {
552 | retrieveMapHandlers.length = 0;
553 | }
554 |
555 | retrieveMapHandlers.unshift(options.retrieveSourceMap);
556 | }
557 |
558 | // Support runtime transpilers that include inline source maps
559 | if (options.hookRequire && !isInBrowser()) {
560 | // Use dynamicRequire to avoid including in browser bundles
561 | var Module = dynamicRequire(module, 'module');
562 | var $compile = Module.prototype._compile;
563 |
564 | if (!$compile.__sourceMapSupport) {
565 | Module.prototype._compile = function(content, filename) {
566 | fileContentsCache[filename] = content;
567 | sourceMapCache[filename] = undefined;
568 | return $compile.call(this, content, filename);
569 | };
570 |
571 | Module.prototype._compile.__sourceMapSupport = true;
572 | }
573 | }
574 |
575 | // Configure options
576 | if (!emptyCacheBetweenOperations) {
577 | emptyCacheBetweenOperations = 'emptyCacheBetweenOperations' in options ?
578 | options.emptyCacheBetweenOperations : false;
579 | }
580 |
581 | // Install the error reformatter
582 | if (!errorFormatterInstalled) {
583 | errorFormatterInstalled = true;
584 | Error.prepareStackTrace = prepareStackTrace;
585 | }
586 |
587 | if (!uncaughtShimInstalled) {
588 | var installHandler = 'handleUncaughtExceptions' in options ?
589 | options.handleUncaughtExceptions : true;
590 |
591 | // Do not override 'uncaughtException' with our own handler in Node.js
592 | // Worker threads. Workers pass the error to the main thread as an event,
593 | // rather than printing something to stderr and exiting.
594 | try {
595 | // We need to use `dynamicRequire` because `require` on it's own will be optimized by WebPack/Browserify.
596 | var worker_threads = dynamicRequire(module, 'worker_threads');
597 | if (worker_threads.isMainThread === false) {
598 | installHandler = false;
599 | }
600 | } catch(e) {}
601 |
602 | // Provide the option to not install the uncaught exception handler. This is
603 | // to support other uncaught exception handlers (in test frameworks, for
604 | // example). If this handler is not installed and there are no other uncaught
605 | // exception handlers, uncaught exceptions will be caught by node's built-in
606 | // exception handler and the process will still be terminated. However, the
607 | // generated JavaScript code will be shown above the stack trace instead of
608 | // the original source code.
609 | if (installHandler && hasGlobalProcessEventEmitter()) {
610 | uncaughtShimInstalled = true;
611 | shimEmitUncaughtException();
612 | }
613 | }
614 | };
615 |
616 | exports.resetRetrieveHandlers = function() {
617 | retrieveFileHandlers.length = 0;
618 | retrieveMapHandlers.length = 0;
619 |
620 | retrieveFileHandlers = originalRetrieveFileHandlers.slice(0);
621 | retrieveMapHandlers = originalRetrieveMapHandlers.slice(0);
622 |
623 | retrieveSourceMap = handlerExec(retrieveMapHandlers);
624 | retrieveFile = handlerExec(retrieveFileHandlers);
625 | }
626 |
--------------------------------------------------------------------------------
/test.js:
--------------------------------------------------------------------------------
1 | require('./source-map-support').install({
2 | emptyCacheBetweenOperations: true // Needed to be able to test for failure
3 | });
4 |
5 | var SourceMapGenerator = require('source-map').SourceMapGenerator;
6 | var child_process = require('child_process');
7 | var assert = require('assert');
8 | var fs = require('fs');
9 | var bufferFrom = require('buffer-from');
10 |
11 | function compareLines(actual, expected) {
12 | assert(actual.length >= expected.length, 'got ' + actual.length + ' lines but expected at least ' + expected.length + ' lines');
13 | for (var i = 0; i < expected.length; i++) {
14 | // Some tests are regular expressions because the output format changed slightly between node v0.9.2 and v0.9.3
15 | if (expected[i] instanceof RegExp) {
16 | assert(expected[i].test(actual[i]), JSON.stringify(actual[i]) + ' does not match ' + expected[i]);
17 | } else {
18 | assert.equal(actual[i], expected[i]);
19 | }
20 | }
21 | }
22 |
23 | function createEmptySourceMap() {
24 | return new SourceMapGenerator({
25 | file: '.generated.js',
26 | sourceRoot: '.'
27 | });
28 | }
29 |
30 | function createSourceMapWithGap() {
31 | var sourceMap = createEmptySourceMap();
32 | sourceMap.addMapping({
33 | generated: { line: 100, column: 0 },
34 | original: { line: 100, column: 0 },
35 | source: '.original.js'
36 | });
37 | return sourceMap;
38 | }
39 |
40 | function createSingleLineSourceMap() {
41 | var sourceMap = createEmptySourceMap();
42 | sourceMap.addMapping({
43 | generated: { line: 1, column: 0 },
44 | original: { line: 1, column: 0 },
45 | source: '.original.js'
46 | });
47 | return sourceMap;
48 | }
49 |
50 | function createSecondLineSourceMap() {
51 | var sourceMap = createEmptySourceMap();
52 | sourceMap.addMapping({
53 | generated: { line: 2, column: 0 },
54 | original: { line: 1, column: 0 },
55 | source: '.original.js'
56 | });
57 | return sourceMap;
58 | }
59 |
60 | function createMultiLineSourceMap() {
61 | var sourceMap = createEmptySourceMap();
62 | for (var i = 1; i <= 100; i++) {
63 | sourceMap.addMapping({
64 | generated: { line: i, column: 0 },
65 | original: { line: 1000 + i, column: 99 + i },
66 | source: 'line' + i + '.js'
67 | });
68 | }
69 | return sourceMap;
70 | }
71 |
72 | function createMultiLineSourceMapWithSourcesContent() {
73 | var sourceMap = createEmptySourceMap();
74 | var original = new Array(1001).join('\n');
75 | for (var i = 1; i <= 100; i++) {
76 | sourceMap.addMapping({
77 | generated: { line: i, column: 0 },
78 | original: { line: 1000 + i, column: 4 },
79 | source: 'original.js'
80 | });
81 | original += ' line ' + i + '\n';
82 | }
83 | sourceMap.setSourceContent('original.js', original);
84 | return sourceMap;
85 | }
86 |
87 | function compareStackTrace(sourceMap, source, expected) {
88 | // Check once with a separate source map
89 | fs.writeFileSync('.generated.js.map', String(sourceMap));
90 | fs.writeFileSync('.generated.js', 'exports.test = function() {' +
91 | source.join('\n') + '};//@ sourceMappingURL=.generated.js.map');
92 | try {
93 | delete require.cache[require.resolve('./.generated')];
94 | require('./.generated').test();
95 | } catch (e) {
96 | compareLines(e.stack.split(/\r\n|\n/), expected);
97 | }
98 | fs.unlinkSync('.generated.js');
99 | fs.unlinkSync('.generated.js.map');
100 |
101 | // Check again with an inline source map (in a data URL)
102 | fs.writeFileSync('.generated.js', 'exports.test = function() {' +
103 | source.join('\n') + '};//@ sourceMappingURL=data:application/json;base64,' +
104 | bufferFrom(sourceMap.toString()).toString('base64'));
105 | try {
106 | delete require.cache[require.resolve('./.generated')];
107 | require('./.generated').test();
108 | } catch (e) {
109 | compareLines(e.stack.split(/\r\n|\n/), expected);
110 | }
111 | fs.unlinkSync('.generated.js');
112 | }
113 |
114 | function compareStdout(done, sourceMap, source, expected) {
115 | fs.writeFileSync('.original.js', 'this is the original code');
116 | fs.writeFileSync('.generated.js.map', String(sourceMap));
117 | fs.writeFileSync('.generated.js', source.join('\n') +
118 | '//@ sourceMappingURL=.generated.js.map');
119 | child_process.exec('node ./.generated', function(error, stdout, stderr) {
120 | try {
121 | compareLines(
122 | (stdout + stderr)
123 | .trim()
124 | .split(/\r\n|\n/)
125 | .filter(function (line) { return line !== '' }), // Empty lines are not relevant.
126 | expected
127 | );
128 | } catch (e) {
129 | return done(e);
130 | }
131 | fs.unlinkSync('.generated.js');
132 | fs.unlinkSync('.generated.js.map');
133 | fs.unlinkSync('.original.js');
134 | done();
135 | });
136 | }
137 |
138 | it('normal throw', function() {
139 | compareStackTrace(createMultiLineSourceMap(), [
140 | 'throw new Error("test");'
141 | ], [
142 | 'Error: test',
143 | /^ at Object\.exports\.test \((?:.*[/\\])?line1\.js:1001:101\)$/
144 | ]);
145 | });
146 |
147 | it('does not crash on missing process object', function() {
148 | var proc = process;
149 | compareStackTrace(createMultiLineSourceMap(), [
150 | 'global.process = null;',
151 | 'throw new Error("test");'
152 | ], [
153 | 'Error: test',
154 | /^ at Object\.exports\.test \((?:.*[/\\])?line2\.js:1002:102\)$/
155 | ]);
156 | global.process = proc;
157 | });
158 |
159 | it('does not crash on missing process.stderr', function() {
160 | var stderr = process.stderr;
161 | compareStackTrace(createMultiLineSourceMap(), [
162 | 'process.stderr = null;',
163 | 'throw new Error("test");'
164 | ], [
165 | 'Error: test',
166 | /^ at Object\.exports\.test \((?:.*[/\\])?line2\.js:1002:102\)$/
167 | ]);
168 | process.stderr = stderr;
169 | });
170 |
171 | /* The following test duplicates some of the code in
172 | * `normal throw` but triggers file read failure.
173 | */
174 | it('fs.readFileSync failure', function() {
175 | compareStackTrace(createMultiLineSourceMap(), [
176 | 'var fs = require("fs");',
177 | 'var rfs = fs.readFileSync;',
178 | 'fs.readFileSync = function() {',
179 | ' throw new Error("no rfs for you");',
180 | '};',
181 | 'try {',
182 | ' throw new Error("test");',
183 | '} finally {',
184 | ' fs.readFileSync = rfs;',
185 | '}'
186 | ], [
187 | 'Error: test',
188 | /^ at Object\.exports\.test \((?:.*[/\\])?line7\.js:1007:107\)$/
189 | ]);
190 | });
191 |
192 |
193 | it('throw inside function', function() {
194 | compareStackTrace(createMultiLineSourceMap(), [
195 | 'function foo() {',
196 | ' throw new Error("test");',
197 | '}',
198 | 'foo();'
199 | ], [
200 | 'Error: test',
201 | /^ at foo \((?:.*[/\\])?line2\.js:1002:102\)$/,
202 | /^ at Object\.exports\.test \((?:.*[/\\])?line4\.js:1004:104\)$/
203 | ]);
204 | });
205 |
206 | it('throw inside function inside function', function() {
207 | compareStackTrace(createMultiLineSourceMap(), [
208 | 'function foo() {',
209 | ' function bar() {',
210 | ' throw new Error("test");',
211 | ' }',
212 | ' bar();',
213 | '}',
214 | 'foo();'
215 | ], [
216 | 'Error: test',
217 | /^ at bar \((?:.*[/\\])?line3\.js:1003:103\)$/,
218 | /^ at foo \((?:.*[/\\])?line5\.js:1005:105\)$/,
219 | /^ at Object\.exports\.test \((?:.*[/\\])?line7\.js:1007:107\)$/
220 | ]);
221 | });
222 |
223 | it('eval', function() {
224 | compareStackTrace(createMultiLineSourceMap(), [
225 | 'eval("throw new Error(\'test\')");'
226 | ], [
227 | 'Error: test',
228 |
229 | // Before Node 4, `Object.eval`, after just `eval`.
230 | /^ at (?:Object\.)?eval \(eval at (|exports.test) \((?:.*[/\\])?line1\.js:1001:101\)/,
231 |
232 | /^ at Object\.exports\.test \((?:.*[/\\])?line1\.js:1001:101\)$/
233 | ]);
234 | });
235 |
236 | it('eval inside eval', function() {
237 | compareStackTrace(createMultiLineSourceMap(), [
238 | 'eval("eval(\'throw new Error(\\"test\\")\')");'
239 | ], [
240 | 'Error: test',
241 | /^ at (?:Object\.)?eval \(eval at (|exports.test) \(eval at (|exports.test) \((?:.*[/\\])?line1\.js:1001:101\)/,
242 | /^ at (?:Object\.)?eval \(eval at (|exports.test) \((?:.*[/\\])?line1\.js:1001:101\)/,
243 | /^ at Object\.exports\.test \((?:.*[/\\])?line1\.js:1001:101\)$/
244 | ]);
245 | });
246 |
247 | it('eval inside function', function() {
248 | compareStackTrace(createMultiLineSourceMap(), [
249 | 'function foo() {',
250 | ' eval("throw new Error(\'test\')");',
251 | '}',
252 | 'foo();'
253 | ], [
254 | 'Error: test',
255 | /^ at eval \(eval at foo \((?:.*[/\\])?line2\.js:1002:102\)/,
256 | /^ at foo \((?:.*[/\\])?line2\.js:1002:102\)/,
257 | /^ at Object\.exports\.test \((?:.*[/\\])?line4\.js:1004:104\)$/
258 | ]);
259 | });
260 |
261 | it('eval with sourceURL', function() {
262 | compareStackTrace(createMultiLineSourceMap(), [
263 | 'eval("throw new Error(\'test\')//@ sourceURL=sourceURL.js");'
264 | ], [
265 | 'Error: test',
266 | /^ at (?:Object\.)?eval \(sourceURL\.js:1:7\)$/,
267 | /^ at Object\.exports\.test \((?:.*[/\\])?line1\.js:1001:101\)$/
268 | ]);
269 | });
270 |
271 | it('eval with sourceURL inside eval', function() {
272 | compareStackTrace(createMultiLineSourceMap(), [
273 | 'eval("eval(\'throw new Error(\\"test\\")//@ sourceURL=sourceURL.js\')");'
274 | ], [
275 | 'Error: test',
276 | /^ at (?:Object\.)?eval \(sourceURL\.js:1:7\)$/,
277 | /^ at (?:Object\.)?eval \(eval at (|exports.test) \((?:.*[/\\])?line1\.js:1001:101\)/,
278 | /^ at Object\.exports\.test \((?:.*[/\\])?line1\.js:1001:101\)$/
279 | ]);
280 | });
281 |
282 | it('native function', function() {
283 | compareStackTrace(createSingleLineSourceMap(), [
284 | '[1].map(function(x) { throw new Error(x); });'
285 | ], [
286 | 'Error: 1',
287 | /[/\\].original\.js/,
288 | /at Array\.map \((native|)\)/
289 | ]);
290 | });
291 |
292 | it('function constructor', function() {
293 | compareStackTrace(createMultiLineSourceMap(), [
294 | 'throw new Function(")");'
295 | ], [
296 | /SyntaxError: Unexpected token '?\)'?/,
297 | ]);
298 | });
299 |
300 | it('throw with empty source map', function() {
301 | compareStackTrace(createEmptySourceMap(), [
302 | 'throw new Error("test");'
303 | ], [
304 | 'Error: test',
305 | /^ at Object\.exports\.test \((?:.*[/\\])?\.generated.js:1:34\)$/
306 | ]);
307 | });
308 |
309 | it('throw in Timeout with empty source map', function(done) {
310 | compareStdout(done, createEmptySourceMap(), [
311 | 'require("./source-map-support").install();',
312 | 'setTimeout(function () {',
313 | ' throw new Error("this is the error")',
314 | '})'
315 | ], [
316 | /[/\\].generated.js:3$/,
317 | ' throw new Error("this is the error")',
318 | /^ \^$/,
319 | 'Error: this is the error',
320 | /^ at ((null)|(Timeout))\._onTimeout \((?:.*[/\\])?.generated\.js:3:11\)$/
321 | ]);
322 | });
323 |
324 | it('throw with source map with gap', function() {
325 | compareStackTrace(createSourceMapWithGap(), [
326 | 'throw new Error("test");'
327 | ], [
328 | 'Error: test',
329 | /^ at Object\.exports\.test \((?:.*[/\\])?\.generated\.js:1:34\)$/
330 | ]);
331 | });
332 |
333 | it('sourcesContent with data URL', function() {
334 | compareStackTrace(createMultiLineSourceMapWithSourcesContent(), [
335 | 'throw new Error("test");'
336 | ], [
337 | 'Error: test',
338 | /^ at Object\.exports\.test \((?:.*[/\\])?original\.js:1001:5\)$/
339 | ]);
340 | });
341 |
342 | it('finds the last sourceMappingURL', function() {
343 | compareStackTrace(createMultiLineSourceMapWithSourcesContent(), [
344 | '//# sourceMappingURL=missing.map.js', // NB: compareStackTrace adds another source mapping.
345 | 'throw new Error("test");'
346 | ], [
347 | 'Error: test',
348 | /^ at Object\.exports\.test \((?:.*[/\\])?original\.js:1002:5\)$/
349 | ]);
350 | });
351 |
352 | it('maps original name from source', function() {
353 | var sourceMap = createEmptySourceMap();
354 | sourceMap.addMapping({
355 | generated: { line: 2, column: 8 },
356 | original: { line: 1000, column: 10 },
357 | source: '.original.js',
358 | });
359 | sourceMap.addMapping({
360 | generated: { line: 4, column: 0 },
361 | original: { line: 1002, column: 1 },
362 | source: ".original.js",
363 | name: "myOriginalName"
364 | });
365 | compareStackTrace(sourceMap, [
366 | 'function foo() {',
367 | ' throw new Error("test");',
368 | '}',
369 | 'foo();'
370 | ], [
371 | 'Error: test',
372 | /^ at myOriginalName \((?:.*[/\\])?\.original.js:1000:11\)$/,
373 | /^ at Object\.exports\.test \((?:.*[/\\])?\.original.js:1002:2\)$/
374 | ]);
375 | });
376 |
377 | it('default options', function(done) {
378 | compareStdout(done, createSecondLineSourceMap(), [
379 | '',
380 | 'function foo() { throw new Error("this is the error"); }',
381 | 'require("./source-map-support").install();',
382 | 'process.nextTick(foo);',
383 | 'process.nextTick(function() { process.exit(1); });'
384 | ], [
385 | /[/\\].original\.js:1$/,
386 | 'this is the original code',
387 | '^',
388 | 'Error: this is the error',
389 | /^ at foo \((?:.*[/\\])?\.original\.js:1:1\)$/
390 | ]);
391 | });
392 |
393 | it('handleUncaughtExceptions is true', function(done) {
394 | compareStdout(done, createSecondLineSourceMap(), [
395 | '',
396 | 'function foo() { throw new Error("this is the error"); }',
397 | 'require("./source-map-support").install({ handleUncaughtExceptions: true });',
398 | 'process.nextTick(foo);'
399 | ], [
400 | /[/\\].original\.js:1$/,
401 | 'this is the original code',
402 | '^',
403 | 'Error: this is the error',
404 | /^ at foo \((?:.*[/\\])?\.original\.js:1:1\)$/
405 | ]);
406 | });
407 |
408 | it('handleUncaughtExceptions is false', function(done) {
409 | compareStdout(done, createSecondLineSourceMap(), [
410 | '',
411 | 'function foo() { throw new Error("this is the error"); }',
412 | 'require("./source-map-support").install({ handleUncaughtExceptions: false });',
413 | 'process.nextTick(foo);'
414 | ], [
415 | /[/\\].generated.js:2$/,
416 | 'function foo() { throw new Error("this is the error"); }',
417 |
418 | // Before Node 4, the arrow points on the `new`, after on the
419 | // `throw`.
420 | /^ (?: )?\^$/,
421 |
422 | 'Error: this is the error',
423 | /^ at foo \((?:.*[/\\])?.original\.js:1:1\)$/
424 | ]);
425 | });
426 |
427 | it('default options with empty source map', function(done) {
428 | compareStdout(done, createEmptySourceMap(), [
429 | '',
430 | 'function foo() { throw new Error("this is the error"); }',
431 | 'require("./source-map-support").install();',
432 | 'process.nextTick(foo);'
433 | ], [
434 | /[/\\].generated.js:2$/,
435 | 'function foo() { throw new Error("this is the error"); }',
436 | /^ (?: )?\^$/,
437 | 'Error: this is the error',
438 | /^ at foo \((?:.*[/\\])?.generated.js:2:24\)$/
439 | ]);
440 | });
441 |
442 | it('default options with source map with gap', function(done) {
443 | compareStdout(done, createSourceMapWithGap(), [
444 | '',
445 | 'function foo() { throw new Error("this is the error"); }',
446 | 'require("./source-map-support").install();',
447 | 'process.nextTick(foo);'
448 | ], [
449 | /[/\\].generated.js:2$/,
450 | 'function foo() { throw new Error("this is the error"); }',
451 | /^ (?: )?\^$/,
452 | 'Error: this is the error',
453 | /^ at foo \((?:.*[/\\])?.generated.js:2:24\)$/
454 | ]);
455 | });
456 |
457 | it('specifically requested error source', function(done) {
458 | compareStdout(done, createSecondLineSourceMap(), [
459 | '',
460 | 'function foo() { throw new Error("this is the error"); }',
461 | 'var sms = require("./source-map-support");',
462 | 'sms.install({ handleUncaughtExceptions: false });',
463 | 'process.on("uncaughtException", function (e) { console.log("SRC:" + sms.getErrorSource(e)); });',
464 | 'process.nextTick(foo);'
465 | ], [
466 | /^SRC:.*[/\\]\.original\.js:1$/,
467 | 'this is the original code',
468 | '^'
469 | ]);
470 | });
471 |
472 | it('sourcesContent', function(done) {
473 | compareStdout(done, createMultiLineSourceMapWithSourcesContent(), [
474 | '',
475 | 'function foo() { throw new Error("this is the error"); }',
476 | 'require("./source-map-support").install();',
477 | 'process.nextTick(foo);',
478 | 'process.nextTick(function() { process.exit(1); });'
479 | ], [
480 | /[/\\]original\.js:1002$/,
481 | ' line 2',
482 | ' ^',
483 | 'Error: this is the error',
484 | /^ at foo \((?:.*[/\\])?original\.js:1002:5\)$/
485 | ]);
486 | });
487 |
488 | it('missing source maps should also be cached', function(done) {
489 | compareStdout(done, createSingleLineSourceMap(), [
490 | '',
491 | 'var count = 0;',
492 | 'function foo() {',
493 | ' console.log(new Error("this is the error").stack.split("\\n").slice(0, 2).join("\\n"));',
494 | '}',
495 | 'require("./source-map-support").install({',
496 | ' overrideRetrieveSourceMap: true,',
497 | ' retrieveSourceMap: function(name) {',
498 | ' if (/\\.generated.js$/.test(name)) count++;',
499 | ' return null;',
500 | ' }',
501 | '});',
502 | 'process.nextTick(foo);',
503 | 'process.nextTick(foo);',
504 | 'process.nextTick(function() { console.log(count); });',
505 | ], [
506 | 'Error: this is the error',
507 | /^ at foo \((?:.*[/\\])?.generated.js:4:15\)$/,
508 | 'Error: this is the error',
509 | /^ at foo \((?:.*[/\\])?.generated.js:4:15\)$/,
510 | '1', // The retrieval should only be attempted once
511 | ]);
512 | });
513 |
514 | it('should consult all retrieve source map providers', function(done) {
515 | compareStdout(done, createSingleLineSourceMap(), [
516 | '',
517 | 'var count = 0;',
518 | 'function foo() {',
519 | ' console.log(new Error("this is the error").stack.split("\\n").slice(0, 2).join("\\n"));',
520 | '}',
521 | 'require("./source-map-support").install({',
522 | ' retrieveSourceMap: function(name) {',
523 | ' if (/\\.generated.js$/.test(name)) count++;',
524 | ' return undefined;',
525 | ' }',
526 | '});',
527 | 'require("./source-map-support").install({',
528 | ' retrieveSourceMap: function(name) {',
529 | ' if (/\\.generated.js$/.test(name)) {',
530 | ' count++;',
531 | ' return ' + JSON.stringify({url: '.original.js', map: createMultiLineSourceMapWithSourcesContent().toJSON()}) + ';',
532 | ' }',
533 | ' }',
534 | '});',
535 | 'process.nextTick(foo);',
536 | 'process.nextTick(foo);',
537 | 'process.nextTick(function() { console.log(count); });',
538 | ], [
539 | 'Error: this is the error',
540 | /^ at foo \((?:.*[/\\])?original\.js:1004:5\)$/,
541 | 'Error: this is the error',
542 | /^ at foo \((?:.*[/\\])?original\.js:1004:5\)$/,
543 | '1', // The retrieval should only be attempted once
544 | ]);
545 | });
546 |
547 | it('should allow for runtime inline source maps', function(done) {
548 | var sourceMap = createMultiLineSourceMapWithSourcesContent();
549 |
550 | fs.writeFileSync('.generated.jss', 'foo');
551 |
552 | compareStdout(function(err) {
553 | fs.unlinkSync('.generated.jss');
554 | done(err);
555 | }, createSingleLineSourceMap(), [
556 | 'require("./source-map-support").install({',
557 | ' hookRequire: true',
558 | '});',
559 | 'require.extensions[".jss"] = function(module, filename) {',
560 | ' module._compile(',
561 | JSON.stringify([
562 | '',
563 | 'var count = 0;',
564 | 'function foo() {',
565 | ' console.log(new Error("this is the error").stack.split("\\n").slice(0, 2).join("\\n"));',
566 | '}',
567 | 'process.nextTick(foo);',
568 | 'process.nextTick(foo);',
569 | 'process.nextTick(function() { console.log(count); });',
570 | '//@ sourceMappingURL=data:application/json;charset=utf8;base64,' + bufferFrom(sourceMap.toString()).toString('base64')
571 | ].join('\n')),
572 | ', filename);',
573 | '};',
574 | 'require("./.generated.jss");',
575 | ], [
576 | 'Error: this is the error',
577 | /^ at foo \(.*[/\\]original\.js:1004:5\)$/,
578 | 'Error: this is the error',
579 | /^ at foo \(.*[/\\]original\.js:1004:5\)$/,
580 | '0', // The retrieval should only be attempted once
581 | ]);
582 | });
583 |
584 | /* The following test duplicates some of the code in
585 | * `compareStackTrace` but appends a charset to the
586 | * source mapping url.
587 | */
588 | it('finds source maps with charset specified', function() {
589 | var sourceMap = createMultiLineSourceMap()
590 | var source = [ 'throw new Error("test");' ];
591 | var expected = [
592 | 'Error: test',
593 | /^ at Object\.exports\.test \((?:.*[/\\])?line1\.js:1001:101\)$/
594 | ];
595 |
596 | fs.writeFileSync('.generated.js', 'exports.test = function() {' +
597 | source.join('\n') + '};//@ sourceMappingURL=data:application/json;charset=utf8;base64,' +
598 | bufferFrom(sourceMap.toString()).toString('base64'));
599 | try {
600 | delete require.cache[require.resolve('./.generated')];
601 | require('./.generated').test();
602 | } catch (e) {
603 | compareLines(e.stack.split(/\r\n|\n/), expected);
604 | }
605 | fs.unlinkSync('.generated.js');
606 | });
607 |
608 | /* The following test duplicates some of the code in
609 | * `compareStackTrace` but appends some code and a
610 | * comment to the source mapping url.
611 | */
612 | it('allows code/comments after sourceMappingURL', function() {
613 | var sourceMap = createMultiLineSourceMap()
614 | var source = [ 'throw new Error("test");' ];
615 | var expected = [
616 | 'Error: test',
617 | /^ at Object\.exports\.test \((?:.*[/\\])?line1\.js:1001:101\)$/
618 | ];
619 |
620 | fs.writeFileSync('.generated.js', 'exports.test = function() {' +
621 | source.join('\n') + '};//# sourceMappingURL=data:application/json;base64,' +
622 | bufferFrom(sourceMap.toString()).toString('base64') +
623 | '\n// Some comment below the sourceMappingURL\nvar foo = 0;');
624 | try {
625 | delete require.cache[require.resolve('./.generated')];
626 | require('./.generated').test();
627 | } catch (e) {
628 | compareLines(e.stack.split(/\r\n|\n/), expected);
629 | }
630 | fs.unlinkSync('.generated.js');
631 | });
632 |
633 | it('handleUncaughtExceptions is true with existing listener', function(done) {
634 | var source = [
635 | 'process.on("uncaughtException", function() { /* Silent */ });',
636 | 'function foo() { throw new Error("this is the error"); }',
637 | 'require("./source-map-support").install();',
638 | 'process.nextTick(foo);',
639 | '//@ sourceMappingURL=.generated.js.map'
640 | ];
641 |
642 | fs.writeFileSync('.original.js', 'this is the original code');
643 | fs.writeFileSync('.generated.js.map', String(createSingleLineSourceMap()));
644 | fs.writeFileSync('.generated.js', source.join('\n'));
645 |
646 | child_process.exec('node ./.generated', function(error, stdout, stderr) {
647 | fs.unlinkSync('.generated.js');
648 | fs.unlinkSync('.generated.js.map');
649 | fs.unlinkSync('.original.js');
650 | assert.equal((stdout + stderr).trim(), '');
651 | done();
652 | });
653 | });
654 |
655 | it('normal console.trace', function(done) {
656 | compareStdout(done, createMultiLineSourceMap(), [
657 | 'require("./source-map-support").install();',
658 | 'console.trace("test");'
659 | ], [
660 | 'Trace: test',
661 | /^ at Object\. \((?:.*[/\\])?line2\.js:1002:102\)$/
662 | ]);
663 | });
664 |
--------------------------------------------------------------------------------
/webpack-test/index.html:
--------------------------------------------------------------------------------
1 |
2 | Make sure to run build.js.
3 | This test should say either "Test failed" or "Test passed":
4 |
5 |
6 |
--------------------------------------------------------------------------------
/webpack-test/script.js:
--------------------------------------------------------------------------------
1 | require('../').install();
2 |
3 | function foo() {
4 | throw new Error('foo');
5 | }
6 |
7 | try {
8 | foo();
9 | } catch (e) {
10 | if (/\bscript\.js\b/.test(e.stack)) {
11 | document.body.appendChild(document.createTextNode('Test passed'));
12 | } else {
13 | document.body.appendChild(document.createTextNode('Test failed'));
14 | console.log(e.stack);
15 | }
16 | }
17 |
--------------------------------------------------------------------------------
/webpack-test/webpack.config.js:
--------------------------------------------------------------------------------
1 | var webpack = require('webpack');
2 |
3 | module.exports = {
4 | entry: './script.js',
5 | devtool: 'inline-source-map',
6 | output: {
7 | filename: 'compiled.js'
8 | },
9 | resolve: {
10 | extensions: ['', '.js']
11 | }
12 | };
13 |
--------------------------------------------------------------------------------