UI for Zipcoin Blue

error-rewrite.ts 12KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321
  1. /**
  2. * @license
  3. * Copyright Google Inc. All Rights Reserved.
  4. *
  5. * Use of this source code is governed by an MIT-style license that can be
  6. * found in the LICENSE file at https://angular.io/license
  7. */
  8. /**
  9. * @fileoverview
  10. * @suppress {globalThis,undefinedVars}
  11. */
  12. /**
  13. * Extend the Error with additional fields for rewritten stack frames
  14. */
  15. interface Error {
  16. /**
  17. * Stack trace where extra frames have been removed and zone names added.
  18. */
  19. zoneAwareStack?: string;
  20. /**
  21. * Original stack trace with no modifications
  22. */
  23. originalStack?: string;
  24. }
  25. Zone.__load_patch('Error', (global: any, Zone: ZoneType, api: _ZonePrivate) => {
  26. /*
  27. * This code patches Error so that:
  28. * - It ignores un-needed stack frames.
  29. * - It Shows the associated Zone for reach frame.
  30. */
  31. const enum FrameType {
  32. /// Skip this frame when printing out stack
  33. blackList,
  34. /// This frame marks zone transition
  35. transition
  36. }
  37. const blacklistedStackFramesSymbol = api.symbol('blacklistedStackFrames');
  38. const NativeError = global[api.symbol('Error')] = global['Error'];
  39. // Store the frames which should be removed from the stack frames
  40. const blackListedStackFrames: {[frame: string]: FrameType} = {};
  41. // We must find the frame where Error was created, otherwise we assume we don't understand stack
  42. let zoneAwareFrame1: string;
  43. let zoneAwareFrame2: string;
  44. global['Error'] = ZoneAwareError;
  45. const stackRewrite = 'stackRewrite';
  46. /**
  47. * This is ZoneAwareError which processes the stack frame and cleans up extra frames as well as
  48. * adds zone information to it.
  49. */
  50. function ZoneAwareError(): Error {
  51. // We always have to return native error otherwise the browser console will not work.
  52. let error: Error = NativeError.apply(this, arguments);
  53. // Save original stack trace
  54. const originalStack = (error as any)['originalStack'] = error.stack;
  55. // Process the stack trace and rewrite the frames.
  56. if ((ZoneAwareError as any)[stackRewrite] && originalStack) {
  57. let frames: string[] = originalStack.split('\n');
  58. let zoneFrame = api.currentZoneFrame();
  59. let i = 0;
  60. // Find the first frame
  61. while (!(frames[i] === zoneAwareFrame1 || frames[i] === zoneAwareFrame2) &&
  62. i < frames.length) {
  63. i++;
  64. }
  65. for (; i < frames.length && zoneFrame; i++) {
  66. let frame = frames[i];
  67. if (frame.trim()) {
  68. switch (blackListedStackFrames[frame]) {
  69. case FrameType.blackList:
  70. frames.splice(i, 1);
  71. i--;
  72. break;
  73. case FrameType.transition:
  74. if (zoneFrame.parent) {
  75. // This is the special frame where zone changed. Print and process it accordingly
  76. zoneFrame = zoneFrame.parent;
  77. } else {
  78. zoneFrame = null;
  79. }
  80. frames.splice(i, 1);
  81. i--;
  82. break;
  83. default:
  84. frames[i] += ` [${zoneFrame.zone.name}]`;
  85. }
  86. }
  87. }
  88. try {
  89. error.stack = error.zoneAwareStack = frames.join('\n');
  90. } catch (e) {
  91. // ignore as some browsers don't allow overriding of stack
  92. }
  93. }
  94. if (this instanceof NativeError && this.constructor != NativeError) {
  95. // We got called with a `new` operator AND we are subclass of ZoneAwareError
  96. // in that case we have to copy all of our properties to `this`.
  97. Object.keys(error).concat('stack', 'message').forEach((key) => {
  98. const value = (error as any)[key];
  99. if (value !== undefined) {
  100. try {
  101. this[key] = value;
  102. } catch (e) {
  103. // ignore the assignment in case it is a setter and it throws.
  104. }
  105. }
  106. });
  107. return this;
  108. }
  109. return error;
  110. }
  111. // Copy the prototype so that instanceof operator works as expected
  112. ZoneAwareError.prototype = NativeError.prototype;
  113. (ZoneAwareError as any)[blacklistedStackFramesSymbol] = blackListedStackFrames;
  114. (ZoneAwareError as any)[stackRewrite] = false;
  115. // those properties need special handling
  116. const specialPropertyNames = ['stackTraceLimit', 'captureStackTrace', 'prepareStackTrace'];
  117. // those properties of NativeError should be set to ZoneAwareError
  118. const nativeErrorProperties = Object.keys(NativeError);
  119. if (nativeErrorProperties) {
  120. nativeErrorProperties.forEach(prop => {
  121. if (specialPropertyNames.filter(sp => sp === prop).length === 0) {
  122. Object.defineProperty(ZoneAwareError, prop, {
  123. get: function() {
  124. return NativeError[prop];
  125. },
  126. set: function(value) {
  127. NativeError[prop] = value;
  128. }
  129. });
  130. }
  131. });
  132. }
  133. if (NativeError.hasOwnProperty('stackTraceLimit')) {
  134. // Extend default stack limit as we will be removing few frames.
  135. NativeError.stackTraceLimit = Math.max(NativeError.stackTraceLimit, 15);
  136. // make sure that ZoneAwareError has the same property which forwards to NativeError.
  137. Object.defineProperty(ZoneAwareError, 'stackTraceLimit', {
  138. get: function() {
  139. return NativeError.stackTraceLimit;
  140. },
  141. set: function(value) {
  142. return NativeError.stackTraceLimit = value;
  143. }
  144. });
  145. }
  146. if (NativeError.hasOwnProperty('captureStackTrace')) {
  147. Object.defineProperty(ZoneAwareError, 'captureStackTrace', {
  148. // add named function here because we need to remove this
  149. // stack frame when prepareStackTrace below
  150. value: function zoneCaptureStackTrace(targetObject: Object, constructorOpt?: Function) {
  151. NativeError.captureStackTrace(targetObject, constructorOpt);
  152. }
  153. });
  154. }
  155. const ZONE_CAPTURESTACKTRACE = 'zoneCaptureStackTrace';
  156. Object.defineProperty(ZoneAwareError, 'prepareStackTrace', {
  157. get: function() {
  158. return NativeError.prepareStackTrace;
  159. },
  160. set: function(value) {
  161. if (!value || typeof value !== 'function') {
  162. return NativeError.prepareStackTrace = value;
  163. }
  164. return NativeError.prepareStackTrace = function(
  165. error: Error, structuredStackTrace: {getFunctionName: Function}[]) {
  166. // remove additional stack information from ZoneAwareError.captureStackTrace
  167. if (structuredStackTrace) {
  168. for (let i = 0; i < structuredStackTrace.length; i++) {
  169. const st = structuredStackTrace[i];
  170. // remove the first function which name is zoneCaptureStackTrace
  171. if (st.getFunctionName() === ZONE_CAPTURESTACKTRACE) {
  172. structuredStackTrace.splice(i, 1);
  173. break;
  174. }
  175. }
  176. }
  177. return value.call(this, error, structuredStackTrace);
  178. };
  179. }
  180. });
  181. // Now we need to populate the `blacklistedStackFrames` as well as find the
  182. // run/runGuarded/runTask frames. This is done by creating a detect zone and then threading
  183. // the execution through all of the above methods so that we can look at the stack trace and
  184. // find the frames of interest.
  185. const ZONE_AWARE_ERROR = 'ZoneAwareError';
  186. const ERROR_DOT = 'Error.';
  187. const EMPTY = '';
  188. const RUN_GUARDED = 'runGuarded';
  189. const RUN_TASK = 'runTask';
  190. const RUN = 'run';
  191. const BRACKETS = '(';
  192. const AT = '@';
  193. let detectZone: Zone = Zone.current.fork({
  194. name: 'detect',
  195. onHandleError: function(parentZD: ZoneDelegate, current: Zone, target: Zone, error: any):
  196. boolean {
  197. if (error.originalStack && Error === ZoneAwareError) {
  198. let frames = error.originalStack.split(/\n/);
  199. let runFrame = false, runGuardedFrame = false, runTaskFrame = false;
  200. while (frames.length) {
  201. let frame = frames.shift();
  202. // On safari it is possible to have stack frame with no line number.
  203. // This check makes sure that we don't filter frames on name only (must have
  204. // line number)
  205. if (/:\d+:\d+/.test(frame)) {
  206. // Get rid of the path so that we don't accidentally find function name in path.
  207. // In chrome the separator is `(` and `@` in FF and safari
  208. // Chrome: at Zone.run (zone.js:100)
  209. // Chrome: at Zone.run (http://localhost:9876/base/build/lib/zone.js:100:24)
  210. // FireFox: Zone.prototype.run@http://localhost:9876/base/build/lib/zone.js:101:24
  211. // Safari: run@http://localhost:9876/base/build/lib/zone.js:101:24
  212. let fnName: string = frame.split(BRACKETS)[0].split(AT)[0];
  213. let frameType = FrameType.transition;
  214. if (fnName.indexOf(ZONE_AWARE_ERROR) !== -1) {
  215. zoneAwareFrame1 = frame;
  216. zoneAwareFrame2 = frame.replace(ERROR_DOT, EMPTY);
  217. blackListedStackFrames[zoneAwareFrame2] = FrameType.blackList;
  218. }
  219. if (fnName.indexOf(RUN_GUARDED) !== -1) {
  220. runGuardedFrame = true;
  221. } else if (fnName.indexOf(RUN_TASK) !== -1) {
  222. runTaskFrame = true;
  223. } else if (fnName.indexOf(RUN) !== -1) {
  224. runFrame = true;
  225. } else {
  226. frameType = FrameType.blackList;
  227. }
  228. blackListedStackFrames[frame] = frameType;
  229. // Once we find all of the frames we can stop looking.
  230. if (runFrame && runGuardedFrame && runTaskFrame) {
  231. (ZoneAwareError as any)[stackRewrite] = true;
  232. break;
  233. }
  234. }
  235. }
  236. }
  237. return false;
  238. }
  239. }) as Zone;
  240. // carefully constructor a stack frame which contains all of the frames of interest which
  241. // need to be detected and blacklisted.
  242. const childDetectZone = detectZone.fork({
  243. name: 'child',
  244. onScheduleTask: function(delegate, curr, target, task) {
  245. return delegate.scheduleTask(target, task);
  246. },
  247. onInvokeTask: function(delegate, curr, target, task, applyThis, applyArgs) {
  248. return delegate.invokeTask(target, task, applyThis, applyArgs);
  249. },
  250. onCancelTask: function(delegate, curr, target, task) {
  251. return delegate.cancelTask(target, task);
  252. },
  253. onInvoke: function(delegate, curr, target, callback, applyThis, applyArgs, source) {
  254. return delegate.invoke(target, callback, applyThis, applyArgs, source);
  255. }
  256. });
  257. // we need to detect all zone related frames, it will
  258. // exceed default stackTraceLimit, so we set it to
  259. // larger number here, and restore it after detect finish.
  260. const originalStackTraceLimit = Error.stackTraceLimit;
  261. Error.stackTraceLimit = 100;
  262. // we schedule event/micro/macro task, and invoke them
  263. // when onSchedule, so we can get all stack traces for
  264. // all kinds of tasks with one error thrown.
  265. childDetectZone.run(() => {
  266. childDetectZone.runGuarded(() => {
  267. const fakeTransitionTo = () => {};
  268. childDetectZone.scheduleEventTask(
  269. blacklistedStackFramesSymbol,
  270. () => {
  271. childDetectZone.scheduleMacroTask(
  272. blacklistedStackFramesSymbol,
  273. () => {
  274. childDetectZone.scheduleMicroTask(
  275. blacklistedStackFramesSymbol,
  276. () => {
  277. throw new (ZoneAwareError as any)(ZoneAwareError, NativeError);
  278. },
  279. null,
  280. (t: Task) => {
  281. (t as any)._transitionTo = fakeTransitionTo;
  282. t.invoke();
  283. });
  284. },
  285. null,
  286. (t) => {
  287. (t as any)._transitionTo = fakeTransitionTo;
  288. t.invoke();
  289. },
  290. () => {});
  291. },
  292. null,
  293. (t) => {
  294. (t as any)._transitionTo = fakeTransitionTo;
  295. t.invoke();
  296. },
  297. () => {});
  298. });
  299. });
  300. Error.stackTraceLimit = originalStackTraceLimit;
  301. });