index.js 7.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345
  1. 'use strict';
  2. /* istanbul ignore next - affordance for node v8 */
  3. if (!String.prototype.trimEnd) {
  4. String.prototype.trimEnd = function () {
  5. return this.replace(/[\n\r\s\t]+$/, '')
  6. }
  7. }
  8. const escapeStringRegexp = require('escape-string-regexp');
  9. const natives = [].concat(
  10. require('module').builtinModules,
  11. 'bootstrap_node',
  12. 'node'
  13. ).map(n => new RegExp(`(?:\\((?:node:)?${n}(?:\\.js)?:\\d+:\\d+\\)$|^\\s*at (?:node:)?${n}(?:\\.js)?:\\d+:\\d+$)`));
  14. natives.push(
  15. /\((?:node:)?internal\/[^:]+:\d+:\d+\)$/,
  16. /\s*at (?:node:)?internal\/[^:]+:\d+:\d+$/,
  17. /\/\.node-spawn-wrap-\w+-\w+\/node:\d+:\d+\)?$/
  18. );
  19. class StackUtils {
  20. constructor (opts) {
  21. opts = Object.assign({}, {
  22. ignoredPackages: []
  23. }, opts);
  24. if ('internals' in opts === false) {
  25. opts.internals = StackUtils.nodeInternals();
  26. }
  27. if ('cwd' in opts === false) {
  28. opts.cwd = process.cwd()
  29. }
  30. this._cwd = opts.cwd.replace(/\\/g, '/');
  31. this._internals = [].concat(
  32. opts.internals,
  33. ignoredPackagesRegExp(opts.ignoredPackages)
  34. );
  35. this._wrapCallSite = opts.wrapCallSite || false;
  36. }
  37. static nodeInternals () {
  38. return natives.slice();
  39. }
  40. clean (stack, indent) {
  41. indent = indent || 0
  42. indent = ' '.repeat(indent);
  43. if (!Array.isArray(stack)) {
  44. stack = stack.split('\n');
  45. }
  46. if (!(/^\s*at /.test(stack[0])) && (/^\s*at /.test(stack[1]))) {
  47. stack = stack.slice(1);
  48. }
  49. let outdent = false;
  50. let lastNonAtLine = null;
  51. const result = [];
  52. stack.forEach(st => {
  53. st = st.replace(/\\/g, '/');
  54. if (this._internals.some(internal => internal.test(st))) {
  55. return;
  56. }
  57. const isAtLine = /^\s*at /.test(st);
  58. if (outdent) {
  59. st = st.trimEnd().replace(/^(\s+)at /, '$1');
  60. } else {
  61. st = st.trim();
  62. if (isAtLine) {
  63. st = st.slice(3);
  64. }
  65. }
  66. st = st.replace(`${this._cwd}/`, '');
  67. if (st) {
  68. if (isAtLine) {
  69. if (lastNonAtLine) {
  70. result.push(lastNonAtLine);
  71. lastNonAtLine = null;
  72. }
  73. result.push(st);
  74. } else {
  75. outdent = true;
  76. lastNonAtLine = st;
  77. }
  78. }
  79. });
  80. return result.map(line => `${indent}${line}\n`).join('');
  81. }
  82. captureString (limit, fn) {
  83. fn = fn || this.captureString
  84. if (typeof limit === 'function') {
  85. fn = limit;
  86. limit = Infinity;
  87. }
  88. const stackTraceLimit = Error.stackTraceLimit;
  89. if (limit) {
  90. Error.stackTraceLimit = limit;
  91. }
  92. const obj = {};
  93. Error.captureStackTrace(obj, fn);
  94. const stack = obj.stack;
  95. Error.stackTraceLimit = stackTraceLimit;
  96. return this.clean(stack);
  97. }
  98. capture (limit, fn) {
  99. fn = fn || this.capture
  100. if (typeof limit === 'function') {
  101. fn = limit;
  102. limit = Infinity;
  103. }
  104. const prepareStackTrace = Error.prepareStackTrace
  105. const stackTraceLimit = Error.stackTraceLimit
  106. Error.prepareStackTrace = (obj, site) => {
  107. if (this._wrapCallSite) {
  108. return site.map(this._wrapCallSite);
  109. }
  110. return site;
  111. };
  112. if (limit) {
  113. Error.stackTraceLimit = limit;
  114. }
  115. const obj = {};
  116. Error.captureStackTrace(obj, fn);
  117. const stack = obj.stack;
  118. Object.assign(Error, {prepareStackTrace, stackTraceLimit});
  119. return stack;
  120. }
  121. at (fn) {
  122. fn = fn || this.at
  123. const site = this.capture(1, fn)[0];
  124. if (!site) {
  125. return {};
  126. }
  127. const res = {
  128. line: site.getLineNumber(),
  129. column: site.getColumnNumber()
  130. };
  131. setFile(res, site.getFileName(), this._cwd);
  132. if (site.isConstructor()) {
  133. res.constructor = true;
  134. }
  135. if (site.isEval()) {
  136. res.evalOrigin = site.getEvalOrigin();
  137. }
  138. // Node v10 stopped with the isNative() on callsites, apparently
  139. /* istanbul ignore next */
  140. if (site.isNative()) {
  141. res.native = true;
  142. }
  143. let typename;
  144. try {
  145. typename = site.getTypeName();
  146. } catch (_) {
  147. }
  148. if (typename && typename !== 'Object' && typename !== '[object Object]') {
  149. res.type = typename;
  150. }
  151. const fname = site.getFunctionName();
  152. if (fname) {
  153. res.function = fname;
  154. }
  155. const meth = site.getMethodName();
  156. if (meth && fname !== meth) {
  157. res.method = meth;
  158. }
  159. return res;
  160. }
  161. parseLine (line) {
  162. const match = line && line.match(re);
  163. if (!match) {
  164. return null;
  165. }
  166. const ctor = match[1] === 'new';
  167. let fname = match[2];
  168. const evalOrigin = match[3];
  169. const evalFile = match[4];
  170. const evalLine = Number(match[5]);
  171. const evalCol = Number(match[6]);
  172. let file = match[7];
  173. const lnum = match[8];
  174. const col = match[9];
  175. const native = match[10] === 'native';
  176. const closeParen = match[11] === ')';
  177. let method;
  178. const res = {};
  179. if (lnum) {
  180. res.line = Number(lnum);
  181. }
  182. if (col) {
  183. res.column = Number(col);
  184. }
  185. if (closeParen && file) {
  186. // make sure parens are balanced
  187. // if we have a file like "asdf) [as foo] (xyz.js", then odds are
  188. // that the fname should be += " (asdf) [as foo]" and the file
  189. // should be just "xyz.js"
  190. // walk backwards from the end to find the last unbalanced (
  191. let closes = 0;
  192. for (let i = file.length - 1; i > 0; i--) {
  193. if (file.charAt(i) === ')') {
  194. closes++;
  195. } else if (file.charAt(i) === '(' && file.charAt(i - 1) === ' ') {
  196. closes--;
  197. if (closes === -1 && file.charAt(i - 1) === ' ') {
  198. const before = file.slice(0, i - 1);
  199. const after = file.slice(i + 1);
  200. file = after;
  201. fname += ` (${before}`;
  202. break;
  203. }
  204. }
  205. }
  206. }
  207. if (fname) {
  208. const methodMatch = fname.match(methodRe);
  209. if (methodMatch) {
  210. fname = methodMatch[1];
  211. method = methodMatch[2];
  212. }
  213. }
  214. setFile(res, file, this._cwd);
  215. if (ctor) {
  216. res.constructor = true;
  217. }
  218. if (evalOrigin) {
  219. res.evalOrigin = evalOrigin;
  220. res.evalLine = evalLine;
  221. res.evalColumn = evalCol;
  222. res.evalFile = evalFile && evalFile.replace(/\\/g, '/');
  223. }
  224. if (native) {
  225. res.native = true;
  226. }
  227. if (fname) {
  228. res.function = fname;
  229. }
  230. if (method && fname !== method) {
  231. res.method = method;
  232. }
  233. return res;
  234. }
  235. }
  236. function setFile (result, filename, cwd) {
  237. if (filename) {
  238. filename = filename.replace(/\\/g, '/');
  239. if (filename.startsWith(`${cwd}/`)) {
  240. filename = filename.slice(cwd.length + 1);
  241. }
  242. result.file = filename;
  243. }
  244. }
  245. function ignoredPackagesRegExp(ignoredPackages) {
  246. if (ignoredPackages.length === 0) {
  247. return [];
  248. }
  249. const packages = ignoredPackages.map(mod => escapeStringRegexp(mod));
  250. return new RegExp(`[\/\\\\]node_modules[\/\\\\](?:${packages.join('|')})[\/\\\\][^:]+:\\d+:\\d+`)
  251. }
  252. const re = new RegExp(
  253. '^' +
  254. // Sometimes we strip out the ' at' because it's noisy
  255. '(?:\\s*at )?' +
  256. // $1 = ctor if 'new'
  257. '(?:(new) )?' +
  258. // $2 = function name (can be literally anything)
  259. // May contain method at the end as [as xyz]
  260. '(?:(.*?) \\()?' +
  261. // (eval at <anonymous> (file.js:1:1),
  262. // $3 = eval origin
  263. // $4:$5:$6 are eval file/line/col, but not normally reported
  264. '(?:eval at ([^ ]+) \\((.+?):(\\d+):(\\d+)\\), )?' +
  265. // file:line:col
  266. // $7:$8:$9
  267. // $10 = 'native' if native
  268. '(?:(.+?):(\\d+):(\\d+)|(native))' +
  269. // maybe close the paren, then end
  270. // if $11 is ), then we only allow balanced parens in the filename
  271. // any imbalance is placed on the fname. This is a heuristic, and
  272. // bound to be incorrect in some edge cases. The bet is that
  273. // having weird characters in method names is more common than
  274. // having weird characters in filenames, which seems reasonable.
  275. '(\\)?)$'
  276. );
  277. const methodRe = /^(.*?) \[as (.*?)\]$/;
  278. module.exports = StackUtils;