qunit-2.4.1.js 142 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061
  1. /*!
  2. * QUnit 2.4.1
  3. * https://qunitjs.com/
  4. *
  5. * Copyright jQuery Foundation and other contributors
  6. * Released under the MIT license
  7. * https://jquery.org/license
  8. *
  9. * Date: 2017-10-22T05:12Z
  10. */
  11. (function (global$1) {
  12. 'use strict';
  13. global$1 = 'default' in global$1 ? global$1['default'] : global$1;
  14. var window = global$1.window;
  15. var self$1 = global$1.self;
  16. var console = global$1.console;
  17. var setTimeout = global$1.setTimeout;
  18. var clearTimeout = global$1.clearTimeout;
  19. var document = window && window.document;
  20. var navigator = window && window.navigator;
  21. var localSessionStorage = function () {
  22. var x = "qunit-test-string";
  23. try {
  24. global$1.sessionStorage.setItem(x, x);
  25. global$1.sessionStorage.removeItem(x);
  26. return global$1.sessionStorage;
  27. } catch (e) {
  28. return undefined;
  29. }
  30. }();
  31. var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) {
  32. return typeof obj;
  33. } : function (obj) {
  34. return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj;
  35. };
  36. var classCallCheck = function (instance, Constructor) {
  37. if (!(instance instanceof Constructor)) {
  38. throw new TypeError("Cannot call a class as a function");
  39. }
  40. };
  41. var createClass = function () {
  42. function defineProperties(target, props) {
  43. for (var i = 0; i < props.length; i++) {
  44. var descriptor = props[i];
  45. descriptor.enumerable = descriptor.enumerable || false;
  46. descriptor.configurable = true;
  47. if ("value" in descriptor) descriptor.writable = true;
  48. Object.defineProperty(target, descriptor.key, descriptor);
  49. }
  50. }
  51. return function (Constructor, protoProps, staticProps) {
  52. if (protoProps) defineProperties(Constructor.prototype, protoProps);
  53. if (staticProps) defineProperties(Constructor, staticProps);
  54. return Constructor;
  55. };
  56. }();
  57. var toConsumableArray = function (arr) {
  58. if (Array.isArray(arr)) {
  59. for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) arr2[i] = arr[i];
  60. return arr2;
  61. } else {
  62. return Array.from(arr);
  63. }
  64. };
  65. var toString = Object.prototype.toString;
  66. var hasOwn = Object.prototype.hasOwnProperty;
  67. var now = Date.now || function () {
  68. return new Date().getTime();
  69. };
  70. var defined = {
  71. document: window && window.document !== undefined,
  72. setTimeout: setTimeout !== undefined
  73. };
  74. // Returns a new Array with the elements that are in a but not in b
  75. function diff(a, b) {
  76. var i,
  77. j,
  78. result = a.slice();
  79. for (i = 0; i < result.length; i++) {
  80. for (j = 0; j < b.length; j++) {
  81. if (result[i] === b[j]) {
  82. result.splice(i, 1);
  83. i--;
  84. break;
  85. }
  86. }
  87. }
  88. return result;
  89. }
  90. /**
  91. * Determines whether an element exists in a given array or not.
  92. *
  93. * @method inArray
  94. * @param {Any} elem
  95. * @param {Array} array
  96. * @return {Boolean}
  97. */
  98. function inArray(elem, array) {
  99. return array.indexOf(elem) !== -1;
  100. }
  101. /**
  102. * Makes a clone of an object using only Array or Object as base,
  103. * and copies over the own enumerable properties.
  104. *
  105. * @param {Object} obj
  106. * @return {Object} New object with only the own properties (recursively).
  107. */
  108. function objectValues(obj) {
  109. var key,
  110. val,
  111. vals = is("array", obj) ? [] : {};
  112. for (key in obj) {
  113. if (hasOwn.call(obj, key)) {
  114. val = obj[key];
  115. vals[key] = val === Object(val) ? objectValues(val) : val;
  116. }
  117. }
  118. return vals;
  119. }
  120. function extend(a, b, undefOnly) {
  121. for (var prop in b) {
  122. if (hasOwn.call(b, prop)) {
  123. if (b[prop] === undefined) {
  124. delete a[prop];
  125. } else if (!(undefOnly && typeof a[prop] !== "undefined")) {
  126. a[prop] = b[prop];
  127. }
  128. }
  129. }
  130. return a;
  131. }
  132. function objectType(obj) {
  133. if (typeof obj === "undefined") {
  134. return "undefined";
  135. }
  136. // Consider: typeof null === object
  137. if (obj === null) {
  138. return "null";
  139. }
  140. var match = toString.call(obj).match(/^\[object\s(.*)\]$/),
  141. type = match && match[1];
  142. switch (type) {
  143. case "Number":
  144. if (isNaN(obj)) {
  145. return "nan";
  146. }
  147. return "number";
  148. case "String":
  149. case "Boolean":
  150. case "Array":
  151. case "Set":
  152. case "Map":
  153. case "Date":
  154. case "RegExp":
  155. case "Function":
  156. case "Symbol":
  157. return type.toLowerCase();
  158. default:
  159. return typeof obj === "undefined" ? "undefined" : _typeof(obj);
  160. }
  161. }
  162. // Safe object type checking
  163. function is(type, obj) {
  164. return objectType(obj) === type;
  165. }
  166. // Based on Java's String.hashCode, a simple but not
  167. // rigorously collision resistant hashing function
  168. function generateHash(module, testName) {
  169. var str = module + "\x1C" + testName;
  170. var hash = 0;
  171. for (var i = 0; i < str.length; i++) {
  172. hash = (hash << 5) - hash + str.charCodeAt(i);
  173. hash |= 0;
  174. }
  175. // Convert the possibly negative integer hash code into an 8 character hex string, which isn't
  176. // strictly necessary but increases user understanding that the id is a SHA-like hash
  177. var hex = (0x100000000 + hash).toString(16);
  178. if (hex.length < 8) {
  179. hex = "0000000" + hex;
  180. }
  181. return hex.slice(-8);
  182. }
  183. // Test for equality any JavaScript type.
  184. // Authors: Philippe Rathé <prathe@gmail.com>, David Chan <david@troi.org>
  185. var equiv = (function () {
  186. // Value pairs queued for comparison. Used for breadth-first processing order, recursion
  187. // detection and avoiding repeated comparison (see below for details).
  188. // Elements are { a: val, b: val }.
  189. var pairs = [];
  190. var getProto = Object.getPrototypeOf || function (obj) {
  191. return obj.__proto__;
  192. };
  193. function useStrictEquality(a, b) {
  194. // This only gets called if a and b are not strict equal, and is used to compare on
  195. // the primitive values inside object wrappers. For example:
  196. // `var i = 1;`
  197. // `var j = new Number(1);`
  198. // Neither a nor b can be null, as a !== b and they have the same type.
  199. if ((typeof a === "undefined" ? "undefined" : _typeof(a)) === "object") {
  200. a = a.valueOf();
  201. }
  202. if ((typeof b === "undefined" ? "undefined" : _typeof(b)) === "object") {
  203. b = b.valueOf();
  204. }
  205. return a === b;
  206. }
  207. function compareConstructors(a, b) {
  208. var protoA = getProto(a);
  209. var protoB = getProto(b);
  210. // Comparing constructors is more strict than using `instanceof`
  211. if (a.constructor === b.constructor) {
  212. return true;
  213. }
  214. // Ref #851
  215. // If the obj prototype descends from a null constructor, treat it
  216. // as a null prototype.
  217. if (protoA && protoA.constructor === null) {
  218. protoA = null;
  219. }
  220. if (protoB && protoB.constructor === null) {
  221. protoB = null;
  222. }
  223. // Allow objects with no prototype to be equivalent to
  224. // objects with Object as their constructor.
  225. if (protoA === null && protoB === Object.prototype || protoB === null && protoA === Object.prototype) {
  226. return true;
  227. }
  228. return false;
  229. }
  230. function getRegExpFlags(regexp) {
  231. return "flags" in regexp ? regexp.flags : regexp.toString().match(/[gimuy]*$/)[0];
  232. }
  233. function isContainer(val) {
  234. return ["object", "array", "map", "set"].indexOf(objectType(val)) !== -1;
  235. }
  236. function breadthFirstCompareChild(a, b) {
  237. // If a is a container not reference-equal to b, postpone the comparison to the
  238. // end of the pairs queue -- unless (a, b) has been seen before, in which case skip
  239. // over the pair.
  240. if (a === b) {
  241. return true;
  242. }
  243. if (!isContainer(a)) {
  244. return typeEquiv(a, b);
  245. }
  246. if (pairs.every(function (pair) {
  247. return pair.a !== a || pair.b !== b;
  248. })) {
  249. // Not yet started comparing this pair
  250. pairs.push({ a: a, b: b });
  251. }
  252. return true;
  253. }
  254. var callbacks = {
  255. "string": useStrictEquality,
  256. "boolean": useStrictEquality,
  257. "number": useStrictEquality,
  258. "null": useStrictEquality,
  259. "undefined": useStrictEquality,
  260. "symbol": useStrictEquality,
  261. "date": useStrictEquality,
  262. "nan": function nan() {
  263. return true;
  264. },
  265. "regexp": function regexp(a, b) {
  266. return a.source === b.source &&
  267. // Include flags in the comparison
  268. getRegExpFlags(a) === getRegExpFlags(b);
  269. },
  270. // abort (identical references / instance methods were skipped earlier)
  271. "function": function _function() {
  272. return false;
  273. },
  274. "array": function array(a, b) {
  275. var i, len;
  276. len = a.length;
  277. if (len !== b.length) {
  278. // Safe and faster
  279. return false;
  280. }
  281. for (i = 0; i < len; i++) {
  282. // Compare non-containers; queue non-reference-equal containers
  283. if (!breadthFirstCompareChild(a[i], b[i])) {
  284. return false;
  285. }
  286. }
  287. return true;
  288. },
  289. // Define sets a and b to be equivalent if for each element aVal in a, there
  290. // is some element bVal in b such that aVal and bVal are equivalent. Element
  291. // repetitions are not counted, so these are equivalent:
  292. // a = new Set( [ {}, [], [] ] );
  293. // b = new Set( [ {}, {}, [] ] );
  294. "set": function set$$1(a, b) {
  295. var innerEq,
  296. outerEq = true;
  297. if (a.size !== b.size) {
  298. // This optimization has certain quirks because of the lack of
  299. // repetition counting. For instance, adding the same
  300. // (reference-identical) element to two equivalent sets can
  301. // make them non-equivalent.
  302. return false;
  303. }
  304. a.forEach(function (aVal) {
  305. // Short-circuit if the result is already known. (Using for...of
  306. // with a break clause would be cleaner here, but it would cause
  307. // a syntax error on older Javascript implementations even if
  308. // Set is unused)
  309. if (!outerEq) {
  310. return;
  311. }
  312. innerEq = false;
  313. b.forEach(function (bVal) {
  314. var parentPairs;
  315. // Likewise, short-circuit if the result is already known
  316. if (innerEq) {
  317. return;
  318. }
  319. // Swap out the global pairs list, as the nested call to
  320. // innerEquiv will clobber its contents
  321. parentPairs = pairs;
  322. if (innerEquiv(bVal, aVal)) {
  323. innerEq = true;
  324. }
  325. // Replace the global pairs list
  326. pairs = parentPairs;
  327. });
  328. if (!innerEq) {
  329. outerEq = false;
  330. }
  331. });
  332. return outerEq;
  333. },
  334. // Define maps a and b to be equivalent if for each key-value pair (aKey, aVal)
  335. // in a, there is some key-value pair (bKey, bVal) in b such that
  336. // [ aKey, aVal ] and [ bKey, bVal ] are equivalent. Key repetitions are not
  337. // counted, so these are equivalent:
  338. // a = new Map( [ [ {}, 1 ], [ {}, 1 ], [ [], 1 ] ] );
  339. // b = new Map( [ [ {}, 1 ], [ [], 1 ], [ [], 1 ] ] );
  340. "map": function map(a, b) {
  341. var innerEq,
  342. outerEq = true;
  343. if (a.size !== b.size) {
  344. // This optimization has certain quirks because of the lack of
  345. // repetition counting. For instance, adding the same
  346. // (reference-identical) key-value pair to two equivalent maps
  347. // can make them non-equivalent.
  348. return false;
  349. }
  350. a.forEach(function (aVal, aKey) {
  351. // Short-circuit if the result is already known. (Using for...of
  352. // with a break clause would be cleaner here, but it would cause
  353. // a syntax error on older Javascript implementations even if
  354. // Map is unused)
  355. if (!outerEq) {
  356. return;
  357. }
  358. innerEq = false;
  359. b.forEach(function (bVal, bKey) {
  360. var parentPairs;
  361. // Likewise, short-circuit if the result is already known
  362. if (innerEq) {
  363. return;
  364. }
  365. // Swap out the global pairs list, as the nested call to
  366. // innerEquiv will clobber its contents
  367. parentPairs = pairs;
  368. if (innerEquiv([bVal, bKey], [aVal, aKey])) {
  369. innerEq = true;
  370. }
  371. // Replace the global pairs list
  372. pairs = parentPairs;
  373. });
  374. if (!innerEq) {
  375. outerEq = false;
  376. }
  377. });
  378. return outerEq;
  379. },
  380. "object": function object(a, b) {
  381. var i,
  382. aProperties = [],
  383. bProperties = [];
  384. if (compareConstructors(a, b) === false) {
  385. return false;
  386. }
  387. // Be strict: don't ensure hasOwnProperty and go deep
  388. for (i in a) {
  389. // Collect a's properties
  390. aProperties.push(i);
  391. // Skip OOP methods that look the same
  392. if (a.constructor !== Object && typeof a.constructor !== "undefined" && typeof a[i] === "function" && typeof b[i] === "function" && a[i].toString() === b[i].toString()) {
  393. continue;
  394. }
  395. // Compare non-containers; queue non-reference-equal containers
  396. if (!breadthFirstCompareChild(a[i], b[i])) {
  397. return false;
  398. }
  399. }
  400. for (i in b) {
  401. // Collect b's properties
  402. bProperties.push(i);
  403. }
  404. // Ensures identical properties name
  405. return typeEquiv(aProperties.sort(), bProperties.sort());
  406. }
  407. };
  408. function typeEquiv(a, b) {
  409. var type = objectType(a);
  410. // Callbacks for containers will append to the pairs queue to achieve breadth-first
  411. // search order. The pairs queue is also used to avoid reprocessing any pair of
  412. // containers that are reference-equal to a previously visited pair (a special case
  413. // this being recursion detection).
  414. //
  415. // Because of this approach, once typeEquiv returns a false value, it should not be
  416. // called again without clearing the pair queue else it may wrongly report a visited
  417. // pair as being equivalent.
  418. return objectType(b) === type && callbacks[type](a, b);
  419. }
  420. function innerEquiv(a, b) {
  421. var i, pair;
  422. // We're done when there's nothing more to compare
  423. if (arguments.length < 2) {
  424. return true;
  425. }
  426. // Clear the global pair queue and add the top-level values being compared
  427. pairs = [{ a: a, b: b }];
  428. for (i = 0; i < pairs.length; i++) {
  429. pair = pairs[i];
  430. // Perform type-specific comparison on any pairs that are not strictly
  431. // equal. For container types, that comparison will postpone comparison
  432. // of any sub-container pair to the end of the pair queue. This gives
  433. // breadth-first search order. It also avoids the reprocessing of
  434. // reference-equal siblings, cousins etc, which can have a significant speed
  435. // impact when comparing a container of small objects each of which has a
  436. // reference to the same (singleton) large object.
  437. if (pair.a !== pair.b && !typeEquiv(pair.a, pair.b)) {
  438. return false;
  439. }
  440. }
  441. // ...across all consecutive argument pairs
  442. return arguments.length === 2 || innerEquiv.apply(this, [].slice.call(arguments, 1));
  443. }
  444. return function () {
  445. var result = innerEquiv.apply(undefined, arguments);
  446. // Release any retained objects
  447. pairs.length = 0;
  448. return result;
  449. };
  450. })();
  451. /**
  452. * Config object: Maintain internal state
  453. * Later exposed as QUnit.config
  454. * `config` initialized at top of scope
  455. */
  456. var config = {
  457. // The queue of tests to run
  458. queue: [],
  459. // Block until document ready
  460. blocking: true,
  461. // By default, run previously failed tests first
  462. // very useful in combination with "Hide passed tests" checked
  463. reorder: true,
  464. // By default, modify document.title when suite is done
  465. altertitle: true,
  466. // HTML Reporter: collapse every test except the first failing test
  467. // If false, all failing tests will be expanded
  468. collapse: true,
  469. // By default, scroll to top of the page when suite is done
  470. scrolltop: true,
  471. // Depth up-to which object will be dumped
  472. maxDepth: 5,
  473. // When enabled, all tests must call expect()
  474. requireExpects: false,
  475. // Placeholder for user-configurable form-exposed URL parameters
  476. urlConfig: [],
  477. // Set of all modules.
  478. modules: [],
  479. // The first unnamed module
  480. currentModule: {
  481. name: "",
  482. tests: [],
  483. childModules: [],
  484. testsRun: 0,
  485. unskippedTestsRun: 0,
  486. hooks: {
  487. before: [],
  488. beforeEach: [],
  489. afterEach: [],
  490. after: []
  491. }
  492. },
  493. callbacks: {},
  494. // The storage module to use for reordering tests
  495. storage: localSessionStorage
  496. };
  497. // take a predefined QUnit.config and extend the defaults
  498. var globalConfig = window && window.QUnit && window.QUnit.config;
  499. // only extend the global config if there is no QUnit overload
  500. if (window && window.QUnit && !window.QUnit.version) {
  501. extend(config, globalConfig);
  502. }
  503. // Push a loose unnamed module to the modules collection
  504. config.modules.push(config.currentModule);
  505. // Based on jsDump by Ariel Flesler
  506. // http://flesler.blogspot.com/2008/05/jsdump-pretty-dump-of-any-javascript.html
  507. var dump = (function () {
  508. function quote(str) {
  509. return "\"" + str.toString().replace(/\\/g, "\\\\").replace(/"/g, "\\\"") + "\"";
  510. }
  511. function literal(o) {
  512. return o + "";
  513. }
  514. function join(pre, arr, post) {
  515. var s = dump.separator(),
  516. base = dump.indent(),
  517. inner = dump.indent(1);
  518. if (arr.join) {
  519. arr = arr.join("," + s + inner);
  520. }
  521. if (!arr) {
  522. return pre + post;
  523. }
  524. return [pre, inner + arr, base + post].join(s);
  525. }
  526. function array(arr, stack) {
  527. var i = arr.length,
  528. ret = new Array(i);
  529. if (dump.maxDepth && dump.depth > dump.maxDepth) {
  530. return "[object Array]";
  531. }
  532. this.up();
  533. while (i--) {
  534. ret[i] = this.parse(arr[i], undefined, stack);
  535. }
  536. this.down();
  537. return join("[", ret, "]");
  538. }
  539. function isArray(obj) {
  540. return (
  541. //Native Arrays
  542. toString.call(obj) === "[object Array]" ||
  543. // NodeList objects
  544. typeof obj.length === "number" && obj.item !== undefined && (obj.length ? obj.item(0) === obj[0] : obj.item(0) === null && obj[0] === undefined)
  545. );
  546. }
  547. var reName = /^function (\w+)/,
  548. dump = {
  549. // The objType is used mostly internally, you can fix a (custom) type in advance
  550. parse: function parse(obj, objType, stack) {
  551. stack = stack || [];
  552. var res,
  553. parser,
  554. parserType,
  555. objIndex = stack.indexOf(obj);
  556. if (objIndex !== -1) {
  557. return "recursion(" + (objIndex - stack.length) + ")";
  558. }
  559. objType = objType || this.typeOf(obj);
  560. parser = this.parsers[objType];
  561. parserType = typeof parser === "undefined" ? "undefined" : _typeof(parser);
  562. if (parserType === "function") {
  563. stack.push(obj);
  564. res = parser.call(this, obj, stack);
  565. stack.pop();
  566. return res;
  567. }
  568. return parserType === "string" ? parser : this.parsers.error;
  569. },
  570. typeOf: function typeOf(obj) {
  571. var type;
  572. if (obj === null) {
  573. type = "null";
  574. } else if (typeof obj === "undefined") {
  575. type = "undefined";
  576. } else if (is("regexp", obj)) {
  577. type = "regexp";
  578. } else if (is("date", obj)) {
  579. type = "date";
  580. } else if (is("function", obj)) {
  581. type = "function";
  582. } else if (obj.setInterval !== undefined && obj.document !== undefined && obj.nodeType === undefined) {
  583. type = "window";
  584. } else if (obj.nodeType === 9) {
  585. type = "document";
  586. } else if (obj.nodeType) {
  587. type = "node";
  588. } else if (isArray(obj)) {
  589. type = "array";
  590. } else if (obj.constructor === Error.prototype.constructor) {
  591. type = "error";
  592. } else {
  593. type = typeof obj === "undefined" ? "undefined" : _typeof(obj);
  594. }
  595. return type;
  596. },
  597. separator: function separator() {
  598. if (this.multiline) {
  599. return this.HTML ? "<br />" : "\n";
  600. } else {
  601. return this.HTML ? "&#160;" : " ";
  602. }
  603. },
  604. // Extra can be a number, shortcut for increasing-calling-decreasing
  605. indent: function indent(extra) {
  606. if (!this.multiline) {
  607. return "";
  608. }
  609. var chr = this.indentChar;
  610. if (this.HTML) {
  611. chr = chr.replace(/\t/g, " ").replace(/ /g, "&#160;");
  612. }
  613. return new Array(this.depth + (extra || 0)).join(chr);
  614. },
  615. up: function up(a) {
  616. this.depth += a || 1;
  617. },
  618. down: function down(a) {
  619. this.depth -= a || 1;
  620. },
  621. setParser: function setParser(name, parser) {
  622. this.parsers[name] = parser;
  623. },
  624. // The next 3 are exposed so you can use them
  625. quote: quote,
  626. literal: literal,
  627. join: join,
  628. depth: 1,
  629. maxDepth: config.maxDepth,
  630. // This is the list of parsers, to modify them, use dump.setParser
  631. parsers: {
  632. window: "[Window]",
  633. document: "[Document]",
  634. error: function error(_error) {
  635. return "Error(\"" + _error.message + "\")";
  636. },
  637. unknown: "[Unknown]",
  638. "null": "null",
  639. "undefined": "undefined",
  640. "function": function _function(fn) {
  641. var ret = "function",
  642. // Functions never have name in IE
  643. name = "name" in fn ? fn.name : (reName.exec(fn) || [])[1];
  644. if (name) {
  645. ret += " " + name;
  646. }
  647. ret += "(";
  648. ret = [ret, dump.parse(fn, "functionArgs"), "){"].join("");
  649. return join(ret, dump.parse(fn, "functionCode"), "}");
  650. },
  651. array: array,
  652. nodelist: array,
  653. "arguments": array,
  654. object: function object(map, stack) {
  655. var keys,
  656. key,
  657. val,
  658. i,
  659. nonEnumerableProperties,
  660. ret = [];
  661. if (dump.maxDepth && dump.depth > dump.maxDepth) {
  662. return "[object Object]";
  663. }
  664. dump.up();
  665. keys = [];
  666. for (key in map) {
  667. keys.push(key);
  668. }
  669. // Some properties are not always enumerable on Error objects.
  670. nonEnumerableProperties = ["message", "name"];
  671. for (i in nonEnumerableProperties) {
  672. key = nonEnumerableProperties[i];
  673. if (key in map && !inArray(key, keys)) {
  674. keys.push(key);
  675. }
  676. }
  677. keys.sort();
  678. for (i = 0; i < keys.length; i++) {
  679. key = keys[i];
  680. val = map[key];
  681. ret.push(dump.parse(key, "key") + ": " + dump.parse(val, undefined, stack));
  682. }
  683. dump.down();
  684. return join("{", ret, "}");
  685. },
  686. node: function node(_node) {
  687. var len,
  688. i,
  689. val,
  690. open = dump.HTML ? "&lt;" : "<",
  691. close = dump.HTML ? "&gt;" : ">",
  692. tag = _node.nodeName.toLowerCase(),
  693. ret = open + tag,
  694. attrs = _node.attributes;
  695. if (attrs) {
  696. for (i = 0, len = attrs.length; i < len; i++) {
  697. val = attrs[i].nodeValue;
  698. // IE6 includes all attributes in .attributes, even ones not explicitly
  699. // set. Those have values like undefined, null, 0, false, "" or
  700. // "inherit".
  701. if (val && val !== "inherit") {
  702. ret += " " + attrs[i].nodeName + "=" + dump.parse(val, "attribute");
  703. }
  704. }
  705. }
  706. ret += close;
  707. // Show content of TextNode or CDATASection
  708. if (_node.nodeType === 3 || _node.nodeType === 4) {
  709. ret += _node.nodeValue;
  710. }
  711. return ret + open + "/" + tag + close;
  712. },
  713. // Function calls it internally, it's the arguments part of the function
  714. functionArgs: function functionArgs(fn) {
  715. var args,
  716. l = fn.length;
  717. if (!l) {
  718. return "";
  719. }
  720. args = new Array(l);
  721. while (l--) {
  722. // 97 is 'a'
  723. args[l] = String.fromCharCode(97 + l);
  724. }
  725. return " " + args.join(", ") + " ";
  726. },
  727. // Object calls it internally, the key part of an item in a map
  728. key: quote,
  729. // Function calls it internally, it's the content of the function
  730. functionCode: "[code]",
  731. // Node calls it internally, it's a html attribute value
  732. attribute: quote,
  733. string: quote,
  734. date: quote,
  735. regexp: literal,
  736. number: literal,
  737. "boolean": literal,
  738. symbol: function symbol(sym) {
  739. return sym.toString();
  740. }
  741. },
  742. // If true, entities are escaped ( <, >, \t, space and \n )
  743. HTML: false,
  744. // Indentation unit
  745. indentChar: " ",
  746. // If true, items in a collection, are separated by a \n, else just a space.
  747. multiline: true
  748. };
  749. return dump;
  750. })();
  751. var LISTENERS = Object.create(null);
  752. var SUPPORTED_EVENTS = ["runStart", "suiteStart", "testStart", "assertion", "testEnd", "suiteEnd", "runEnd"];
  753. /**
  754. * Emits an event with the specified data to all currently registered listeners.
  755. * Callbacks will fire in the order in which they are registered (FIFO). This
  756. * function is not exposed publicly; it is used by QUnit internals to emit
  757. * logging events.
  758. *
  759. * @private
  760. * @method emit
  761. * @param {String} eventName
  762. * @param {Object} data
  763. * @return {Void}
  764. */
  765. function emit(eventName, data) {
  766. if (objectType(eventName) !== "string") {
  767. throw new TypeError("eventName must be a string when emitting an event");
  768. }
  769. // Clone the callbacks in case one of them registers a new callback
  770. var originalCallbacks = LISTENERS[eventName];
  771. var callbacks = originalCallbacks ? [].concat(toConsumableArray(originalCallbacks)) : [];
  772. for (var i = 0; i < callbacks.length; i++) {
  773. callbacks[i](data);
  774. }
  775. }
  776. /**
  777. * Registers a callback as a listener to the specified event.
  778. *
  779. * @public
  780. * @method on
  781. * @param {String} eventName
  782. * @param {Function} callback
  783. * @return {Void}
  784. */
  785. function on(eventName, callback) {
  786. if (objectType(eventName) !== "string") {
  787. throw new TypeError("eventName must be a string when registering a listener");
  788. } else if (!inArray(eventName, SUPPORTED_EVENTS)) {
  789. var events = SUPPORTED_EVENTS.join(", ");
  790. throw new Error("\"" + eventName + "\" is not a valid event; must be one of: " + events + ".");
  791. } else if (objectType(callback) !== "function") {
  792. throw new TypeError("callback must be a function when registering a listener");
  793. }
  794. if (!LISTENERS[eventName]) {
  795. LISTENERS[eventName] = [];
  796. }
  797. // Don't register the same callback more than once
  798. if (!inArray(callback, LISTENERS[eventName])) {
  799. LISTENERS[eventName].push(callback);
  800. }
  801. }
  802. // Register logging callbacks
  803. function registerLoggingCallbacks(obj) {
  804. var i,
  805. l,
  806. key,
  807. callbackNames = ["begin", "done", "log", "testStart", "testDone", "moduleStart", "moduleDone"];
  808. function registerLoggingCallback(key) {
  809. var loggingCallback = function loggingCallback(callback) {
  810. if (objectType(callback) !== "function") {
  811. throw new Error("QUnit logging methods require a callback function as their first parameters.");
  812. }
  813. config.callbacks[key].push(callback);
  814. };
  815. return loggingCallback;
  816. }
  817. for (i = 0, l = callbackNames.length; i < l; i++) {
  818. key = callbackNames[i];
  819. // Initialize key collection of logging callback
  820. if (objectType(config.callbacks[key]) === "undefined") {
  821. config.callbacks[key] = [];
  822. }
  823. obj[key] = registerLoggingCallback(key);
  824. }
  825. }
  826. function runLoggingCallbacks(key, args) {
  827. var i, l, callbacks;
  828. callbacks = config.callbacks[key];
  829. for (i = 0, l = callbacks.length; i < l; i++) {
  830. callbacks[i](args);
  831. }
  832. }
  833. // Doesn't support IE9, it will return undefined on these browsers
  834. // See also https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Error/Stack
  835. var fileName = (sourceFromStacktrace(0) || "").replace(/(:\d+)+\)?/, "").replace(/.+\//, "");
  836. function extractStacktrace(e, offset) {
  837. offset = offset === undefined ? 4 : offset;
  838. var stack, include, i;
  839. if (e && e.stack) {
  840. stack = e.stack.split("\n");
  841. if (/^error$/i.test(stack[0])) {
  842. stack.shift();
  843. }
  844. if (fileName) {
  845. include = [];
  846. for (i = offset; i < stack.length; i++) {
  847. if (stack[i].indexOf(fileName) !== -1) {
  848. break;
  849. }
  850. include.push(stack[i]);
  851. }
  852. if (include.length) {
  853. return include.join("\n");
  854. }
  855. }
  856. return stack[offset];
  857. }
  858. }
  859. function sourceFromStacktrace(offset) {
  860. var error = new Error();
  861. // Support: Safari <=7 only, IE <=10 - 11 only
  862. // Not all browsers generate the `stack` property for `new Error()`, see also #636
  863. if (!error.stack) {
  864. try {
  865. throw error;
  866. } catch (err) {
  867. error = err;
  868. }
  869. }
  870. return extractStacktrace(error, offset);
  871. }
  872. var priorityCount = 0;
  873. var unitSampler = void 0;
  874. /**
  875. * Advances the ProcessingQueue to the next item if it is ready.
  876. * @param {Boolean} last
  877. */
  878. function advance() {
  879. var start = now();
  880. config.depth = (config.depth || 0) + 1;
  881. while (config.queue.length && !config.blocking) {
  882. var elapsedTime = now() - start;
  883. if (!defined.setTimeout || config.updateRate <= 0 || elapsedTime < config.updateRate) {
  884. if (priorityCount > 0) {
  885. priorityCount--;
  886. }
  887. config.queue.shift()();
  888. } else {
  889. setTimeout(advance, 13);
  890. break;
  891. }
  892. }
  893. config.depth--;
  894. if (!config.blocking && !config.queue.length && config.depth === 0) {
  895. done();
  896. }
  897. }
  898. function addToQueueImmediate(callback) {
  899. if (objectType(callback) === "array") {
  900. while (callback.length) {
  901. addToQueueImmediate(callback.pop());
  902. }
  903. return;
  904. }
  905. config.queue.unshift(callback);
  906. priorityCount++;
  907. }
  908. /**
  909. * Adds a function to the ProcessingQueue for execution.
  910. * @param {Function|Array} callback
  911. * @param {Boolean} priority
  912. * @param {String} seed
  913. */
  914. function addToQueue(callback, prioritize, seed) {
  915. if (prioritize) {
  916. config.queue.splice(priorityCount++, 0, callback);
  917. } else if (seed) {
  918. if (!unitSampler) {
  919. unitSampler = unitSamplerGenerator(seed);
  920. }
  921. // Insert into a random position after all prioritized items
  922. var index = Math.floor(unitSampler() * (config.queue.length - priorityCount + 1));
  923. config.queue.splice(priorityCount + index, 0, callback);
  924. } else {
  925. config.queue.push(callback);
  926. }
  927. }
  928. /**
  929. * Creates a seeded "sample" generator which is used for randomizing tests.
  930. */
  931. function unitSamplerGenerator(seed) {
  932. // 32-bit xorshift, requires only a nonzero seed
  933. // http://excamera.com/sphinx/article-xorshift.html
  934. var sample = parseInt(generateHash(seed), 16) || -1;
  935. return function () {
  936. sample ^= sample << 13;
  937. sample ^= sample >>> 17;
  938. sample ^= sample << 5;
  939. // ECMAScript has no unsigned number type
  940. if (sample < 0) {
  941. sample += 0x100000000;
  942. }
  943. return sample / 0x100000000;
  944. };
  945. }
  946. /**
  947. * This function is called when the ProcessingQueue is done processing all
  948. * items. It handles emitting the final run events.
  949. */
  950. function done() {
  951. var storage = config.storage;
  952. ProcessingQueue.finished = true;
  953. var runtime = now() - config.started;
  954. var passed = config.stats.all - config.stats.bad;
  955. emit("runEnd", globalSuite.end(true));
  956. runLoggingCallbacks("done", {
  957. passed: passed,
  958. failed: config.stats.bad,
  959. total: config.stats.all,
  960. runtime: runtime
  961. });
  962. // Clear own storage items if all tests passed
  963. if (storage && config.stats.bad === 0) {
  964. for (var i = storage.length - 1; i >= 0; i--) {
  965. var key = storage.key(i);
  966. if (key.indexOf("qunit-test-") === 0) {
  967. storage.removeItem(key);
  968. }
  969. }
  970. }
  971. }
  972. var ProcessingQueue = {
  973. finished: false,
  974. add: addToQueue,
  975. addImmediate: addToQueueImmediate,
  976. advance: advance
  977. };
  978. var TestReport = function () {
  979. function TestReport(name, suite, options) {
  980. classCallCheck(this, TestReport);
  981. this.name = name;
  982. this.suiteName = suite.name;
  983. this.fullName = suite.fullName.concat(name);
  984. this.runtime = 0;
  985. this.assertions = [];
  986. this.skipped = !!options.skip;
  987. this.todo = !!options.todo;
  988. this.valid = options.valid;
  989. this._startTime = 0;
  990. this._endTime = 0;
  991. suite.pushTest(this);
  992. }
  993. createClass(TestReport, [{
  994. key: "start",
  995. value: function start(recordTime) {
  996. if (recordTime) {
  997. this._startTime = Date.now();
  998. }
  999. return {
  1000. name: this.name,
  1001. suiteName: this.suiteName,
  1002. fullName: this.fullName.slice()
  1003. };
  1004. }
  1005. }, {
  1006. key: "end",
  1007. value: function end(recordTime) {
  1008. if (recordTime) {
  1009. this._endTime = Date.now();
  1010. }
  1011. return extend(this.start(), {
  1012. runtime: this.getRuntime(),
  1013. status: this.getStatus(),
  1014. errors: this.getFailedAssertions(),
  1015. assertions: this.getAssertions()
  1016. });
  1017. }
  1018. }, {
  1019. key: "pushAssertion",
  1020. value: function pushAssertion(assertion) {
  1021. this.assertions.push(assertion);
  1022. }
  1023. }, {
  1024. key: "getRuntime",
  1025. value: function getRuntime() {
  1026. return this._endTime - this._startTime;
  1027. }
  1028. }, {
  1029. key: "getStatus",
  1030. value: function getStatus() {
  1031. if (this.skipped) {
  1032. return "skipped";
  1033. }
  1034. var testPassed = this.getFailedAssertions().length > 0 ? this.todo : !this.todo;
  1035. if (!testPassed) {
  1036. return "failed";
  1037. } else if (this.todo) {
  1038. return "todo";
  1039. } else {
  1040. return "passed";
  1041. }
  1042. }
  1043. }, {
  1044. key: "getFailedAssertions",
  1045. value: function getFailedAssertions() {
  1046. return this.assertions.filter(function (assertion) {
  1047. return !assertion.passed;
  1048. });
  1049. }
  1050. }, {
  1051. key: "getAssertions",
  1052. value: function getAssertions() {
  1053. return this.assertions.slice();
  1054. }
  1055. // Remove actual and expected values from assertions. This is to prevent
  1056. // leaking memory throughout a test suite.
  1057. }, {
  1058. key: "slimAssertions",
  1059. value: function slimAssertions() {
  1060. this.assertions = this.assertions.map(function (assertion) {
  1061. delete assertion.actual;
  1062. delete assertion.expected;
  1063. return assertion;
  1064. });
  1065. }
  1066. }]);
  1067. return TestReport;
  1068. }();
  1069. var focused$1 = false;
  1070. function Test(settings) {
  1071. var i, l;
  1072. ++Test.count;
  1073. this.expected = null;
  1074. this.assertions = [];
  1075. this.semaphore = 0;
  1076. this.module = config.currentModule;
  1077. this.stack = sourceFromStacktrace(3);
  1078. this.steps = [];
  1079. this.timeout = undefined;
  1080. // If a module is skipped, all its tests and the tests of the child suites
  1081. // should be treated as skipped even if they are defined as `only` or `todo`.
  1082. // As for `todo` module, all its tests will be treated as `todo` except for
  1083. // tests defined as `skip` which will be left intact.
  1084. //
  1085. // So, if a test is defined as `todo` and is inside a skipped module, we should
  1086. // then treat that test as if was defined as `skip`.
  1087. if (this.module.skip) {
  1088. settings.skip = true;
  1089. settings.todo = false;
  1090. // Skipped tests should be left intact
  1091. } else if (this.module.todo && !settings.skip) {
  1092. settings.todo = true;
  1093. }
  1094. extend(this, settings);
  1095. this.testReport = new TestReport(settings.testName, this.module.suiteReport, {
  1096. todo: settings.todo,
  1097. skip: settings.skip,
  1098. valid: this.valid()
  1099. });
  1100. // Register unique strings
  1101. for (i = 0, l = this.module.tests; i < l.length; i++) {
  1102. if (this.module.tests[i].name === this.testName) {
  1103. this.testName += " ";
  1104. }
  1105. }
  1106. this.testId = generateHash(this.module.name, this.testName);
  1107. this.module.tests.push({
  1108. name: this.testName,
  1109. testId: this.testId,
  1110. skip: !!settings.skip
  1111. });
  1112. if (settings.skip) {
  1113. // Skipped tests will fully ignore any sent callback
  1114. this.callback = function () {};
  1115. this.async = false;
  1116. this.expected = 0;
  1117. } else {
  1118. if (typeof this.callback !== "function") {
  1119. var method = this.todo ? "todo" : "test";
  1120. // eslint-disable-next-line max-len
  1121. throw new TypeError("You must provide a function as a test callback to QUnit." + method + "(\"" + settings.testName + "\")");
  1122. }
  1123. this.assert = new Assert(this);
  1124. }
  1125. }
  1126. Test.count = 0;
  1127. function getNotStartedModules(startModule) {
  1128. var module = startModule,
  1129. modules = [];
  1130. while (module && module.testsRun === 0) {
  1131. modules.push(module);
  1132. module = module.parentModule;
  1133. }
  1134. return modules;
  1135. }
  1136. Test.prototype = {
  1137. before: function before() {
  1138. var i,
  1139. startModule,
  1140. module = this.module,
  1141. notStartedModules = getNotStartedModules(module);
  1142. for (i = notStartedModules.length - 1; i >= 0; i--) {
  1143. startModule = notStartedModules[i];
  1144. startModule.stats = { all: 0, bad: 0, started: now() };
  1145. emit("suiteStart", startModule.suiteReport.start(true));
  1146. runLoggingCallbacks("moduleStart", {
  1147. name: startModule.name,
  1148. tests: startModule.tests
  1149. });
  1150. }
  1151. config.current = this;
  1152. this.testEnvironment = extend({}, module.testEnvironment);
  1153. this.started = now();
  1154. emit("testStart", this.testReport.start(true));
  1155. runLoggingCallbacks("testStart", {
  1156. name: this.testName,
  1157. module: module.name,
  1158. testId: this.testId,
  1159. previousFailure: this.previousFailure
  1160. });
  1161. if (!config.pollution) {
  1162. saveGlobal();
  1163. }
  1164. },
  1165. run: function run() {
  1166. var promise;
  1167. config.current = this;
  1168. this.callbackStarted = now();
  1169. if (config.notrycatch) {
  1170. runTest(this);
  1171. return;
  1172. }
  1173. try {
  1174. runTest(this);
  1175. } catch (e) {
  1176. this.pushFailure("Died on test #" + (this.assertions.length + 1) + " " + this.stack + ": " + (e.message || e), extractStacktrace(e, 0));
  1177. // Else next test will carry the responsibility
  1178. saveGlobal();
  1179. // Restart the tests if they're blocking
  1180. if (config.blocking) {
  1181. internalRecover(this);
  1182. }
  1183. }
  1184. function runTest(test) {
  1185. promise = test.callback.call(test.testEnvironment, test.assert);
  1186. test.resolvePromise(promise);
  1187. // If the test has a "lock" on it, but the timeout is 0, then we push a
  1188. // failure as the test should be synchronous.
  1189. if (test.timeout === 0 && test.semaphore !== 0) {
  1190. pushFailure("Test did not finish synchronously even though assert.timeout( 0 ) was used.", sourceFromStacktrace(2));
  1191. }
  1192. }
  1193. },
  1194. after: function after() {
  1195. checkPollution();
  1196. },
  1197. queueHook: function queueHook(hook, hookName, hookOwner) {
  1198. var _this = this;
  1199. var callHook = function callHook() {
  1200. var promise = hook.call(_this.testEnvironment, _this.assert);
  1201. _this.resolvePromise(promise, hookName);
  1202. };
  1203. var runHook = function runHook() {
  1204. if (hookName === "before") {
  1205. if (hookOwner.unskippedTestsRun !== 0) {
  1206. return;
  1207. }
  1208. _this.preserveEnvironment = true;
  1209. }
  1210. if (hookName === "after" && hookOwner.unskippedTestsRun !== numberOfUnskippedTests(hookOwner) - 1 && config.queue.length > 2) {
  1211. return;
  1212. }
  1213. config.current = _this;
  1214. if (config.notrycatch) {
  1215. callHook();
  1216. return;
  1217. }
  1218. try {
  1219. callHook();
  1220. } catch (error) {
  1221. _this.pushFailure(hookName + " failed on " + _this.testName + ": " + (error.message || error), extractStacktrace(error, 0));
  1222. }
  1223. };
  1224. return runHook;
  1225. },
  1226. // Currently only used for module level hooks, can be used to add global level ones
  1227. hooks: function hooks(handler) {
  1228. var hooks = [];
  1229. function processHooks(test, module) {
  1230. if (module.parentModule) {
  1231. processHooks(test, module.parentModule);
  1232. }
  1233. if (module.hooks[handler].length) {
  1234. for (var i = 0; i < module.hooks[handler].length; i++) {
  1235. hooks.push(test.queueHook(module.hooks[handler][i], handler, module));
  1236. }
  1237. }
  1238. }
  1239. // Hooks are ignored on skipped tests
  1240. if (!this.skip) {
  1241. processHooks(this, this.module);
  1242. }
  1243. return hooks;
  1244. },
  1245. finish: function finish() {
  1246. config.current = this;
  1247. if (config.requireExpects && this.expected === null) {
  1248. this.pushFailure("Expected number of assertions to be defined, but expect() was " + "not called.", this.stack);
  1249. } else if (this.expected !== null && this.expected !== this.assertions.length) {
  1250. this.pushFailure("Expected " + this.expected + " assertions, but " + this.assertions.length + " were run", this.stack);
  1251. } else if (this.expected === null && !this.assertions.length) {
  1252. this.pushFailure("Expected at least one assertion, but none were run - call " + "expect(0) to accept zero assertions.", this.stack);
  1253. }
  1254. var i,
  1255. module = this.module,
  1256. moduleName = module.name,
  1257. testName = this.testName,
  1258. skipped = !!this.skip,
  1259. todo = !!this.todo,
  1260. bad = 0,
  1261. storage = config.storage;
  1262. this.runtime = now() - this.started;
  1263. config.stats.all += this.assertions.length;
  1264. module.stats.all += this.assertions.length;
  1265. for (i = 0; i < this.assertions.length; i++) {
  1266. if (!this.assertions[i].result) {
  1267. bad++;
  1268. config.stats.bad++;
  1269. module.stats.bad++;
  1270. }
  1271. }
  1272. notifyTestsRan(module, skipped);
  1273. // Store result when possible
  1274. if (storage) {
  1275. if (bad) {
  1276. storage.setItem("qunit-test-" + moduleName + "-" + testName, bad);
  1277. } else {
  1278. storage.removeItem("qunit-test-" + moduleName + "-" + testName);
  1279. }
  1280. }
  1281. // After emitting the js-reporters event we cleanup the assertion data to
  1282. // avoid leaking it. It is not used by the legacy testDone callbacks.
  1283. emit("testEnd", this.testReport.end(true));
  1284. this.testReport.slimAssertions();
  1285. runLoggingCallbacks("testDone", {
  1286. name: testName,
  1287. module: moduleName,
  1288. skipped: skipped,
  1289. todo: todo,
  1290. failed: bad,
  1291. passed: this.assertions.length - bad,
  1292. total: this.assertions.length,
  1293. runtime: skipped ? 0 : this.runtime,
  1294. // HTML Reporter use
  1295. assertions: this.assertions,
  1296. testId: this.testId,
  1297. // Source of Test
  1298. source: this.stack
  1299. });
  1300. if (module.testsRun === numberOfTests(module)) {
  1301. logSuiteEnd(module);
  1302. // Check if the parent modules, iteratively, are done. If that the case,
  1303. // we emit the `suiteEnd` event and trigger `moduleDone` callback.
  1304. var parent = module.parentModule;
  1305. while (parent && parent.testsRun === numberOfTests(parent)) {
  1306. logSuiteEnd(parent);
  1307. parent = parent.parentModule;
  1308. }
  1309. }
  1310. config.current = undefined;
  1311. function logSuiteEnd(module) {
  1312. emit("suiteEnd", module.suiteReport.end(true));
  1313. runLoggingCallbacks("moduleDone", {
  1314. name: module.name,
  1315. tests: module.tests,
  1316. failed: module.stats.bad,
  1317. passed: module.stats.all - module.stats.bad,
  1318. total: module.stats.all,
  1319. runtime: now() - module.stats.started
  1320. });
  1321. }
  1322. },
  1323. preserveTestEnvironment: function preserveTestEnvironment() {
  1324. if (this.preserveEnvironment) {
  1325. this.module.testEnvironment = this.testEnvironment;
  1326. this.testEnvironment = extend({}, this.module.testEnvironment);
  1327. }
  1328. },
  1329. queue: function queue() {
  1330. var test = this;
  1331. if (!this.valid()) {
  1332. return;
  1333. }
  1334. function runTest() {
  1335. // Each of these can by async
  1336. ProcessingQueue.addImmediate([function () {
  1337. test.before();
  1338. }, test.hooks("before"), function () {
  1339. test.preserveTestEnvironment();
  1340. }, test.hooks("beforeEach"), function () {
  1341. test.run();
  1342. }, test.hooks("afterEach").reverse(), test.hooks("after").reverse(), function () {
  1343. test.after();
  1344. }, function () {
  1345. test.finish();
  1346. }]);
  1347. }
  1348. var previousFailCount = config.storage && +config.storage.getItem("qunit-test-" + this.module.name + "-" + this.testName);
  1349. // Prioritize previously failed tests, detected from storage
  1350. var prioritize = config.reorder && !!previousFailCount;
  1351. this.previousFailure = !!previousFailCount;
  1352. ProcessingQueue.add(runTest, prioritize, config.seed);
  1353. // If the queue has already finished, we manually process the new test
  1354. if (ProcessingQueue.finished) {
  1355. ProcessingQueue.advance();
  1356. }
  1357. },
  1358. pushResult: function pushResult(resultInfo) {
  1359. if (this !== config.current) {
  1360. throw new Error("Assertion occured after test had finished.");
  1361. }
  1362. // Destructure of resultInfo = { result, actual, expected, message, negative }
  1363. var source,
  1364. details = {
  1365. module: this.module.name,
  1366. name: this.testName,
  1367. result: resultInfo.result,
  1368. message: resultInfo.message,
  1369. actual: resultInfo.actual,
  1370. testId: this.testId,
  1371. negative: resultInfo.negative || false,
  1372. runtime: now() - this.started,
  1373. todo: !!this.todo
  1374. };
  1375. if (hasOwn.call(resultInfo, "expected")) {
  1376. details.expected = resultInfo.expected;
  1377. }
  1378. if (!resultInfo.result) {
  1379. source = resultInfo.source || sourceFromStacktrace();
  1380. if (source) {
  1381. details.source = source;
  1382. }
  1383. }
  1384. this.logAssertion(details);
  1385. this.assertions.push({
  1386. result: !!resultInfo.result,
  1387. message: resultInfo.message
  1388. });
  1389. },
  1390. pushFailure: function pushFailure(message, source, actual) {
  1391. if (!(this instanceof Test)) {
  1392. throw new Error("pushFailure() assertion outside test context, was " + sourceFromStacktrace(2));
  1393. }
  1394. this.pushResult({
  1395. result: false,
  1396. message: message || "error",
  1397. actual: actual || null,
  1398. source: source
  1399. });
  1400. },
  1401. /**
  1402. * Log assertion details using both the old QUnit.log interface and
  1403. * QUnit.on( "assertion" ) interface.
  1404. *
  1405. * @private
  1406. */
  1407. logAssertion: function logAssertion(details) {
  1408. runLoggingCallbacks("log", details);
  1409. var assertion = {
  1410. passed: details.result,
  1411. actual: details.actual,
  1412. expected: details.expected,
  1413. message: details.message,
  1414. stack: details.source,
  1415. todo: details.todo
  1416. };
  1417. this.testReport.pushAssertion(assertion);
  1418. emit("assertion", assertion);
  1419. },
  1420. resolvePromise: function resolvePromise(promise, phase) {
  1421. var then,
  1422. resume,
  1423. message,
  1424. test = this;
  1425. if (promise != null) {
  1426. then = promise.then;
  1427. if (objectType(then) === "function") {
  1428. resume = internalStop(test);
  1429. then.call(promise, function () {
  1430. resume();
  1431. }, function (error) {
  1432. message = "Promise rejected " + (!phase ? "during" : phase.replace(/Each$/, "")) + " \"" + test.testName + "\": " + (error && error.message || error);
  1433. test.pushFailure(message, extractStacktrace(error, 0));
  1434. // Else next test will carry the responsibility
  1435. saveGlobal();
  1436. // Unblock
  1437. resume();
  1438. });
  1439. }
  1440. }
  1441. },
  1442. valid: function valid() {
  1443. var filter = config.filter,
  1444. regexFilter = /^(!?)\/([\w\W]*)\/(i?$)/.exec(filter),
  1445. module = config.module && config.module.toLowerCase(),
  1446. fullName = this.module.name + ": " + this.testName;
  1447. function moduleChainNameMatch(testModule) {
  1448. var testModuleName = testModule.name ? testModule.name.toLowerCase() : null;
  1449. if (testModuleName === module) {
  1450. return true;
  1451. } else if (testModule.parentModule) {
  1452. return moduleChainNameMatch(testModule.parentModule);
  1453. } else {
  1454. return false;
  1455. }
  1456. }
  1457. function moduleChainIdMatch(testModule) {
  1458. return inArray(testModule.moduleId, config.moduleId) || testModule.parentModule && moduleChainIdMatch(testModule.parentModule);
  1459. }
  1460. // Internally-generated tests are always valid
  1461. if (this.callback && this.callback.validTest) {
  1462. return true;
  1463. }
  1464. if (config.moduleId && config.moduleId.length > 0 && !moduleChainIdMatch(this.module)) {
  1465. return false;
  1466. }
  1467. if (config.testId && config.testId.length > 0 && !inArray(this.testId, config.testId)) {
  1468. return false;
  1469. }
  1470. if (module && !moduleChainNameMatch(this.module)) {
  1471. return false;
  1472. }
  1473. if (!filter) {
  1474. return true;
  1475. }
  1476. return regexFilter ? this.regexFilter(!!regexFilter[1], regexFilter[2], regexFilter[3], fullName) : this.stringFilter(filter, fullName);
  1477. },
  1478. regexFilter: function regexFilter(exclude, pattern, flags, fullName) {
  1479. var regex = new RegExp(pattern, flags);
  1480. var match = regex.test(fullName);
  1481. return match !== exclude;
  1482. },
  1483. stringFilter: function stringFilter(filter, fullName) {
  1484. filter = filter.toLowerCase();
  1485. fullName = fullName.toLowerCase();
  1486. var include = filter.charAt(0) !== "!";
  1487. if (!include) {
  1488. filter = filter.slice(1);
  1489. }
  1490. // If the filter matches, we need to honour include
  1491. if (fullName.indexOf(filter) !== -1) {
  1492. return include;
  1493. }
  1494. // Otherwise, do the opposite
  1495. return !include;
  1496. }
  1497. };
  1498. function pushFailure() {
  1499. if (!config.current) {
  1500. throw new Error("pushFailure() assertion outside test context, in " + sourceFromStacktrace(2));
  1501. }
  1502. // Gets current test obj
  1503. var currentTest = config.current;
  1504. return currentTest.pushFailure.apply(currentTest, arguments);
  1505. }
  1506. function saveGlobal() {
  1507. config.pollution = [];
  1508. if (config.noglobals) {
  1509. for (var key in global$1) {
  1510. if (hasOwn.call(global$1, key)) {
  1511. // In Opera sometimes DOM element ids show up here, ignore them
  1512. if (/^qunit-test-output/.test(key)) {
  1513. continue;
  1514. }
  1515. config.pollution.push(key);
  1516. }
  1517. }
  1518. }
  1519. }
  1520. function checkPollution() {
  1521. var newGlobals,
  1522. deletedGlobals,
  1523. old = config.pollution;
  1524. saveGlobal();
  1525. newGlobals = diff(config.pollution, old);
  1526. if (newGlobals.length > 0) {
  1527. pushFailure("Introduced global variable(s): " + newGlobals.join(", "));
  1528. }
  1529. deletedGlobals = diff(old, config.pollution);
  1530. if (deletedGlobals.length > 0) {
  1531. pushFailure("Deleted global variable(s): " + deletedGlobals.join(", "));
  1532. }
  1533. }
  1534. // Will be exposed as QUnit.test
  1535. function test(testName, callback) {
  1536. if (focused$1) {
  1537. return;
  1538. }
  1539. var newTest = new Test({
  1540. testName: testName,
  1541. callback: callback
  1542. });
  1543. newTest.queue();
  1544. }
  1545. function todo(testName, callback) {
  1546. if (focused$1) {
  1547. return;
  1548. }
  1549. var newTest = new Test({
  1550. testName: testName,
  1551. callback: callback,
  1552. todo: true
  1553. });
  1554. newTest.queue();
  1555. }
  1556. // Will be exposed as QUnit.skip
  1557. function skip(testName) {
  1558. if (focused$1) {
  1559. return;
  1560. }
  1561. var test = new Test({
  1562. testName: testName,
  1563. skip: true
  1564. });
  1565. test.queue();
  1566. }
  1567. // Will be exposed as QUnit.only
  1568. function only(testName, callback) {
  1569. if (focused$1) {
  1570. return;
  1571. }
  1572. config.queue.length = 0;
  1573. focused$1 = true;
  1574. var newTest = new Test({
  1575. testName: testName,
  1576. callback: callback
  1577. });
  1578. newTest.queue();
  1579. }
  1580. // Put a hold on processing and return a function that will release it.
  1581. function internalStop(test) {
  1582. test.semaphore += 1;
  1583. config.blocking = true;
  1584. // Set a recovery timeout, if so configured.
  1585. if (defined.setTimeout) {
  1586. var timeoutDuration = void 0;
  1587. if (typeof test.timeout === "number") {
  1588. timeoutDuration = test.timeout;
  1589. } else if (typeof config.testTimeout === "number") {
  1590. timeoutDuration = config.testTimeout;
  1591. }
  1592. if (typeof timeoutDuration === "number" && timeoutDuration > 0) {
  1593. clearTimeout(config.timeout);
  1594. config.timeout = setTimeout(function () {
  1595. pushFailure("Test took longer than " + timeoutDuration + "ms; test timed out.", sourceFromStacktrace(2));
  1596. internalRecover(test);
  1597. }, timeoutDuration);
  1598. }
  1599. }
  1600. var released = false;
  1601. return function resume() {
  1602. if (released) {
  1603. return;
  1604. }
  1605. released = true;
  1606. test.semaphore -= 1;
  1607. internalStart(test);
  1608. };
  1609. }
  1610. // Forcefully release all processing holds.
  1611. function internalRecover(test) {
  1612. test.semaphore = 0;
  1613. internalStart(test);
  1614. }
  1615. // Release a processing hold, scheduling a resumption attempt if no holds remain.
  1616. function internalStart(test) {
  1617. // If semaphore is non-numeric, throw error
  1618. if (isNaN(test.semaphore)) {
  1619. test.semaphore = 0;
  1620. pushFailure("Invalid value on test.semaphore", sourceFromStacktrace(2));
  1621. return;
  1622. }
  1623. // Don't start until equal number of stop-calls
  1624. if (test.semaphore > 0) {
  1625. return;
  1626. }
  1627. // Throw an Error if start is called more often than stop
  1628. if (test.semaphore < 0) {
  1629. test.semaphore = 0;
  1630. pushFailure("Tried to restart test while already started (test's semaphore was 0 already)", sourceFromStacktrace(2));
  1631. return;
  1632. }
  1633. // Add a slight delay to allow more assertions etc.
  1634. if (defined.setTimeout) {
  1635. if (config.timeout) {
  1636. clearTimeout(config.timeout);
  1637. }
  1638. config.timeout = setTimeout(function () {
  1639. if (test.semaphore > 0) {
  1640. return;
  1641. }
  1642. if (config.timeout) {
  1643. clearTimeout(config.timeout);
  1644. }
  1645. begin();
  1646. }, 13);
  1647. } else {
  1648. begin();
  1649. }
  1650. }
  1651. function collectTests(module) {
  1652. var tests = [].concat(module.tests);
  1653. var modules = [].concat(toConsumableArray(module.childModules));
  1654. // Do a breadth-first traversal of the child modules
  1655. while (modules.length) {
  1656. var nextModule = modules.shift();
  1657. tests.push.apply(tests, nextModule.tests);
  1658. modules.push.apply(modules, toConsumableArray(nextModule.childModules));
  1659. }
  1660. return tests;
  1661. }
  1662. function numberOfTests(module) {
  1663. return collectTests(module).length;
  1664. }
  1665. function numberOfUnskippedTests(module) {
  1666. return collectTests(module).filter(function (test) {
  1667. return !test.skip;
  1668. }).length;
  1669. }
  1670. function notifyTestsRan(module, skipped) {
  1671. module.testsRun++;
  1672. if (!skipped) {
  1673. module.unskippedTestsRun++;
  1674. }
  1675. while (module = module.parentModule) {
  1676. module.testsRun++;
  1677. if (!skipped) {
  1678. module.unskippedTestsRun++;
  1679. }
  1680. }
  1681. }
  1682. /**
  1683. * Returns a function that proxies to the given method name on the globals
  1684. * console object. The proxy will also detect if the console doesn't exist and
  1685. * will appropriately no-op. This allows support for IE9, which doesn't have a
  1686. * console if the developer tools are not open.
  1687. */
  1688. function consoleProxy(method) {
  1689. return function () {
  1690. if (console) {
  1691. console[method].apply(console, arguments);
  1692. }
  1693. };
  1694. }
  1695. var Logger = {
  1696. warn: consoleProxy("warn")
  1697. };
  1698. var Assert = function () {
  1699. function Assert(testContext) {
  1700. classCallCheck(this, Assert);
  1701. this.test = testContext;
  1702. }
  1703. // Assert helpers
  1704. createClass(Assert, [{
  1705. key: "timeout",
  1706. value: function timeout(duration) {
  1707. if (typeof duration !== "number") {
  1708. throw new Error("You must pass a number as the duration to assert.timeout");
  1709. }
  1710. this.test.timeout = duration;
  1711. }
  1712. // Documents a "step", which is a string value, in a test as a passing assertion
  1713. }, {
  1714. key: "step",
  1715. value: function step(message) {
  1716. var result = !!message;
  1717. this.test.steps.push(message);
  1718. return this.pushResult({
  1719. result: result,
  1720. message: message || "You must provide a message to assert.step"
  1721. });
  1722. }
  1723. // Verifies the steps in a test match a given array of string values
  1724. }, {
  1725. key: "verifySteps",
  1726. value: function verifySteps(steps, message) {
  1727. this.deepEqual(this.test.steps, steps, message);
  1728. }
  1729. // Specify the number of expected assertions to guarantee that failed test
  1730. // (no assertions are run at all) don't slip through.
  1731. }, {
  1732. key: "expect",
  1733. value: function expect(asserts) {
  1734. if (arguments.length === 1) {
  1735. this.test.expected = asserts;
  1736. } else {
  1737. return this.test.expected;
  1738. }
  1739. }
  1740. // Put a hold on processing and return a function that will release it a maximum of once.
  1741. }, {
  1742. key: "async",
  1743. value: function async(count) {
  1744. var test$$1 = this.test;
  1745. var popped = false,
  1746. acceptCallCount = count;
  1747. if (typeof acceptCallCount === "undefined") {
  1748. acceptCallCount = 1;
  1749. }
  1750. var resume = internalStop(test$$1);
  1751. return function done() {
  1752. if (config.current !== test$$1) {
  1753. throw Error("assert.async callback called after test finished.");
  1754. }
  1755. if (popped) {
  1756. test$$1.pushFailure("Too many calls to the `assert.async` callback", sourceFromStacktrace(2));
  1757. return;
  1758. }
  1759. acceptCallCount -= 1;
  1760. if (acceptCallCount > 0) {
  1761. return;
  1762. }
  1763. popped = true;
  1764. resume();
  1765. };
  1766. }
  1767. // Exports test.push() to the user API
  1768. // Alias of pushResult.
  1769. }, {
  1770. key: "push",
  1771. value: function push(result, actual, expected, message, negative) {
  1772. Logger.warn("assert.push is deprecated and will be removed in QUnit 3.0." + " Please use assert.pushResult instead (https://api.qunitjs.com/assert/pushResult).");
  1773. var currentAssert = this instanceof Assert ? this : config.current.assert;
  1774. return currentAssert.pushResult({
  1775. result: result,
  1776. actual: actual,
  1777. expected: expected,
  1778. message: message,
  1779. negative: negative
  1780. });
  1781. }
  1782. }, {
  1783. key: "pushResult",
  1784. value: function pushResult(resultInfo) {
  1785. // Destructure of resultInfo = { result, actual, expected, message, negative }
  1786. var assert = this;
  1787. var currentTest = assert instanceof Assert && assert.test || config.current;
  1788. // Backwards compatibility fix.
  1789. // Allows the direct use of global exported assertions and QUnit.assert.*
  1790. // Although, it's use is not recommended as it can leak assertions
  1791. // to other tests from async tests, because we only get a reference to the current test,
  1792. // not exactly the test where assertion were intended to be called.
  1793. if (!currentTest) {
  1794. throw new Error("assertion outside test context, in " + sourceFromStacktrace(2));
  1795. }
  1796. if (!(assert instanceof Assert)) {
  1797. assert = currentTest.assert;
  1798. }
  1799. return assert.test.pushResult(resultInfo);
  1800. }
  1801. }, {
  1802. key: "ok",
  1803. value: function ok(result, message) {
  1804. if (!message) {
  1805. message = result ? "okay" : "failed, expected argument to be truthy, was: " + dump.parse(result);
  1806. }
  1807. this.pushResult({
  1808. result: !!result,
  1809. actual: result,
  1810. expected: true,
  1811. message: message
  1812. });
  1813. }
  1814. }, {
  1815. key: "notOk",
  1816. value: function notOk(result, message) {
  1817. if (!message) {
  1818. message = !result ? "okay" : "failed, expected argument to be falsy, was: " + dump.parse(result);
  1819. }
  1820. this.pushResult({
  1821. result: !result,
  1822. actual: result,
  1823. expected: false,
  1824. message: message
  1825. });
  1826. }
  1827. }, {
  1828. key: "equal",
  1829. value: function equal(actual, expected, message) {
  1830. // eslint-disable-next-line eqeqeq
  1831. var result = expected == actual;
  1832. this.pushResult({
  1833. result: result,
  1834. actual: actual,
  1835. expected: expected,
  1836. message: message
  1837. });
  1838. }
  1839. }, {
  1840. key: "notEqual",
  1841. value: function notEqual(actual, expected, message) {
  1842. // eslint-disable-next-line eqeqeq
  1843. var result = expected != actual;
  1844. this.pushResult({
  1845. result: result,
  1846. actual: actual,
  1847. expected: expected,
  1848. message: message,
  1849. negative: true
  1850. });
  1851. }
  1852. }, {
  1853. key: "propEqual",
  1854. value: function propEqual(actual, expected, message) {
  1855. actual = objectValues(actual);
  1856. expected = objectValues(expected);
  1857. this.pushResult({
  1858. result: equiv(actual, expected),
  1859. actual: actual,
  1860. expected: expected,
  1861. message: message
  1862. });
  1863. }
  1864. }, {
  1865. key: "notPropEqual",
  1866. value: function notPropEqual(actual, expected, message) {
  1867. actual = objectValues(actual);
  1868. expected = objectValues(expected);
  1869. this.pushResult({
  1870. result: !equiv(actual, expected),
  1871. actual: actual,
  1872. expected: expected,
  1873. message: message,
  1874. negative: true
  1875. });
  1876. }
  1877. }, {
  1878. key: "deepEqual",
  1879. value: function deepEqual(actual, expected, message) {
  1880. this.pushResult({
  1881. result: equiv(actual, expected),
  1882. actual: actual,
  1883. expected: expected,
  1884. message: message
  1885. });
  1886. }
  1887. }, {
  1888. key: "notDeepEqual",
  1889. value: function notDeepEqual(actual, expected, message) {
  1890. this.pushResult({
  1891. result: !equiv(actual, expected),
  1892. actual: actual,
  1893. expected: expected,
  1894. message: message,
  1895. negative: true
  1896. });
  1897. }
  1898. }, {
  1899. key: "strictEqual",
  1900. value: function strictEqual(actual, expected, message) {
  1901. this.pushResult({
  1902. result: expected === actual,
  1903. actual: actual,
  1904. expected: expected,
  1905. message: message
  1906. });
  1907. }
  1908. }, {
  1909. key: "notStrictEqual",
  1910. value: function notStrictEqual(actual, expected, message) {
  1911. this.pushResult({
  1912. result: expected !== actual,
  1913. actual: actual,
  1914. expected: expected,
  1915. message: message,
  1916. negative: true
  1917. });
  1918. }
  1919. }, {
  1920. key: "throws",
  1921. value: function throws(block, expected, message) {
  1922. var actual = void 0,
  1923. result = false;
  1924. var currentTest = this instanceof Assert && this.test || config.current;
  1925. // 'expected' is optional unless doing string comparison
  1926. if (objectType(expected) === "string") {
  1927. if (message == null) {
  1928. message = expected;
  1929. expected = null;
  1930. } else {
  1931. throw new Error("throws/raises does not accept a string value for the expected argument.\n" + "Use a non-string object value (e.g. regExp) instead if it's necessary.");
  1932. }
  1933. }
  1934. currentTest.ignoreGlobalErrors = true;
  1935. try {
  1936. block.call(currentTest.testEnvironment);
  1937. } catch (e) {
  1938. actual = e;
  1939. }
  1940. currentTest.ignoreGlobalErrors = false;
  1941. if (actual) {
  1942. var expectedType = objectType(expected);
  1943. // We don't want to validate thrown error
  1944. if (!expected) {
  1945. result = true;
  1946. expected = null;
  1947. // Expected is a regexp
  1948. } else if (expectedType === "regexp") {
  1949. result = expected.test(errorString(actual));
  1950. // Expected is a constructor, maybe an Error constructor
  1951. } else if (expectedType === "function" && actual instanceof expected) {
  1952. result = true;
  1953. // Expected is an Error object
  1954. } else if (expectedType === "object") {
  1955. result = actual instanceof expected.constructor && actual.name === expected.name && actual.message === expected.message;
  1956. // Expected is a validation function which returns true if validation passed
  1957. } else if (expectedType === "function" && expected.call({}, actual) === true) {
  1958. expected = null;
  1959. result = true;
  1960. }
  1961. }
  1962. currentTest.assert.pushResult({
  1963. result: result,
  1964. actual: actual,
  1965. expected: expected,
  1966. message: message
  1967. });
  1968. }
  1969. }]);
  1970. return Assert;
  1971. }();
  1972. // Provide an alternative to assert.throws(), for environments that consider throws a reserved word
  1973. // Known to us are: Closure Compiler, Narwhal
  1974. // eslint-disable-next-line dot-notation
  1975. Assert.prototype.raises = Assert.prototype["throws"];
  1976. /**
  1977. * Converts an error into a simple string for comparisons.
  1978. *
  1979. * @param {Error} error
  1980. * @return {String}
  1981. */
  1982. function errorString(error) {
  1983. var resultErrorString = error.toString();
  1984. if (resultErrorString.substring(0, 7) === "[object") {
  1985. var name = error.name ? error.name.toString() : "Error";
  1986. var message = error.message ? error.message.toString() : "";
  1987. if (name && message) {
  1988. return name + ": " + message;
  1989. } else if (name) {
  1990. return name;
  1991. } else if (message) {
  1992. return message;
  1993. } else {
  1994. return "Error";
  1995. }
  1996. } else {
  1997. return resultErrorString;
  1998. }
  1999. }
  2000. /* global module, exports, define */
  2001. function exportQUnit(QUnit) {
  2002. if (defined.document) {
  2003. // QUnit may be defined when it is preconfigured but then only QUnit and QUnit.config may be defined.
  2004. if (window.QUnit && window.QUnit.version) {
  2005. throw new Error("QUnit has already been defined.");
  2006. }
  2007. window.QUnit = QUnit;
  2008. }
  2009. // For nodejs
  2010. if (typeof module !== "undefined" && module && module.exports) {
  2011. module.exports = QUnit;
  2012. // For consistency with CommonJS environments' exports
  2013. module.exports.QUnit = QUnit;
  2014. }
  2015. // For CommonJS with exports, but without module.exports, like Rhino
  2016. if (typeof exports !== "undefined" && exports) {
  2017. exports.QUnit = QUnit;
  2018. }
  2019. if (typeof define === "function" && define.amd) {
  2020. define(function () {
  2021. return QUnit;
  2022. });
  2023. QUnit.config.autostart = false;
  2024. }
  2025. // For Web/Service Workers
  2026. if (self$1 && self$1.WorkerGlobalScope && self$1 instanceof self$1.WorkerGlobalScope) {
  2027. self$1.QUnit = QUnit;
  2028. }
  2029. }
  2030. var SuiteReport = function () {
  2031. function SuiteReport(name, parentSuite) {
  2032. classCallCheck(this, SuiteReport);
  2033. this.name = name;
  2034. this.fullName = parentSuite ? parentSuite.fullName.concat(name) : [];
  2035. this.tests = [];
  2036. this.childSuites = [];
  2037. if (parentSuite) {
  2038. parentSuite.pushChildSuite(this);
  2039. }
  2040. }
  2041. createClass(SuiteReport, [{
  2042. key: "start",
  2043. value: function start(recordTime) {
  2044. if (recordTime) {
  2045. this._startTime = Date.now();
  2046. }
  2047. return {
  2048. name: this.name,
  2049. fullName: this.fullName.slice(),
  2050. tests: this.tests.map(function (test) {
  2051. return test.start();
  2052. }),
  2053. childSuites: this.childSuites.map(function (suite) {
  2054. return suite.start();
  2055. }),
  2056. testCounts: {
  2057. total: this.getTestCounts().total
  2058. }
  2059. };
  2060. }
  2061. }, {
  2062. key: "end",
  2063. value: function end(recordTime) {
  2064. if (recordTime) {
  2065. this._endTime = Date.now();
  2066. }
  2067. return {
  2068. name: this.name,
  2069. fullName: this.fullName.slice(),
  2070. tests: this.tests.map(function (test) {
  2071. return test.end();
  2072. }),
  2073. childSuites: this.childSuites.map(function (suite) {
  2074. return suite.end();
  2075. }),
  2076. testCounts: this.getTestCounts(),
  2077. runtime: this.getRuntime(),
  2078. status: this.getStatus()
  2079. };
  2080. }
  2081. }, {
  2082. key: "pushChildSuite",
  2083. value: function pushChildSuite(suite) {
  2084. this.childSuites.push(suite);
  2085. }
  2086. }, {
  2087. key: "pushTest",
  2088. value: function pushTest(test) {
  2089. this.tests.push(test);
  2090. }
  2091. }, {
  2092. key: "getRuntime",
  2093. value: function getRuntime() {
  2094. return this._endTime - this._startTime;
  2095. }
  2096. }, {
  2097. key: "getTestCounts",
  2098. value: function getTestCounts() {
  2099. var counts = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : { passed: 0, failed: 0, skipped: 0, todo: 0, total: 0 };
  2100. counts = this.tests.reduce(function (counts, test) {
  2101. if (test.valid) {
  2102. counts[test.getStatus()]++;
  2103. counts.total++;
  2104. }
  2105. return counts;
  2106. }, counts);
  2107. return this.childSuites.reduce(function (counts, suite) {
  2108. return suite.getTestCounts(counts);
  2109. }, counts);
  2110. }
  2111. }, {
  2112. key: "getStatus",
  2113. value: function getStatus() {
  2114. var _getTestCounts = this.getTestCounts(),
  2115. total = _getTestCounts.total,
  2116. failed = _getTestCounts.failed,
  2117. skipped = _getTestCounts.skipped,
  2118. todo = _getTestCounts.todo;
  2119. if (failed) {
  2120. return "failed";
  2121. } else {
  2122. if (skipped === total) {
  2123. return "skipped";
  2124. } else if (todo === total) {
  2125. return "todo";
  2126. } else {
  2127. return "passed";
  2128. }
  2129. }
  2130. }
  2131. }]);
  2132. return SuiteReport;
  2133. }();
  2134. // Handle an unhandled exception. By convention, returns true if further
  2135. // error handling should be suppressed and false otherwise.
  2136. // In this case, we will only suppress further error handling if the
  2137. // "ignoreGlobalErrors" configuration option is enabled.
  2138. function onError(error) {
  2139. for (var _len = arguments.length, args = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
  2140. args[_key - 1] = arguments[_key];
  2141. }
  2142. if (config.current) {
  2143. if (config.current.ignoreGlobalErrors) {
  2144. return true;
  2145. }
  2146. pushFailure.apply(undefined, [error.message, error.fileName + ":" + error.lineNumber].concat(args));
  2147. } else {
  2148. test("global failure", extend(function () {
  2149. pushFailure.apply(undefined, [error.message, error.fileName + ":" + error.lineNumber].concat(args));
  2150. }, { validTest: true }));
  2151. }
  2152. return false;
  2153. }
  2154. var focused = false;
  2155. var QUnit = {};
  2156. var globalSuite = new SuiteReport();
  2157. // The initial "currentModule" represents the global (or top-level) module that
  2158. // is not explicitly defined by the user, therefore we add the "globalSuite" to
  2159. // it since each module has a suiteReport associated with it.
  2160. config.currentModule.suiteReport = globalSuite;
  2161. var moduleStack = [];
  2162. var globalStartCalled = false;
  2163. var runStarted = false;
  2164. // Figure out if we're running the tests from a server or not
  2165. QUnit.isLocal = !(defined.document && window.location.protocol !== "file:");
  2166. // Expose the current QUnit version
  2167. QUnit.version = "2.4.1";
  2168. function createModule(name, testEnvironment, modifiers) {
  2169. var parentModule = moduleStack.length ? moduleStack.slice(-1)[0] : null;
  2170. var moduleName = parentModule !== null ? [parentModule.name, name].join(" > ") : name;
  2171. var parentSuite = parentModule ? parentModule.suiteReport : globalSuite;
  2172. var skip$$1 = parentModule !== null && parentModule.skip || modifiers.skip;
  2173. var todo$$1 = parentModule !== null && parentModule.todo || modifiers.todo;
  2174. var module = {
  2175. name: moduleName,
  2176. parentModule: parentModule,
  2177. tests: [],
  2178. moduleId: generateHash(moduleName),
  2179. testsRun: 0,
  2180. unskippedTestsRun: 0,
  2181. childModules: [],
  2182. suiteReport: new SuiteReport(name, parentSuite),
  2183. // Pass along `skip` and `todo` properties from parent module, in case
  2184. // there is one, to childs. And use own otherwise.
  2185. // This property will be used to mark own tests and tests of child suites
  2186. // as either `skipped` or `todo`.
  2187. skip: skip$$1,
  2188. todo: skip$$1 ? false : todo$$1
  2189. };
  2190. var env = {};
  2191. if (parentModule) {
  2192. parentModule.childModules.push(module);
  2193. extend(env, parentModule.testEnvironment);
  2194. }
  2195. extend(env, testEnvironment);
  2196. module.testEnvironment = env;
  2197. config.modules.push(module);
  2198. return module;
  2199. }
  2200. function processModule(name, options, executeNow) {
  2201. var modifiers = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {};
  2202. var module = createModule(name, options, modifiers);
  2203. // Move any hooks to a 'hooks' object
  2204. var testEnvironment = module.testEnvironment;
  2205. var hooks = module.hooks = {};
  2206. setHookFromEnvironment(hooks, testEnvironment, "before");
  2207. setHookFromEnvironment(hooks, testEnvironment, "beforeEach");
  2208. setHookFromEnvironment(hooks, testEnvironment, "afterEach");
  2209. setHookFromEnvironment(hooks, testEnvironment, "after");
  2210. function setHookFromEnvironment(hooks, environment, name) {
  2211. var potentialHook = environment[name];
  2212. hooks[name] = typeof potentialHook === "function" ? [potentialHook] : [];
  2213. delete environment[name];
  2214. }
  2215. var moduleFns = {
  2216. before: setHookFunction(module, "before"),
  2217. beforeEach: setHookFunction(module, "beforeEach"),
  2218. afterEach: setHookFunction(module, "afterEach"),
  2219. after: setHookFunction(module, "after")
  2220. };
  2221. var currentModule = config.currentModule;
  2222. if (objectType(executeNow) === "function") {
  2223. moduleStack.push(module);
  2224. config.currentModule = module;
  2225. executeNow.call(module.testEnvironment, moduleFns);
  2226. moduleStack.pop();
  2227. module = module.parentModule || currentModule;
  2228. }
  2229. config.currentModule = module;
  2230. }
  2231. // TODO: extract this to a new file alongside its related functions
  2232. function module$1(name, options, executeNow) {
  2233. if (focused) {
  2234. return;
  2235. }
  2236. if (arguments.length === 2) {
  2237. if (objectType(options) === "function") {
  2238. executeNow = options;
  2239. options = undefined;
  2240. }
  2241. }
  2242. processModule(name, options, executeNow);
  2243. }
  2244. module$1.only = function () {
  2245. if (focused) {
  2246. return;
  2247. }
  2248. config.modules.length = 0;
  2249. config.queue.length = 0;
  2250. module$1.apply(undefined, arguments);
  2251. focused = true;
  2252. };
  2253. module$1.skip = function (name, options, executeNow) {
  2254. if (focused) {
  2255. return;
  2256. }
  2257. if (arguments.length === 2) {
  2258. if (objectType(options) === "function") {
  2259. executeNow = options;
  2260. options = undefined;
  2261. }
  2262. }
  2263. processModule(name, options, executeNow, { skip: true });
  2264. };
  2265. module$1.todo = function (name, options, executeNow) {
  2266. if (focused) {
  2267. return;
  2268. }
  2269. if (arguments.length === 2) {
  2270. if (objectType(options) === "function") {
  2271. executeNow = options;
  2272. options = undefined;
  2273. }
  2274. }
  2275. processModule(name, options, executeNow, { todo: true });
  2276. };
  2277. extend(QUnit, {
  2278. on: on,
  2279. module: module$1,
  2280. test: test,
  2281. todo: todo,
  2282. skip: skip,
  2283. only: only,
  2284. start: function start(count) {
  2285. var globalStartAlreadyCalled = globalStartCalled;
  2286. if (!config.current) {
  2287. globalStartCalled = true;
  2288. if (runStarted) {
  2289. throw new Error("Called start() while test already started running");
  2290. } else if (globalStartAlreadyCalled || count > 1) {
  2291. throw new Error("Called start() outside of a test context too many times");
  2292. } else if (config.autostart) {
  2293. throw new Error("Called start() outside of a test context when " + "QUnit.config.autostart was true");
  2294. } else if (!config.pageLoaded) {
  2295. // The page isn't completely loaded yet, so we set autostart and then
  2296. // load if we're in Node or wait for the browser's load event.
  2297. config.autostart = true;
  2298. // Starts from Node even if .load was not previously called. We still return
  2299. // early otherwise we'll wind up "beginning" twice.
  2300. if (!defined.document) {
  2301. QUnit.load();
  2302. }
  2303. return;
  2304. }
  2305. } else {
  2306. throw new Error("QUnit.start cannot be called inside a test context.");
  2307. }
  2308. scheduleBegin();
  2309. },
  2310. config: config,
  2311. is: is,
  2312. objectType: objectType,
  2313. extend: extend,
  2314. load: function load() {
  2315. config.pageLoaded = true;
  2316. // Initialize the configuration options
  2317. extend(config, {
  2318. stats: { all: 0, bad: 0 },
  2319. started: 0,
  2320. updateRate: 1000,
  2321. autostart: true,
  2322. filter: ""
  2323. }, true);
  2324. if (!runStarted) {
  2325. config.blocking = false;
  2326. if (config.autostart) {
  2327. scheduleBegin();
  2328. }
  2329. }
  2330. },
  2331. stack: function stack(offset) {
  2332. offset = (offset || 0) + 2;
  2333. return sourceFromStacktrace(offset);
  2334. },
  2335. onError: onError
  2336. });
  2337. QUnit.pushFailure = pushFailure;
  2338. QUnit.assert = Assert.prototype;
  2339. QUnit.equiv = equiv;
  2340. QUnit.dump = dump;
  2341. registerLoggingCallbacks(QUnit);
  2342. function scheduleBegin() {
  2343. runStarted = true;
  2344. // Add a slight delay to allow definition of more modules and tests.
  2345. if (defined.setTimeout) {
  2346. setTimeout(function () {
  2347. begin();
  2348. }, 13);
  2349. } else {
  2350. begin();
  2351. }
  2352. }
  2353. function begin() {
  2354. var i,
  2355. l,
  2356. modulesLog = [];
  2357. // If the test run hasn't officially begun yet
  2358. if (!config.started) {
  2359. // Record the time of the test run's beginning
  2360. config.started = now();
  2361. // Delete the loose unnamed module if unused.
  2362. if (config.modules[0].name === "" && config.modules[0].tests.length === 0) {
  2363. config.modules.shift();
  2364. }
  2365. // Avoid unnecessary information by not logging modules' test environments
  2366. for (i = 0, l = config.modules.length; i < l; i++) {
  2367. modulesLog.push({
  2368. name: config.modules[i].name,
  2369. tests: config.modules[i].tests
  2370. });
  2371. }
  2372. // The test run is officially beginning now
  2373. emit("runStart", globalSuite.start(true));
  2374. runLoggingCallbacks("begin", {
  2375. totalTests: Test.count,
  2376. modules: modulesLog
  2377. });
  2378. }
  2379. config.blocking = false;
  2380. ProcessingQueue.advance();
  2381. }
  2382. function setHookFunction(module, hookName) {
  2383. return function setHook(callback) {
  2384. module.hooks[hookName].push(callback);
  2385. };
  2386. }
  2387. exportQUnit(QUnit);
  2388. (function () {
  2389. if (typeof window === "undefined" || typeof document === "undefined") {
  2390. return;
  2391. }
  2392. var config = QUnit.config,
  2393. hasOwn = Object.prototype.hasOwnProperty;
  2394. // Stores fixture HTML for resetting later
  2395. function storeFixture() {
  2396. // Avoid overwriting user-defined values
  2397. if (hasOwn.call(config, "fixture")) {
  2398. return;
  2399. }
  2400. var fixture = document.getElementById("qunit-fixture");
  2401. if (fixture) {
  2402. config.fixture = fixture.innerHTML;
  2403. }
  2404. }
  2405. QUnit.begin(storeFixture);
  2406. // Resets the fixture DOM element if available.
  2407. function resetFixture() {
  2408. if (config.fixture == null) {
  2409. return;
  2410. }
  2411. var fixture = document.getElementById("qunit-fixture");
  2412. if (fixture) {
  2413. fixture.innerHTML = config.fixture;
  2414. }
  2415. }
  2416. QUnit.testStart(resetFixture);
  2417. })();
  2418. (function () {
  2419. // Only interact with URLs via window.location
  2420. var location = typeof window !== "undefined" && window.location;
  2421. if (!location) {
  2422. return;
  2423. }
  2424. var urlParams = getUrlParams();
  2425. QUnit.urlParams = urlParams;
  2426. // Match module/test by inclusion in an array
  2427. QUnit.config.moduleId = [].concat(urlParams.moduleId || []);
  2428. QUnit.config.testId = [].concat(urlParams.testId || []);
  2429. // Exact case-insensitive match of the module name
  2430. QUnit.config.module = urlParams.module;
  2431. // Regular expression or case-insenstive substring match against "moduleName: testName"
  2432. QUnit.config.filter = urlParams.filter;
  2433. // Test order randomization
  2434. if (urlParams.seed === true) {
  2435. // Generate a random seed if the option is specified without a value
  2436. QUnit.config.seed = Math.random().toString(36).slice(2);
  2437. } else if (urlParams.seed) {
  2438. QUnit.config.seed = urlParams.seed;
  2439. }
  2440. // Add URL-parameter-mapped config values with UI form rendering data
  2441. QUnit.config.urlConfig.push({
  2442. id: "hidepassed",
  2443. label: "Hide passed tests",
  2444. tooltip: "Only show tests and assertions that fail. Stored as query-strings."
  2445. }, {
  2446. id: "noglobals",
  2447. label: "Check for Globals",
  2448. tooltip: "Enabling this will test if any test introduces new properties on the " + "global object (`window` in Browsers). Stored as query-strings."
  2449. }, {
  2450. id: "notrycatch",
  2451. label: "No try-catch",
  2452. tooltip: "Enabling this will run tests outside of a try-catch block. Makes debugging " + "exceptions in IE reasonable. Stored as query-strings."
  2453. });
  2454. QUnit.begin(function () {
  2455. var i,
  2456. option,
  2457. urlConfig = QUnit.config.urlConfig;
  2458. for (i = 0; i < urlConfig.length; i++) {
  2459. // Options can be either strings or objects with nonempty "id" properties
  2460. option = QUnit.config.urlConfig[i];
  2461. if (typeof option !== "string") {
  2462. option = option.id;
  2463. }
  2464. if (QUnit.config[option] === undefined) {
  2465. QUnit.config[option] = urlParams[option];
  2466. }
  2467. }
  2468. });
  2469. function getUrlParams() {
  2470. var i, param, name, value;
  2471. var urlParams = Object.create(null);
  2472. var params = location.search.slice(1).split("&");
  2473. var length = params.length;
  2474. for (i = 0; i < length; i++) {
  2475. if (params[i]) {
  2476. param = params[i].split("=");
  2477. name = decodeQueryParam(param[0]);
  2478. // Allow just a key to turn on a flag, e.g., test.html?noglobals
  2479. value = param.length === 1 || decodeQueryParam(param.slice(1).join("="));
  2480. if (name in urlParams) {
  2481. urlParams[name] = [].concat(urlParams[name], value);
  2482. } else {
  2483. urlParams[name] = value;
  2484. }
  2485. }
  2486. }
  2487. return urlParams;
  2488. }
  2489. function decodeQueryParam(param) {
  2490. return decodeURIComponent(param.replace(/\+/g, "%20"));
  2491. }
  2492. })();
  2493. var stats = {
  2494. passedTests: 0,
  2495. failedTests: 0,
  2496. skippedTests: 0,
  2497. todoTests: 0
  2498. };
  2499. // Escape text for attribute or text content.
  2500. function escapeText(s) {
  2501. if (!s) {
  2502. return "";
  2503. }
  2504. s = s + "";
  2505. // Both single quotes and double quotes (for attributes)
  2506. return s.replace(/['"<>&]/g, function (s) {
  2507. switch (s) {
  2508. case "'":
  2509. return "&#039;";
  2510. case "\"":
  2511. return "&quot;";
  2512. case "<":
  2513. return "&lt;";
  2514. case ">":
  2515. return "&gt;";
  2516. case "&":
  2517. return "&amp;";
  2518. }
  2519. });
  2520. }
  2521. (function () {
  2522. // Don't load the HTML Reporter on non-browser environments
  2523. if (typeof window === "undefined" || !window.document) {
  2524. return;
  2525. }
  2526. var config = QUnit.config,
  2527. document$$1 = window.document,
  2528. collapseNext = false,
  2529. hasOwn = Object.prototype.hasOwnProperty,
  2530. unfilteredUrl = setUrl({ filter: undefined, module: undefined,
  2531. moduleId: undefined, testId: undefined }),
  2532. modulesList = [];
  2533. function addEvent(elem, type, fn) {
  2534. elem.addEventListener(type, fn, false);
  2535. }
  2536. function removeEvent(elem, type, fn) {
  2537. elem.removeEventListener(type, fn, false);
  2538. }
  2539. function addEvents(elems, type, fn) {
  2540. var i = elems.length;
  2541. while (i--) {
  2542. addEvent(elems[i], type, fn);
  2543. }
  2544. }
  2545. function hasClass(elem, name) {
  2546. return (" " + elem.className + " ").indexOf(" " + name + " ") >= 0;
  2547. }
  2548. function addClass(elem, name) {
  2549. if (!hasClass(elem, name)) {
  2550. elem.className += (elem.className ? " " : "") + name;
  2551. }
  2552. }
  2553. function toggleClass(elem, name, force) {
  2554. if (force || typeof force === "undefined" && !hasClass(elem, name)) {
  2555. addClass(elem, name);
  2556. } else {
  2557. removeClass(elem, name);
  2558. }
  2559. }
  2560. function removeClass(elem, name) {
  2561. var set = " " + elem.className + " ";
  2562. // Class name may appear multiple times
  2563. while (set.indexOf(" " + name + " ") >= 0) {
  2564. set = set.replace(" " + name + " ", " ");
  2565. }
  2566. // Trim for prettiness
  2567. elem.className = typeof set.trim === "function" ? set.trim() : set.replace(/^\s+|\s+$/g, "");
  2568. }
  2569. function id(name) {
  2570. return document$$1.getElementById && document$$1.getElementById(name);
  2571. }
  2572. function abortTests() {
  2573. var abortButton = id("qunit-abort-tests-button");
  2574. if (abortButton) {
  2575. abortButton.disabled = true;
  2576. abortButton.innerHTML = "Aborting...";
  2577. }
  2578. QUnit.config.queue.length = 0;
  2579. return false;
  2580. }
  2581. function interceptNavigation(ev) {
  2582. applyUrlParams();
  2583. if (ev && ev.preventDefault) {
  2584. ev.preventDefault();
  2585. }
  2586. return false;
  2587. }
  2588. function getUrlConfigHtml() {
  2589. var i,
  2590. j,
  2591. val,
  2592. escaped,
  2593. escapedTooltip,
  2594. selection = false,
  2595. urlConfig = config.urlConfig,
  2596. urlConfigHtml = "";
  2597. for (i = 0; i < urlConfig.length; i++) {
  2598. // Options can be either strings or objects with nonempty "id" properties
  2599. val = config.urlConfig[i];
  2600. if (typeof val === "string") {
  2601. val = {
  2602. id: val,
  2603. label: val
  2604. };
  2605. }
  2606. escaped = escapeText(val.id);
  2607. escapedTooltip = escapeText(val.tooltip);
  2608. if (!val.value || typeof val.value === "string") {
  2609. urlConfigHtml += "<label for='qunit-urlconfig-" + escaped + "' title='" + escapedTooltip + "'><input id='qunit-urlconfig-" + escaped + "' name='" + escaped + "' type='checkbox'" + (val.value ? " value='" + escapeText(val.value) + "'" : "") + (config[val.id] ? " checked='checked'" : "") + " title='" + escapedTooltip + "' />" + escapeText(val.label) + "</label>";
  2610. } else {
  2611. urlConfigHtml += "<label for='qunit-urlconfig-" + escaped + "' title='" + escapedTooltip + "'>" + val.label + ": </label><select id='qunit-urlconfig-" + escaped + "' name='" + escaped + "' title='" + escapedTooltip + "'><option></option>";
  2612. if (QUnit.is("array", val.value)) {
  2613. for (j = 0; j < val.value.length; j++) {
  2614. escaped = escapeText(val.value[j]);
  2615. urlConfigHtml += "<option value='" + escaped + "'" + (config[val.id] === val.value[j] ? (selection = true) && " selected='selected'" : "") + ">" + escaped + "</option>";
  2616. }
  2617. } else {
  2618. for (j in val.value) {
  2619. if (hasOwn.call(val.value, j)) {
  2620. urlConfigHtml += "<option value='" + escapeText(j) + "'" + (config[val.id] === j ? (selection = true) && " selected='selected'" : "") + ">" + escapeText(val.value[j]) + "</option>";
  2621. }
  2622. }
  2623. }
  2624. if (config[val.id] && !selection) {
  2625. escaped = escapeText(config[val.id]);
  2626. urlConfigHtml += "<option value='" + escaped + "' selected='selected' disabled='disabled'>" + escaped + "</option>";
  2627. }
  2628. urlConfigHtml += "</select>";
  2629. }
  2630. }
  2631. return urlConfigHtml;
  2632. }
  2633. // Handle "click" events on toolbar checkboxes and "change" for select menus.
  2634. // Updates the URL with the new state of `config.urlConfig` values.
  2635. function toolbarChanged() {
  2636. var updatedUrl,
  2637. value,
  2638. tests,
  2639. field = this,
  2640. params = {};
  2641. // Detect if field is a select menu or a checkbox
  2642. if ("selectedIndex" in field) {
  2643. value = field.options[field.selectedIndex].value || undefined;
  2644. } else {
  2645. value = field.checked ? field.defaultValue || true : undefined;
  2646. }
  2647. params[field.name] = value;
  2648. updatedUrl = setUrl(params);
  2649. // Check if we can apply the change without a page refresh
  2650. if ("hidepassed" === field.name && "replaceState" in window.history) {
  2651. QUnit.urlParams[field.name] = value;
  2652. config[field.name] = value || false;
  2653. tests = id("qunit-tests");
  2654. if (tests) {
  2655. toggleClass(tests, "hidepass", value || false);
  2656. }
  2657. window.history.replaceState(null, "", updatedUrl);
  2658. } else {
  2659. window.location = updatedUrl;
  2660. }
  2661. }
  2662. function setUrl(params) {
  2663. var key,
  2664. arrValue,
  2665. i,
  2666. querystring = "?",
  2667. location = window.location;
  2668. params = QUnit.extend(QUnit.extend({}, QUnit.urlParams), params);
  2669. for (key in params) {
  2670. // Skip inherited or undefined properties
  2671. if (hasOwn.call(params, key) && params[key] !== undefined) {
  2672. // Output a parameter for each value of this key
  2673. // (but usually just one)
  2674. arrValue = [].concat(params[key]);
  2675. for (i = 0; i < arrValue.length; i++) {
  2676. querystring += encodeURIComponent(key);
  2677. if (arrValue[i] !== true) {
  2678. querystring += "=" + encodeURIComponent(arrValue[i]);
  2679. }
  2680. querystring += "&";
  2681. }
  2682. }
  2683. }
  2684. return location.protocol + "//" + location.host + location.pathname + querystring.slice(0, -1);
  2685. }
  2686. function applyUrlParams() {
  2687. var i,
  2688. selectedModules = [],
  2689. modulesList = id("qunit-modulefilter-dropdown-list").getElementsByTagName("input"),
  2690. filter = id("qunit-filter-input").value;
  2691. for (i = 0; i < modulesList.length; i++) {
  2692. if (modulesList[i].checked) {
  2693. selectedModules.push(modulesList[i].value);
  2694. }
  2695. }
  2696. window.location = setUrl({
  2697. filter: filter === "" ? undefined : filter,
  2698. moduleId: selectedModules.length === 0 ? undefined : selectedModules,
  2699. // Remove module and testId filter
  2700. module: undefined,
  2701. testId: undefined
  2702. });
  2703. }
  2704. function toolbarUrlConfigContainer() {
  2705. var urlConfigContainer = document$$1.createElement("span");
  2706. urlConfigContainer.innerHTML = getUrlConfigHtml();
  2707. addClass(urlConfigContainer, "qunit-url-config");
  2708. addEvents(urlConfigContainer.getElementsByTagName("input"), "change", toolbarChanged);
  2709. addEvents(urlConfigContainer.getElementsByTagName("select"), "change", toolbarChanged);
  2710. return urlConfigContainer;
  2711. }
  2712. function abortTestsButton() {
  2713. var button = document$$1.createElement("button");
  2714. button.id = "qunit-abort-tests-button";
  2715. button.innerHTML = "Abort";
  2716. addEvent(button, "click", abortTests);
  2717. return button;
  2718. }
  2719. function toolbarLooseFilter() {
  2720. var filter = document$$1.createElement("form"),
  2721. label = document$$1.createElement("label"),
  2722. input = document$$1.createElement("input"),
  2723. button = document$$1.createElement("button");
  2724. addClass(filter, "qunit-filter");
  2725. label.innerHTML = "Filter: ";
  2726. input.type = "text";
  2727. input.value = config.filter || "";
  2728. input.name = "filter";
  2729. input.id = "qunit-filter-input";
  2730. button.innerHTML = "Go";
  2731. label.appendChild(input);
  2732. filter.appendChild(label);
  2733. filter.appendChild(document$$1.createTextNode(" "));
  2734. filter.appendChild(button);
  2735. addEvent(filter, "submit", interceptNavigation);
  2736. return filter;
  2737. }
  2738. function moduleListHtml() {
  2739. var i,
  2740. checked,
  2741. html = "";
  2742. for (i = 0; i < config.modules.length; i++) {
  2743. if (config.modules[i].name !== "") {
  2744. checked = config.moduleId.indexOf(config.modules[i].moduleId) > -1;
  2745. html += "<li><label class='clickable" + (checked ? " checked" : "") + "'><input type='checkbox' " + "value='" + config.modules[i].moduleId + "'" + (checked ? " checked='checked'" : "") + " />" + escapeText(config.modules[i].name) + "</label></li>";
  2746. }
  2747. }
  2748. return html;
  2749. }
  2750. function toolbarModuleFilter() {
  2751. var allCheckbox,
  2752. commit,
  2753. reset,
  2754. moduleFilter = document$$1.createElement("form"),
  2755. label = document$$1.createElement("label"),
  2756. moduleSearch = document$$1.createElement("input"),
  2757. dropDown = document$$1.createElement("div"),
  2758. actions = document$$1.createElement("span"),
  2759. dropDownList = document$$1.createElement("ul"),
  2760. dirty = false;
  2761. moduleSearch.id = "qunit-modulefilter-search";
  2762. addEvent(moduleSearch, "input", searchInput);
  2763. addEvent(moduleSearch, "input", searchFocus);
  2764. addEvent(moduleSearch, "focus", searchFocus);
  2765. addEvent(moduleSearch, "click", searchFocus);
  2766. label.id = "qunit-modulefilter-search-container";
  2767. label.innerHTML = "Module: ";
  2768. label.appendChild(moduleSearch);
  2769. actions.id = "qunit-modulefilter-actions";
  2770. actions.innerHTML = "<button style='display:none'>Apply</button>" + "<button type='reset' style='display:none'>Reset</button>" + "<label class='clickable" + (config.moduleId.length ? "" : " checked") + "'><input type='checkbox'" + (config.moduleId.length ? "" : " checked='checked'") + ">All modules</label>";
  2771. allCheckbox = actions.lastChild.firstChild;
  2772. commit = actions.firstChild;
  2773. reset = commit.nextSibling;
  2774. addEvent(commit, "click", applyUrlParams);
  2775. dropDownList.id = "qunit-modulefilter-dropdown-list";
  2776. dropDownList.innerHTML = moduleListHtml();
  2777. dropDown.id = "qunit-modulefilter-dropdown";
  2778. dropDown.style.display = "none";
  2779. dropDown.appendChild(actions);
  2780. dropDown.appendChild(dropDownList);
  2781. addEvent(dropDown, "change", selectionChange);
  2782. selectionChange();
  2783. moduleFilter.id = "qunit-modulefilter";
  2784. moduleFilter.appendChild(label);
  2785. moduleFilter.appendChild(dropDown);
  2786. addEvent(moduleFilter, "submit", interceptNavigation);
  2787. addEvent(moduleFilter, "reset", function () {
  2788. // Let the reset happen, then update styles
  2789. window.setTimeout(selectionChange);
  2790. });
  2791. // Enables show/hide for the dropdown
  2792. function searchFocus() {
  2793. if (dropDown.style.display !== "none") {
  2794. return;
  2795. }
  2796. dropDown.style.display = "block";
  2797. addEvent(document$$1, "click", hideHandler);
  2798. addEvent(document$$1, "keydown", hideHandler);
  2799. // Hide on Escape keydown or outside-container click
  2800. function hideHandler(e) {
  2801. var inContainer = moduleFilter.contains(e.target);
  2802. if (e.keyCode === 27 || !inContainer) {
  2803. if (e.keyCode === 27 && inContainer) {
  2804. moduleSearch.focus();
  2805. }
  2806. dropDown.style.display = "none";
  2807. removeEvent(document$$1, "click", hideHandler);
  2808. removeEvent(document$$1, "keydown", hideHandler);
  2809. moduleSearch.value = "";
  2810. searchInput();
  2811. }
  2812. }
  2813. }
  2814. // Processes module search box input
  2815. function searchInput() {
  2816. var i,
  2817. item,
  2818. searchText = moduleSearch.value.toLowerCase(),
  2819. listItems = dropDownList.children;
  2820. for (i = 0; i < listItems.length; i++) {
  2821. item = listItems[i];
  2822. if (!searchText || item.textContent.toLowerCase().indexOf(searchText) > -1) {
  2823. item.style.display = "";
  2824. } else {
  2825. item.style.display = "none";
  2826. }
  2827. }
  2828. }
  2829. // Processes selection changes
  2830. function selectionChange(evt) {
  2831. var i,
  2832. item,
  2833. checkbox = evt && evt.target || allCheckbox,
  2834. modulesList = dropDownList.getElementsByTagName("input"),
  2835. selectedNames = [];
  2836. toggleClass(checkbox.parentNode, "checked", checkbox.checked);
  2837. dirty = false;
  2838. if (checkbox.checked && checkbox !== allCheckbox) {
  2839. allCheckbox.checked = false;
  2840. removeClass(allCheckbox.parentNode, "checked");
  2841. }
  2842. for (i = 0; i < modulesList.length; i++) {
  2843. item = modulesList[i];
  2844. if (!evt) {
  2845. toggleClass(item.parentNode, "checked", item.checked);
  2846. } else if (checkbox === allCheckbox && checkbox.checked) {
  2847. item.checked = false;
  2848. removeClass(item.parentNode, "checked");
  2849. }
  2850. dirty = dirty || item.checked !== item.defaultChecked;
  2851. if (item.checked) {
  2852. selectedNames.push(item.parentNode.textContent);
  2853. }
  2854. }
  2855. commit.style.display = reset.style.display = dirty ? "" : "none";
  2856. moduleSearch.placeholder = selectedNames.join(", ") || allCheckbox.parentNode.textContent;
  2857. moduleSearch.title = "Type to filter list. Current selection:\n" + (selectedNames.join("\n") || allCheckbox.parentNode.textContent);
  2858. }
  2859. return moduleFilter;
  2860. }
  2861. function appendToolbar() {
  2862. var toolbar = id("qunit-testrunner-toolbar");
  2863. if (toolbar) {
  2864. toolbar.appendChild(toolbarUrlConfigContainer());
  2865. toolbar.appendChild(toolbarModuleFilter());
  2866. toolbar.appendChild(toolbarLooseFilter());
  2867. toolbar.appendChild(document$$1.createElement("div")).className = "clearfix";
  2868. }
  2869. }
  2870. function appendHeader() {
  2871. var header = id("qunit-header");
  2872. if (header) {
  2873. header.innerHTML = "<a href='" + escapeText(unfilteredUrl) + "'>" + header.innerHTML + "</a> ";
  2874. }
  2875. }
  2876. function appendBanner() {
  2877. var banner = id("qunit-banner");
  2878. if (banner) {
  2879. banner.className = "";
  2880. }
  2881. }
  2882. function appendTestResults() {
  2883. var tests = id("qunit-tests"),
  2884. result = id("qunit-testresult"),
  2885. controls;
  2886. if (result) {
  2887. result.parentNode.removeChild(result);
  2888. }
  2889. if (tests) {
  2890. tests.innerHTML = "";
  2891. result = document$$1.createElement("p");
  2892. result.id = "qunit-testresult";
  2893. result.className = "result";
  2894. tests.parentNode.insertBefore(result, tests);
  2895. result.innerHTML = "<div id=\"qunit-testresult-display\">Running...<br />&#160;</div>" + "<div id=\"qunit-testresult-controls\"></div>" + "<div class=\"clearfix\"></div>";
  2896. controls = id("qunit-testresult-controls");
  2897. }
  2898. if (controls) {
  2899. controls.appendChild(abortTestsButton());
  2900. }
  2901. }
  2902. function appendFilteredTest() {
  2903. var testId = QUnit.config.testId;
  2904. if (!testId || testId.length <= 0) {
  2905. return "";
  2906. }
  2907. return "<div id='qunit-filteredTest'>Rerunning selected tests: " + escapeText(testId.join(", ")) + " <a id='qunit-clearFilter' href='" + escapeText(unfilteredUrl) + "'>Run all tests</a></div>";
  2908. }
  2909. function appendUserAgent() {
  2910. var userAgent = id("qunit-userAgent");
  2911. if (userAgent) {
  2912. userAgent.innerHTML = "";
  2913. userAgent.appendChild(document$$1.createTextNode("QUnit " + QUnit.version + "; " + navigator.userAgent));
  2914. }
  2915. }
  2916. function appendInterface() {
  2917. var qunit = id("qunit");
  2918. if (qunit) {
  2919. qunit.innerHTML = "<h1 id='qunit-header'>" + escapeText(document$$1.title) + "</h1>" + "<h2 id='qunit-banner'></h2>" + "<div id='qunit-testrunner-toolbar'></div>" + appendFilteredTest() + "<h2 id='qunit-userAgent'></h2>" + "<ol id='qunit-tests'></ol>";
  2920. }
  2921. appendHeader();
  2922. appendBanner();
  2923. appendTestResults();
  2924. appendUserAgent();
  2925. appendToolbar();
  2926. }
  2927. function appendTestsList(modules) {
  2928. var i, l, x, z, test, moduleObj;
  2929. for (i = 0, l = modules.length; i < l; i++) {
  2930. moduleObj = modules[i];
  2931. for (x = 0, z = moduleObj.tests.length; x < z; x++) {
  2932. test = moduleObj.tests[x];
  2933. appendTest(test.name, test.testId, moduleObj.name);
  2934. }
  2935. }
  2936. }
  2937. function appendTest(name, testId, moduleName) {
  2938. var title,
  2939. rerunTrigger,
  2940. testBlock,
  2941. assertList,
  2942. tests = id("qunit-tests");
  2943. if (!tests) {
  2944. return;
  2945. }
  2946. title = document$$1.createElement("strong");
  2947. title.innerHTML = getNameHtml(name, moduleName);
  2948. rerunTrigger = document$$1.createElement("a");
  2949. rerunTrigger.innerHTML = "Rerun";
  2950. rerunTrigger.href = setUrl({ testId: testId });
  2951. testBlock = document$$1.createElement("li");
  2952. testBlock.appendChild(title);
  2953. testBlock.appendChild(rerunTrigger);
  2954. testBlock.id = "qunit-test-output-" + testId;
  2955. assertList = document$$1.createElement("ol");
  2956. assertList.className = "qunit-assert-list";
  2957. testBlock.appendChild(assertList);
  2958. tests.appendChild(testBlock);
  2959. }
  2960. // HTML Reporter initialization and load
  2961. QUnit.begin(function (details) {
  2962. var i, moduleObj, tests;
  2963. // Sort modules by name for the picker
  2964. for (i = 0; i < details.modules.length; i++) {
  2965. moduleObj = details.modules[i];
  2966. if (moduleObj.name) {
  2967. modulesList.push(moduleObj.name);
  2968. }
  2969. }
  2970. modulesList.sort(function (a, b) {
  2971. return a.localeCompare(b);
  2972. });
  2973. // Initialize QUnit elements
  2974. appendInterface();
  2975. appendTestsList(details.modules);
  2976. tests = id("qunit-tests");
  2977. if (tests && config.hidepassed) {
  2978. addClass(tests, "hidepass");
  2979. }
  2980. });
  2981. QUnit.done(function (details) {
  2982. var banner = id("qunit-banner"),
  2983. tests = id("qunit-tests"),
  2984. abortButton = id("qunit-abort-tests-button"),
  2985. totalTests = stats.passedTests + stats.skippedTests + stats.todoTests + stats.failedTests,
  2986. html = [totalTests, " tests completed in ", details.runtime, " milliseconds, with ", stats.failedTests, " failed, ", stats.skippedTests, " skipped, and ", stats.todoTests, " todo.<br />", "<span class='passed'>", details.passed, "</span> assertions of <span class='total'>", details.total, "</span> passed, <span class='failed'>", details.failed, "</span> failed."].join(""),
  2987. test,
  2988. assertLi,
  2989. assertList;
  2990. // Update remaing tests to aborted
  2991. if (abortButton && abortButton.disabled) {
  2992. html = "Tests aborted after " + details.runtime + " milliseconds.";
  2993. for (var i = 0; i < tests.children.length; i++) {
  2994. test = tests.children[i];
  2995. if (test.className === "" || test.className === "running") {
  2996. test.className = "aborted";
  2997. assertList = test.getElementsByTagName("ol")[0];
  2998. assertLi = document$$1.createElement("li");
  2999. assertLi.className = "fail";
  3000. assertLi.innerHTML = "Test aborted.";
  3001. assertList.appendChild(assertLi);
  3002. }
  3003. }
  3004. }
  3005. if (banner && (!abortButton || abortButton.disabled === false)) {
  3006. banner.className = stats.failedTests ? "qunit-fail" : "qunit-pass";
  3007. }
  3008. if (abortButton) {
  3009. abortButton.parentNode.removeChild(abortButton);
  3010. }
  3011. if (tests) {
  3012. id("qunit-testresult-display").innerHTML = html;
  3013. }
  3014. if (config.altertitle && document$$1.title) {
  3015. // Show ✖ for good, ✔ for bad suite result in title
  3016. // use escape sequences in case file gets loaded with non-utf-8
  3017. // charset
  3018. document$$1.title = [stats.failedTests ? "\u2716" : "\u2714", document$$1.title.replace(/^[\u2714\u2716] /i, "")].join(" ");
  3019. }
  3020. // Scroll back to top to show results
  3021. if (config.scrolltop && window.scrollTo) {
  3022. window.scrollTo(0, 0);
  3023. }
  3024. });
  3025. function getNameHtml(name, module) {
  3026. var nameHtml = "";
  3027. if (module) {
  3028. nameHtml = "<span class='module-name'>" + escapeText(module) + "</span>: ";
  3029. }
  3030. nameHtml += "<span class='test-name'>" + escapeText(name) + "</span>";
  3031. return nameHtml;
  3032. }
  3033. QUnit.testStart(function (details) {
  3034. var running, testBlock, bad;
  3035. testBlock = id("qunit-test-output-" + details.testId);
  3036. if (testBlock) {
  3037. testBlock.className = "running";
  3038. } else {
  3039. // Report later registered tests
  3040. appendTest(details.name, details.testId, details.module);
  3041. }
  3042. running = id("qunit-testresult-display");
  3043. if (running) {
  3044. bad = QUnit.config.reorder && details.previousFailure;
  3045. running.innerHTML = [bad ? "Rerunning previously failed test: <br />" : "Running: <br />", getNameHtml(details.name, details.module)].join("");
  3046. }
  3047. });
  3048. function stripHtml(string) {
  3049. // Strip tags, html entity and whitespaces
  3050. return string.replace(/<\/?[^>]+(>|$)/g, "").replace(/\&quot;/g, "").replace(/\s+/g, "");
  3051. }
  3052. QUnit.log(function (details) {
  3053. var assertList,
  3054. assertLi,
  3055. message,
  3056. expected,
  3057. actual,
  3058. diff,
  3059. showDiff = false,
  3060. testItem = id("qunit-test-output-" + details.testId);
  3061. if (!testItem) {
  3062. return;
  3063. }
  3064. message = escapeText(details.message) || (details.result ? "okay" : "failed");
  3065. message = "<span class='test-message'>" + message + "</span>";
  3066. message += "<span class='runtime'>@ " + details.runtime + " ms</span>";
  3067. // The pushFailure doesn't provide details.expected
  3068. // when it calls, it's implicit to also not show expected and diff stuff
  3069. // Also, we need to check details.expected existence, as it can exist and be undefined
  3070. if (!details.result && hasOwn.call(details, "expected")) {
  3071. if (details.negative) {
  3072. expected = "NOT " + QUnit.dump.parse(details.expected);
  3073. } else {
  3074. expected = QUnit.dump.parse(details.expected);
  3075. }
  3076. actual = QUnit.dump.parse(details.actual);
  3077. message += "<table><tr class='test-expected'><th>Expected: </th><td><pre>" + escapeText(expected) + "</pre></td></tr>";
  3078. if (actual !== expected) {
  3079. message += "<tr class='test-actual'><th>Result: </th><td><pre>" + escapeText(actual) + "</pre></td></tr>";
  3080. if (typeof details.actual === "number" && typeof details.expected === "number") {
  3081. if (!isNaN(details.actual) && !isNaN(details.expected)) {
  3082. showDiff = true;
  3083. diff = details.actual - details.expected;
  3084. diff = (diff > 0 ? "+" : "") + diff;
  3085. }
  3086. } else if (typeof details.actual !== "boolean" && typeof details.expected !== "boolean") {
  3087. diff = QUnit.diff(expected, actual);
  3088. // don't show diff if there is zero overlap
  3089. showDiff = stripHtml(diff).length !== stripHtml(expected).length + stripHtml(actual).length;
  3090. }
  3091. if (showDiff) {
  3092. message += "<tr class='test-diff'><th>Diff: </th><td><pre>" + diff + "</pre></td></tr>";
  3093. }
  3094. } else if (expected.indexOf("[object Array]") !== -1 || expected.indexOf("[object Object]") !== -1) {
  3095. message += "<tr class='test-message'><th>Message: </th><td>" + "Diff suppressed as the depth of object is more than current max depth (" + QUnit.config.maxDepth + ").<p>Hint: Use <code>QUnit.dump.maxDepth</code> to " + " run with a higher max depth or <a href='" + escapeText(setUrl({ maxDepth: -1 })) + "'>" + "Rerun</a> without max depth.</p></td></tr>";
  3096. } else {
  3097. message += "<tr class='test-message'><th>Message: </th><td>" + "Diff suppressed as the expected and actual results have an equivalent" + " serialization</td></tr>";
  3098. }
  3099. if (details.source) {
  3100. message += "<tr class='test-source'><th>Source: </th><td><pre>" + escapeText(details.source) + "</pre></td></tr>";
  3101. }
  3102. message += "</table>";
  3103. // This occurs when pushFailure is set and we have an extracted stack trace
  3104. } else if (!details.result && details.source) {
  3105. message += "<table>" + "<tr class='test-source'><th>Source: </th><td><pre>" + escapeText(details.source) + "</pre></td></tr>" + "</table>";
  3106. }
  3107. assertList = testItem.getElementsByTagName("ol")[0];
  3108. assertLi = document$$1.createElement("li");
  3109. assertLi.className = details.result ? "pass" : "fail";
  3110. assertLi.innerHTML = message;
  3111. assertList.appendChild(assertLi);
  3112. });
  3113. QUnit.testDone(function (details) {
  3114. var testTitle,
  3115. time,
  3116. testItem,
  3117. assertList,
  3118. good,
  3119. bad,
  3120. testCounts,
  3121. skipped,
  3122. sourceName,
  3123. tests = id("qunit-tests");
  3124. if (!tests) {
  3125. return;
  3126. }
  3127. testItem = id("qunit-test-output-" + details.testId);
  3128. assertList = testItem.getElementsByTagName("ol")[0];
  3129. good = details.passed;
  3130. bad = details.failed;
  3131. // This test passed if it has no unexpected failed assertions
  3132. var testPassed = details.failed > 0 ? details.todo : !details.todo;
  3133. if (testPassed) {
  3134. // Collapse the passing tests
  3135. addClass(assertList, "qunit-collapsed");
  3136. } else if (config.collapse) {
  3137. if (!collapseNext) {
  3138. // Skip collapsing the first failing test
  3139. collapseNext = true;
  3140. } else {
  3141. // Collapse remaining tests
  3142. addClass(assertList, "qunit-collapsed");
  3143. }
  3144. }
  3145. // The testItem.firstChild is the test name
  3146. testTitle = testItem.firstChild;
  3147. testCounts = bad ? "<b class='failed'>" + bad + "</b>, " + "<b class='passed'>" + good + "</b>, " : "";
  3148. testTitle.innerHTML += " <b class='counts'>(" + testCounts + details.assertions.length + ")</b>";
  3149. if (details.skipped) {
  3150. stats.skippedTests++;
  3151. testItem.className = "skipped";
  3152. skipped = document$$1.createElement("em");
  3153. skipped.className = "qunit-skipped-label";
  3154. skipped.innerHTML = "skipped";
  3155. testItem.insertBefore(skipped, testTitle);
  3156. } else {
  3157. addEvent(testTitle, "click", function () {
  3158. toggleClass(assertList, "qunit-collapsed");
  3159. });
  3160. testItem.className = testPassed ? "pass" : "fail";
  3161. if (details.todo) {
  3162. var todoLabel = document$$1.createElement("em");
  3163. todoLabel.className = "qunit-todo-label";
  3164. todoLabel.innerHTML = "todo";
  3165. testItem.className += " todo";
  3166. testItem.insertBefore(todoLabel, testTitle);
  3167. }
  3168. time = document$$1.createElement("span");
  3169. time.className = "runtime";
  3170. time.innerHTML = details.runtime + " ms";
  3171. testItem.insertBefore(time, assertList);
  3172. if (!testPassed) {
  3173. stats.failedTests++;
  3174. } else if (details.todo) {
  3175. stats.todoTests++;
  3176. } else {
  3177. stats.passedTests++;
  3178. }
  3179. }
  3180. // Show the source of the test when showing assertions
  3181. if (details.source) {
  3182. sourceName = document$$1.createElement("p");
  3183. sourceName.innerHTML = "<strong>Source: </strong>" + details.source;
  3184. addClass(sourceName, "qunit-source");
  3185. if (testPassed) {
  3186. addClass(sourceName, "qunit-collapsed");
  3187. }
  3188. addEvent(testTitle, "click", function () {
  3189. toggleClass(sourceName, "qunit-collapsed");
  3190. });
  3191. testItem.appendChild(sourceName);
  3192. }
  3193. });
  3194. // Avoid readyState issue with phantomjs
  3195. // Ref: #818
  3196. var notPhantom = function (p) {
  3197. return !(p && p.version && p.version.major > 0);
  3198. }(window.phantom);
  3199. if (notPhantom && document$$1.readyState === "complete") {
  3200. QUnit.load();
  3201. } else {
  3202. addEvent(window, "load", QUnit.load);
  3203. }
  3204. // Wrap window.onerror. We will call the original window.onerror to see if
  3205. // the existing handler fully handles the error; if not, we will call the
  3206. // QUnit.onError function.
  3207. var originalWindowOnError = window.onerror;
  3208. // Cover uncaught exceptions
  3209. // Returning true will suppress the default browser handler,
  3210. // returning false will let it run.
  3211. window.onerror = function (message, fileName, lineNumber) {
  3212. var ret = false;
  3213. if (originalWindowOnError) {
  3214. for (var _len = arguments.length, args = Array(_len > 3 ? _len - 3 : 0), _key = 3; _key < _len; _key++) {
  3215. args[_key - 3] = arguments[_key];
  3216. }
  3217. ret = originalWindowOnError.call.apply(originalWindowOnError, [this, message, fileName, lineNumber].concat(args));
  3218. }
  3219. // Treat return value as window.onerror itself does,
  3220. // Only do our handling if not suppressed.
  3221. if (ret !== true) {
  3222. var error = {
  3223. message: message,
  3224. fileName: fileName,
  3225. lineNumber: lineNumber
  3226. };
  3227. ret = QUnit.onError(error);
  3228. }
  3229. return ret;
  3230. };
  3231. })();
  3232. /*
  3233. * This file is a modified version of google-diff-match-patch's JavaScript implementation
  3234. * (https://code.google.com/p/google-diff-match-patch/source/browse/trunk/javascript/diff_match_patch_uncompressed.js),
  3235. * modifications are licensed as more fully set forth in LICENSE.txt.
  3236. *
  3237. * The original source of google-diff-match-patch is attributable and licensed as follows:
  3238. *
  3239. * Copyright 2006 Google Inc.
  3240. * https://code.google.com/p/google-diff-match-patch/
  3241. *
  3242. * Licensed under the Apache License, Version 2.0 (the "License");
  3243. * you may not use this file except in compliance with the License.
  3244. * You may obtain a copy of the License at
  3245. *
  3246. * https://www.apache.org/licenses/LICENSE-2.0
  3247. *
  3248. * Unless required by applicable law or agreed to in writing, software
  3249. * distributed under the License is distributed on an "AS IS" BASIS,
  3250. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  3251. * See the License for the specific language governing permissions and
  3252. * limitations under the License.
  3253. *
  3254. * More Info:
  3255. * https://code.google.com/p/google-diff-match-patch/
  3256. *
  3257. * Usage: QUnit.diff(expected, actual)
  3258. *
  3259. */
  3260. QUnit.diff = function () {
  3261. function DiffMatchPatch() {}
  3262. // DIFF FUNCTIONS
  3263. /**
  3264. * The data structure representing a diff is an array of tuples:
  3265. * [[DIFF_DELETE, 'Hello'], [DIFF_INSERT, 'Goodbye'], [DIFF_EQUAL, ' world.']]
  3266. * which means: delete 'Hello', add 'Goodbye' and keep ' world.'
  3267. */
  3268. var DIFF_DELETE = -1,
  3269. DIFF_INSERT = 1,
  3270. DIFF_EQUAL = 0;
  3271. /**
  3272. * Find the differences between two texts. Simplifies the problem by stripping
  3273. * any common prefix or suffix off the texts before diffing.
  3274. * @param {string} text1 Old string to be diffed.
  3275. * @param {string} text2 New string to be diffed.
  3276. * @param {boolean=} optChecklines Optional speedup flag. If present and false,
  3277. * then don't run a line-level diff first to identify the changed areas.
  3278. * Defaults to true, which does a faster, slightly less optimal diff.
  3279. * @return {!Array.<!DiffMatchPatch.Diff>} Array of diff tuples.
  3280. */
  3281. DiffMatchPatch.prototype.DiffMain = function (text1, text2, optChecklines) {
  3282. var deadline, checklines, commonlength, commonprefix, commonsuffix, diffs;
  3283. // The diff must be complete in up to 1 second.
  3284. deadline = new Date().getTime() + 1000;
  3285. // Check for null inputs.
  3286. if (text1 === null || text2 === null) {
  3287. throw new Error("Null input. (DiffMain)");
  3288. }
  3289. // Check for equality (speedup).
  3290. if (text1 === text2) {
  3291. if (text1) {
  3292. return [[DIFF_EQUAL, text1]];
  3293. }
  3294. return [];
  3295. }
  3296. if (typeof optChecklines === "undefined") {
  3297. optChecklines = true;
  3298. }
  3299. checklines = optChecklines;
  3300. // Trim off common prefix (speedup).
  3301. commonlength = this.diffCommonPrefix(text1, text2);
  3302. commonprefix = text1.substring(0, commonlength);
  3303. text1 = text1.substring(commonlength);
  3304. text2 = text2.substring(commonlength);
  3305. // Trim off common suffix (speedup).
  3306. commonlength = this.diffCommonSuffix(text1, text2);
  3307. commonsuffix = text1.substring(text1.length - commonlength);
  3308. text1 = text1.substring(0, text1.length - commonlength);
  3309. text2 = text2.substring(0, text2.length - commonlength);
  3310. // Compute the diff on the middle block.
  3311. diffs = this.diffCompute(text1, text2, checklines, deadline);
  3312. // Restore the prefix and suffix.
  3313. if (commonprefix) {
  3314. diffs.unshift([DIFF_EQUAL, commonprefix]);
  3315. }
  3316. if (commonsuffix) {
  3317. diffs.push([DIFF_EQUAL, commonsuffix]);
  3318. }
  3319. this.diffCleanupMerge(diffs);
  3320. return diffs;
  3321. };
  3322. /**
  3323. * Reduce the number of edits by eliminating operationally trivial equalities.
  3324. * @param {!Array.<!DiffMatchPatch.Diff>} diffs Array of diff tuples.
  3325. */
  3326. DiffMatchPatch.prototype.diffCleanupEfficiency = function (diffs) {
  3327. var changes, equalities, equalitiesLength, lastequality, pointer, preIns, preDel, postIns, postDel;
  3328. changes = false;
  3329. equalities = []; // Stack of indices where equalities are found.
  3330. equalitiesLength = 0; // Keeping our own length var is faster in JS.
  3331. /** @type {?string} */
  3332. lastequality = null;
  3333. // Always equal to diffs[equalities[equalitiesLength - 1]][1]
  3334. pointer = 0; // Index of current position.
  3335. // Is there an insertion operation before the last equality.
  3336. preIns = false;
  3337. // Is there a deletion operation before the last equality.
  3338. preDel = false;
  3339. // Is there an insertion operation after the last equality.
  3340. postIns = false;
  3341. // Is there a deletion operation after the last equality.
  3342. postDel = false;
  3343. while (pointer < diffs.length) {
  3344. // Equality found.
  3345. if (diffs[pointer][0] === DIFF_EQUAL) {
  3346. if (diffs[pointer][1].length < 4 && (postIns || postDel)) {
  3347. // Candidate found.
  3348. equalities[equalitiesLength++] = pointer;
  3349. preIns = postIns;
  3350. preDel = postDel;
  3351. lastequality = diffs[pointer][1];
  3352. } else {
  3353. // Not a candidate, and can never become one.
  3354. equalitiesLength = 0;
  3355. lastequality = null;
  3356. }
  3357. postIns = postDel = false;
  3358. // An insertion or deletion.
  3359. } else {
  3360. if (diffs[pointer][0] === DIFF_DELETE) {
  3361. postDel = true;
  3362. } else {
  3363. postIns = true;
  3364. }
  3365. /*
  3366. * Five types to be split:
  3367. * <ins>A</ins><del>B</del>XY<ins>C</ins><del>D</del>
  3368. * <ins>A</ins>X<ins>C</ins><del>D</del>
  3369. * <ins>A</ins><del>B</del>X<ins>C</ins>
  3370. * <ins>A</del>X<ins>C</ins><del>D</del>
  3371. * <ins>A</ins><del>B</del>X<del>C</del>
  3372. */
  3373. if (lastequality && (preIns && preDel && postIns && postDel || lastequality.length < 2 && preIns + preDel + postIns + postDel === 3)) {
  3374. // Duplicate record.
  3375. diffs.splice(equalities[equalitiesLength - 1], 0, [DIFF_DELETE, lastequality]);
  3376. // Change second copy to insert.
  3377. diffs[equalities[equalitiesLength - 1] + 1][0] = DIFF_INSERT;
  3378. equalitiesLength--; // Throw away the equality we just deleted;
  3379. lastequality = null;
  3380. if (preIns && preDel) {
  3381. // No changes made which could affect previous entry, keep going.
  3382. postIns = postDel = true;
  3383. equalitiesLength = 0;
  3384. } else {
  3385. equalitiesLength--; // Throw away the previous equality.
  3386. pointer = equalitiesLength > 0 ? equalities[equalitiesLength - 1] : -1;
  3387. postIns = postDel = false;
  3388. }
  3389. changes = true;
  3390. }
  3391. }
  3392. pointer++;
  3393. }
  3394. if (changes) {
  3395. this.diffCleanupMerge(diffs);
  3396. }
  3397. };
  3398. /**
  3399. * Convert a diff array into a pretty HTML report.
  3400. * @param {!Array.<!DiffMatchPatch.Diff>} diffs Array of diff tuples.
  3401. * @param {integer} string to be beautified.
  3402. * @return {string} HTML representation.
  3403. */
  3404. DiffMatchPatch.prototype.diffPrettyHtml = function (diffs) {
  3405. var op,
  3406. data,
  3407. x,
  3408. html = [];
  3409. for (x = 0; x < diffs.length; x++) {
  3410. op = diffs[x][0]; // Operation (insert, delete, equal)
  3411. data = diffs[x][1]; // Text of change.
  3412. switch (op) {
  3413. case DIFF_INSERT:
  3414. html[x] = "<ins>" + escapeText(data) + "</ins>";
  3415. break;
  3416. case DIFF_DELETE:
  3417. html[x] = "<del>" + escapeText(data) + "</del>";
  3418. break;
  3419. case DIFF_EQUAL:
  3420. html[x] = "<span>" + escapeText(data) + "</span>";
  3421. break;
  3422. }
  3423. }
  3424. return html.join("");
  3425. };
  3426. /**
  3427. * Determine the common prefix of two strings.
  3428. * @param {string} text1 First string.
  3429. * @param {string} text2 Second string.
  3430. * @return {number} The number of characters common to the start of each
  3431. * string.
  3432. */
  3433. DiffMatchPatch.prototype.diffCommonPrefix = function (text1, text2) {
  3434. var pointermid, pointermax, pointermin, pointerstart;
  3435. // Quick check for common null cases.
  3436. if (!text1 || !text2 || text1.charAt(0) !== text2.charAt(0)) {
  3437. return 0;
  3438. }
  3439. // Binary search.
  3440. // Performance analysis: https://neil.fraser.name/news/2007/10/09/
  3441. pointermin = 0;
  3442. pointermax = Math.min(text1.length, text2.length);
  3443. pointermid = pointermax;
  3444. pointerstart = 0;
  3445. while (pointermin < pointermid) {
  3446. if (text1.substring(pointerstart, pointermid) === text2.substring(pointerstart, pointermid)) {
  3447. pointermin = pointermid;
  3448. pointerstart = pointermin;
  3449. } else {
  3450. pointermax = pointermid;
  3451. }
  3452. pointermid = Math.floor((pointermax - pointermin) / 2 + pointermin);
  3453. }
  3454. return pointermid;
  3455. };
  3456. /**
  3457. * Determine the common suffix of two strings.
  3458. * @param {string} text1 First string.
  3459. * @param {string} text2 Second string.
  3460. * @return {number} The number of characters common to the end of each string.
  3461. */
  3462. DiffMatchPatch.prototype.diffCommonSuffix = function (text1, text2) {
  3463. var pointermid, pointermax, pointermin, pointerend;
  3464. // Quick check for common null cases.
  3465. if (!text1 || !text2 || text1.charAt(text1.length - 1) !== text2.charAt(text2.length - 1)) {
  3466. return 0;
  3467. }
  3468. // Binary search.
  3469. // Performance analysis: https://neil.fraser.name/news/2007/10/09/
  3470. pointermin = 0;
  3471. pointermax = Math.min(text1.length, text2.length);
  3472. pointermid = pointermax;
  3473. pointerend = 0;
  3474. while (pointermin < pointermid) {
  3475. if (text1.substring(text1.length - pointermid, text1.length - pointerend) === text2.substring(text2.length - pointermid, text2.length - pointerend)) {
  3476. pointermin = pointermid;
  3477. pointerend = pointermin;
  3478. } else {
  3479. pointermax = pointermid;
  3480. }
  3481. pointermid = Math.floor((pointermax - pointermin) / 2 + pointermin);
  3482. }
  3483. return pointermid;
  3484. };
  3485. /**
  3486. * Find the differences between two texts. Assumes that the texts do not
  3487. * have any common prefix or suffix.
  3488. * @param {string} text1 Old string to be diffed.
  3489. * @param {string} text2 New string to be diffed.
  3490. * @param {boolean} checklines Speedup flag. If false, then don't run a
  3491. * line-level diff first to identify the changed areas.
  3492. * If true, then run a faster, slightly less optimal diff.
  3493. * @param {number} deadline Time when the diff should be complete by.
  3494. * @return {!Array.<!DiffMatchPatch.Diff>} Array of diff tuples.
  3495. * @private
  3496. */
  3497. DiffMatchPatch.prototype.diffCompute = function (text1, text2, checklines, deadline) {
  3498. var diffs, longtext, shorttext, i, hm, text1A, text2A, text1B, text2B, midCommon, diffsA, diffsB;
  3499. if (!text1) {
  3500. // Just add some text (speedup).
  3501. return [[DIFF_INSERT, text2]];
  3502. }
  3503. if (!text2) {
  3504. // Just delete some text (speedup).
  3505. return [[DIFF_DELETE, text1]];
  3506. }
  3507. longtext = text1.length > text2.length ? text1 : text2;
  3508. shorttext = text1.length > text2.length ? text2 : text1;
  3509. i = longtext.indexOf(shorttext);
  3510. if (i !== -1) {
  3511. // Shorter text is inside the longer text (speedup).
  3512. diffs = [[DIFF_INSERT, longtext.substring(0, i)], [DIFF_EQUAL, shorttext], [DIFF_INSERT, longtext.substring(i + shorttext.length)]];
  3513. // Swap insertions for deletions if diff is reversed.
  3514. if (text1.length > text2.length) {
  3515. diffs[0][0] = diffs[2][0] = DIFF_DELETE;
  3516. }
  3517. return diffs;
  3518. }
  3519. if (shorttext.length === 1) {
  3520. // Single character string.
  3521. // After the previous speedup, the character can't be an equality.
  3522. return [[DIFF_DELETE, text1], [DIFF_INSERT, text2]];
  3523. }
  3524. // Check to see if the problem can be split in two.
  3525. hm = this.diffHalfMatch(text1, text2);
  3526. if (hm) {
  3527. // A half-match was found, sort out the return data.
  3528. text1A = hm[0];
  3529. text1B = hm[1];
  3530. text2A = hm[2];
  3531. text2B = hm[3];
  3532. midCommon = hm[4];
  3533. // Send both pairs off for separate processing.
  3534. diffsA = this.DiffMain(text1A, text2A, checklines, deadline);
  3535. diffsB = this.DiffMain(text1B, text2B, checklines, deadline);
  3536. // Merge the results.
  3537. return diffsA.concat([[DIFF_EQUAL, midCommon]], diffsB);
  3538. }
  3539. if (checklines && text1.length > 100 && text2.length > 100) {
  3540. return this.diffLineMode(text1, text2, deadline);
  3541. }
  3542. return this.diffBisect(text1, text2, deadline);
  3543. };
  3544. /**
  3545. * Do the two texts share a substring which is at least half the length of the
  3546. * longer text?
  3547. * This speedup can produce non-minimal diffs.
  3548. * @param {string} text1 First string.
  3549. * @param {string} text2 Second string.
  3550. * @return {Array.<string>} Five element Array, containing the prefix of
  3551. * text1, the suffix of text1, the prefix of text2, the suffix of
  3552. * text2 and the common middle. Or null if there was no match.
  3553. * @private
  3554. */
  3555. DiffMatchPatch.prototype.diffHalfMatch = function (text1, text2) {
  3556. var longtext, shorttext, dmp, text1A, text2B, text2A, text1B, midCommon, hm1, hm2, hm;
  3557. longtext = text1.length > text2.length ? text1 : text2;
  3558. shorttext = text1.length > text2.length ? text2 : text1;
  3559. if (longtext.length < 4 || shorttext.length * 2 < longtext.length) {
  3560. return null; // Pointless.
  3561. }
  3562. dmp = this; // 'this' becomes 'window' in a closure.
  3563. /**
  3564. * Does a substring of shorttext exist within longtext such that the substring
  3565. * is at least half the length of longtext?
  3566. * Closure, but does not reference any external variables.
  3567. * @param {string} longtext Longer string.
  3568. * @param {string} shorttext Shorter string.
  3569. * @param {number} i Start index of quarter length substring within longtext.
  3570. * @return {Array.<string>} Five element Array, containing the prefix of
  3571. * longtext, the suffix of longtext, the prefix of shorttext, the suffix
  3572. * of shorttext and the common middle. Or null if there was no match.
  3573. * @private
  3574. */
  3575. function diffHalfMatchI(longtext, shorttext, i) {
  3576. var seed, j, bestCommon, prefixLength, suffixLength, bestLongtextA, bestLongtextB, bestShorttextA, bestShorttextB;
  3577. // Start with a 1/4 length substring at position i as a seed.
  3578. seed = longtext.substring(i, i + Math.floor(longtext.length / 4));
  3579. j = -1;
  3580. bestCommon = "";
  3581. while ((j = shorttext.indexOf(seed, j + 1)) !== -1) {
  3582. prefixLength = dmp.diffCommonPrefix(longtext.substring(i), shorttext.substring(j));
  3583. suffixLength = dmp.diffCommonSuffix(longtext.substring(0, i), shorttext.substring(0, j));
  3584. if (bestCommon.length < suffixLength + prefixLength) {
  3585. bestCommon = shorttext.substring(j - suffixLength, j) + shorttext.substring(j, j + prefixLength);
  3586. bestLongtextA = longtext.substring(0, i - suffixLength);
  3587. bestLongtextB = longtext.substring(i + prefixLength);
  3588. bestShorttextA = shorttext.substring(0, j - suffixLength);
  3589. bestShorttextB = shorttext.substring(j + prefixLength);
  3590. }
  3591. }
  3592. if (bestCommon.length * 2 >= longtext.length) {
  3593. return [bestLongtextA, bestLongtextB, bestShorttextA, bestShorttextB, bestCommon];
  3594. } else {
  3595. return null;
  3596. }
  3597. }
  3598. // First check if the second quarter is the seed for a half-match.
  3599. hm1 = diffHalfMatchI(longtext, shorttext, Math.ceil(longtext.length / 4));
  3600. // Check again based on the third quarter.
  3601. hm2 = diffHalfMatchI(longtext, shorttext, Math.ceil(longtext.length / 2));
  3602. if (!hm1 && !hm2) {
  3603. return null;
  3604. } else if (!hm2) {
  3605. hm = hm1;
  3606. } else if (!hm1) {
  3607. hm = hm2;
  3608. } else {
  3609. // Both matched. Select the longest.
  3610. hm = hm1[4].length > hm2[4].length ? hm1 : hm2;
  3611. }
  3612. // A half-match was found, sort out the return data.
  3613. if (text1.length > text2.length) {
  3614. text1A = hm[0];
  3615. text1B = hm[1];
  3616. text2A = hm[2];
  3617. text2B = hm[3];
  3618. } else {
  3619. text2A = hm[0];
  3620. text2B = hm[1];
  3621. text1A = hm[2];
  3622. text1B = hm[3];
  3623. }
  3624. midCommon = hm[4];
  3625. return [text1A, text1B, text2A, text2B, midCommon];
  3626. };
  3627. /**
  3628. * Do a quick line-level diff on both strings, then rediff the parts for
  3629. * greater accuracy.
  3630. * This speedup can produce non-minimal diffs.
  3631. * @param {string} text1 Old string to be diffed.
  3632. * @param {string} text2 New string to be diffed.
  3633. * @param {number} deadline Time when the diff should be complete by.
  3634. * @return {!Array.<!DiffMatchPatch.Diff>} Array of diff tuples.
  3635. * @private
  3636. */
  3637. DiffMatchPatch.prototype.diffLineMode = function (text1, text2, deadline) {
  3638. var a, diffs, linearray, pointer, countInsert, countDelete, textInsert, textDelete, j;
  3639. // Scan the text on a line-by-line basis first.
  3640. a = this.diffLinesToChars(text1, text2);
  3641. text1 = a.chars1;
  3642. text2 = a.chars2;
  3643. linearray = a.lineArray;
  3644. diffs = this.DiffMain(text1, text2, false, deadline);
  3645. // Convert the diff back to original text.
  3646. this.diffCharsToLines(diffs, linearray);
  3647. // Eliminate freak matches (e.g. blank lines)
  3648. this.diffCleanupSemantic(diffs);
  3649. // Rediff any replacement blocks, this time character-by-character.
  3650. // Add a dummy entry at the end.
  3651. diffs.push([DIFF_EQUAL, ""]);
  3652. pointer = 0;
  3653. countDelete = 0;
  3654. countInsert = 0;
  3655. textDelete = "";
  3656. textInsert = "";
  3657. while (pointer < diffs.length) {
  3658. switch (diffs[pointer][0]) {
  3659. case DIFF_INSERT:
  3660. countInsert++;
  3661. textInsert += diffs[pointer][1];
  3662. break;
  3663. case DIFF_DELETE:
  3664. countDelete++;
  3665. textDelete += diffs[pointer][1];
  3666. break;
  3667. case DIFF_EQUAL:
  3668. // Upon reaching an equality, check for prior redundancies.
  3669. if (countDelete >= 1 && countInsert >= 1) {
  3670. // Delete the offending records and add the merged ones.
  3671. diffs.splice(pointer - countDelete - countInsert, countDelete + countInsert);
  3672. pointer = pointer - countDelete - countInsert;
  3673. a = this.DiffMain(textDelete, textInsert, false, deadline);
  3674. for (j = a.length - 1; j >= 0; j--) {
  3675. diffs.splice(pointer, 0, a[j]);
  3676. }
  3677. pointer = pointer + a.length;
  3678. }
  3679. countInsert = 0;
  3680. countDelete = 0;
  3681. textDelete = "";
  3682. textInsert = "";
  3683. break;
  3684. }
  3685. pointer++;
  3686. }
  3687. diffs.pop(); // Remove the dummy entry at the end.
  3688. return diffs;
  3689. };
  3690. /**
  3691. * Find the 'middle snake' of a diff, split the problem in two
  3692. * and return the recursively constructed diff.
  3693. * See Myers 1986 paper: An O(ND) Difference Algorithm and Its Variations.
  3694. * @param {string} text1 Old string to be diffed.
  3695. * @param {string} text2 New string to be diffed.
  3696. * @param {number} deadline Time at which to bail if not yet complete.
  3697. * @return {!Array.<!DiffMatchPatch.Diff>} Array of diff tuples.
  3698. * @private
  3699. */
  3700. DiffMatchPatch.prototype.diffBisect = function (text1, text2, deadline) {
  3701. var text1Length, text2Length, maxD, vOffset, vLength, v1, v2, x, delta, front, k1start, k1end, k2start, k2end, k2Offset, k1Offset, x1, x2, y1, y2, d, k1, k2;
  3702. // Cache the text lengths to prevent multiple calls.
  3703. text1Length = text1.length;
  3704. text2Length = text2.length;
  3705. maxD = Math.ceil((text1Length + text2Length) / 2);
  3706. vOffset = maxD;
  3707. vLength = 2 * maxD;
  3708. v1 = new Array(vLength);
  3709. v2 = new Array(vLength);
  3710. // Setting all elements to -1 is faster in Chrome & Firefox than mixing
  3711. // integers and undefined.
  3712. for (x = 0; x < vLength; x++) {
  3713. v1[x] = -1;
  3714. v2[x] = -1;
  3715. }
  3716. v1[vOffset + 1] = 0;
  3717. v2[vOffset + 1] = 0;
  3718. delta = text1Length - text2Length;
  3719. // If the total number of characters is odd, then the front path will collide
  3720. // with the reverse path.
  3721. front = delta % 2 !== 0;
  3722. // Offsets for start and end of k loop.
  3723. // Prevents mapping of space beyond the grid.
  3724. k1start = 0;
  3725. k1end = 0;
  3726. k2start = 0;
  3727. k2end = 0;
  3728. for (d = 0; d < maxD; d++) {
  3729. // Bail out if deadline is reached.
  3730. if (new Date().getTime() > deadline) {
  3731. break;
  3732. }
  3733. // Walk the front path one step.
  3734. for (k1 = -d + k1start; k1 <= d - k1end; k1 += 2) {
  3735. k1Offset = vOffset + k1;
  3736. if (k1 === -d || k1 !== d && v1[k1Offset - 1] < v1[k1Offset + 1]) {
  3737. x1 = v1[k1Offset + 1];
  3738. } else {
  3739. x1 = v1[k1Offset - 1] + 1;
  3740. }
  3741. y1 = x1 - k1;
  3742. while (x1 < text1Length && y1 < text2Length && text1.charAt(x1) === text2.charAt(y1)) {
  3743. x1++;
  3744. y1++;
  3745. }
  3746. v1[k1Offset] = x1;
  3747. if (x1 > text1Length) {
  3748. // Ran off the right of the graph.
  3749. k1end += 2;
  3750. } else if (y1 > text2Length) {
  3751. // Ran off the bottom of the graph.
  3752. k1start += 2;
  3753. } else if (front) {
  3754. k2Offset = vOffset + delta - k1;
  3755. if (k2Offset >= 0 && k2Offset < vLength && v2[k2Offset] !== -1) {
  3756. // Mirror x2 onto top-left coordinate system.
  3757. x2 = text1Length - v2[k2Offset];
  3758. if (x1 >= x2) {
  3759. // Overlap detected.
  3760. return this.diffBisectSplit(text1, text2, x1, y1, deadline);
  3761. }
  3762. }
  3763. }
  3764. }
  3765. // Walk the reverse path one step.
  3766. for (k2 = -d + k2start; k2 <= d - k2end; k2 += 2) {
  3767. k2Offset = vOffset + k2;
  3768. if (k2 === -d || k2 !== d && v2[k2Offset - 1] < v2[k2Offset + 1]) {
  3769. x2 = v2[k2Offset + 1];
  3770. } else {
  3771. x2 = v2[k2Offset - 1] + 1;
  3772. }
  3773. y2 = x2 - k2;
  3774. while (x2 < text1Length && y2 < text2Length && text1.charAt(text1Length - x2 - 1) === text2.charAt(text2Length - y2 - 1)) {
  3775. x2++;
  3776. y2++;
  3777. }
  3778. v2[k2Offset] = x2;
  3779. if (x2 > text1Length) {
  3780. // Ran off the left of the graph.
  3781. k2end += 2;
  3782. } else if (y2 > text2Length) {
  3783. // Ran off the top of the graph.
  3784. k2start += 2;
  3785. } else if (!front) {
  3786. k1Offset = vOffset + delta - k2;
  3787. if (k1Offset >= 0 && k1Offset < vLength && v1[k1Offset] !== -1) {
  3788. x1 = v1[k1Offset];
  3789. y1 = vOffset + x1 - k1Offset;
  3790. // Mirror x2 onto top-left coordinate system.
  3791. x2 = text1Length - x2;
  3792. if (x1 >= x2) {
  3793. // Overlap detected.
  3794. return this.diffBisectSplit(text1, text2, x1, y1, deadline);
  3795. }
  3796. }
  3797. }
  3798. }
  3799. }
  3800. // Diff took too long and hit the deadline or
  3801. // number of diffs equals number of characters, no commonality at all.
  3802. return [[DIFF_DELETE, text1], [DIFF_INSERT, text2]];
  3803. };
  3804. /**
  3805. * Given the location of the 'middle snake', split the diff in two parts
  3806. * and recurse.
  3807. * @param {string} text1 Old string to be diffed.
  3808. * @param {string} text2 New string to be diffed.
  3809. * @param {number} x Index of split point in text1.
  3810. * @param {number} y Index of split point in text2.
  3811. * @param {number} deadline Time at which to bail if not yet complete.
  3812. * @return {!Array.<!DiffMatchPatch.Diff>} Array of diff tuples.
  3813. * @private
  3814. */
  3815. DiffMatchPatch.prototype.diffBisectSplit = function (text1, text2, x, y, deadline) {
  3816. var text1a, text1b, text2a, text2b, diffs, diffsb;
  3817. text1a = text1.substring(0, x);
  3818. text2a = text2.substring(0, y);
  3819. text1b = text1.substring(x);
  3820. text2b = text2.substring(y);
  3821. // Compute both diffs serially.
  3822. diffs = this.DiffMain(text1a, text2a, false, deadline);
  3823. diffsb = this.DiffMain(text1b, text2b, false, deadline);
  3824. return diffs.concat(diffsb);
  3825. };
  3826. /**
  3827. * Reduce the number of edits by eliminating semantically trivial equalities.
  3828. * @param {!Array.<!DiffMatchPatch.Diff>} diffs Array of diff tuples.
  3829. */
  3830. DiffMatchPatch.prototype.diffCleanupSemantic = function (diffs) {
  3831. var changes, equalities, equalitiesLength, lastequality, pointer, lengthInsertions2, lengthDeletions2, lengthInsertions1, lengthDeletions1, deletion, insertion, overlapLength1, overlapLength2;
  3832. changes = false;
  3833. equalities = []; // Stack of indices where equalities are found.
  3834. equalitiesLength = 0; // Keeping our own length var is faster in JS.
  3835. /** @type {?string} */
  3836. lastequality = null;
  3837. // Always equal to diffs[equalities[equalitiesLength - 1]][1]
  3838. pointer = 0; // Index of current position.
  3839. // Number of characters that changed prior to the equality.
  3840. lengthInsertions1 = 0;
  3841. lengthDeletions1 = 0;
  3842. // Number of characters that changed after the equality.
  3843. lengthInsertions2 = 0;
  3844. lengthDeletions2 = 0;
  3845. while (pointer < diffs.length) {
  3846. if (diffs[pointer][0] === DIFF_EQUAL) {
  3847. // Equality found.
  3848. equalities[equalitiesLength++] = pointer;
  3849. lengthInsertions1 = lengthInsertions2;
  3850. lengthDeletions1 = lengthDeletions2;
  3851. lengthInsertions2 = 0;
  3852. lengthDeletions2 = 0;
  3853. lastequality = diffs[pointer][1];
  3854. } else {
  3855. // An insertion or deletion.
  3856. if (diffs[pointer][0] === DIFF_INSERT) {
  3857. lengthInsertions2 += diffs[pointer][1].length;
  3858. } else {
  3859. lengthDeletions2 += diffs[pointer][1].length;
  3860. }
  3861. // Eliminate an equality that is smaller or equal to the edits on both
  3862. // sides of it.
  3863. if (lastequality && lastequality.length <= Math.max(lengthInsertions1, lengthDeletions1) && lastequality.length <= Math.max(lengthInsertions2, lengthDeletions2)) {
  3864. // Duplicate record.
  3865. diffs.splice(equalities[equalitiesLength - 1], 0, [DIFF_DELETE, lastequality]);
  3866. // Change second copy to insert.
  3867. diffs[equalities[equalitiesLength - 1] + 1][0] = DIFF_INSERT;
  3868. // Throw away the equality we just deleted.
  3869. equalitiesLength--;
  3870. // Throw away the previous equality (it needs to be reevaluated).
  3871. equalitiesLength--;
  3872. pointer = equalitiesLength > 0 ? equalities[equalitiesLength - 1] : -1;
  3873. // Reset the counters.
  3874. lengthInsertions1 = 0;
  3875. lengthDeletions1 = 0;
  3876. lengthInsertions2 = 0;
  3877. lengthDeletions2 = 0;
  3878. lastequality = null;
  3879. changes = true;
  3880. }
  3881. }
  3882. pointer++;
  3883. }
  3884. // Normalize the diff.
  3885. if (changes) {
  3886. this.diffCleanupMerge(diffs);
  3887. }
  3888. // Find any overlaps between deletions and insertions.
  3889. // e.g: <del>abcxxx</del><ins>xxxdef</ins>
  3890. // -> <del>abc</del>xxx<ins>def</ins>
  3891. // e.g: <del>xxxabc</del><ins>defxxx</ins>
  3892. // -> <ins>def</ins>xxx<del>abc</del>
  3893. // Only extract an overlap if it is as big as the edit ahead or behind it.
  3894. pointer = 1;
  3895. while (pointer < diffs.length) {
  3896. if (diffs[pointer - 1][0] === DIFF_DELETE && diffs[pointer][0] === DIFF_INSERT) {
  3897. deletion = diffs[pointer - 1][1];
  3898. insertion = diffs[pointer][1];
  3899. overlapLength1 = this.diffCommonOverlap(deletion, insertion);
  3900. overlapLength2 = this.diffCommonOverlap(insertion, deletion);
  3901. if (overlapLength1 >= overlapLength2) {
  3902. if (overlapLength1 >= deletion.length / 2 || overlapLength1 >= insertion.length / 2) {
  3903. // Overlap found. Insert an equality and trim the surrounding edits.
  3904. diffs.splice(pointer, 0, [DIFF_EQUAL, insertion.substring(0, overlapLength1)]);
  3905. diffs[pointer - 1][1] = deletion.substring(0, deletion.length - overlapLength1);
  3906. diffs[pointer + 1][1] = insertion.substring(overlapLength1);
  3907. pointer++;
  3908. }
  3909. } else {
  3910. if (overlapLength2 >= deletion.length / 2 || overlapLength2 >= insertion.length / 2) {
  3911. // Reverse overlap found.
  3912. // Insert an equality and swap and trim the surrounding edits.
  3913. diffs.splice(pointer, 0, [DIFF_EQUAL, deletion.substring(0, overlapLength2)]);
  3914. diffs[pointer - 1][0] = DIFF_INSERT;
  3915. diffs[pointer - 1][1] = insertion.substring(0, insertion.length - overlapLength2);
  3916. diffs[pointer + 1][0] = DIFF_DELETE;
  3917. diffs[pointer + 1][1] = deletion.substring(overlapLength2);
  3918. pointer++;
  3919. }
  3920. }
  3921. pointer++;
  3922. }
  3923. pointer++;
  3924. }
  3925. };
  3926. /**
  3927. * Determine if the suffix of one string is the prefix of another.
  3928. * @param {string} text1 First string.
  3929. * @param {string} text2 Second string.
  3930. * @return {number} The number of characters common to the end of the first
  3931. * string and the start of the second string.
  3932. * @private
  3933. */
  3934. DiffMatchPatch.prototype.diffCommonOverlap = function (text1, text2) {
  3935. var text1Length, text2Length, textLength, best, length, pattern, found;
  3936. // Cache the text lengths to prevent multiple calls.
  3937. text1Length = text1.length;
  3938. text2Length = text2.length;
  3939. // Eliminate the null case.
  3940. if (text1Length === 0 || text2Length === 0) {
  3941. return 0;
  3942. }
  3943. // Truncate the longer string.
  3944. if (text1Length > text2Length) {
  3945. text1 = text1.substring(text1Length - text2Length);
  3946. } else if (text1Length < text2Length) {
  3947. text2 = text2.substring(0, text1Length);
  3948. }
  3949. textLength = Math.min(text1Length, text2Length);
  3950. // Quick check for the worst case.
  3951. if (text1 === text2) {
  3952. return textLength;
  3953. }
  3954. // Start by looking for a single character match
  3955. // and increase length until no match is found.
  3956. // Performance analysis: https://neil.fraser.name/news/2010/11/04/
  3957. best = 0;
  3958. length = 1;
  3959. while (true) {
  3960. pattern = text1.substring(textLength - length);
  3961. found = text2.indexOf(pattern);
  3962. if (found === -1) {
  3963. return best;
  3964. }
  3965. length += found;
  3966. if (found === 0 || text1.substring(textLength - length) === text2.substring(0, length)) {
  3967. best = length;
  3968. length++;
  3969. }
  3970. }
  3971. };
  3972. /**
  3973. * Split two texts into an array of strings. Reduce the texts to a string of
  3974. * hashes where each Unicode character represents one line.
  3975. * @param {string} text1 First string.
  3976. * @param {string} text2 Second string.
  3977. * @return {{chars1: string, chars2: string, lineArray: !Array.<string>}}
  3978. * An object containing the encoded text1, the encoded text2 and
  3979. * the array of unique strings.
  3980. * The zeroth element of the array of unique strings is intentionally blank.
  3981. * @private
  3982. */
  3983. DiffMatchPatch.prototype.diffLinesToChars = function (text1, text2) {
  3984. var lineArray, lineHash, chars1, chars2;
  3985. lineArray = []; // E.g. lineArray[4] === 'Hello\n'
  3986. lineHash = {}; // E.g. lineHash['Hello\n'] === 4
  3987. // '\x00' is a valid character, but various debuggers don't like it.
  3988. // So we'll insert a junk entry to avoid generating a null character.
  3989. lineArray[0] = "";
  3990. /**
  3991. * Split a text into an array of strings. Reduce the texts to a string of
  3992. * hashes where each Unicode character represents one line.
  3993. * Modifies linearray and linehash through being a closure.
  3994. * @param {string} text String to encode.
  3995. * @return {string} Encoded string.
  3996. * @private
  3997. */
  3998. function diffLinesToCharsMunge(text) {
  3999. var chars, lineStart, lineEnd, lineArrayLength, line;
  4000. chars = "";
  4001. // Walk the text, pulling out a substring for each line.
  4002. // text.split('\n') would would temporarily double our memory footprint.
  4003. // Modifying text would create many large strings to garbage collect.
  4004. lineStart = 0;
  4005. lineEnd = -1;
  4006. // Keeping our own length variable is faster than looking it up.
  4007. lineArrayLength = lineArray.length;
  4008. while (lineEnd < text.length - 1) {
  4009. lineEnd = text.indexOf("\n", lineStart);
  4010. if (lineEnd === -1) {
  4011. lineEnd = text.length - 1;
  4012. }
  4013. line = text.substring(lineStart, lineEnd + 1);
  4014. lineStart = lineEnd + 1;
  4015. var lineHashExists = lineHash.hasOwnProperty ? lineHash.hasOwnProperty(line) : lineHash[line] !== undefined;
  4016. if (lineHashExists) {
  4017. chars += String.fromCharCode(lineHash[line]);
  4018. } else {
  4019. chars += String.fromCharCode(lineArrayLength);
  4020. lineHash[line] = lineArrayLength;
  4021. lineArray[lineArrayLength++] = line;
  4022. }
  4023. }
  4024. return chars;
  4025. }
  4026. chars1 = diffLinesToCharsMunge(text1);
  4027. chars2 = diffLinesToCharsMunge(text2);
  4028. return {
  4029. chars1: chars1,
  4030. chars2: chars2,
  4031. lineArray: lineArray
  4032. };
  4033. };
  4034. /**
  4035. * Rehydrate the text in a diff from a string of line hashes to real lines of
  4036. * text.
  4037. * @param {!Array.<!DiffMatchPatch.Diff>} diffs Array of diff tuples.
  4038. * @param {!Array.<string>} lineArray Array of unique strings.
  4039. * @private
  4040. */
  4041. DiffMatchPatch.prototype.diffCharsToLines = function (diffs, lineArray) {
  4042. var x, chars, text, y;
  4043. for (x = 0; x < diffs.length; x++) {
  4044. chars = diffs[x][1];
  4045. text = [];
  4046. for (y = 0; y < chars.length; y++) {
  4047. text[y] = lineArray[chars.charCodeAt(y)];
  4048. }
  4049. diffs[x][1] = text.join("");
  4050. }
  4051. };
  4052. /**
  4053. * Reorder and merge like edit sections. Merge equalities.
  4054. * Any edit section can move as long as it doesn't cross an equality.
  4055. * @param {!Array.<!DiffMatchPatch.Diff>} diffs Array of diff tuples.
  4056. */
  4057. DiffMatchPatch.prototype.diffCleanupMerge = function (diffs) {
  4058. var pointer, countDelete, countInsert, textInsert, textDelete, commonlength, changes, diffPointer, position;
  4059. diffs.push([DIFF_EQUAL, ""]); // Add a dummy entry at the end.
  4060. pointer = 0;
  4061. countDelete = 0;
  4062. countInsert = 0;
  4063. textDelete = "";
  4064. textInsert = "";
  4065. while (pointer < diffs.length) {
  4066. switch (diffs[pointer][0]) {
  4067. case DIFF_INSERT:
  4068. countInsert++;
  4069. textInsert += diffs[pointer][1];
  4070. pointer++;
  4071. break;
  4072. case DIFF_DELETE:
  4073. countDelete++;
  4074. textDelete += diffs[pointer][1];
  4075. pointer++;
  4076. break;
  4077. case DIFF_EQUAL:
  4078. // Upon reaching an equality, check for prior redundancies.
  4079. if (countDelete + countInsert > 1) {
  4080. if (countDelete !== 0 && countInsert !== 0) {
  4081. // Factor out any common prefixes.
  4082. commonlength = this.diffCommonPrefix(textInsert, textDelete);
  4083. if (commonlength !== 0) {
  4084. if (pointer - countDelete - countInsert > 0 && diffs[pointer - countDelete - countInsert - 1][0] === DIFF_EQUAL) {
  4085. diffs[pointer - countDelete - countInsert - 1][1] += textInsert.substring(0, commonlength);
  4086. } else {
  4087. diffs.splice(0, 0, [DIFF_EQUAL, textInsert.substring(0, commonlength)]);
  4088. pointer++;
  4089. }
  4090. textInsert = textInsert.substring(commonlength);
  4091. textDelete = textDelete.substring(commonlength);
  4092. }
  4093. // Factor out any common suffixies.
  4094. commonlength = this.diffCommonSuffix(textInsert, textDelete);
  4095. if (commonlength !== 0) {
  4096. diffs[pointer][1] = textInsert.substring(textInsert.length - commonlength) + diffs[pointer][1];
  4097. textInsert = textInsert.substring(0, textInsert.length - commonlength);
  4098. textDelete = textDelete.substring(0, textDelete.length - commonlength);
  4099. }
  4100. }
  4101. // Delete the offending records and add the merged ones.
  4102. if (countDelete === 0) {
  4103. diffs.splice(pointer - countInsert, countDelete + countInsert, [DIFF_INSERT, textInsert]);
  4104. } else if (countInsert === 0) {
  4105. diffs.splice(pointer - countDelete, countDelete + countInsert, [DIFF_DELETE, textDelete]);
  4106. } else {
  4107. diffs.splice(pointer - countDelete - countInsert, countDelete + countInsert, [DIFF_DELETE, textDelete], [DIFF_INSERT, textInsert]);
  4108. }
  4109. pointer = pointer - countDelete - countInsert + (countDelete ? 1 : 0) + (countInsert ? 1 : 0) + 1;
  4110. } else if (pointer !== 0 && diffs[pointer - 1][0] === DIFF_EQUAL) {
  4111. // Merge this equality with the previous one.
  4112. diffs[pointer - 1][1] += diffs[pointer][1];
  4113. diffs.splice(pointer, 1);
  4114. } else {
  4115. pointer++;
  4116. }
  4117. countInsert = 0;
  4118. countDelete = 0;
  4119. textDelete = "";
  4120. textInsert = "";
  4121. break;
  4122. }
  4123. }
  4124. if (diffs[diffs.length - 1][1] === "") {
  4125. diffs.pop(); // Remove the dummy entry at the end.
  4126. }
  4127. // Second pass: look for single edits surrounded on both sides by equalities
  4128. // which can be shifted sideways to eliminate an equality.
  4129. // e.g: A<ins>BA</ins>C -> <ins>AB</ins>AC
  4130. changes = false;
  4131. pointer = 1;
  4132. // Intentionally ignore the first and last element (don't need checking).
  4133. while (pointer < diffs.length - 1) {
  4134. if (diffs[pointer - 1][0] === DIFF_EQUAL && diffs[pointer + 1][0] === DIFF_EQUAL) {
  4135. diffPointer = diffs[pointer][1];
  4136. position = diffPointer.substring(diffPointer.length - diffs[pointer - 1][1].length);
  4137. // This is a single edit surrounded by equalities.
  4138. if (position === diffs[pointer - 1][1]) {
  4139. // Shift the edit over the previous equality.
  4140. diffs[pointer][1] = diffs[pointer - 1][1] + diffs[pointer][1].substring(0, diffs[pointer][1].length - diffs[pointer - 1][1].length);
  4141. diffs[pointer + 1][1] = diffs[pointer - 1][1] + diffs[pointer + 1][1];
  4142. diffs.splice(pointer - 1, 1);
  4143. changes = true;
  4144. } else if (diffPointer.substring(0, diffs[pointer + 1][1].length) === diffs[pointer + 1][1]) {
  4145. // Shift the edit over the next equality.
  4146. diffs[pointer - 1][1] += diffs[pointer + 1][1];
  4147. diffs[pointer][1] = diffs[pointer][1].substring(diffs[pointer + 1][1].length) + diffs[pointer + 1][1];
  4148. diffs.splice(pointer + 1, 1);
  4149. changes = true;
  4150. }
  4151. }
  4152. pointer++;
  4153. }
  4154. // If shifts were made, the diff needs reordering and another shift sweep.
  4155. if (changes) {
  4156. this.diffCleanupMerge(diffs);
  4157. }
  4158. };
  4159. return function (o, n) {
  4160. var diff, output, text;
  4161. diff = new DiffMatchPatch();
  4162. output = diff.DiffMain(o, n);
  4163. diff.diffCleanupEfficiency(output);
  4164. text = diff.diffPrettyHtml(output);
  4165. return text;
  4166. };
  4167. }();
  4168. }((function() { return this; }())));