raven.js 130 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542
  1. /*! Raven.js 3.20.1 (42adaf5) | github.com/getsentry/raven-js */
  2. /*
  3. * Includes TraceKit
  4. * https://github.com/getsentry/TraceKit
  5. *
  6. * Copyright 2017 Matt Robenolt and other contributors
  7. * Released under the BSD license
  8. * https://github.com/getsentry/raven-js/blob/master/LICENSE
  9. *
  10. */
  11. (function (f) {
  12. if (typeof exports === "object" && typeof module !== "undefined") {
  13. module.exports = f();
  14. } else if (typeof define === "function" && define.amd) {
  15. define([], f);
  16. } else {
  17. var g;
  18. if (typeof window !== "undefined") {
  19. g = window;
  20. } else if (typeof global !== "undefined") {
  21. g = global;
  22. } else if (typeof self !== "undefined") {
  23. g = self;
  24. } else {
  25. g = this;
  26. }
  27. g.Raven = f();
  28. }
  29. })(function () {
  30. var define, module, exports;
  31. return (function e(t, n, r) {
  32. function s(o, u) {
  33. if (!n[o]) {
  34. if (!t[o]) {
  35. var a = typeof require == "function" && require;
  36. if (!u && a) return a(o, !0);
  37. if (i) return i(o, !0);
  38. var f = new Error("Cannot find module '" + o + "'");
  39. throw ((f.code = "MODULE_NOT_FOUND"), f);
  40. }
  41. var l = (n[o] = { exports: {} });
  42. t[o][0].call(
  43. l.exports,
  44. function (e) {
  45. var n = t[o][1][e];
  46. return s(n ? n : e);
  47. },
  48. l,
  49. l.exports,
  50. e,
  51. t,
  52. n,
  53. r,
  54. );
  55. }
  56. return n[o].exports;
  57. }
  58. var i = typeof require == "function" && require;
  59. for (var o = 0; o < r.length; o++) s(r[o]);
  60. return s;
  61. })(
  62. {
  63. 1: [
  64. function (_dereq_, module, exports) {
  65. function RavenConfigError(message) {
  66. this.name = "RavenConfigError";
  67. this.message = message;
  68. }
  69. RavenConfigError.prototype = new Error();
  70. RavenConfigError.prototype.constructor = RavenConfigError;
  71. module.exports = RavenConfigError;
  72. },
  73. {},
  74. ],
  75. 2: [
  76. function (_dereq_, module, exports) {
  77. var wrapMethod = function (console, level, callback) {
  78. var originalConsoleLevel = console[level];
  79. var originalConsole = console;
  80. if (!(level in console)) {
  81. return;
  82. }
  83. var sentryLevel = level === "warn" ? "warning" : level;
  84. console[level] = function () {
  85. var args = [].slice.call(arguments);
  86. var msg = "" + args.join(" ");
  87. var data = {
  88. level: sentryLevel,
  89. logger: "console",
  90. extra: { arguments: args },
  91. };
  92. if (level === "assert") {
  93. if (args[0] === false) {
  94. // Default browsers message
  95. msg =
  96. "Assertion failed: " +
  97. (args.slice(1).join(" ") || "console.assert");
  98. data.extra.arguments = args.slice(1);
  99. callback && callback(msg, data);
  100. }
  101. } else {
  102. callback && callback(msg, data);
  103. }
  104. // this fails for some browsers. :(
  105. if (originalConsoleLevel) {
  106. // IE9 doesn't allow calling apply on console functions directly
  107. // See: https://stackoverflow.com/questions/5472938/does-ie9-support-console-log-and-is-it-a-real-function#answer-5473193
  108. Function.prototype.apply.call(
  109. originalConsoleLevel,
  110. originalConsole,
  111. args,
  112. );
  113. }
  114. };
  115. };
  116. module.exports = {
  117. wrapMethod: wrapMethod,
  118. };
  119. },
  120. {},
  121. ],
  122. 3: [
  123. function (_dereq_, module, exports) {
  124. (function (global) {
  125. /*global XDomainRequest:false */
  126. var TraceKit = _dereq_(6);
  127. var stringify = _dereq_(7);
  128. var RavenConfigError = _dereq_(1);
  129. var utils = _dereq_(5);
  130. var isError = utils.isError;
  131. var isObject = utils.isObject;
  132. var isErrorEvent = utils.isErrorEvent;
  133. var isUndefined = utils.isUndefined;
  134. var isFunction = utils.isFunction;
  135. var isString = utils.isString;
  136. var isArray = utils.isArray;
  137. var isEmptyObject = utils.isEmptyObject;
  138. var each = utils.each;
  139. var objectMerge = utils.objectMerge;
  140. var truncate = utils.truncate;
  141. var objectFrozen = utils.objectFrozen;
  142. var hasKey = utils.hasKey;
  143. var joinRegExp = utils.joinRegExp;
  144. var urlencode = utils.urlencode;
  145. var uuid4 = utils.uuid4;
  146. var htmlTreeAsString = utils.htmlTreeAsString;
  147. var isSameException = utils.isSameException;
  148. var isSameStacktrace = utils.isSameStacktrace;
  149. var parseUrl = utils.parseUrl;
  150. var fill = utils.fill;
  151. var wrapConsoleMethod = _dereq_(2).wrapMethod;
  152. var dsnKeys = "source protocol user pass host port path".split(" "),
  153. dsnPattern =
  154. /^(?:(\w+):)?\/\/(?:(\w+)(:\w+)?@)?([\w\.-]+)(?::(\d+))?(\/.*)/;
  155. function now() {
  156. return +new Date();
  157. }
  158. // This is to be defensive in environments where window does not exist (see https://github.com/getsentry/raven-js/pull/785)
  159. var _window =
  160. typeof window !== "undefined"
  161. ? window
  162. : typeof global !== "undefined"
  163. ? global
  164. : typeof self !== "undefined"
  165. ? self
  166. : {};
  167. var _document = _window.document;
  168. var _navigator = _window.navigator;
  169. function keepOriginalCallback(original, callback) {
  170. return isFunction(callback)
  171. ? function (data) {
  172. return callback(data, original);
  173. }
  174. : callback;
  175. }
  176. // First, check for JSON support
  177. // If there is no JSON, we no-op the core features of Raven
  178. // since JSON is required to encode the payload
  179. function Raven() {
  180. this._hasJSON = !!(typeof JSON === "object" && JSON.stringify);
  181. // Raven can run in contexts where there's no document (react-native)
  182. this._hasDocument = !isUndefined(_document);
  183. this._hasNavigator = !isUndefined(_navigator);
  184. this._lastCapturedException = null;
  185. this._lastData = null;
  186. this._lastEventId = null;
  187. this._globalServer = null;
  188. this._globalKey = null;
  189. this._globalProject = null;
  190. this._globalContext = {};
  191. this._globalOptions = {
  192. logger: "javascript",
  193. ignoreErrors: [],
  194. ignoreUrls: [],
  195. whitelistUrls: [],
  196. includePaths: [],
  197. collectWindowErrors: true,
  198. maxMessageLength: 0,
  199. // By default, truncates URL values to 250 chars
  200. maxUrlLength: 250,
  201. stackTraceLimit: 50,
  202. autoBreadcrumbs: true,
  203. instrument: true,
  204. sampleRate: 1,
  205. };
  206. this._ignoreOnError = 0;
  207. this._isRavenInstalled = false;
  208. this._originalErrorStackTraceLimit = Error.stackTraceLimit;
  209. // capture references to window.console *and* all its methods first
  210. // before the console plugin has a chance to monkey patch
  211. this._originalConsole = _window.console || {};
  212. this._originalConsoleMethods = {};
  213. this._plugins = [];
  214. this._startTime = now();
  215. this._wrappedBuiltIns = [];
  216. this._breadcrumbs = [];
  217. this._lastCapturedEvent = null;
  218. this._keypressTimeout;
  219. this._location = _window.location;
  220. this._lastHref = this._location && this._location.href;
  221. this._resetBackoff();
  222. // eslint-disable-next-line guard-for-in
  223. for (var method in this._originalConsole) {
  224. this._originalConsoleMethods[method] =
  225. this._originalConsole[method];
  226. }
  227. }
  228. /*
  229. * The core Raven singleton
  230. *
  231. * @this {Raven}
  232. */
  233. Raven.prototype = {
  234. // Hardcode version string so that raven source can be loaded directly via
  235. // webpack (using a build step causes webpack #1617). Grunt verifies that
  236. // this value matches package.json during build.
  237. // See: https://github.com/getsentry/raven-js/issues/465
  238. VERSION: "3.20.1",
  239. debug: false,
  240. TraceKit: TraceKit, // alias to TraceKit
  241. /*
  242. * Configure Raven with a DSN and extra options
  243. *
  244. * @param {string} dsn The public Sentry DSN
  245. * @param {object} options Set of global options [optional]
  246. * @return {Raven}
  247. */
  248. config: function (dsn, options) {
  249. var self = this;
  250. if (self._globalServer) {
  251. this._logDebug(
  252. "error",
  253. "Error: Raven has already been configured",
  254. );
  255. return self;
  256. }
  257. if (!dsn) return self;
  258. var globalOptions = self._globalOptions;
  259. // merge in options
  260. if (options) {
  261. each(options, function (key, value) {
  262. // tags and extra are special and need to be put into context
  263. if (key === "tags" || key === "extra" || key === "user") {
  264. self._globalContext[key] = value;
  265. } else {
  266. globalOptions[key] = value;
  267. }
  268. });
  269. }
  270. self.setDSN(dsn);
  271. // "Script error." is hard coded into browsers for errors that it can't read.
  272. // this is the result of a script being pulled in from an external domain and CORS.
  273. globalOptions.ignoreErrors.push(/^Script error\.?$/);
  274. globalOptions.ignoreErrors.push(
  275. /^Javascript error: Script error\.? on line 0$/,
  276. );
  277. // join regexp rules into one big rule
  278. globalOptions.ignoreErrors = joinRegExp(
  279. globalOptions.ignoreErrors,
  280. );
  281. globalOptions.ignoreUrls = globalOptions.ignoreUrls.length
  282. ? joinRegExp(globalOptions.ignoreUrls)
  283. : false;
  284. globalOptions.whitelistUrls = globalOptions.whitelistUrls.length
  285. ? joinRegExp(globalOptions.whitelistUrls)
  286. : false;
  287. globalOptions.includePaths = joinRegExp(
  288. globalOptions.includePaths,
  289. );
  290. globalOptions.maxBreadcrumbs = Math.max(
  291. 0,
  292. Math.min(globalOptions.maxBreadcrumbs || 100, 100),
  293. ); // default and hard limit is 100
  294. var autoBreadcrumbDefaults = {
  295. xhr: true,
  296. console: true,
  297. dom: true,
  298. location: true,
  299. sentry: true,
  300. };
  301. var autoBreadcrumbs = globalOptions.autoBreadcrumbs;
  302. if ({}.toString.call(autoBreadcrumbs) === "[object Object]") {
  303. autoBreadcrumbs = objectMerge(
  304. autoBreadcrumbDefaults,
  305. autoBreadcrumbs,
  306. );
  307. } else if (autoBreadcrumbs !== false) {
  308. autoBreadcrumbs = autoBreadcrumbDefaults;
  309. }
  310. globalOptions.autoBreadcrumbs = autoBreadcrumbs;
  311. var instrumentDefaults = {
  312. tryCatch: true,
  313. };
  314. var instrument = globalOptions.instrument;
  315. if ({}.toString.call(instrument) === "[object Object]") {
  316. instrument = objectMerge(instrumentDefaults, instrument);
  317. } else if (instrument !== false) {
  318. instrument = instrumentDefaults;
  319. }
  320. globalOptions.instrument = instrument;
  321. TraceKit.collectWindowErrors =
  322. !!globalOptions.collectWindowErrors;
  323. // return for chaining
  324. return self;
  325. },
  326. /*
  327. * Installs a global window.onerror error handler
  328. * to capture and report uncaught exceptions.
  329. * At this point, install() is required to be called due
  330. * to the way TraceKit is set up.
  331. *
  332. * @return {Raven}
  333. */
  334. install: function () {
  335. var self = this;
  336. if (self.isSetup() && !self._isRavenInstalled) {
  337. TraceKit.report.subscribe(function () {
  338. self._handleOnErrorStackInfo.apply(self, arguments);
  339. });
  340. self._patchFunctionToString();
  341. if (
  342. self._globalOptions.instrument &&
  343. self._globalOptions.instrument.tryCatch
  344. ) {
  345. self._instrumentTryCatch();
  346. }
  347. if (self._globalOptions.autoBreadcrumbs)
  348. self._instrumentBreadcrumbs();
  349. // Install all of the plugins
  350. self._drainPlugins();
  351. self._isRavenInstalled = true;
  352. }
  353. Error.stackTraceLimit = self._globalOptions.stackTraceLimit;
  354. return this;
  355. },
  356. /*
  357. * Set the DSN (can be called multiple time unlike config)
  358. *
  359. * @param {string} dsn The public Sentry DSN
  360. */
  361. setDSN: function (dsn) {
  362. var self = this,
  363. uri = self._parseDSN(dsn),
  364. lastSlash = uri.path.lastIndexOf("/"),
  365. path = uri.path.substr(1, lastSlash);
  366. self._dsn = dsn;
  367. self._globalKey = uri.user;
  368. self._globalSecret = uri.pass && uri.pass.substr(1);
  369. self._globalProject = uri.path.substr(lastSlash + 1);
  370. self._globalServer = self._getGlobalServer(uri);
  371. self._globalEndpoint =
  372. self._globalServer +
  373. "/" +
  374. path +
  375. "api/" +
  376. self._globalProject +
  377. "/store/";
  378. // Reset backoff state since we may be pointing at a
  379. // new project/server
  380. this._resetBackoff();
  381. },
  382. /*
  383. * Wrap code within a context so Raven can capture errors
  384. * reliably across domains that is executed immediately.
  385. *
  386. * @param {object} options A specific set of options for this context [optional]
  387. * @param {function} func The callback to be immediately executed within the context
  388. * @param {array} args An array of arguments to be called with the callback [optional]
  389. */
  390. context: function (options, func, args) {
  391. if (isFunction(options)) {
  392. args = func || [];
  393. func = options;
  394. options = undefined;
  395. }
  396. return this.wrap(options, func).apply(this, args);
  397. },
  398. /*
  399. * Wrap code within a context and returns back a new function to be executed
  400. *
  401. * @param {object} options A specific set of options for this context [optional]
  402. * @param {function} func The function to be wrapped in a new context
  403. * @param {function} func A function to call before the try/catch wrapper [optional, private]
  404. * @return {function} The newly wrapped functions with a context
  405. */
  406. wrap: function (options, func, _before) {
  407. var self = this;
  408. // 1 argument has been passed, and it's not a function
  409. // so just return it
  410. if (isUndefined(func) && !isFunction(options)) {
  411. return options;
  412. }
  413. // options is optional
  414. if (isFunction(options)) {
  415. func = options;
  416. options = undefined;
  417. }
  418. // At this point, we've passed along 2 arguments, and the second one
  419. // is not a function either, so we'll just return the second argument.
  420. if (!isFunction(func)) {
  421. return func;
  422. }
  423. // We don't wanna wrap it twice!
  424. try {
  425. if (func.__raven__) {
  426. return func;
  427. }
  428. // If this has already been wrapped in the past, return that
  429. if (func.__raven_wrapper__) {
  430. return func.__raven_wrapper__;
  431. }
  432. } catch (e) {
  433. // Just accessing custom props in some Selenium environments
  434. // can cause a "Permission denied" exception (see raven-js#495).
  435. // Bail on wrapping and return the function as-is (defers to window.onerror).
  436. return func;
  437. }
  438. function wrapped() {
  439. var args = [],
  440. i = arguments.length,
  441. deep = !options || (options && options.deep !== false);
  442. if (_before && isFunction(_before)) {
  443. _before.apply(this, arguments);
  444. }
  445. // Recursively wrap all of a function's arguments that are
  446. // functions themselves.
  447. while (i--)
  448. args[i] = deep
  449. ? self.wrap(options, arguments[i])
  450. : arguments[i];
  451. try {
  452. // Attempt to invoke user-land function
  453. // NOTE: If you are a Sentry user, and you are seeing this stack frame, it
  454. // means Raven caught an error invoking your application code. This is
  455. // expected behavior and NOT indicative of a bug with Raven.js.
  456. return func.apply(this, args);
  457. } catch (e) {
  458. self._ignoreNextOnError();
  459. self.captureException(e, options);
  460. throw e;
  461. }
  462. }
  463. // copy over properties of the old function
  464. for (var property in func) {
  465. if (hasKey(func, property)) {
  466. wrapped[property] = func[property];
  467. }
  468. }
  469. wrapped.prototype = func.prototype;
  470. func.__raven_wrapper__ = wrapped;
  471. // Signal that this function has been wrapped/filled already
  472. // for both debugging and to prevent it to being wrapped/filled twice
  473. wrapped.__raven__ = true;
  474. wrapped.__orig__ = func;
  475. return wrapped;
  476. },
  477. /*
  478. * Uninstalls the global error handler.
  479. *
  480. * @return {Raven}
  481. */
  482. uninstall: function () {
  483. TraceKit.report.uninstall();
  484. this._unpatchFunctionToString();
  485. this._restoreBuiltIns();
  486. Error.stackTraceLimit = this._originalErrorStackTraceLimit;
  487. this._isRavenInstalled = false;
  488. return this;
  489. },
  490. /*
  491. * Manually capture an exception and send it over to Sentry
  492. *
  493. * @param {error} ex An exception to be logged
  494. * @param {object} options A specific set of options for this error [optional]
  495. * @return {Raven}
  496. */
  497. captureException: function (ex, options) {
  498. // Cases for sending ex as a message, rather than an exception
  499. var isNotError = !isError(ex);
  500. var isNotErrorEvent = !isErrorEvent(ex);
  501. var isErrorEventWithoutError = isErrorEvent(ex) && !ex.error;
  502. if (
  503. (isNotError && isNotErrorEvent) ||
  504. isErrorEventWithoutError
  505. ) {
  506. return this.captureMessage(
  507. ex,
  508. objectMerge(
  509. {
  510. trimHeadFrames: 1,
  511. stacktrace: true, // if we fall back to captureMessage, default to attempting a new trace
  512. },
  513. options,
  514. ),
  515. );
  516. }
  517. // Get actual Error from ErrorEvent
  518. if (isErrorEvent(ex)) ex = ex.error;
  519. // Store the raw exception object for potential debugging and introspection
  520. this._lastCapturedException = ex;
  521. // TraceKit.report will re-raise any exception passed to it,
  522. // which means you have to wrap it in try/catch. Instead, we
  523. // can wrap it here and only re-raise if TraceKit.report
  524. // raises an exception different from the one we asked to
  525. // report on.
  526. try {
  527. var stack = TraceKit.computeStackTrace(ex);
  528. this._handleStackInfo(stack, options);
  529. } catch (ex1) {
  530. if (ex !== ex1) {
  531. throw ex1;
  532. }
  533. }
  534. return this;
  535. },
  536. /*
  537. * Manually send a message to Sentry
  538. *
  539. * @param {string} msg A plain message to be captured in Sentry
  540. * @param {object} options A specific set of options for this message [optional]
  541. * @return {Raven}
  542. */
  543. captureMessage: function (msg, options) {
  544. // config() automagically converts ignoreErrors from a list to a RegExp so we need to test for an
  545. // early call; we'll error on the side of logging anything called before configuration since it's
  546. // probably something you should see:
  547. if (
  548. !!this._globalOptions.ignoreErrors.test &&
  549. this._globalOptions.ignoreErrors.test(msg)
  550. ) {
  551. return;
  552. }
  553. options = options || {};
  554. var data = objectMerge(
  555. {
  556. message: msg + "", // Make sure it's actually a string
  557. },
  558. options,
  559. );
  560. var ex;
  561. // Generate a "synthetic" stack trace from this point.
  562. // NOTE: If you are a Sentry user, and you are seeing this stack frame, it is NOT indicative
  563. // of a bug with Raven.js. Sentry generates synthetic traces either by configuration,
  564. // or if it catches a thrown object without a "stack" property.
  565. try {
  566. throw new Error(msg);
  567. } catch (ex1) {
  568. ex = ex1;
  569. }
  570. // null exception name so `Error` isn't prefixed to msg
  571. ex.name = null;
  572. var stack = TraceKit.computeStackTrace(ex);
  573. // stack[0] is `throw new Error(msg)` call itself, we are interested in the frame that was just before that, stack[1]
  574. var initialCall = isArray(stack.stack) && stack.stack[1];
  575. var fileurl = (initialCall && initialCall.url) || "";
  576. if (
  577. !!this._globalOptions.ignoreUrls.test &&
  578. this._globalOptions.ignoreUrls.test(fileurl)
  579. ) {
  580. return;
  581. }
  582. if (
  583. !!this._globalOptions.whitelistUrls.test &&
  584. !this._globalOptions.whitelistUrls.test(fileurl)
  585. ) {
  586. return;
  587. }
  588. if (
  589. this._globalOptions.stacktrace ||
  590. (options && options.stacktrace)
  591. ) {
  592. options = objectMerge(
  593. {
  594. // fingerprint on msg, not stack trace (legacy behavior, could be
  595. // revisited)
  596. fingerprint: msg,
  597. // since we know this is a synthetic trace, the top N-most frames
  598. // MUST be from Raven.js, so mark them as in_app later by setting
  599. // trimHeadFrames
  600. trimHeadFrames: (options.trimHeadFrames || 0) + 1,
  601. },
  602. options,
  603. );
  604. var frames = this._prepareFrames(stack, options);
  605. data.stacktrace = {
  606. // Sentry expects frames oldest to newest
  607. frames: frames.reverse(),
  608. };
  609. }
  610. // Fire away!
  611. this._send(data);
  612. return this;
  613. },
  614. captureBreadcrumb: function (obj) {
  615. var crumb = objectMerge(
  616. {
  617. timestamp: now() / 1000,
  618. },
  619. obj,
  620. );
  621. if (isFunction(this._globalOptions.breadcrumbCallback)) {
  622. var result = this._globalOptions.breadcrumbCallback(crumb);
  623. if (isObject(result) && !isEmptyObject(result)) {
  624. crumb = result;
  625. } else if (result === false) {
  626. return this;
  627. }
  628. }
  629. this._breadcrumbs.push(crumb);
  630. if (
  631. this._breadcrumbs.length > this._globalOptions.maxBreadcrumbs
  632. ) {
  633. this._breadcrumbs.shift();
  634. }
  635. return this;
  636. },
  637. addPlugin: function (plugin /*arg1, arg2, ... argN*/) {
  638. var pluginArgs = [].slice.call(arguments, 1);
  639. this._plugins.push([plugin, pluginArgs]);
  640. if (this._isRavenInstalled) {
  641. this._drainPlugins();
  642. }
  643. return this;
  644. },
  645. /*
  646. * Set/clear a user to be sent along with the payload.
  647. *
  648. * @param {object} user An object representing user data [optional]
  649. * @return {Raven}
  650. */
  651. setUserContext: function (user) {
  652. // Intentionally do not merge here since that's an unexpected behavior.
  653. this._globalContext.user = user;
  654. return this;
  655. },
  656. /*
  657. * Merge extra attributes to be sent along with the payload.
  658. *
  659. * @param {object} extra An object representing extra data [optional]
  660. * @return {Raven}
  661. */
  662. setExtraContext: function (extra) {
  663. this._mergeContext("extra", extra);
  664. return this;
  665. },
  666. /*
  667. * Merge tags to be sent along with the payload.
  668. *
  669. * @param {object} tags An object representing tags [optional]
  670. * @return {Raven}
  671. */
  672. setTagsContext: function (tags) {
  673. this._mergeContext("tags", tags);
  674. return this;
  675. },
  676. /*
  677. * Clear all of the context.
  678. *
  679. * @return {Raven}
  680. */
  681. clearContext: function () {
  682. this._globalContext = {};
  683. return this;
  684. },
  685. /*
  686. * Get a copy of the current context. This cannot be mutated.
  687. *
  688. * @return {object} copy of context
  689. */
  690. getContext: function () {
  691. // lol javascript
  692. return JSON.parse(stringify(this._globalContext));
  693. },
  694. /*
  695. * Set environment of application
  696. *
  697. * @param {string} environment Typically something like 'production'.
  698. * @return {Raven}
  699. */
  700. setEnvironment: function (environment) {
  701. this._globalOptions.environment = environment;
  702. return this;
  703. },
  704. /*
  705. * Set release version of application
  706. *
  707. * @param {string} release Typically something like a git SHA to identify version
  708. * @return {Raven}
  709. */
  710. setRelease: function (release) {
  711. this._globalOptions.release = release;
  712. return this;
  713. },
  714. /*
  715. * Set the dataCallback option
  716. *
  717. * @param {function} callback The callback to run which allows the
  718. * data blob to be mutated before sending
  719. * @return {Raven}
  720. */
  721. setDataCallback: function (callback) {
  722. var original = this._globalOptions.dataCallback;
  723. this._globalOptions.dataCallback = keepOriginalCallback(
  724. original,
  725. callback,
  726. );
  727. return this;
  728. },
  729. /*
  730. * Set the breadcrumbCallback option
  731. *
  732. * @param {function} callback The callback to run which allows filtering
  733. * or mutating breadcrumbs
  734. * @return {Raven}
  735. */
  736. setBreadcrumbCallback: function (callback) {
  737. var original = this._globalOptions.breadcrumbCallback;
  738. this._globalOptions.breadcrumbCallback = keepOriginalCallback(
  739. original,
  740. callback,
  741. );
  742. return this;
  743. },
  744. /*
  745. * Set the shouldSendCallback option
  746. *
  747. * @param {function} callback The callback to run which allows
  748. * introspecting the blob before sending
  749. * @return {Raven}
  750. */
  751. setShouldSendCallback: function (callback) {
  752. var original = this._globalOptions.shouldSendCallback;
  753. this._globalOptions.shouldSendCallback = keepOriginalCallback(
  754. original,
  755. callback,
  756. );
  757. return this;
  758. },
  759. /**
  760. * Override the default HTTP transport mechanism that transmits data
  761. * to the Sentry server.
  762. *
  763. * @param {function} transport Function invoked instead of the default
  764. * `makeRequest` handler.
  765. *
  766. * @return {Raven}
  767. */
  768. setTransport: function (transport) {
  769. this._globalOptions.transport = transport;
  770. return this;
  771. },
  772. /*
  773. * Get the latest raw exception that was captured by Raven.
  774. *
  775. * @return {error}
  776. */
  777. lastException: function () {
  778. return this._lastCapturedException;
  779. },
  780. /*
  781. * Get the last event id
  782. *
  783. * @return {string}
  784. */
  785. lastEventId: function () {
  786. return this._lastEventId;
  787. },
  788. /*
  789. * Determine if Raven is setup and ready to go.
  790. *
  791. * @return {boolean}
  792. */
  793. isSetup: function () {
  794. if (!this._hasJSON) return false; // needs JSON support
  795. if (!this._globalServer) {
  796. if (!this.ravenNotConfiguredError) {
  797. this.ravenNotConfiguredError = true;
  798. this._logDebug(
  799. "error",
  800. "Error: Raven has not been configured.",
  801. );
  802. }
  803. return false;
  804. }
  805. return true;
  806. },
  807. afterLoad: function () {
  808. // TODO: remove window dependence?
  809. // Attempt to initialize Raven on load
  810. var RavenConfig = _window.RavenConfig;
  811. if (RavenConfig) {
  812. this.config(RavenConfig.dsn, RavenConfig.config).install();
  813. }
  814. },
  815. showReportDialog: function (options) {
  816. if (
  817. !_document // doesn't work without a document (React native)
  818. )
  819. return;
  820. options = options || {};
  821. var lastEventId = options.eventId || this.lastEventId();
  822. if (!lastEventId) {
  823. throw new RavenConfigError("Missing eventId");
  824. }
  825. var dsn = options.dsn || this._dsn;
  826. if (!dsn) {
  827. throw new RavenConfigError("Missing DSN");
  828. }
  829. var encode = encodeURIComponent;
  830. var qs = "";
  831. qs += "?eventId=" + encode(lastEventId);
  832. qs += "&dsn=" + encode(dsn);
  833. var user = options.user || this._globalContext.user;
  834. if (user) {
  835. if (user.name) qs += "&name=" + encode(user.name);
  836. if (user.email) qs += "&email=" + encode(user.email);
  837. }
  838. var globalServer = this._getGlobalServer(this._parseDSN(dsn));
  839. var script = _document.createElement("script");
  840. script.async = true;
  841. script.src = globalServer + "/api/embed/error-page/" + qs;
  842. (_document.head || _document.body).appendChild(script);
  843. },
  844. /**** Private functions ****/
  845. _ignoreNextOnError: function () {
  846. var self = this;
  847. this._ignoreOnError += 1;
  848. setTimeout(function () {
  849. // onerror should trigger before setTimeout
  850. self._ignoreOnError -= 1;
  851. });
  852. },
  853. _triggerEvent: function (eventType, options) {
  854. // NOTE: `event` is a native browser thing, so let's avoid conflicting with it
  855. var evt, key;
  856. if (!this._hasDocument) return;
  857. options = options || {};
  858. eventType =
  859. "raven" +
  860. eventType.substr(0, 1).toUpperCase() +
  861. eventType.substr(1);
  862. if (_document.createEvent) {
  863. evt = _document.createEvent("HTMLEvents");
  864. evt.initEvent(eventType, true, true);
  865. } else {
  866. evt = _document.createEventObject();
  867. evt.eventType = eventType;
  868. }
  869. for (key in options)
  870. if (hasKey(options, key)) {
  871. evt[key] = options[key];
  872. }
  873. if (_document.createEvent) {
  874. // IE9 if standards
  875. _document.dispatchEvent(evt);
  876. } else {
  877. // IE8 regardless of Quirks or Standards
  878. // IE9 if quirks
  879. try {
  880. _document.fireEvent(
  881. "on" + evt.eventType.toLowerCase(),
  882. evt,
  883. );
  884. } catch (e) {
  885. // Do nothing
  886. }
  887. }
  888. },
  889. /**
  890. * Wraps addEventListener to capture UI breadcrumbs
  891. * @param evtName the event name (e.g. "click")
  892. * @returns {Function}
  893. * @private
  894. */
  895. _breadcrumbEventHandler: function (evtName) {
  896. var self = this;
  897. return function (evt) {
  898. // reset keypress timeout; e.g. triggering a 'click' after
  899. // a 'keypress' will reset the keypress debounce so that a new
  900. // set of keypresses can be recorded
  901. self._keypressTimeout = null;
  902. // It's possible this handler might trigger multiple times for the same
  903. // event (e.g. event propagation through node ancestors). Ignore if we've
  904. // already captured the event.
  905. if (self._lastCapturedEvent === evt) return;
  906. self._lastCapturedEvent = evt;
  907. // try/catch both:
  908. // - accessing evt.target (see getsentry/raven-js#838, #768)
  909. // - `htmlTreeAsString` because it's complex, and just accessing the DOM incorrectly
  910. // can throw an exception in some circumstances.
  911. var target;
  912. try {
  913. target = htmlTreeAsString(evt.target);
  914. } catch (e) {
  915. target = "<unknown>";
  916. }
  917. self.captureBreadcrumb({
  918. category: "ui." + evtName, // e.g. ui.click, ui.input
  919. message: target,
  920. });
  921. };
  922. },
  923. /**
  924. * Wraps addEventListener to capture keypress UI events
  925. * @returns {Function}
  926. * @private
  927. */
  928. _keypressEventHandler: function () {
  929. var self = this,
  930. debounceDuration = 1000; // milliseconds
  931. // TODO: if somehow user switches keypress target before
  932. // debounce timeout is triggered, we will only capture
  933. // a single breadcrumb from the FIRST target (acceptable?)
  934. return function (evt) {
  935. var target;
  936. try {
  937. target = evt.target;
  938. } catch (e) {
  939. // just accessing event properties can throw an exception in some rare circumstances
  940. // see: https://github.com/getsentry/raven-js/issues/838
  941. return;
  942. }
  943. var tagName = target && target.tagName;
  944. // only consider keypress events on actual input elements
  945. // this will disregard keypresses targeting body (e.g. tabbing
  946. // through elements, hotkeys, etc)
  947. if (
  948. !tagName ||
  949. (tagName !== "INPUT" &&
  950. tagName !== "TEXTAREA" &&
  951. !target.isContentEditable)
  952. )
  953. return;
  954. // record first keypress in a series, but ignore subsequent
  955. // keypresses until debounce clears
  956. var timeout = self._keypressTimeout;
  957. if (!timeout) {
  958. self._breadcrumbEventHandler("input")(evt);
  959. }
  960. clearTimeout(timeout);
  961. self._keypressTimeout = setTimeout(function () {
  962. self._keypressTimeout = null;
  963. }, debounceDuration);
  964. };
  965. },
  966. /**
  967. * Captures a breadcrumb of type "navigation", normalizing input URLs
  968. * @param to the originating URL
  969. * @param from the target URL
  970. * @private
  971. */
  972. _captureUrlChange: function (from, to) {
  973. var parsedLoc = parseUrl(this._location.href);
  974. var parsedTo = parseUrl(to);
  975. var parsedFrom = parseUrl(from);
  976. // because onpopstate only tells you the "new" (to) value of location.href, and
  977. // not the previous (from) value, we need to track the value of the current URL
  978. // state ourselves
  979. this._lastHref = to;
  980. // Use only the path component of the URL if the URL matches the current
  981. // document (almost all the time when using pushState)
  982. if (
  983. parsedLoc.protocol === parsedTo.protocol &&
  984. parsedLoc.host === parsedTo.host
  985. )
  986. to = parsedTo.relative;
  987. if (
  988. parsedLoc.protocol === parsedFrom.protocol &&
  989. parsedLoc.host === parsedFrom.host
  990. )
  991. from = parsedFrom.relative;
  992. this.captureBreadcrumb({
  993. category: "navigation",
  994. data: {
  995. to: to,
  996. from: from,
  997. },
  998. });
  999. },
  1000. _patchFunctionToString: function () {
  1001. var self = this;
  1002. self._originalFunctionToString = Function.prototype.toString;
  1003. // eslint-disable-next-line no-extend-native
  1004. Function.prototype.toString = function () {
  1005. if (typeof this === "function" && this.__raven__) {
  1006. return self._originalFunctionToString.apply(
  1007. this.__orig__,
  1008. arguments,
  1009. );
  1010. }
  1011. return self._originalFunctionToString.apply(this, arguments);
  1012. };
  1013. },
  1014. _unpatchFunctionToString: function () {
  1015. if (this._originalFunctionToString) {
  1016. // eslint-disable-next-line no-extend-native
  1017. Function.prototype.toString = this._originalFunctionToString;
  1018. }
  1019. },
  1020. /**
  1021. * Wrap timer functions and event targets to catch errors and provide
  1022. * better metadata.
  1023. */
  1024. _instrumentTryCatch: function () {
  1025. var self = this;
  1026. var wrappedBuiltIns = self._wrappedBuiltIns;
  1027. function wrapTimeFn(orig) {
  1028. return function (fn, t) {
  1029. // preserve arity
  1030. // Make a copy of the arguments to prevent deoptimization
  1031. // https://github.com/petkaantonov/bluebird/wiki/Optimization-killers#32-leaking-arguments
  1032. var args = new Array(arguments.length);
  1033. for (var i = 0; i < args.length; ++i) {
  1034. args[i] = arguments[i];
  1035. }
  1036. var originalCallback = args[0];
  1037. if (isFunction(originalCallback)) {
  1038. args[0] = self.wrap(originalCallback);
  1039. }
  1040. // IE < 9 doesn't support .call/.apply on setInterval/setTimeout, but it
  1041. // also supports only two arguments and doesn't care what this is, so we
  1042. // can just call the original function directly.
  1043. if (orig.apply) {
  1044. return orig.apply(this, args);
  1045. } else {
  1046. return orig(args[0], args[1]);
  1047. }
  1048. };
  1049. }
  1050. var autoBreadcrumbs = this._globalOptions.autoBreadcrumbs;
  1051. function wrapEventTarget(global) {
  1052. var proto = _window[global] && _window[global].prototype;
  1053. if (
  1054. proto &&
  1055. proto.hasOwnProperty &&
  1056. proto.hasOwnProperty("addEventListener")
  1057. ) {
  1058. fill(
  1059. proto,
  1060. "addEventListener",
  1061. function (orig) {
  1062. return function (evtName, fn, capture, secure) {
  1063. // preserve arity
  1064. try {
  1065. if (fn && fn.handleEvent) {
  1066. fn.handleEvent = self.wrap(fn.handleEvent);
  1067. }
  1068. } catch (err) {
  1069. // can sometimes get 'Permission denied to access property "handle Event'
  1070. }
  1071. // More breadcrumb DOM capture ... done here and not in `_instrumentBreadcrumbs`
  1072. // so that we don't have more than one wrapper function
  1073. var before, clickHandler, keypressHandler;
  1074. if (
  1075. autoBreadcrumbs &&
  1076. autoBreadcrumbs.dom &&
  1077. (global === "EventTarget" || global === "Node")
  1078. ) {
  1079. // NOTE: generating multiple handlers per addEventListener invocation, should
  1080. // revisit and verify we can just use one (almost certainly)
  1081. clickHandler =
  1082. self._breadcrumbEventHandler("click");
  1083. keypressHandler = self._keypressEventHandler();
  1084. before = function (evt) {
  1085. // need to intercept every DOM event in `before` argument, in case that
  1086. // same wrapped method is re-used for different events (e.g. mousemove THEN click)
  1087. // see #724
  1088. if (!evt) return;
  1089. var eventType;
  1090. try {
  1091. eventType = evt.type;
  1092. } catch (e) {
  1093. // just accessing event properties can throw an exception in some rare circumstances
  1094. // see: https://github.com/getsentry/raven-js/issues/838
  1095. return;
  1096. }
  1097. if (eventType === "click")
  1098. return clickHandler(evt);
  1099. else if (eventType === "keypress")
  1100. return keypressHandler(evt);
  1101. };
  1102. }
  1103. return orig.call(
  1104. this,
  1105. evtName,
  1106. self.wrap(fn, undefined, before),
  1107. capture,
  1108. secure,
  1109. );
  1110. };
  1111. },
  1112. wrappedBuiltIns,
  1113. );
  1114. fill(
  1115. proto,
  1116. "removeEventListener",
  1117. function (orig) {
  1118. return function (evt, fn, capture, secure) {
  1119. try {
  1120. fn =
  1121. fn &&
  1122. (fn.__raven_wrapper__
  1123. ? fn.__raven_wrapper__
  1124. : fn);
  1125. } catch (e) {
  1126. // ignore, accessing __raven_wrapper__ will throw in some Selenium environments
  1127. }
  1128. return orig.call(this, evt, fn, capture, secure);
  1129. };
  1130. },
  1131. wrappedBuiltIns,
  1132. );
  1133. }
  1134. }
  1135. fill(_window, "setTimeout", wrapTimeFn, wrappedBuiltIns);
  1136. fill(_window, "setInterval", wrapTimeFn, wrappedBuiltIns);
  1137. if (_requestAnimationFrame) {
  1138. fill(
  1139. _window,
  1140. "requestAnimationFrame",
  1141. function (orig) {
  1142. return function (cb) {
  1143. return orig(self.wrap(cb));
  1144. };
  1145. },
  1146. wrappedBuiltIns,
  1147. );
  1148. }
  1149. // event targets borrowed from bugsnag-js:
  1150. // https://github.com/bugsnag/bugsnag-js/blob/master/src/bugsnag.js#L666
  1151. var eventTargets = [
  1152. "EventTarget",
  1153. "Window",
  1154. "Node",
  1155. "ApplicationCache",
  1156. "AudioTrackList",
  1157. "ChannelMergerNode",
  1158. "CryptoOperation",
  1159. "EventSource",
  1160. "FileReader",
  1161. "HTMLUnknownElement",
  1162. "IDBDatabase",
  1163. "IDBRequest",
  1164. "IDBTransaction",
  1165. "KeyOperation",
  1166. "MediaController",
  1167. "MessagePort",
  1168. "ModalWindow",
  1169. "Notification",
  1170. "SVGElementInstance",
  1171. "Screen",
  1172. "TextTrack",
  1173. "TextTrackCue",
  1174. "TextTrackList",
  1175. "WebSocket",
  1176. "WebSocketWorker",
  1177. "Worker",
  1178. "XMLHttpRequest",
  1179. "XMLHttpRequestEventTarget",
  1180. "XMLHttpRequestUpload",
  1181. ];
  1182. for (var i = 0; i < eventTargets.length; i++) {
  1183. wrapEventTarget(eventTargets[i]);
  1184. }
  1185. },
  1186. /**
  1187. * Instrument browser built-ins w/ breadcrumb capturing
  1188. * - XMLHttpRequests
  1189. * - DOM interactions (click/typing)
  1190. * - window.location changes
  1191. * - console
  1192. *
  1193. * Can be disabled or individually configured via the `autoBreadcrumbs` config option
  1194. */
  1195. _instrumentBreadcrumbs: function () {
  1196. var self = this;
  1197. var autoBreadcrumbs = this._globalOptions.autoBreadcrumbs;
  1198. var wrappedBuiltIns = self._wrappedBuiltIns;
  1199. function wrapProp(prop, xhr) {
  1200. if (prop in xhr && isFunction(xhr[prop])) {
  1201. fill(xhr, prop, function (orig) {
  1202. return self.wrap(orig);
  1203. }); // intentionally don't track filled methods on XHR instances
  1204. }
  1205. }
  1206. if (autoBreadcrumbs.xhr && "XMLHttpRequest" in _window) {
  1207. var xhrproto = XMLHttpRequest.prototype;
  1208. fill(
  1209. xhrproto,
  1210. "open",
  1211. function (origOpen) {
  1212. return function (method, url) {
  1213. // preserve arity
  1214. // if Sentry key appears in URL, don't capture
  1215. if (
  1216. isString(url) &&
  1217. url.indexOf(self._globalKey) === -1
  1218. ) {
  1219. this.__raven_xhr = {
  1220. method: method,
  1221. url: url,
  1222. status_code: null,
  1223. };
  1224. }
  1225. return origOpen.apply(this, arguments);
  1226. };
  1227. },
  1228. wrappedBuiltIns,
  1229. );
  1230. fill(
  1231. xhrproto,
  1232. "send",
  1233. function (origSend) {
  1234. return function (data) {
  1235. // preserve arity
  1236. var xhr = this;
  1237. function onreadystatechangeHandler() {
  1238. if (xhr.__raven_xhr && xhr.readyState === 4) {
  1239. try {
  1240. // touching statusCode in some platforms throws
  1241. // an exception
  1242. xhr.__raven_xhr.status_code = xhr.status;
  1243. } catch (e) {
  1244. /* do nothing */
  1245. }
  1246. self.captureBreadcrumb({
  1247. type: "http",
  1248. category: "xhr",
  1249. data: xhr.__raven_xhr,
  1250. });
  1251. }
  1252. }
  1253. var props = ["onload", "onerror", "onprogress"];
  1254. for (var j = 0; j < props.length; j++) {
  1255. wrapProp(props[j], xhr);
  1256. }
  1257. if (
  1258. "onreadystatechange" in xhr &&
  1259. isFunction(xhr.onreadystatechange)
  1260. ) {
  1261. fill(
  1262. xhr,
  1263. "onreadystatechange",
  1264. function (orig) {
  1265. return self.wrap(
  1266. orig,
  1267. undefined,
  1268. onreadystatechangeHandler,
  1269. );
  1270. } /* intentionally don't track this instrumentation */,
  1271. );
  1272. } else {
  1273. // if onreadystatechange wasn't actually set by the page on this xhr, we
  1274. // are free to set our own and capture the breadcrumb
  1275. xhr.onreadystatechange = onreadystatechangeHandler;
  1276. }
  1277. return origSend.apply(this, arguments);
  1278. };
  1279. },
  1280. wrappedBuiltIns,
  1281. );
  1282. }
  1283. if (autoBreadcrumbs.xhr && "fetch" in _window) {
  1284. fill(
  1285. _window,
  1286. "fetch",
  1287. function (origFetch) {
  1288. return function (fn, t) {
  1289. // preserve arity
  1290. // Make a copy of the arguments to prevent deoptimization
  1291. // https://github.com/petkaantonov/bluebird/wiki/Optimization-killers#32-leaking-arguments
  1292. var args = new Array(arguments.length);
  1293. for (var i = 0; i < args.length; ++i) {
  1294. args[i] = arguments[i];
  1295. }
  1296. var fetchInput = args[0];
  1297. var method = "GET";
  1298. var url;
  1299. if (typeof fetchInput === "string") {
  1300. url = fetchInput;
  1301. } else if (
  1302. "Request" in _window &&
  1303. fetchInput instanceof _window.Request
  1304. ) {
  1305. url = fetchInput.url;
  1306. if (fetchInput.method) {
  1307. method = fetchInput.method;
  1308. }
  1309. } else {
  1310. url = "" + fetchInput;
  1311. }
  1312. if (args[1] && args[1].method) {
  1313. method = args[1].method;
  1314. }
  1315. var fetchData = {
  1316. method: method,
  1317. url: url,
  1318. status_code: null,
  1319. };
  1320. self.captureBreadcrumb({
  1321. type: "http",
  1322. category: "fetch",
  1323. data: fetchData,
  1324. });
  1325. return origFetch
  1326. .apply(this, args)
  1327. .then(function (response) {
  1328. fetchData.status_code = response.status;
  1329. return response;
  1330. });
  1331. };
  1332. },
  1333. wrappedBuiltIns,
  1334. );
  1335. }
  1336. // Capture breadcrumbs from any click that is unhandled / bubbled up all the way
  1337. // to the document. Do this before we instrument addEventListener.
  1338. if (autoBreadcrumbs.dom && this._hasDocument) {
  1339. if (_document.addEventListener) {
  1340. _document.addEventListener(
  1341. "click",
  1342. self._breadcrumbEventHandler("click"),
  1343. false,
  1344. );
  1345. _document.addEventListener(
  1346. "keypress",
  1347. self._keypressEventHandler(),
  1348. false,
  1349. );
  1350. } else {
  1351. // IE8 Compatibility
  1352. _document.attachEvent(
  1353. "onclick",
  1354. self._breadcrumbEventHandler("click"),
  1355. );
  1356. _document.attachEvent(
  1357. "onkeypress",
  1358. self._keypressEventHandler(),
  1359. );
  1360. }
  1361. }
  1362. // record navigation (URL) changes
  1363. // NOTE: in Chrome App environment, touching history.pushState, *even inside
  1364. // a try/catch block*, will cause Chrome to output an error to console.error
  1365. // borrowed from: https://github.com/angular/angular.js/pull/13945/files
  1366. var chrome = _window.chrome;
  1367. var isChromePackagedApp =
  1368. chrome && chrome.app && chrome.app.runtime;
  1369. var hasPushAndReplaceState =
  1370. !isChromePackagedApp &&
  1371. _window.history &&
  1372. history.pushState &&
  1373. history.replaceState;
  1374. if (autoBreadcrumbs.location && hasPushAndReplaceState) {
  1375. // TODO: remove onpopstate handler on uninstall()
  1376. var oldOnPopState = _window.onpopstate;
  1377. _window.onpopstate = function () {
  1378. var currentHref = self._location.href;
  1379. self._captureUrlChange(self._lastHref, currentHref);
  1380. if (oldOnPopState) {
  1381. return oldOnPopState.apply(this, arguments);
  1382. }
  1383. };
  1384. var historyReplacementFunction = function (origHistFunction) {
  1385. // note history.pushState.length is 0; intentionally not declaring
  1386. // params to preserve 0 arity
  1387. return function (/* state, title, url */) {
  1388. var url = arguments.length > 2 ? arguments[2] : undefined;
  1389. // url argument is optional
  1390. if (url) {
  1391. // coerce to string (this is what pushState does)
  1392. self._captureUrlChange(self._lastHref, url + "");
  1393. }
  1394. return origHistFunction.apply(this, arguments);
  1395. };
  1396. };
  1397. fill(
  1398. history,
  1399. "pushState",
  1400. historyReplacementFunction,
  1401. wrappedBuiltIns,
  1402. );
  1403. fill(
  1404. history,
  1405. "replaceState",
  1406. historyReplacementFunction,
  1407. wrappedBuiltIns,
  1408. );
  1409. }
  1410. if (
  1411. autoBreadcrumbs.console &&
  1412. "console" in _window &&
  1413. console.log
  1414. ) {
  1415. // console
  1416. var consoleMethodCallback = function (msg, data) {
  1417. self.captureBreadcrumb({
  1418. message: msg,
  1419. level: data.level,
  1420. category: "console",
  1421. });
  1422. };
  1423. each(
  1424. ["debug", "info", "warn", "error", "log"],
  1425. function (_, level) {
  1426. wrapConsoleMethod(console, level, consoleMethodCallback);
  1427. },
  1428. );
  1429. }
  1430. },
  1431. _restoreBuiltIns: function () {
  1432. // restore any wrapped builtins
  1433. var builtin;
  1434. while (this._wrappedBuiltIns.length) {
  1435. builtin = this._wrappedBuiltIns.shift();
  1436. var obj = builtin[0],
  1437. name = builtin[1],
  1438. orig = builtin[2];
  1439. obj[name] = orig;
  1440. }
  1441. },
  1442. _drainPlugins: function () {
  1443. var self = this;
  1444. // FIX ME TODO
  1445. each(this._plugins, function (_, plugin) {
  1446. var installer = plugin[0];
  1447. var args = plugin[1];
  1448. installer.apply(self, [self].concat(args));
  1449. });
  1450. },
  1451. _parseDSN: function (str) {
  1452. var m = dsnPattern.exec(str),
  1453. dsn = {},
  1454. i = 7;
  1455. try {
  1456. while (i--) dsn[dsnKeys[i]] = m[i] || "";
  1457. } catch (e) {
  1458. throw new RavenConfigError("Invalid DSN: " + str);
  1459. }
  1460. if (dsn.pass && !this._globalOptions.allowSecretKey) {
  1461. throw new RavenConfigError(
  1462. "Do not specify your secret key in the DSN. See: http://bit.ly/raven-secret-key",
  1463. );
  1464. }
  1465. return dsn;
  1466. },
  1467. _getGlobalServer: function (uri) {
  1468. // assemble the endpoint from the uri pieces
  1469. var globalServer =
  1470. "//" + uri.host + (uri.port ? ":" + uri.port : "");
  1471. if (uri.protocol) {
  1472. globalServer = uri.protocol + ":" + globalServer;
  1473. }
  1474. return globalServer;
  1475. },
  1476. _handleOnErrorStackInfo: function () {
  1477. // if we are intentionally ignoring errors via onerror, bail out
  1478. if (!this._ignoreOnError) {
  1479. this._handleStackInfo.apply(this, arguments);
  1480. }
  1481. },
  1482. _handleStackInfo: function (stackInfo, options) {
  1483. var frames = this._prepareFrames(stackInfo, options);
  1484. this._triggerEvent("handle", {
  1485. stackInfo: stackInfo,
  1486. options: options,
  1487. });
  1488. this._processException(
  1489. stackInfo.name,
  1490. stackInfo.message,
  1491. stackInfo.url,
  1492. stackInfo.lineno,
  1493. frames,
  1494. options,
  1495. );
  1496. },
  1497. _prepareFrames: function (stackInfo, options) {
  1498. var self = this;
  1499. var frames = [];
  1500. if (stackInfo.stack && stackInfo.stack.length) {
  1501. each(stackInfo.stack, function (i, stack) {
  1502. var frame = self._normalizeFrame(stack, stackInfo.url);
  1503. if (frame) {
  1504. frames.push(frame);
  1505. }
  1506. });
  1507. // e.g. frames captured via captureMessage throw
  1508. if (options && options.trimHeadFrames) {
  1509. for (
  1510. var j = 0;
  1511. j < options.trimHeadFrames && j < frames.length;
  1512. j++
  1513. ) {
  1514. frames[j].in_app = false;
  1515. }
  1516. }
  1517. }
  1518. frames = frames.slice(0, this._globalOptions.stackTraceLimit);
  1519. return frames;
  1520. },
  1521. _normalizeFrame: function (frame, stackInfoUrl) {
  1522. // normalize the frames data
  1523. var normalized = {
  1524. filename: frame.url,
  1525. lineno: frame.line,
  1526. colno: frame.column,
  1527. function: frame.func || "?",
  1528. };
  1529. // Case when we don't have any information about the error
  1530. // E.g. throwing a string or raw object, instead of an `Error` in Firefox
  1531. // Generating synthetic error doesn't add any value here
  1532. //
  1533. // We should probably somehow let a user know that they should fix their code
  1534. if (!frame.url) {
  1535. normalized.filename = stackInfoUrl; // fallback to whole stacks url from onerror handler
  1536. }
  1537. normalized.in_app = !(
  1538. // determine if an exception came from outside of our app
  1539. // first we check the global includePaths list.
  1540. (
  1541. (!!this._globalOptions.includePaths.test &&
  1542. !this._globalOptions.includePaths.test(
  1543. normalized.filename,
  1544. )) ||
  1545. // Now we check for fun, if the function name is Raven or TraceKit
  1546. /(Raven|TraceKit)\./.test(normalized["function"]) ||
  1547. // finally, we do a last ditch effort and check for raven.min.js
  1548. /raven\.(min\.)?js$/.test(normalized.filename)
  1549. )
  1550. );
  1551. return normalized;
  1552. },
  1553. _processException: function (
  1554. type,
  1555. message,
  1556. fileurl,
  1557. lineno,
  1558. frames,
  1559. options,
  1560. ) {
  1561. var prefixedMessage =
  1562. (type ? type + ": " : "") + (message || "");
  1563. if (
  1564. !!this._globalOptions.ignoreErrors.test &&
  1565. (this._globalOptions.ignoreErrors.test(message) ||
  1566. this._globalOptions.ignoreErrors.test(prefixedMessage))
  1567. ) {
  1568. return;
  1569. }
  1570. var stacktrace;
  1571. if (frames && frames.length) {
  1572. fileurl = frames[0].filename || fileurl;
  1573. // Sentry expects frames oldest to newest
  1574. // and JS sends them as newest to oldest
  1575. frames.reverse();
  1576. stacktrace = { frames: frames };
  1577. } else if (fileurl) {
  1578. stacktrace = {
  1579. frames: [
  1580. {
  1581. filename: fileurl,
  1582. lineno: lineno,
  1583. in_app: true,
  1584. },
  1585. ],
  1586. };
  1587. }
  1588. if (
  1589. !!this._globalOptions.ignoreUrls.test &&
  1590. this._globalOptions.ignoreUrls.test(fileurl)
  1591. ) {
  1592. return;
  1593. }
  1594. if (
  1595. !!this._globalOptions.whitelistUrls.test &&
  1596. !this._globalOptions.whitelistUrls.test(fileurl)
  1597. ) {
  1598. return;
  1599. }
  1600. var data = objectMerge(
  1601. {
  1602. // sentry.interfaces.Exception
  1603. exception: {
  1604. values: [
  1605. {
  1606. type: type,
  1607. value: message,
  1608. stacktrace: stacktrace,
  1609. },
  1610. ],
  1611. },
  1612. culprit: fileurl,
  1613. },
  1614. options,
  1615. );
  1616. // Fire away!
  1617. this._send(data);
  1618. },
  1619. _trimPacket: function (data) {
  1620. // For now, we only want to truncate the two different messages
  1621. // but this could/should be expanded to just trim everything
  1622. var max = this._globalOptions.maxMessageLength;
  1623. if (data.message) {
  1624. data.message = truncate(data.message, max);
  1625. }
  1626. if (data.exception) {
  1627. var exception = data.exception.values[0];
  1628. exception.value = truncate(exception.value, max);
  1629. }
  1630. var request = data.request;
  1631. if (request) {
  1632. if (request.url) {
  1633. request.url = truncate(
  1634. request.url,
  1635. this._globalOptions.maxUrlLength,
  1636. );
  1637. }
  1638. if (request.Referer) {
  1639. request.Referer = truncate(
  1640. request.Referer,
  1641. this._globalOptions.maxUrlLength,
  1642. );
  1643. }
  1644. }
  1645. if (data.breadcrumbs && data.breadcrumbs.values)
  1646. this._trimBreadcrumbs(data.breadcrumbs);
  1647. return data;
  1648. },
  1649. /**
  1650. * Truncate breadcrumb values (right now just URLs)
  1651. */
  1652. _trimBreadcrumbs: function (breadcrumbs) {
  1653. // known breadcrumb properties with urls
  1654. // TODO: also consider arbitrary prop values that start with (https?)?://
  1655. var urlProps = ["to", "from", "url"],
  1656. urlProp,
  1657. crumb,
  1658. data;
  1659. for (var i = 0; i < breadcrumbs.values.length; ++i) {
  1660. crumb = breadcrumbs.values[i];
  1661. if (
  1662. !crumb.hasOwnProperty("data") ||
  1663. !isObject(crumb.data) ||
  1664. objectFrozen(crumb.data)
  1665. )
  1666. continue;
  1667. data = objectMerge({}, crumb.data);
  1668. for (var j = 0; j < urlProps.length; ++j) {
  1669. urlProp = urlProps[j];
  1670. if (data.hasOwnProperty(urlProp) && data[urlProp]) {
  1671. data[urlProp] = truncate(
  1672. data[urlProp],
  1673. this._globalOptions.maxUrlLength,
  1674. );
  1675. }
  1676. }
  1677. breadcrumbs.values[i].data = data;
  1678. }
  1679. },
  1680. _getHttpData: function () {
  1681. if (!this._hasNavigator && !this._hasDocument) return;
  1682. var httpData = {};
  1683. if (this._hasNavigator && _navigator.userAgent) {
  1684. httpData.headers = {
  1685. "User-Agent": navigator.userAgent,
  1686. };
  1687. }
  1688. if (this._hasDocument) {
  1689. if (_document.location && _document.location.href) {
  1690. httpData.url = _document.location.href;
  1691. }
  1692. if (_document.referrer) {
  1693. if (!httpData.headers) httpData.headers = {};
  1694. httpData.headers.Referer = _document.referrer;
  1695. }
  1696. }
  1697. return httpData;
  1698. },
  1699. _resetBackoff: function () {
  1700. this._backoffDuration = 0;
  1701. this._backoffStart = null;
  1702. },
  1703. _shouldBackoff: function () {
  1704. return (
  1705. this._backoffDuration &&
  1706. now() - this._backoffStart < this._backoffDuration
  1707. );
  1708. },
  1709. /**
  1710. * Returns true if the in-process data payload matches the signature
  1711. * of the previously-sent data
  1712. *
  1713. * NOTE: This has to be done at this level because TraceKit can generate
  1714. * data from window.onerror WITHOUT an exception object (IE8, IE9,
  1715. * other old browsers). This can take the form of an "exception"
  1716. * data object with a single frame (derived from the onerror args).
  1717. */
  1718. _isRepeatData: function (current) {
  1719. var last = this._lastData;
  1720. if (
  1721. !last ||
  1722. current.message !== last.message || // defined for captureMessage
  1723. current.culprit !== last.culprit // defined for captureException/onerror
  1724. )
  1725. return false;
  1726. // Stacktrace interface (i.e. from captureMessage)
  1727. if (current.stacktrace || last.stacktrace) {
  1728. return isSameStacktrace(current.stacktrace, last.stacktrace);
  1729. } else if (current.exception || last.exception) {
  1730. // Exception interface (i.e. from captureException/onerror)
  1731. return isSameException(current.exception, last.exception);
  1732. }
  1733. return true;
  1734. },
  1735. _setBackoffState: function (request) {
  1736. // If we are already in a backoff state, don't change anything
  1737. if (this._shouldBackoff()) {
  1738. return;
  1739. }
  1740. var status = request.status;
  1741. // 400 - project_id doesn't exist or some other fatal
  1742. // 401 - invalid/revoked dsn
  1743. // 429 - too many requests
  1744. if (!(status === 400 || status === 401 || status === 429))
  1745. return;
  1746. var retry;
  1747. try {
  1748. // If Retry-After is not in Access-Control-Expose-Headers, most
  1749. // browsers will throw an exception trying to access it
  1750. retry = request.getResponseHeader("Retry-After");
  1751. retry = parseInt(retry, 10) * 1000; // Retry-After is returned in seconds
  1752. } catch (e) {
  1753. /* eslint no-empty:0 */
  1754. }
  1755. this._backoffDuration = retry
  1756. ? // If Sentry server returned a Retry-After value, use it
  1757. retry
  1758. : // Otherwise, double the last backoff duration (starts at 1 sec)
  1759. this._backoffDuration * 2 || 1000;
  1760. this._backoffStart = now();
  1761. },
  1762. _send: function (data) {
  1763. var globalOptions = this._globalOptions;
  1764. var baseData = {
  1765. project: this._globalProject,
  1766. logger: globalOptions.logger,
  1767. platform: "javascript",
  1768. },
  1769. httpData = this._getHttpData();
  1770. if (httpData) {
  1771. baseData.request = httpData;
  1772. }
  1773. // HACK: delete `trimHeadFrames` to prevent from appearing in outbound payload
  1774. if (data.trimHeadFrames) delete data.trimHeadFrames;
  1775. data = objectMerge(baseData, data);
  1776. // Merge in the tags and extra separately since objectMerge doesn't handle a deep merge
  1777. data.tags = objectMerge(
  1778. objectMerge({}, this._globalContext.tags),
  1779. data.tags,
  1780. );
  1781. data.extra = objectMerge(
  1782. objectMerge({}, this._globalContext.extra),
  1783. data.extra,
  1784. );
  1785. // Send along our own collected metadata with extra
  1786. data.extra["session:duration"] = now() - this._startTime;
  1787. if (this._breadcrumbs && this._breadcrumbs.length > 0) {
  1788. // intentionally make shallow copy so that additions
  1789. // to breadcrumbs aren't accidentally sent in this request
  1790. data.breadcrumbs = {
  1791. values: [].slice.call(this._breadcrumbs, 0),
  1792. };
  1793. }
  1794. // If there are no tags/extra, strip the key from the payload alltogther.
  1795. if (isEmptyObject(data.tags)) delete data.tags;
  1796. if (this._globalContext.user) {
  1797. // sentry.interfaces.User
  1798. data.user = this._globalContext.user;
  1799. }
  1800. // Include the environment if it's defined in globalOptions
  1801. if (globalOptions.environment)
  1802. data.environment = globalOptions.environment;
  1803. // Include the release if it's defined in globalOptions
  1804. if (globalOptions.release) data.release = globalOptions.release;
  1805. // Include server_name if it's defined in globalOptions
  1806. if (globalOptions.serverName)
  1807. data.server_name = globalOptions.serverName;
  1808. if (isFunction(globalOptions.dataCallback)) {
  1809. data = globalOptions.dataCallback(data) || data;
  1810. }
  1811. // Why??????????
  1812. if (!data || isEmptyObject(data)) {
  1813. return;
  1814. }
  1815. // Check if the request should be filtered or not
  1816. if (
  1817. isFunction(globalOptions.shouldSendCallback) &&
  1818. !globalOptions.shouldSendCallback(data)
  1819. ) {
  1820. return;
  1821. }
  1822. // Backoff state: Sentry server previously responded w/ an error (e.g. 429 - too many requests),
  1823. // so drop requests until "cool-off" period has elapsed.
  1824. if (this._shouldBackoff()) {
  1825. this._logDebug(
  1826. "warn",
  1827. "Raven dropped error due to backoff: ",
  1828. data,
  1829. );
  1830. return;
  1831. }
  1832. if (typeof globalOptions.sampleRate === "number") {
  1833. if (Math.random() < globalOptions.sampleRate) {
  1834. this._sendProcessedPayload(data);
  1835. }
  1836. } else {
  1837. this._sendProcessedPayload(data);
  1838. }
  1839. },
  1840. _getUuid: function () {
  1841. return uuid4();
  1842. },
  1843. _sendProcessedPayload: function (data, callback) {
  1844. var self = this;
  1845. var globalOptions = this._globalOptions;
  1846. if (!this.isSetup()) return;
  1847. // Try and clean up the packet before sending by truncating long values
  1848. data = this._trimPacket(data);
  1849. // ideally duplicate error testing should occur *before* dataCallback/shouldSendCallback,
  1850. // but this would require copying an un-truncated copy of the data packet, which can be
  1851. // arbitrarily deep (extra_data) -- could be worthwhile? will revisit
  1852. if (
  1853. !this._globalOptions.allowDuplicates &&
  1854. this._isRepeatData(data)
  1855. ) {
  1856. this._logDebug("warn", "Raven dropped repeat event: ", data);
  1857. return;
  1858. }
  1859. // Send along an event_id if not explicitly passed.
  1860. // This event_id can be used to reference the error within Sentry itself.
  1861. // Set lastEventId after we know the error should actually be sent
  1862. this._lastEventId =
  1863. data.event_id || (data.event_id = this._getUuid());
  1864. // Store outbound payload after trim
  1865. this._lastData = data;
  1866. this._logDebug("debug", "Raven about to send:", data);
  1867. var auth = {
  1868. sentry_version: "7",
  1869. sentry_client: "raven-js/" + this.VERSION,
  1870. sentry_key: this._globalKey,
  1871. };
  1872. if (this._globalSecret) {
  1873. auth.sentry_secret = this._globalSecret;
  1874. }
  1875. var exception = data.exception && data.exception.values[0];
  1876. // only capture 'sentry' breadcrumb is autoBreadcrumbs is truthy
  1877. if (
  1878. this._globalOptions.autoBreadcrumbs &&
  1879. this._globalOptions.autoBreadcrumbs.sentry
  1880. ) {
  1881. this.captureBreadcrumb({
  1882. category: "sentry",
  1883. message: exception
  1884. ? (exception.type ? exception.type + ": " : "") +
  1885. exception.value
  1886. : data.message,
  1887. event_id: data.event_id,
  1888. level: data.level || "error", // presume error unless specified
  1889. });
  1890. }
  1891. var url = this._globalEndpoint;
  1892. (globalOptions.transport || this._makeRequest).call(this, {
  1893. url: url,
  1894. auth: auth,
  1895. data: data,
  1896. options: globalOptions,
  1897. onSuccess: function success() {
  1898. self._resetBackoff();
  1899. self._triggerEvent("success", {
  1900. data: data,
  1901. src: url,
  1902. });
  1903. callback && callback();
  1904. },
  1905. onError: function failure(error) {
  1906. self._logDebug(
  1907. "error",
  1908. "Raven transport failed to send: ",
  1909. error,
  1910. );
  1911. if (error.request) {
  1912. self._setBackoffState(error.request);
  1913. }
  1914. self._triggerEvent("failure", {
  1915. data: data,
  1916. src: url,
  1917. });
  1918. error =
  1919. error ||
  1920. new Error(
  1921. "Raven send failed (no additional details provided)",
  1922. );
  1923. callback && callback(error);
  1924. },
  1925. });
  1926. },
  1927. _makeRequest: function (opts) {
  1928. var request =
  1929. _window.XMLHttpRequest && new _window.XMLHttpRequest();
  1930. if (!request) return;
  1931. // if browser doesn't support CORS (e.g. IE7), we are out of luck
  1932. var hasCORS =
  1933. "withCredentials" in request ||
  1934. typeof XDomainRequest !== "undefined";
  1935. if (!hasCORS) return;
  1936. var url = opts.url;
  1937. if ("withCredentials" in request) {
  1938. request.onreadystatechange = function () {
  1939. if (request.readyState !== 4) {
  1940. return;
  1941. } else if (request.status === 200) {
  1942. opts.onSuccess && opts.onSuccess();
  1943. } else if (opts.onError) {
  1944. var err = new Error(
  1945. "Sentry error code: " + request.status,
  1946. );
  1947. err.request = request;
  1948. opts.onError(err);
  1949. }
  1950. };
  1951. } else {
  1952. request = new XDomainRequest();
  1953. // xdomainrequest cannot go http -> https (or vice versa),
  1954. // so always use protocol relative
  1955. url = url.replace(/^https?:/, "");
  1956. // onreadystatechange not supported by XDomainRequest
  1957. if (opts.onSuccess) {
  1958. request.onload = opts.onSuccess;
  1959. }
  1960. if (opts.onError) {
  1961. request.onerror = function () {
  1962. var err = new Error("Sentry error code: XDomainRequest");
  1963. err.request = request;
  1964. opts.onError(err);
  1965. };
  1966. }
  1967. }
  1968. // NOTE: auth is intentionally sent as part of query string (NOT as custom
  1969. // HTTP header) so as to avoid preflight CORS requests
  1970. request.open("POST", url + "?" + urlencode(opts.auth));
  1971. request.send(stringify(opts.data));
  1972. },
  1973. _logDebug: function (level) {
  1974. if (this._originalConsoleMethods[level] && this.debug) {
  1975. // In IE<10 console methods do not have their own 'apply' method
  1976. Function.prototype.apply.call(
  1977. this._originalConsoleMethods[level],
  1978. this._originalConsole,
  1979. [].slice.call(arguments, 1),
  1980. );
  1981. }
  1982. },
  1983. _mergeContext: function (key, context) {
  1984. if (isUndefined(context)) {
  1985. delete this._globalContext[key];
  1986. } else {
  1987. this._globalContext[key] = objectMerge(
  1988. this._globalContext[key] || {},
  1989. context,
  1990. );
  1991. }
  1992. },
  1993. };
  1994. // Deprecations
  1995. Raven.prototype.setUser = Raven.prototype.setUserContext;
  1996. Raven.prototype.setReleaseContext = Raven.prototype.setRelease;
  1997. module.exports = Raven;
  1998. }).call(
  1999. this,
  2000. typeof global !== "undefined"
  2001. ? global
  2002. : typeof self !== "undefined"
  2003. ? self
  2004. : typeof window !== "undefined"
  2005. ? window
  2006. : {},
  2007. );
  2008. },
  2009. { 1: 1, 2: 2, 5: 5, 6: 6, 7: 7 },
  2010. ],
  2011. 4: [
  2012. function (_dereq_, module, exports) {
  2013. (function (global) {
  2014. /**
  2015. * Enforces a single instance of the Raven client, and the
  2016. * main entry point for Raven. If you are a consumer of the
  2017. * Raven library, you SHOULD load this file (vs raven.js).
  2018. **/
  2019. var RavenConstructor = _dereq_(3);
  2020. // This is to be defensive in environments where window does not exist (see https://github.com/getsentry/raven-js/pull/785)
  2021. var _window =
  2022. typeof window !== "undefined"
  2023. ? window
  2024. : typeof global !== "undefined"
  2025. ? global
  2026. : typeof self !== "undefined"
  2027. ? self
  2028. : {};
  2029. var _Raven = _window.Raven;
  2030. var Raven = new RavenConstructor();
  2031. /*
  2032. * Allow multiple versions of Raven to be installed.
  2033. * Strip Raven from the global context and returns the instance.
  2034. *
  2035. * @return {Raven}
  2036. */
  2037. Raven.noConflict = function () {
  2038. _window.Raven = _Raven;
  2039. return Raven;
  2040. };
  2041. Raven.afterLoad();
  2042. module.exports = Raven;
  2043. }).call(
  2044. this,
  2045. typeof global !== "undefined"
  2046. ? global
  2047. : typeof self !== "undefined"
  2048. ? self
  2049. : typeof window !== "undefined"
  2050. ? window
  2051. : {},
  2052. );
  2053. },
  2054. { 3: 3 },
  2055. ],
  2056. 5: [
  2057. function (_dereq_, module, exports) {
  2058. (function (global) {
  2059. var _window =
  2060. typeof window !== "undefined"
  2061. ? window
  2062. : typeof global !== "undefined"
  2063. ? global
  2064. : typeof self !== "undefined"
  2065. ? self
  2066. : {};
  2067. function isObject(what) {
  2068. return typeof what === "object" && what !== null;
  2069. }
  2070. // Yanked from https://git.io/vS8DV re-used under CC0
  2071. // with some tiny modifications
  2072. function isError(value) {
  2073. switch ({}.toString.call(value)) {
  2074. case "[object Error]":
  2075. return true;
  2076. case "[object Exception]":
  2077. return true;
  2078. case "[object DOMException]":
  2079. return true;
  2080. default:
  2081. return value instanceof Error;
  2082. }
  2083. }
  2084. function isErrorEvent(value) {
  2085. return (
  2086. supportsErrorEvent() &&
  2087. {}.toString.call(value) === "[object ErrorEvent]"
  2088. );
  2089. }
  2090. function isUndefined(what) {
  2091. return what === void 0;
  2092. }
  2093. function isFunction(what) {
  2094. return typeof what === "function";
  2095. }
  2096. function isString(what) {
  2097. return Object.prototype.toString.call(what) === "[object String]";
  2098. }
  2099. function isArray(what) {
  2100. return Object.prototype.toString.call(what) === "[object Array]";
  2101. }
  2102. function isEmptyObject(what) {
  2103. for (var _ in what) {
  2104. if (what.hasOwnProperty(_)) {
  2105. return false;
  2106. }
  2107. }
  2108. return true;
  2109. }
  2110. function supportsErrorEvent() {
  2111. try {
  2112. new ErrorEvent(""); // eslint-disable-line no-new
  2113. return true;
  2114. } catch (e) {
  2115. return false;
  2116. }
  2117. }
  2118. function wrappedCallback(callback) {
  2119. function dataCallback(data, original) {
  2120. var normalizedData = callback(data) || data;
  2121. if (original) {
  2122. return original(normalizedData) || normalizedData;
  2123. }
  2124. return normalizedData;
  2125. }
  2126. return dataCallback;
  2127. }
  2128. function each(obj, callback) {
  2129. var i, j;
  2130. if (isUndefined(obj.length)) {
  2131. for (i in obj) {
  2132. if (hasKey(obj, i)) {
  2133. callback.call(null, i, obj[i]);
  2134. }
  2135. }
  2136. } else {
  2137. j = obj.length;
  2138. if (j) {
  2139. for (i = 0; i < j; i++) {
  2140. callback.call(null, i, obj[i]);
  2141. }
  2142. }
  2143. }
  2144. }
  2145. function objectMerge(obj1, obj2) {
  2146. if (!obj2) {
  2147. return obj1;
  2148. }
  2149. each(obj2, function (key, value) {
  2150. obj1[key] = value;
  2151. });
  2152. return obj1;
  2153. }
  2154. /**
  2155. * This function is only used for react-native.
  2156. * react-native freezes object that have already been sent over the
  2157. * js bridge. We need this function in order to check if the object is frozen.
  2158. * So it's ok that objectFrozen returns false if Object.isFrozen is not
  2159. * supported because it's not relevant for other "platforms". See related issue:
  2160. * https://github.com/getsentry/react-native-sentry/issues/57
  2161. */
  2162. function objectFrozen(obj) {
  2163. if (!Object.isFrozen) {
  2164. return false;
  2165. }
  2166. return Object.isFrozen(obj);
  2167. }
  2168. function truncate(str, max) {
  2169. return !max || str.length <= max
  2170. ? str
  2171. : str.substr(0, max) + "\u2026";
  2172. }
  2173. /**
  2174. * hasKey, a better form of hasOwnProperty
  2175. * Example: hasKey(MainHostObject, property) === true/false
  2176. *
  2177. * @param {Object} host object to check property
  2178. * @param {string} key to check
  2179. */
  2180. function hasKey(object, key) {
  2181. return Object.prototype.hasOwnProperty.call(object, key);
  2182. }
  2183. function joinRegExp(patterns) {
  2184. // Combine an array of regular expressions and strings into one large regexp
  2185. // Be mad.
  2186. var sources = [],
  2187. i = 0,
  2188. len = patterns.length,
  2189. pattern;
  2190. for (; i < len; i++) {
  2191. pattern = patterns[i];
  2192. if (isString(pattern)) {
  2193. // If it's a string, we need to escape it
  2194. // Taken from: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions
  2195. sources.push(
  2196. pattern.replace(/([.*+?^=!:${}()|\[\]\/\\])/g, "\\$1"),
  2197. );
  2198. } else if (pattern && pattern.source) {
  2199. // If it's a regexp already, we want to extract the source
  2200. sources.push(pattern.source);
  2201. }
  2202. // Intentionally skip other cases
  2203. }
  2204. return new RegExp(sources.join("|"), "i");
  2205. }
  2206. function urlencode(o) {
  2207. var pairs = [];
  2208. each(o, function (key, value) {
  2209. pairs.push(
  2210. encodeURIComponent(key) + "=" + encodeURIComponent(value),
  2211. );
  2212. });
  2213. return pairs.join("&");
  2214. }
  2215. // borrowed from https://datatracker.ietf.org/doc/html/rfc3986#appendix-B
  2216. // intentionally using regex and not <a/> href parsing trick because React Native and other
  2217. // environments where DOM might not be available
  2218. function parseUrl(url) {
  2219. var match = url.match(
  2220. /^(([^:\/?#]+):)?(\/\/([^\/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?$/,
  2221. );
  2222. if (!match) return {};
  2223. // coerce to undefined values to empty string so we don't get 'undefined'
  2224. var query = match[6] || "";
  2225. var fragment = match[8] || "";
  2226. return {
  2227. protocol: match[2],
  2228. host: match[4],
  2229. path: match[5],
  2230. relative: match[5] + query + fragment, // everything minus origin
  2231. };
  2232. }
  2233. function uuid4() {
  2234. var crypto = _window.crypto || _window.msCrypto;
  2235. if (!isUndefined(crypto) && crypto.getRandomValues) {
  2236. // Use window.crypto API if available
  2237. // eslint-disable-next-line no-undef
  2238. var arr = new Uint16Array(8);
  2239. crypto.getRandomValues(arr);
  2240. // set 4 in byte 7
  2241. arr[3] = (arr[3] & 0xfff) | 0x4000;
  2242. // set 2 most significant bits of byte 9 to '10'
  2243. arr[4] = (arr[4] & 0x3fff) | 0x8000;
  2244. var pad = function (num) {
  2245. var v = num.toString(16);
  2246. while (v.length < 4) {
  2247. v = "0" + v;
  2248. }
  2249. return v;
  2250. };
  2251. return (
  2252. pad(arr[0]) +
  2253. pad(arr[1]) +
  2254. pad(arr[2]) +
  2255. pad(arr[3]) +
  2256. pad(arr[4]) +
  2257. pad(arr[5]) +
  2258. pad(arr[6]) +
  2259. pad(arr[7])
  2260. );
  2261. } else {
  2262. // http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#2117523
  2263. return "xxxxxxxxxxxx4xxxyxxxxxxxxxxxxxxx".replace(
  2264. /[xy]/g,
  2265. function (c) {
  2266. var r = (Math.random() * 16) | 0,
  2267. v = c === "x" ? r : (r & 0x3) | 0x8;
  2268. return v.toString(16);
  2269. },
  2270. );
  2271. }
  2272. }
  2273. /**
  2274. * Given a child DOM element, returns a query-selector statement describing that
  2275. * and its ancestors
  2276. * e.g. [HTMLElement] => body > div > input#foo.btn[name=baz]
  2277. * @param elem
  2278. * @returns {string}
  2279. */
  2280. function htmlTreeAsString(elem) {
  2281. /* eslint no-extra-parens:0*/
  2282. var MAX_TRAVERSE_HEIGHT = 5,
  2283. MAX_OUTPUT_LEN = 80,
  2284. out = [],
  2285. height = 0,
  2286. len = 0,
  2287. separator = " > ",
  2288. sepLength = separator.length,
  2289. nextStr;
  2290. while (elem && height++ < MAX_TRAVERSE_HEIGHT) {
  2291. nextStr = htmlElementAsString(elem);
  2292. // bail out if
  2293. // - nextStr is the 'html' element
  2294. // - the length of the string that would be created exceeds MAX_OUTPUT_LEN
  2295. // (ignore this limit if we are on the first iteration)
  2296. if (
  2297. nextStr === "html" ||
  2298. (height > 1 &&
  2299. len + out.length * sepLength + nextStr.length >=
  2300. MAX_OUTPUT_LEN)
  2301. ) {
  2302. break;
  2303. }
  2304. out.push(nextStr);
  2305. len += nextStr.length;
  2306. elem = elem.parentNode;
  2307. }
  2308. return out.reverse().join(separator);
  2309. }
  2310. /**
  2311. * Returns a simple, query-selector representation of a DOM element
  2312. * e.g. [HTMLElement] => input#foo.btn[name=baz]
  2313. * @param HTMLElement
  2314. * @returns {string}
  2315. */
  2316. function htmlElementAsString(elem) {
  2317. var out = [],
  2318. className,
  2319. classes,
  2320. key,
  2321. attr,
  2322. i;
  2323. if (!elem || !elem.tagName) {
  2324. return "";
  2325. }
  2326. out.push(elem.tagName.toLowerCase());
  2327. if (elem.id) {
  2328. out.push("#" + elem.id);
  2329. }
  2330. className = elem.className;
  2331. if (className && isString(className)) {
  2332. classes = className.split(/\s+/);
  2333. for (i = 0; i < classes.length; i++) {
  2334. out.push("." + classes[i]);
  2335. }
  2336. }
  2337. var attrWhitelist = ["type", "name", "title", "alt"];
  2338. for (i = 0; i < attrWhitelist.length; i++) {
  2339. key = attrWhitelist[i];
  2340. attr = elem.getAttribute(key);
  2341. if (attr) {
  2342. out.push("[" + key + '="' + attr + '"]');
  2343. }
  2344. }
  2345. return out.join("");
  2346. }
  2347. /**
  2348. * Returns true if either a OR b is truthy, but not both
  2349. */
  2350. function isOnlyOneTruthy(a, b) {
  2351. return !!(!!a ^ !!b);
  2352. }
  2353. /**
  2354. * Returns true if the two input exception interfaces have the same content
  2355. */
  2356. function isSameException(ex1, ex2) {
  2357. if (isOnlyOneTruthy(ex1, ex2)) return false;
  2358. ex1 = ex1.values[0];
  2359. ex2 = ex2.values[0];
  2360. if (ex1.type !== ex2.type || ex1.value !== ex2.value)
  2361. return false;
  2362. return isSameStacktrace(ex1.stacktrace, ex2.stacktrace);
  2363. }
  2364. /**
  2365. * Returns true if the two input stack trace interfaces have the same content
  2366. */
  2367. function isSameStacktrace(stack1, stack2) {
  2368. if (isOnlyOneTruthy(stack1, stack2)) return false;
  2369. var frames1 = stack1.frames;
  2370. var frames2 = stack2.frames;
  2371. // Exit early if frame count differs
  2372. if (frames1.length !== frames2.length) return false;
  2373. // Iterate through every frame; bail out if anything differs
  2374. var a, b;
  2375. for (var i = 0; i < frames1.length; i++) {
  2376. a = frames1[i];
  2377. b = frames2[i];
  2378. if (
  2379. a.filename !== b.filename ||
  2380. a.lineno !== b.lineno ||
  2381. a.colno !== b.colno ||
  2382. a["function"] !== b["function"]
  2383. )
  2384. return false;
  2385. }
  2386. return true;
  2387. }
  2388. /**
  2389. * Polyfill a method
  2390. * @param obj object e.g. `document`
  2391. * @param name method name present on object e.g. `addEventListener`
  2392. * @param replacement replacement function
  2393. * @param track {optional} record instrumentation to an array
  2394. */
  2395. function fill(obj, name, replacement, track) {
  2396. var orig = obj[name];
  2397. obj[name] = replacement(orig);
  2398. obj[name].__raven__ = true;
  2399. obj[name].__orig__ = orig;
  2400. if (track) {
  2401. track.push([obj, name, orig]);
  2402. }
  2403. }
  2404. module.exports = {
  2405. isObject: isObject,
  2406. isError: isError,
  2407. isErrorEvent: isErrorEvent,
  2408. isUndefined: isUndefined,
  2409. isFunction: isFunction,
  2410. isString: isString,
  2411. isArray: isArray,
  2412. isEmptyObject: isEmptyObject,
  2413. supportsErrorEvent: supportsErrorEvent,
  2414. wrappedCallback: wrappedCallback,
  2415. each: each,
  2416. objectMerge: objectMerge,
  2417. truncate: truncate,
  2418. objectFrozen: objectFrozen,
  2419. hasKey: hasKey,
  2420. joinRegExp: joinRegExp,
  2421. urlencode: urlencode,
  2422. uuid4: uuid4,
  2423. htmlTreeAsString: htmlTreeAsString,
  2424. htmlElementAsString: htmlElementAsString,
  2425. isSameException: isSameException,
  2426. isSameStacktrace: isSameStacktrace,
  2427. parseUrl: parseUrl,
  2428. fill: fill,
  2429. };
  2430. }).call(
  2431. this,
  2432. typeof global !== "undefined"
  2433. ? global
  2434. : typeof self !== "undefined"
  2435. ? self
  2436. : typeof window !== "undefined"
  2437. ? window
  2438. : {},
  2439. );
  2440. },
  2441. {},
  2442. ],
  2443. 6: [
  2444. function (_dereq_, module, exports) {
  2445. (function (global) {
  2446. var utils = _dereq_(5);
  2447. /*
  2448. TraceKit - Cross brower stack traces
  2449. This was originally forked from github.com/occ/TraceKit, but has since been
  2450. largely re-written and is now maintained as part of raven-js. Tests for
  2451. this are in test/vendor.
  2452. MIT license
  2453. */
  2454. var TraceKit = {
  2455. collectWindowErrors: true,
  2456. debug: false,
  2457. };
  2458. // This is to be defensive in environments where window does not exist (see https://github.com/getsentry/raven-js/pull/785)
  2459. var _window =
  2460. typeof window !== "undefined"
  2461. ? window
  2462. : typeof global !== "undefined"
  2463. ? global
  2464. : typeof self !== "undefined"
  2465. ? self
  2466. : {};
  2467. // global reference to slice
  2468. var _slice = [].slice;
  2469. var UNKNOWN_FUNCTION = "?";
  2470. // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error#Error_types
  2471. var ERROR_TYPES_RE =
  2472. /^(?:[Uu]ncaught (?:exception: )?)?(?:((?:Eval|Internal|Range|Reference|Syntax|Type|URI|)Error): )?(.*)$/;
  2473. function getLocationHref() {
  2474. if (typeof document === "undefined" || document.location == null)
  2475. return "";
  2476. return document.location.href;
  2477. }
  2478. /**
  2479. * TraceKit.report: cross-browser processing of unhandled exceptions
  2480. *
  2481. * Syntax:
  2482. * TraceKit.report.subscribe(function(stackInfo) { ... })
  2483. * TraceKit.report.unsubscribe(function(stackInfo) { ... })
  2484. * TraceKit.report(exception)
  2485. * try { ...code... } catch(ex) { TraceKit.report(ex); }
  2486. *
  2487. * Supports:
  2488. * - Firefox: full stack trace with line numbers, plus column number
  2489. * on top frame; column number is not guaranteed
  2490. * - Opera: full stack trace with line and column numbers
  2491. * - Chrome: full stack trace with line and column numbers
  2492. * - Safari: line and column number for the top frame only; some frames
  2493. * may be missing, and column number is not guaranteed
  2494. * - IE: line and column number for the top frame only; some frames
  2495. * may be missing, and column number is not guaranteed
  2496. *
  2497. * In theory, TraceKit should work on all of the following versions:
  2498. * - IE5.5+ (only 8.0 tested)
  2499. * - Firefox 0.9+ (only 3.5+ tested)
  2500. * - Opera 7+ (only 10.50 tested; versions 9 and earlier may require
  2501. * Exceptions Have Stacktrace to be enabled in opera:config)
  2502. * - Safari 3+ (only 4+ tested)
  2503. * - Chrome 1+ (only 5+ tested)
  2504. * - Konqueror 3.5+ (untested)
  2505. *
  2506. * Requires TraceKit.computeStackTrace.
  2507. *
  2508. * Tries to catch all unhandled exceptions and report them to the
  2509. * subscribed handlers. Please note that TraceKit.report will rethrow the
  2510. * exception. This is REQUIRED in order to get a useful stack trace in IE.
  2511. * If the exception does not reach the top of the browser, you will only
  2512. * get a stack trace from the point where TraceKit.report was called.
  2513. *
  2514. * Handlers receive a stackInfo object as described in the
  2515. * TraceKit.computeStackTrace docs.
  2516. */
  2517. TraceKit.report = (function reportModuleWrapper() {
  2518. var handlers = [],
  2519. lastArgs = null,
  2520. lastException = null,
  2521. lastExceptionStack = null;
  2522. /**
  2523. * Add a crash handler.
  2524. * @param {Function} handler
  2525. */
  2526. function subscribe(handler) {
  2527. installGlobalHandler();
  2528. handlers.push(handler);
  2529. }
  2530. /**
  2531. * Remove a crash handler.
  2532. * @param {Function} handler
  2533. */
  2534. function unsubscribe(handler) {
  2535. for (var i = handlers.length - 1; i >= 0; --i) {
  2536. if (handlers[i] === handler) {
  2537. handlers.splice(i, 1);
  2538. }
  2539. }
  2540. }
  2541. /**
  2542. * Remove all crash handlers.
  2543. */
  2544. function unsubscribeAll() {
  2545. uninstallGlobalHandler();
  2546. handlers = [];
  2547. }
  2548. /**
  2549. * Dispatch stack information to all handlers.
  2550. * @param {Object.<string, *>} stack
  2551. */
  2552. function notifyHandlers(stack, isWindowError) {
  2553. var exception = null;
  2554. if (isWindowError && !TraceKit.collectWindowErrors) {
  2555. return;
  2556. }
  2557. for (var i in handlers) {
  2558. if (handlers.hasOwnProperty(i)) {
  2559. try {
  2560. handlers[i].apply(
  2561. null,
  2562. [stack].concat(_slice.call(arguments, 2)),
  2563. );
  2564. } catch (inner) {
  2565. exception = inner;
  2566. }
  2567. }
  2568. }
  2569. if (exception) {
  2570. throw exception;
  2571. }
  2572. }
  2573. var _oldOnerrorHandler, _onErrorHandlerInstalled;
  2574. /**
  2575. * Ensures all global unhandled exceptions are recorded.
  2576. * Supported by Gecko and IE.
  2577. * @param {string} message Error message.
  2578. * @param {string} url URL of script that generated the exception.
  2579. * @param {(number|string)} lineNo The line number at which the error
  2580. * occurred.
  2581. * @param {?(number|string)} colNo The column number at which the error
  2582. * occurred.
  2583. * @param {?Error} ex The actual Error object.
  2584. */
  2585. function traceKitWindowOnError(message, url, lineNo, colNo, ex) {
  2586. var stack = null;
  2587. if (lastExceptionStack) {
  2588. TraceKit.computeStackTrace.augmentStackTraceWithInitialElement(
  2589. lastExceptionStack,
  2590. url,
  2591. lineNo,
  2592. message,
  2593. );
  2594. processLastException();
  2595. } else if (ex && utils.isError(ex)) {
  2596. // non-string `ex` arg; attempt to extract stack trace
  2597. // New chrome and blink send along a real error object
  2598. // Let's just report that like a normal error.
  2599. // See: https://mikewest.org/2013/08/debugging-runtime-errors-with-window-onerror
  2600. stack = TraceKit.computeStackTrace(ex);
  2601. notifyHandlers(stack, true);
  2602. } else {
  2603. var location = {
  2604. url: url,
  2605. line: lineNo,
  2606. column: colNo,
  2607. };
  2608. var name = undefined;
  2609. var msg = message; // must be new var or will modify original `arguments`
  2610. var groups;
  2611. if ({}.toString.call(message) === "[object String]") {
  2612. var groups = message.match(ERROR_TYPES_RE);
  2613. if (groups) {
  2614. name = groups[1];
  2615. msg = groups[2];
  2616. }
  2617. }
  2618. location.func = UNKNOWN_FUNCTION;
  2619. stack = {
  2620. name: name,
  2621. message: msg,
  2622. url: getLocationHref(),
  2623. stack: [location],
  2624. };
  2625. notifyHandlers(stack, true);
  2626. }
  2627. if (_oldOnerrorHandler) {
  2628. return _oldOnerrorHandler.apply(this, arguments);
  2629. }
  2630. return false;
  2631. }
  2632. function installGlobalHandler() {
  2633. if (_onErrorHandlerInstalled) {
  2634. return;
  2635. }
  2636. _oldOnerrorHandler = _window.onerror;
  2637. _window.onerror = traceKitWindowOnError;
  2638. _onErrorHandlerInstalled = true;
  2639. }
  2640. function uninstallGlobalHandler() {
  2641. if (!_onErrorHandlerInstalled) {
  2642. return;
  2643. }
  2644. _window.onerror = _oldOnerrorHandler;
  2645. _onErrorHandlerInstalled = false;
  2646. _oldOnerrorHandler = undefined;
  2647. }
  2648. function processLastException() {
  2649. var _lastExceptionStack = lastExceptionStack,
  2650. _lastArgs = lastArgs;
  2651. lastArgs = null;
  2652. lastExceptionStack = null;
  2653. lastException = null;
  2654. notifyHandlers.apply(
  2655. null,
  2656. [_lastExceptionStack, false].concat(_lastArgs),
  2657. );
  2658. }
  2659. /**
  2660. * Reports an unhandled Error to TraceKit.
  2661. * @param {Error} ex
  2662. * @param {?boolean} rethrow If false, do not re-throw the exception.
  2663. * Only used for window.onerror to not cause an infinite loop of
  2664. * rethrowing.
  2665. */
  2666. function report(ex, rethrow) {
  2667. var args = _slice.call(arguments, 1);
  2668. if (lastExceptionStack) {
  2669. if (lastException === ex) {
  2670. return; // already caught by an inner catch block, ignore
  2671. } else {
  2672. processLastException();
  2673. }
  2674. }
  2675. var stack = TraceKit.computeStackTrace(ex);
  2676. lastExceptionStack = stack;
  2677. lastException = ex;
  2678. lastArgs = args;
  2679. // If the stack trace is incomplete, wait for 2 seconds for
  2680. // slow slow IE to see if onerror occurs or not before reporting
  2681. // this exception; otherwise, we will end up with an incomplete
  2682. // stack trace
  2683. setTimeout(
  2684. function () {
  2685. if (lastException === ex) {
  2686. processLastException();
  2687. }
  2688. },
  2689. stack.incomplete ? 2000 : 0,
  2690. );
  2691. if (rethrow !== false) {
  2692. throw ex; // re-throw to propagate to the top level (and cause window.onerror)
  2693. }
  2694. }
  2695. report.subscribe = subscribe;
  2696. report.unsubscribe = unsubscribe;
  2697. report.uninstall = unsubscribeAll;
  2698. return report;
  2699. })();
  2700. /**
  2701. * TraceKit.computeStackTrace: cross-browser stack traces in JavaScript
  2702. *
  2703. * Syntax:
  2704. * s = TraceKit.computeStackTrace(exception) // consider using TraceKit.report instead (see below)
  2705. * Returns:
  2706. * s.name - exception name
  2707. * s.message - exception message
  2708. * s.stack[i].url - JavaScript or HTML file URL
  2709. * s.stack[i].func - function name, or empty for anonymous functions (if guessing did not work)
  2710. * s.stack[i].args - arguments passed to the function, if known
  2711. * s.stack[i].line - line number, if known
  2712. * s.stack[i].column - column number, if known
  2713. *
  2714. * Supports:
  2715. * - Firefox: full stack trace with line numbers and unreliable column
  2716. * number on top frame
  2717. * - Opera 10: full stack trace with line and column numbers
  2718. * - Opera 9-: full stack trace with line numbers
  2719. * - Chrome: full stack trace with line and column numbers
  2720. * - Safari: line and column number for the topmost stacktrace element
  2721. * only
  2722. * - IE: no line numbers whatsoever
  2723. *
  2724. * Tries to guess names of anonymous functions by looking for assignments
  2725. * in the source code. In IE and Safari, we have to guess source file names
  2726. * by searching for function bodies inside all page scripts. This will not
  2727. * work for scripts that are loaded cross-domain.
  2728. * Here be dragons: some function names may be guessed incorrectly, and
  2729. * duplicate functions may be mismatched.
  2730. *
  2731. * TraceKit.computeStackTrace should only be used for tracing purposes.
  2732. * Logging of unhandled exceptions should be done with TraceKit.report,
  2733. * which builds on top of TraceKit.computeStackTrace and provides better
  2734. * IE support by utilizing the window.onerror event to retrieve information
  2735. * about the top of the stack.
  2736. *
  2737. * Note: In IE and Safari, no stack trace is recorded on the Error object,
  2738. * so computeStackTrace instead walks its *own* chain of callers.
  2739. * This means that:
  2740. * * in Safari, some methods may be missing from the stack trace;
  2741. * * in IE, the topmost function in the stack trace will always be the
  2742. * caller of computeStackTrace.
  2743. *
  2744. * This is okay for tracing (because you are likely to be calling
  2745. * computeStackTrace from the function you want to be the topmost element
  2746. * of the stack trace anyway), but not okay for logging unhandled
  2747. * exceptions (because your catch block will likely be far away from the
  2748. * inner function that actually caused the exception).
  2749. *
  2750. */
  2751. TraceKit.computeStackTrace = (function computeStackTraceWrapper() {
  2752. // Contents of Exception in various browsers.
  2753. //
  2754. // SAFARI:
  2755. // ex.message = Can't find variable: qq
  2756. // ex.line = 59
  2757. // ex.sourceId = 580238192
  2758. // ex.sourceURL = http://...
  2759. // ex.expressionBeginOffset = 96
  2760. // ex.expressionCaretOffset = 98
  2761. // ex.expressionEndOffset = 98
  2762. // ex.name = ReferenceError
  2763. //
  2764. // FIREFOX:
  2765. // ex.message = qq is not defined
  2766. // ex.fileName = http://...
  2767. // ex.lineNumber = 59
  2768. // ex.columnNumber = 69
  2769. // ex.stack = ...stack trace... (see the example below)
  2770. // ex.name = ReferenceError
  2771. //
  2772. // CHROME:
  2773. // ex.message = qq is not defined
  2774. // ex.name = ReferenceError
  2775. // ex.type = not_defined
  2776. // ex.arguments = ['aa']
  2777. // ex.stack = ...stack trace...
  2778. //
  2779. // INTERNET EXPLORER:
  2780. // ex.message = ...
  2781. // ex.name = ReferenceError
  2782. //
  2783. // OPERA:
  2784. // ex.message = ...message... (see the example below)
  2785. // ex.name = ReferenceError
  2786. // ex.opera#sourceloc = 11 (pretty much useless, duplicates the info in ex.message)
  2787. // ex.stacktrace = n/a; see 'opera:config#UserPrefs|Exceptions Have Stacktrace'
  2788. /**
  2789. * Computes stack trace information from the stack property.
  2790. * Chrome and Gecko use this property.
  2791. * @param {Error} ex
  2792. * @return {?Object.<string, *>} Stack trace information.
  2793. */
  2794. function computeStackTraceFromStackProp(ex) {
  2795. if (typeof ex.stack === "undefined" || !ex.stack) return;
  2796. var chrome =
  2797. /^\s*at (.*?) ?\(((?:file|https?|blob|chrome-extension|native|eval|webpack|<anonymous>|[a-z]:|\/).*?)(?::(\d+))?(?::(\d+))?\)?\s*$/i,
  2798. gecko =
  2799. /^\s*(.*?)(?:\((.*?)\))?(?:^|@)((?:file|https?|blob|chrome|webpack|resource|\[native).*?|[^@]*bundle)(?::(\d+))?(?::(\d+))?\s*$/i,
  2800. winjs =
  2801. /^\s*at (?:((?:\[object object\])?.+) )?\(?((?:file|ms-appx|https?|webpack|blob):.*?):(\d+)(?::(\d+))?\)?\s*$/i,
  2802. // Used to additionally parse URL/line/column from eval frames
  2803. geckoEval = /(\S+) line (\d+)(?: > eval line \d+)* > eval/i,
  2804. chromeEval = /\((\S*)(?::(\d+))(?::(\d+))\)/,
  2805. lines = ex.stack.split("\n"),
  2806. stack = [],
  2807. submatch,
  2808. parts,
  2809. element,
  2810. reference = /^(.*) is undefined$/.exec(ex.message);
  2811. for (var i = 0, j = lines.length; i < j; ++i) {
  2812. if ((parts = chrome.exec(lines[i]))) {
  2813. var isNative = parts[2] && parts[2].indexOf("native") === 0; // start of line
  2814. var isEval = parts[2] && parts[2].indexOf("eval") === 0; // start of line
  2815. if (isEval && (submatch = chromeEval.exec(parts[2]))) {
  2816. // throw out eval line/column and use top-most line/column number
  2817. parts[2] = submatch[1]; // url
  2818. parts[3] = submatch[2]; // line
  2819. parts[4] = submatch[3]; // column
  2820. }
  2821. element = {
  2822. url: !isNative ? parts[2] : null,
  2823. func: parts[1] || UNKNOWN_FUNCTION,
  2824. args: isNative ? [parts[2]] : [],
  2825. line: parts[3] ? +parts[3] : null,
  2826. column: parts[4] ? +parts[4] : null,
  2827. };
  2828. } else if ((parts = winjs.exec(lines[i]))) {
  2829. element = {
  2830. url: parts[2],
  2831. func: parts[1] || UNKNOWN_FUNCTION,
  2832. args: [],
  2833. line: +parts[3],
  2834. column: parts[4] ? +parts[4] : null,
  2835. };
  2836. } else if ((parts = gecko.exec(lines[i]))) {
  2837. var isEval = parts[3] && parts[3].indexOf(" > eval") > -1;
  2838. if (isEval && (submatch = geckoEval.exec(parts[3]))) {
  2839. // throw out eval line/column and use top-most line number
  2840. parts[3] = submatch[1];
  2841. parts[4] = submatch[2];
  2842. parts[5] = null; // no column when eval
  2843. } else if (
  2844. i === 0 &&
  2845. !parts[5] &&
  2846. typeof ex.columnNumber !== "undefined"
  2847. ) {
  2848. // FireFox uses this awesome columnNumber property for its top frame
  2849. // Also note, Firefox's column number is 0-based and everything else expects 1-based,
  2850. // so adding 1
  2851. // NOTE: this hack doesn't work if top-most frame is eval
  2852. stack[0].column = ex.columnNumber + 1;
  2853. }
  2854. element = {
  2855. url: parts[3],
  2856. func: parts[1] || UNKNOWN_FUNCTION,
  2857. args: parts[2] ? parts[2].split(",") : [],
  2858. line: parts[4] ? +parts[4] : null,
  2859. column: parts[5] ? +parts[5] : null,
  2860. };
  2861. } else {
  2862. continue;
  2863. }
  2864. if (!element.func && element.line) {
  2865. element.func = UNKNOWN_FUNCTION;
  2866. }
  2867. stack.push(element);
  2868. }
  2869. if (!stack.length) {
  2870. return null;
  2871. }
  2872. return {
  2873. name: ex.name,
  2874. message: ex.message,
  2875. url: getLocationHref(),
  2876. stack: stack,
  2877. };
  2878. }
  2879. /**
  2880. * Adds information about the first frame to incomplete stack traces.
  2881. * Safari and IE require this to get complete data on the first frame.
  2882. * @param {Object.<string, *>} stackInfo Stack trace information from
  2883. * one of the compute* methods.
  2884. * @param {string} url The URL of the script that caused an error.
  2885. * @param {(number|string)} lineNo The line number of the script that
  2886. * caused an error.
  2887. * @param {string=} message The error generated by the browser, which
  2888. * hopefully contains the name of the object that caused the error.
  2889. * @return {boolean} Whether or not the stack information was
  2890. * augmented.
  2891. */
  2892. function augmentStackTraceWithInitialElement(
  2893. stackInfo,
  2894. url,
  2895. lineNo,
  2896. message,
  2897. ) {
  2898. var initial = {
  2899. url: url,
  2900. line: lineNo,
  2901. };
  2902. if (initial.url && initial.line) {
  2903. stackInfo.incomplete = false;
  2904. if (!initial.func) {
  2905. initial.func = UNKNOWN_FUNCTION;
  2906. }
  2907. if (stackInfo.stack.length > 0) {
  2908. if (stackInfo.stack[0].url === initial.url) {
  2909. if (stackInfo.stack[0].line === initial.line) {
  2910. return false; // already in stack trace
  2911. } else if (
  2912. !stackInfo.stack[0].line &&
  2913. stackInfo.stack[0].func === initial.func
  2914. ) {
  2915. stackInfo.stack[0].line = initial.line;
  2916. return false;
  2917. }
  2918. }
  2919. }
  2920. stackInfo.stack.unshift(initial);
  2921. stackInfo.partial = true;
  2922. return true;
  2923. } else {
  2924. stackInfo.incomplete = true;
  2925. }
  2926. return false;
  2927. }
  2928. /**
  2929. * Computes stack trace information by walking the arguments.caller
  2930. * chain at the time the exception occurred. This will cause earlier
  2931. * frames to be missed but is the only way to get any stack trace in
  2932. * Safari and IE. The top frame is restored by
  2933. * {@link augmentStackTraceWithInitialElement}.
  2934. * @param {Error} ex
  2935. * @return {?Object.<string, *>} Stack trace information.
  2936. */
  2937. function computeStackTraceByWalkingCallerChain(ex, depth) {
  2938. var functionName =
  2939. /function\s+([_$a-zA-Z\xA0-\uFFFF][_$a-zA-Z0-9\xA0-\uFFFF]*)?\s*\(/i,
  2940. stack = [],
  2941. funcs = {},
  2942. recursion = false,
  2943. parts,
  2944. item,
  2945. source;
  2946. for (
  2947. var curr = computeStackTraceByWalkingCallerChain.caller;
  2948. curr && !recursion;
  2949. curr = curr.caller
  2950. ) {
  2951. if (curr === computeStackTrace || curr === TraceKit.report) {
  2952. // console.log('skipping internal function');
  2953. continue;
  2954. }
  2955. item = {
  2956. url: null,
  2957. func: UNKNOWN_FUNCTION,
  2958. line: null,
  2959. column: null,
  2960. };
  2961. if (curr.name) {
  2962. item.func = curr.name;
  2963. } else if ((parts = functionName.exec(curr.toString()))) {
  2964. item.func = parts[1];
  2965. }
  2966. if (typeof item.func === "undefined") {
  2967. try {
  2968. item.func = parts.input.substring(
  2969. 0,
  2970. parts.input.indexOf("{"),
  2971. );
  2972. } catch (e) {}
  2973. }
  2974. if (funcs["" + curr]) {
  2975. recursion = true;
  2976. } else {
  2977. funcs["" + curr] = true;
  2978. }
  2979. stack.push(item);
  2980. }
  2981. if (depth) {
  2982. // console.log('depth is ' + depth);
  2983. // console.log('stack is ' + stack.length);
  2984. stack.splice(0, depth);
  2985. }
  2986. var result = {
  2987. name: ex.name,
  2988. message: ex.message,
  2989. url: getLocationHref(),
  2990. stack: stack,
  2991. };
  2992. augmentStackTraceWithInitialElement(
  2993. result,
  2994. ex.sourceURL || ex.fileName,
  2995. ex.line || ex.lineNumber,
  2996. ex.message || ex.description,
  2997. );
  2998. return result;
  2999. }
  3000. /**
  3001. * Computes a stack trace for an exception.
  3002. * @param {Error} ex
  3003. * @param {(string|number)=} depth
  3004. */
  3005. function computeStackTrace(ex, depth) {
  3006. var stack = null;
  3007. depth = depth == null ? 0 : +depth;
  3008. try {
  3009. stack = computeStackTraceFromStackProp(ex);
  3010. if (stack) {
  3011. return stack;
  3012. }
  3013. } catch (e) {
  3014. if (TraceKit.debug) {
  3015. throw e;
  3016. }
  3017. }
  3018. try {
  3019. stack = computeStackTraceByWalkingCallerChain(ex, depth + 1);
  3020. if (stack) {
  3021. return stack;
  3022. }
  3023. } catch (e) {
  3024. if (TraceKit.debug) {
  3025. throw e;
  3026. }
  3027. }
  3028. return {
  3029. name: ex.name,
  3030. message: ex.message,
  3031. url: getLocationHref(),
  3032. };
  3033. }
  3034. computeStackTrace.augmentStackTraceWithInitialElement =
  3035. augmentStackTraceWithInitialElement;
  3036. computeStackTrace.computeStackTraceFromStackProp =
  3037. computeStackTraceFromStackProp;
  3038. return computeStackTrace;
  3039. })();
  3040. module.exports = TraceKit;
  3041. }).call(
  3042. this,
  3043. typeof global !== "undefined"
  3044. ? global
  3045. : typeof self !== "undefined"
  3046. ? self
  3047. : typeof window !== "undefined"
  3048. ? window
  3049. : {},
  3050. );
  3051. },
  3052. { 5: 5 },
  3053. ],
  3054. 7: [
  3055. function (_dereq_, module, exports) {
  3056. /*
  3057. json-stringify-safe
  3058. Like JSON.stringify, but doesn't throw on circular references.
  3059. Originally forked from https://github.com/isaacs/json-stringify-safe
  3060. version 5.0.1 on 3/8/2017 and modified to handle Errors serialization
  3061. and IE8 compatibility. Tests for this are in test/vendor.
  3062. ISC license: https://github.com/isaacs/json-stringify-safe/blob/master/LICENSE
  3063. */
  3064. exports = module.exports = stringify;
  3065. exports.getSerialize = serializer;
  3066. function indexOf(haystack, needle) {
  3067. for (var i = 0; i < haystack.length; ++i) {
  3068. if (haystack[i] === needle) return i;
  3069. }
  3070. return -1;
  3071. }
  3072. function stringify(obj, replacer, spaces, cycleReplacer) {
  3073. return JSON.stringify(
  3074. obj,
  3075. serializer(replacer, cycleReplacer),
  3076. spaces,
  3077. );
  3078. }
  3079. // https://github.com/ftlabs/js-abbreviate/blob/fa709e5f139e7770a71827b1893f22418097fbda/index.js#L95-L106
  3080. function stringifyError(value) {
  3081. var err = {
  3082. // These properties are implemented as magical getters and don't show up in for in
  3083. stack: value.stack,
  3084. message: value.message,
  3085. name: value.name,
  3086. };
  3087. for (var i in value) {
  3088. if (Object.prototype.hasOwnProperty.call(value, i)) {
  3089. err[i] = value[i];
  3090. }
  3091. }
  3092. return err;
  3093. }
  3094. function serializer(replacer, cycleReplacer) {
  3095. var stack = [];
  3096. var keys = [];
  3097. if (cycleReplacer == null) {
  3098. cycleReplacer = function (key, value) {
  3099. if (stack[0] === value) {
  3100. return "[Circular ~]";
  3101. }
  3102. return (
  3103. "[Circular ~." +
  3104. keys.slice(0, indexOf(stack, value)).join(".") +
  3105. "]"
  3106. );
  3107. };
  3108. }
  3109. return function (key, value) {
  3110. if (stack.length > 0) {
  3111. var thisPos = indexOf(stack, this);
  3112. ~thisPos ? stack.splice(thisPos + 1) : stack.push(this);
  3113. ~thisPos ? keys.splice(thisPos, Infinity, key) : keys.push(key);
  3114. if (~indexOf(stack, value)) {
  3115. value = cycleReplacer.call(this, key, value);
  3116. }
  3117. } else {
  3118. stack.push(value);
  3119. }
  3120. return replacer == null
  3121. ? value instanceof Error
  3122. ? stringifyError(value)
  3123. : value
  3124. : replacer.call(this, key, value);
  3125. };
  3126. }
  3127. },
  3128. {},
  3129. ],
  3130. },
  3131. {},
  3132. [4],
  3133. )(4);
  3134. });