qunit-2.5.0.js 146 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189
  1. /*!
  2. * QUnit 2.5.0
  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: 2018-01-10T02:56Z
  10. */
  11. (function (global$1) {
  12. 'use strict';
  13. global$1 = global$1 && global$1.hasOwnProperty('default') ? 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);
  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 occurred 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. if (config.notrycatch) {
  1430. then.call(promise, function () {
  1431. resume();
  1432. });
  1433. } else {
  1434. then.call(promise, function () {
  1435. resume();
  1436. }, function (error) {
  1437. message = "Promise rejected " + (!phase ? "during" : phase.replace(/Each$/, "")) + " \"" + test.testName + "\": " + (error && error.message || error);
  1438. test.pushFailure(message, extractStacktrace(error, 0));
  1439. // Else next test will carry the responsibility
  1440. saveGlobal();
  1441. // Unblock
  1442. resume();
  1443. });
  1444. }
  1445. }
  1446. }
  1447. },
  1448. valid: function valid() {
  1449. var filter = config.filter,
  1450. regexFilter = /^(!?)\/([\w\W]*)\/(i?$)/.exec(filter),
  1451. module = config.module && config.module.toLowerCase(),
  1452. fullName = this.module.name + ": " + this.testName;
  1453. function moduleChainNameMatch(testModule) {
  1454. var testModuleName = testModule.name ? testModule.name.toLowerCase() : null;
  1455. if (testModuleName === module) {
  1456. return true;
  1457. } else if (testModule.parentModule) {
  1458. return moduleChainNameMatch(testModule.parentModule);
  1459. } else {
  1460. return false;
  1461. }
  1462. }
  1463. function moduleChainIdMatch(testModule) {
  1464. return inArray(testModule.moduleId, config.moduleId) || testModule.parentModule && moduleChainIdMatch(testModule.parentModule);
  1465. }
  1466. // Internally-generated tests are always valid
  1467. if (this.callback && this.callback.validTest) {
  1468. return true;
  1469. }
  1470. if (config.moduleId && config.moduleId.length > 0 && !moduleChainIdMatch(this.module)) {
  1471. return false;
  1472. }
  1473. if (config.testId && config.testId.length > 0 && !inArray(this.testId, config.testId)) {
  1474. return false;
  1475. }
  1476. if (module && !moduleChainNameMatch(this.module)) {
  1477. return false;
  1478. }
  1479. if (!filter) {
  1480. return true;
  1481. }
  1482. return regexFilter ? this.regexFilter(!!regexFilter[1], regexFilter[2], regexFilter[3], fullName) : this.stringFilter(filter, fullName);
  1483. },
  1484. regexFilter: function regexFilter(exclude, pattern, flags, fullName) {
  1485. var regex = new RegExp(pattern, flags);
  1486. var match = regex.test(fullName);
  1487. return match !== exclude;
  1488. },
  1489. stringFilter: function stringFilter(filter, fullName) {
  1490. filter = filter.toLowerCase();
  1491. fullName = fullName.toLowerCase();
  1492. var include = filter.charAt(0) !== "!";
  1493. if (!include) {
  1494. filter = filter.slice(1);
  1495. }
  1496. // If the filter matches, we need to honour include
  1497. if (fullName.indexOf(filter) !== -1) {
  1498. return include;
  1499. }
  1500. // Otherwise, do the opposite
  1501. return !include;
  1502. }
  1503. };
  1504. function pushFailure() {
  1505. if (!config.current) {
  1506. throw new Error("pushFailure() assertion outside test context, in " + sourceFromStacktrace(2));
  1507. }
  1508. // Gets current test obj
  1509. var currentTest = config.current;
  1510. return currentTest.pushFailure.apply(currentTest, arguments);
  1511. }
  1512. function saveGlobal() {
  1513. config.pollution = [];
  1514. if (config.noglobals) {
  1515. for (var key in global$1) {
  1516. if (hasOwn.call(global$1, key)) {
  1517. // In Opera sometimes DOM element ids show up here, ignore them
  1518. if (/^qunit-test-output/.test(key)) {
  1519. continue;
  1520. }
  1521. config.pollution.push(key);
  1522. }
  1523. }
  1524. }
  1525. }
  1526. function checkPollution() {
  1527. var newGlobals,
  1528. deletedGlobals,
  1529. old = config.pollution;
  1530. saveGlobal();
  1531. newGlobals = diff(config.pollution, old);
  1532. if (newGlobals.length > 0) {
  1533. pushFailure("Introduced global variable(s): " + newGlobals.join(", "));
  1534. }
  1535. deletedGlobals = diff(old, config.pollution);
  1536. if (deletedGlobals.length > 0) {
  1537. pushFailure("Deleted global variable(s): " + deletedGlobals.join(", "));
  1538. }
  1539. }
  1540. // Will be exposed as QUnit.test
  1541. function test(testName, callback) {
  1542. if (focused$1) {
  1543. return;
  1544. }
  1545. var newTest = new Test({
  1546. testName: testName,
  1547. callback: callback
  1548. });
  1549. newTest.queue();
  1550. }
  1551. function todo(testName, callback) {
  1552. if (focused$1) {
  1553. return;
  1554. }
  1555. var newTest = new Test({
  1556. testName: testName,
  1557. callback: callback,
  1558. todo: true
  1559. });
  1560. newTest.queue();
  1561. }
  1562. // Will be exposed as QUnit.skip
  1563. function skip(testName) {
  1564. if (focused$1) {
  1565. return;
  1566. }
  1567. var test = new Test({
  1568. testName: testName,
  1569. skip: true
  1570. });
  1571. test.queue();
  1572. }
  1573. // Will be exposed as QUnit.only
  1574. function only(testName, callback) {
  1575. if (focused$1) {
  1576. return;
  1577. }
  1578. config.queue.length = 0;
  1579. focused$1 = true;
  1580. var newTest = new Test({
  1581. testName: testName,
  1582. callback: callback
  1583. });
  1584. newTest.queue();
  1585. }
  1586. // Put a hold on processing and return a function that will release it.
  1587. function internalStop(test) {
  1588. test.semaphore += 1;
  1589. config.blocking = true;
  1590. // Set a recovery timeout, if so configured.
  1591. if (defined.setTimeout) {
  1592. var timeoutDuration = void 0;
  1593. if (typeof test.timeout === "number") {
  1594. timeoutDuration = test.timeout;
  1595. } else if (typeof config.testTimeout === "number") {
  1596. timeoutDuration = config.testTimeout;
  1597. }
  1598. if (typeof timeoutDuration === "number" && timeoutDuration > 0) {
  1599. clearTimeout(config.timeout);
  1600. config.timeout = setTimeout(function () {
  1601. pushFailure("Test took longer than " + timeoutDuration + "ms; test timed out.", sourceFromStacktrace(2));
  1602. internalRecover(test);
  1603. }, timeoutDuration);
  1604. }
  1605. }
  1606. var released = false;
  1607. return function resume() {
  1608. if (released) {
  1609. return;
  1610. }
  1611. released = true;
  1612. test.semaphore -= 1;
  1613. internalStart(test);
  1614. };
  1615. }
  1616. // Forcefully release all processing holds.
  1617. function internalRecover(test) {
  1618. test.semaphore = 0;
  1619. internalStart(test);
  1620. }
  1621. // Release a processing hold, scheduling a resumption attempt if no holds remain.
  1622. function internalStart(test) {
  1623. // If semaphore is non-numeric, throw error
  1624. if (isNaN(test.semaphore)) {
  1625. test.semaphore = 0;
  1626. pushFailure("Invalid value on test.semaphore", sourceFromStacktrace(2));
  1627. return;
  1628. }
  1629. // Don't start until equal number of stop-calls
  1630. if (test.semaphore > 0) {
  1631. return;
  1632. }
  1633. // Throw an Error if start is called more often than stop
  1634. if (test.semaphore < 0) {
  1635. test.semaphore = 0;
  1636. pushFailure("Tried to restart test while already started (test's semaphore was 0 already)", sourceFromStacktrace(2));
  1637. return;
  1638. }
  1639. // Add a slight delay to allow more assertions etc.
  1640. if (defined.setTimeout) {
  1641. if (config.timeout) {
  1642. clearTimeout(config.timeout);
  1643. }
  1644. config.timeout = setTimeout(function () {
  1645. if (test.semaphore > 0) {
  1646. return;
  1647. }
  1648. if (config.timeout) {
  1649. clearTimeout(config.timeout);
  1650. }
  1651. begin();
  1652. });
  1653. } else {
  1654. begin();
  1655. }
  1656. }
  1657. function collectTests(module) {
  1658. var tests = [].concat(module.tests);
  1659. var modules = [].concat(toConsumableArray(module.childModules));
  1660. // Do a breadth-first traversal of the child modules
  1661. while (modules.length) {
  1662. var nextModule = modules.shift();
  1663. tests.push.apply(tests, nextModule.tests);
  1664. modules.push.apply(modules, toConsumableArray(nextModule.childModules));
  1665. }
  1666. return tests;
  1667. }
  1668. function numberOfTests(module) {
  1669. return collectTests(module).length;
  1670. }
  1671. function numberOfUnskippedTests(module) {
  1672. return collectTests(module).filter(function (test) {
  1673. return !test.skip;
  1674. }).length;
  1675. }
  1676. function notifyTestsRan(module, skipped) {
  1677. module.testsRun++;
  1678. if (!skipped) {
  1679. module.unskippedTestsRun++;
  1680. }
  1681. while (module = module.parentModule) {
  1682. module.testsRun++;
  1683. if (!skipped) {
  1684. module.unskippedTestsRun++;
  1685. }
  1686. }
  1687. }
  1688. /**
  1689. * Returns a function that proxies to the given method name on the globals
  1690. * console object. The proxy will also detect if the console doesn't exist and
  1691. * will appropriately no-op. This allows support for IE9, which doesn't have a
  1692. * console if the developer tools are not open.
  1693. */
  1694. function consoleProxy(method) {
  1695. return function () {
  1696. if (console) {
  1697. console[method].apply(console, arguments);
  1698. }
  1699. };
  1700. }
  1701. var Logger = {
  1702. warn: consoleProxy("warn")
  1703. };
  1704. var Assert = function () {
  1705. function Assert(testContext) {
  1706. classCallCheck(this, Assert);
  1707. this.test = testContext;
  1708. }
  1709. // Assert helpers
  1710. createClass(Assert, [{
  1711. key: "timeout",
  1712. value: function timeout(duration) {
  1713. if (typeof duration !== "number") {
  1714. throw new Error("You must pass a number as the duration to assert.timeout");
  1715. }
  1716. this.test.timeout = duration;
  1717. }
  1718. // Documents a "step", which is a string value, in a test as a passing assertion
  1719. }, {
  1720. key: "step",
  1721. value: function step(message) {
  1722. var result = !!message;
  1723. this.test.steps.push(message);
  1724. return this.pushResult({
  1725. result: result,
  1726. message: message || "You must provide a message to assert.step"
  1727. });
  1728. }
  1729. // Verifies the steps in a test match a given array of string values
  1730. }, {
  1731. key: "verifySteps",
  1732. value: function verifySteps(steps, message) {
  1733. this.deepEqual(this.test.steps, steps, message);
  1734. this.test.steps.length = 0;
  1735. }
  1736. // Specify the number of expected assertions to guarantee that failed test
  1737. // (no assertions are run at all) don't slip through.
  1738. }, {
  1739. key: "expect",
  1740. value: function expect(asserts) {
  1741. if (arguments.length === 1) {
  1742. this.test.expected = asserts;
  1743. } else {
  1744. return this.test.expected;
  1745. }
  1746. }
  1747. // Put a hold on processing and return a function that will release it a maximum of once.
  1748. }, {
  1749. key: "async",
  1750. value: function async(count) {
  1751. var test$$1 = this.test;
  1752. var popped = false,
  1753. acceptCallCount = count;
  1754. if (typeof acceptCallCount === "undefined") {
  1755. acceptCallCount = 1;
  1756. }
  1757. var resume = internalStop(test$$1);
  1758. return function done() {
  1759. if (config.current !== test$$1) {
  1760. throw Error("assert.async callback called after test finished.");
  1761. }
  1762. if (popped) {
  1763. test$$1.pushFailure("Too many calls to the `assert.async` callback", sourceFromStacktrace(2));
  1764. return;
  1765. }
  1766. acceptCallCount -= 1;
  1767. if (acceptCallCount > 0) {
  1768. return;
  1769. }
  1770. popped = true;
  1771. resume();
  1772. };
  1773. }
  1774. // Exports test.push() to the user API
  1775. // Alias of pushResult.
  1776. }, {
  1777. key: "push",
  1778. value: function push(result, actual, expected, message, negative) {
  1779. 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).");
  1780. var currentAssert = this instanceof Assert ? this : config.current.assert;
  1781. return currentAssert.pushResult({
  1782. result: result,
  1783. actual: actual,
  1784. expected: expected,
  1785. message: message,
  1786. negative: negative
  1787. });
  1788. }
  1789. }, {
  1790. key: "pushResult",
  1791. value: function pushResult(resultInfo) {
  1792. // Destructure of resultInfo = { result, actual, expected, message, negative }
  1793. var assert = this;
  1794. var currentTest = assert instanceof Assert && assert.test || config.current;
  1795. // Backwards compatibility fix.
  1796. // Allows the direct use of global exported assertions and QUnit.assert.*
  1797. // Although, it's use is not recommended as it can leak assertions
  1798. // to other tests from async tests, because we only get a reference to the current test,
  1799. // not exactly the test where assertion were intended to be called.
  1800. if (!currentTest) {
  1801. throw new Error("assertion outside test context, in " + sourceFromStacktrace(2));
  1802. }
  1803. if (!(assert instanceof Assert)) {
  1804. assert = currentTest.assert;
  1805. }
  1806. return assert.test.pushResult(resultInfo);
  1807. }
  1808. }, {
  1809. key: "ok",
  1810. value: function ok(result, message) {
  1811. if (!message) {
  1812. message = result ? "okay" : "failed, expected argument to be truthy, was: " + dump.parse(result);
  1813. }
  1814. this.pushResult({
  1815. result: !!result,
  1816. actual: result,
  1817. expected: true,
  1818. message: message
  1819. });
  1820. }
  1821. }, {
  1822. key: "notOk",
  1823. value: function notOk(result, message) {
  1824. if (!message) {
  1825. message = !result ? "okay" : "failed, expected argument to be falsy, was: " + dump.parse(result);
  1826. }
  1827. this.pushResult({
  1828. result: !result,
  1829. actual: result,
  1830. expected: false,
  1831. message: message
  1832. });
  1833. }
  1834. }, {
  1835. key: "equal",
  1836. value: function equal(actual, expected, message) {
  1837. // eslint-disable-next-line eqeqeq
  1838. var result = expected == actual;
  1839. this.pushResult({
  1840. result: result,
  1841. actual: actual,
  1842. expected: expected,
  1843. message: message
  1844. });
  1845. }
  1846. }, {
  1847. key: "notEqual",
  1848. value: function notEqual(actual, expected, message) {
  1849. // eslint-disable-next-line eqeqeq
  1850. var result = expected != actual;
  1851. this.pushResult({
  1852. result: result,
  1853. actual: actual,
  1854. expected: expected,
  1855. message: message,
  1856. negative: true
  1857. });
  1858. }
  1859. }, {
  1860. key: "propEqual",
  1861. value: function propEqual(actual, expected, message) {
  1862. actual = objectValues(actual);
  1863. expected = objectValues(expected);
  1864. this.pushResult({
  1865. result: equiv(actual, expected),
  1866. actual: actual,
  1867. expected: expected,
  1868. message: message
  1869. });
  1870. }
  1871. }, {
  1872. key: "notPropEqual",
  1873. value: function notPropEqual(actual, expected, message) {
  1874. actual = objectValues(actual);
  1875. expected = objectValues(expected);
  1876. this.pushResult({
  1877. result: !equiv(actual, expected),
  1878. actual: actual,
  1879. expected: expected,
  1880. message: message,
  1881. negative: true
  1882. });
  1883. }
  1884. }, {
  1885. key: "deepEqual",
  1886. value: function deepEqual(actual, expected, message) {
  1887. this.pushResult({
  1888. result: equiv(actual, expected),
  1889. actual: actual,
  1890. expected: expected,
  1891. message: message
  1892. });
  1893. }
  1894. }, {
  1895. key: "notDeepEqual",
  1896. value: function notDeepEqual(actual, expected, message) {
  1897. this.pushResult({
  1898. result: !equiv(actual, expected),
  1899. actual: actual,
  1900. expected: expected,
  1901. message: message,
  1902. negative: true
  1903. });
  1904. }
  1905. }, {
  1906. key: "strictEqual",
  1907. value: function strictEqual(actual, expected, message) {
  1908. this.pushResult({
  1909. result: expected === actual,
  1910. actual: actual,
  1911. expected: expected,
  1912. message: message
  1913. });
  1914. }
  1915. }, {
  1916. key: "notStrictEqual",
  1917. value: function notStrictEqual(actual, expected, message) {
  1918. this.pushResult({
  1919. result: expected !== actual,
  1920. actual: actual,
  1921. expected: expected,
  1922. message: message,
  1923. negative: true
  1924. });
  1925. }
  1926. }, {
  1927. key: "throws",
  1928. value: function throws(block, expected, message) {
  1929. var actual = void 0,
  1930. result = false;
  1931. var currentTest = this instanceof Assert && this.test || config.current;
  1932. // 'expected' is optional unless doing string comparison
  1933. if (objectType(expected) === "string") {
  1934. if (message == null) {
  1935. message = expected;
  1936. expected = null;
  1937. } else {
  1938. 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.");
  1939. }
  1940. }
  1941. currentTest.ignoreGlobalErrors = true;
  1942. try {
  1943. block.call(currentTest.testEnvironment);
  1944. } catch (e) {
  1945. actual = e;
  1946. }
  1947. currentTest.ignoreGlobalErrors = false;
  1948. if (actual) {
  1949. var expectedType = objectType(expected);
  1950. // We don't want to validate thrown error
  1951. if (!expected) {
  1952. result = true;
  1953. expected = null;
  1954. // Expected is a regexp
  1955. } else if (expectedType === "regexp") {
  1956. result = expected.test(errorString(actual));
  1957. // Expected is a constructor, maybe an Error constructor
  1958. } else if (expectedType === "function" && actual instanceof expected) {
  1959. result = true;
  1960. // Expected is an Error object
  1961. } else if (expectedType === "object") {
  1962. result = actual instanceof expected.constructor && actual.name === expected.name && actual.message === expected.message;
  1963. // Expected is a validation function which returns true if validation passed
  1964. } else if (expectedType === "function" && expected.call({}, actual) === true) {
  1965. expected = null;
  1966. result = true;
  1967. }
  1968. }
  1969. currentTest.assert.pushResult({
  1970. result: result,
  1971. actual: actual,
  1972. expected: expected,
  1973. message: message
  1974. });
  1975. }
  1976. }, {
  1977. key: "rejects",
  1978. value: function rejects(promise, expected, message) {
  1979. var result = false;
  1980. var currentTest = this instanceof Assert && this.test || config.current;
  1981. // 'expected' is optional unless doing string comparison
  1982. if (objectType(expected) === "string") {
  1983. if (message === undefined) {
  1984. message = expected;
  1985. expected = undefined;
  1986. } else {
  1987. message = "assert.rejects does not accept a string value for the expected " + "argument.\nUse a non-string object value (e.g. validator function) instead " + "if necessary.";
  1988. currentTest.assert.pushResult({
  1989. result: false,
  1990. message: message
  1991. });
  1992. return;
  1993. }
  1994. }
  1995. var then = promise && promise.then;
  1996. if (objectType(then) !== "function") {
  1997. var _message = "The value provided to `assert.rejects` in " + "\"" + currentTest.testName + "\" was not a promise.";
  1998. currentTest.assert.pushResult({
  1999. result: false,
  2000. message: _message,
  2001. actual: promise
  2002. });
  2003. return;
  2004. }
  2005. var done = this.async();
  2006. return then.call(promise, function handleFulfillment() {
  2007. var message = "The promise returned by the `assert.rejects` callback in " + "\"" + currentTest.testName + "\" did not reject.";
  2008. currentTest.assert.pushResult({
  2009. result: false,
  2010. message: message,
  2011. actual: promise
  2012. });
  2013. done();
  2014. }, function handleRejection(actual) {
  2015. if (actual) {
  2016. var expectedType = objectType(expected);
  2017. // We don't want to validate
  2018. if (expected === undefined) {
  2019. result = true;
  2020. expected = null;
  2021. // Expected is a regexp
  2022. } else if (expectedType === "regexp") {
  2023. result = expected.test(errorString(actual));
  2024. // Expected is a constructor, maybe an Error constructor
  2025. } else if (expectedType === "function" && actual instanceof expected) {
  2026. result = true;
  2027. // Expected is an Error object
  2028. } else if (expectedType === "object") {
  2029. result = actual instanceof expected.constructor && actual.name === expected.name && actual.message === expected.message;
  2030. // Expected is a validation function which returns true if validation passed
  2031. } else {
  2032. if (expectedType === "function") {
  2033. result = expected.call({}, actual) === true;
  2034. expected = null;
  2035. // Expected is some other invalid type
  2036. } else {
  2037. result = false;
  2038. message = "invalid expected value provided to `assert.rejects` " + "callback in \"" + currentTest.testName + "\": " + expectedType + ".";
  2039. }
  2040. }
  2041. }
  2042. currentTest.assert.pushResult({
  2043. result: result,
  2044. actual: actual,
  2045. expected: expected,
  2046. message: message
  2047. });
  2048. done();
  2049. });
  2050. }
  2051. }]);
  2052. return Assert;
  2053. }();
  2054. // Provide an alternative to assert.throws(), for environments that consider throws a reserved word
  2055. // Known to us are: Closure Compiler, Narwhal
  2056. // eslint-disable-next-line dot-notation
  2057. Assert.prototype.raises = Assert.prototype["throws"];
  2058. /**
  2059. * Converts an error into a simple string for comparisons.
  2060. *
  2061. * @param {Error} error
  2062. * @return {String}
  2063. */
  2064. function errorString(error) {
  2065. var resultErrorString = error.toString();
  2066. if (resultErrorString.substring(0, 7) === "[object") {
  2067. var name = error.name ? error.name.toString() : "Error";
  2068. var message = error.message ? error.message.toString() : "";
  2069. if (name && message) {
  2070. return name + ": " + message;
  2071. } else if (name) {
  2072. return name;
  2073. } else if (message) {
  2074. return message;
  2075. } else {
  2076. return "Error";
  2077. }
  2078. } else {
  2079. return resultErrorString;
  2080. }
  2081. }
  2082. /* global module, exports, define */
  2083. function exportQUnit(QUnit) {
  2084. if (defined.document) {
  2085. // QUnit may be defined when it is preconfigured but then only QUnit and QUnit.config may be defined.
  2086. if (window.QUnit && window.QUnit.version) {
  2087. throw new Error("QUnit has already been defined.");
  2088. }
  2089. window.QUnit = QUnit;
  2090. }
  2091. // For nodejs
  2092. if (typeof module !== "undefined" && module && module.exports) {
  2093. module.exports = QUnit;
  2094. // For consistency with CommonJS environments' exports
  2095. module.exports.QUnit = QUnit;
  2096. }
  2097. // For CommonJS with exports, but without module.exports, like Rhino
  2098. if (typeof exports !== "undefined" && exports) {
  2099. exports.QUnit = QUnit;
  2100. }
  2101. if (typeof define === "function" && define.amd) {
  2102. define(function () {
  2103. return QUnit;
  2104. });
  2105. QUnit.config.autostart = false;
  2106. }
  2107. // For Web/Service Workers
  2108. if (self$1 && self$1.WorkerGlobalScope && self$1 instanceof self$1.WorkerGlobalScope) {
  2109. self$1.QUnit = QUnit;
  2110. }
  2111. }
  2112. var SuiteReport = function () {
  2113. function SuiteReport(name, parentSuite) {
  2114. classCallCheck(this, SuiteReport);
  2115. this.name = name;
  2116. this.fullName = parentSuite ? parentSuite.fullName.concat(name) : [];
  2117. this.tests = [];
  2118. this.childSuites = [];
  2119. if (parentSuite) {
  2120. parentSuite.pushChildSuite(this);
  2121. }
  2122. }
  2123. createClass(SuiteReport, [{
  2124. key: "start",
  2125. value: function start(recordTime) {
  2126. if (recordTime) {
  2127. this._startTime = Date.now();
  2128. }
  2129. return {
  2130. name: this.name,
  2131. fullName: this.fullName.slice(),
  2132. tests: this.tests.map(function (test) {
  2133. return test.start();
  2134. }),
  2135. childSuites: this.childSuites.map(function (suite) {
  2136. return suite.start();
  2137. }),
  2138. testCounts: {
  2139. total: this.getTestCounts().total
  2140. }
  2141. };
  2142. }
  2143. }, {
  2144. key: "end",
  2145. value: function end(recordTime) {
  2146. if (recordTime) {
  2147. this._endTime = Date.now();
  2148. }
  2149. return {
  2150. name: this.name,
  2151. fullName: this.fullName.slice(),
  2152. tests: this.tests.map(function (test) {
  2153. return test.end();
  2154. }),
  2155. childSuites: this.childSuites.map(function (suite) {
  2156. return suite.end();
  2157. }),
  2158. testCounts: this.getTestCounts(),
  2159. runtime: this.getRuntime(),
  2160. status: this.getStatus()
  2161. };
  2162. }
  2163. }, {
  2164. key: "pushChildSuite",
  2165. value: function pushChildSuite(suite) {
  2166. this.childSuites.push(suite);
  2167. }
  2168. }, {
  2169. key: "pushTest",
  2170. value: function pushTest(test) {
  2171. this.tests.push(test);
  2172. }
  2173. }, {
  2174. key: "getRuntime",
  2175. value: function getRuntime() {
  2176. return this._endTime - this._startTime;
  2177. }
  2178. }, {
  2179. key: "getTestCounts",
  2180. value: function getTestCounts() {
  2181. var counts = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : { passed: 0, failed: 0, skipped: 0, todo: 0, total: 0 };
  2182. counts = this.tests.reduce(function (counts, test) {
  2183. if (test.valid) {
  2184. counts[test.getStatus()]++;
  2185. counts.total++;
  2186. }
  2187. return counts;
  2188. }, counts);
  2189. return this.childSuites.reduce(function (counts, suite) {
  2190. return suite.getTestCounts(counts);
  2191. }, counts);
  2192. }
  2193. }, {
  2194. key: "getStatus",
  2195. value: function getStatus() {
  2196. var _getTestCounts = this.getTestCounts(),
  2197. total = _getTestCounts.total,
  2198. failed = _getTestCounts.failed,
  2199. skipped = _getTestCounts.skipped,
  2200. todo = _getTestCounts.todo;
  2201. if (failed) {
  2202. return "failed";
  2203. } else {
  2204. if (skipped === total) {
  2205. return "skipped";
  2206. } else if (todo === total) {
  2207. return "todo";
  2208. } else {
  2209. return "passed";
  2210. }
  2211. }
  2212. }
  2213. }]);
  2214. return SuiteReport;
  2215. }();
  2216. // Handle an unhandled exception. By convention, returns true if further
  2217. // error handling should be suppressed and false otherwise.
  2218. // In this case, we will only suppress further error handling if the
  2219. // "ignoreGlobalErrors" configuration option is enabled.
  2220. function onError(error) {
  2221. for (var _len = arguments.length, args = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
  2222. args[_key - 1] = arguments[_key];
  2223. }
  2224. if (config.current) {
  2225. if (config.current.ignoreGlobalErrors) {
  2226. return true;
  2227. }
  2228. pushFailure.apply(undefined, [error.message, error.fileName + ":" + error.lineNumber].concat(args));
  2229. } else {
  2230. test("global failure", extend(function () {
  2231. pushFailure.apply(undefined, [error.message, error.fileName + ":" + error.lineNumber].concat(args));
  2232. }, { validTest: true }));
  2233. }
  2234. return false;
  2235. }
  2236. // Handle an unhandled rejection
  2237. function onUnhandledRejection(reason) {
  2238. var resultInfo = {
  2239. result: false,
  2240. message: reason.message || "error",
  2241. actual: reason,
  2242. source: reason.stack || sourceFromStacktrace(3)
  2243. };
  2244. var currentTest = config.current;
  2245. if (currentTest) {
  2246. currentTest.assert.pushResult(resultInfo);
  2247. } else {
  2248. test("global failure", extend(function (assert) {
  2249. assert.pushResult(resultInfo);
  2250. }, { validTest: true }));
  2251. }
  2252. }
  2253. var focused = false;
  2254. var QUnit = {};
  2255. var globalSuite = new SuiteReport();
  2256. // The initial "currentModule" represents the global (or top-level) module that
  2257. // is not explicitly defined by the user, therefore we add the "globalSuite" to
  2258. // it since each module has a suiteReport associated with it.
  2259. config.currentModule.suiteReport = globalSuite;
  2260. var moduleStack = [];
  2261. var globalStartCalled = false;
  2262. var runStarted = false;
  2263. // Figure out if we're running the tests from a server or not
  2264. QUnit.isLocal = !(defined.document && window.location.protocol !== "file:");
  2265. // Expose the current QUnit version
  2266. QUnit.version = "2.5.0";
  2267. function createModule(name, testEnvironment, modifiers) {
  2268. var parentModule = moduleStack.length ? moduleStack.slice(-1)[0] : null;
  2269. var moduleName = parentModule !== null ? [parentModule.name, name].join(" > ") : name;
  2270. var parentSuite = parentModule ? parentModule.suiteReport : globalSuite;
  2271. var skip$$1 = parentModule !== null && parentModule.skip || modifiers.skip;
  2272. var todo$$1 = parentModule !== null && parentModule.todo || modifiers.todo;
  2273. var module = {
  2274. name: moduleName,
  2275. parentModule: parentModule,
  2276. tests: [],
  2277. moduleId: generateHash(moduleName),
  2278. testsRun: 0,
  2279. unskippedTestsRun: 0,
  2280. childModules: [],
  2281. suiteReport: new SuiteReport(name, parentSuite),
  2282. // Pass along `skip` and `todo` properties from parent module, in case
  2283. // there is one, to childs. And use own otherwise.
  2284. // This property will be used to mark own tests and tests of child suites
  2285. // as either `skipped` or `todo`.
  2286. skip: skip$$1,
  2287. todo: skip$$1 ? false : todo$$1
  2288. };
  2289. var env = {};
  2290. if (parentModule) {
  2291. parentModule.childModules.push(module);
  2292. extend(env, parentModule.testEnvironment);
  2293. }
  2294. extend(env, testEnvironment);
  2295. module.testEnvironment = env;
  2296. config.modules.push(module);
  2297. return module;
  2298. }
  2299. function processModule(name, options, executeNow) {
  2300. var modifiers = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {};
  2301. var module = createModule(name, options, modifiers);
  2302. // Move any hooks to a 'hooks' object
  2303. var testEnvironment = module.testEnvironment;
  2304. var hooks = module.hooks = {};
  2305. setHookFromEnvironment(hooks, testEnvironment, "before");
  2306. setHookFromEnvironment(hooks, testEnvironment, "beforeEach");
  2307. setHookFromEnvironment(hooks, testEnvironment, "afterEach");
  2308. setHookFromEnvironment(hooks, testEnvironment, "after");
  2309. function setHookFromEnvironment(hooks, environment, name) {
  2310. var potentialHook = environment[name];
  2311. hooks[name] = typeof potentialHook === "function" ? [potentialHook] : [];
  2312. delete environment[name];
  2313. }
  2314. var moduleFns = {
  2315. before: setHookFunction(module, "before"),
  2316. beforeEach: setHookFunction(module, "beforeEach"),
  2317. afterEach: setHookFunction(module, "afterEach"),
  2318. after: setHookFunction(module, "after")
  2319. };
  2320. var currentModule = config.currentModule;
  2321. if (objectType(executeNow) === "function") {
  2322. moduleStack.push(module);
  2323. config.currentModule = module;
  2324. executeNow.call(module.testEnvironment, moduleFns);
  2325. moduleStack.pop();
  2326. module = module.parentModule || currentModule;
  2327. }
  2328. config.currentModule = module;
  2329. }
  2330. // TODO: extract this to a new file alongside its related functions
  2331. function module$1(name, options, executeNow) {
  2332. if (focused) {
  2333. return;
  2334. }
  2335. if (arguments.length === 2) {
  2336. if (objectType(options) === "function") {
  2337. executeNow = options;
  2338. options = undefined;
  2339. }
  2340. }
  2341. processModule(name, options, executeNow);
  2342. }
  2343. module$1.only = function () {
  2344. if (focused) {
  2345. return;
  2346. }
  2347. config.modules.length = 0;
  2348. config.queue.length = 0;
  2349. module$1.apply(undefined, arguments);
  2350. focused = true;
  2351. };
  2352. module$1.skip = function (name, options, executeNow) {
  2353. if (focused) {
  2354. return;
  2355. }
  2356. if (arguments.length === 2) {
  2357. if (objectType(options) === "function") {
  2358. executeNow = options;
  2359. options = undefined;
  2360. }
  2361. }
  2362. processModule(name, options, executeNow, { skip: true });
  2363. };
  2364. module$1.todo = function (name, options, executeNow) {
  2365. if (focused) {
  2366. return;
  2367. }
  2368. if (arguments.length === 2) {
  2369. if (objectType(options) === "function") {
  2370. executeNow = options;
  2371. options = undefined;
  2372. }
  2373. }
  2374. processModule(name, options, executeNow, { todo: true });
  2375. };
  2376. extend(QUnit, {
  2377. on: on,
  2378. module: module$1,
  2379. test: test,
  2380. todo: todo,
  2381. skip: skip,
  2382. only: only,
  2383. start: function start(count) {
  2384. var globalStartAlreadyCalled = globalStartCalled;
  2385. if (!config.current) {
  2386. globalStartCalled = true;
  2387. if (runStarted) {
  2388. throw new Error("Called start() while test already started running");
  2389. } else if (globalStartAlreadyCalled || count > 1) {
  2390. throw new Error("Called start() outside of a test context too many times");
  2391. } else if (config.autostart) {
  2392. throw new Error("Called start() outside of a test context when " + "QUnit.config.autostart was true");
  2393. } else if (!config.pageLoaded) {
  2394. // The page isn't completely loaded yet, so we set autostart and then
  2395. // load if we're in Node or wait for the browser's load event.
  2396. config.autostart = true;
  2397. // Starts from Node even if .load was not previously called. We still return
  2398. // early otherwise we'll wind up "beginning" twice.
  2399. if (!defined.document) {
  2400. QUnit.load();
  2401. }
  2402. return;
  2403. }
  2404. } else {
  2405. throw new Error("QUnit.start cannot be called inside a test context.");
  2406. }
  2407. scheduleBegin();
  2408. },
  2409. config: config,
  2410. is: is,
  2411. objectType: objectType,
  2412. extend: extend,
  2413. load: function load() {
  2414. config.pageLoaded = true;
  2415. // Initialize the configuration options
  2416. extend(config, {
  2417. stats: { all: 0, bad: 0 },
  2418. started: 0,
  2419. updateRate: 1000,
  2420. autostart: true,
  2421. filter: ""
  2422. }, true);
  2423. if (!runStarted) {
  2424. config.blocking = false;
  2425. if (config.autostart) {
  2426. scheduleBegin();
  2427. }
  2428. }
  2429. },
  2430. stack: function stack(offset) {
  2431. offset = (offset || 0) + 2;
  2432. return sourceFromStacktrace(offset);
  2433. },
  2434. onError: onError,
  2435. onUnhandledRejection: onUnhandledRejection
  2436. });
  2437. QUnit.pushFailure = pushFailure;
  2438. QUnit.assert = Assert.prototype;
  2439. QUnit.equiv = equiv;
  2440. QUnit.dump = dump;
  2441. registerLoggingCallbacks(QUnit);
  2442. function scheduleBegin() {
  2443. runStarted = true;
  2444. // Add a slight delay to allow definition of more modules and tests.
  2445. if (defined.setTimeout) {
  2446. setTimeout(function () {
  2447. begin();
  2448. });
  2449. } else {
  2450. begin();
  2451. }
  2452. }
  2453. function begin() {
  2454. var i,
  2455. l,
  2456. modulesLog = [];
  2457. // If the test run hasn't officially begun yet
  2458. if (!config.started) {
  2459. // Record the time of the test run's beginning
  2460. config.started = now();
  2461. // Delete the loose unnamed module if unused.
  2462. if (config.modules[0].name === "" && config.modules[0].tests.length === 0) {
  2463. config.modules.shift();
  2464. }
  2465. // Avoid unnecessary information by not logging modules' test environments
  2466. for (i = 0, l = config.modules.length; i < l; i++) {
  2467. modulesLog.push({
  2468. name: config.modules[i].name,
  2469. tests: config.modules[i].tests
  2470. });
  2471. }
  2472. // The test run is officially beginning now
  2473. emit("runStart", globalSuite.start(true));
  2474. runLoggingCallbacks("begin", {
  2475. totalTests: Test.count,
  2476. modules: modulesLog
  2477. });
  2478. }
  2479. config.blocking = false;
  2480. ProcessingQueue.advance();
  2481. }
  2482. function setHookFunction(module, hookName) {
  2483. return function setHook(callback) {
  2484. module.hooks[hookName].push(callback);
  2485. };
  2486. }
  2487. exportQUnit(QUnit);
  2488. (function () {
  2489. if (typeof window === "undefined" || typeof document === "undefined") {
  2490. return;
  2491. }
  2492. var config = QUnit.config,
  2493. hasOwn = Object.prototype.hasOwnProperty;
  2494. // Stores fixture HTML for resetting later
  2495. function storeFixture() {
  2496. // Avoid overwriting user-defined values
  2497. if (hasOwn.call(config, "fixture")) {
  2498. return;
  2499. }
  2500. var fixture = document.getElementById("qunit-fixture");
  2501. if (fixture) {
  2502. config.fixture = fixture.innerHTML;
  2503. }
  2504. }
  2505. QUnit.begin(storeFixture);
  2506. // Resets the fixture DOM element if available.
  2507. function resetFixture() {
  2508. if (config.fixture == null) {
  2509. return;
  2510. }
  2511. var fixture = document.getElementById("qunit-fixture");
  2512. if (fixture) {
  2513. fixture.innerHTML = config.fixture;
  2514. }
  2515. }
  2516. QUnit.testStart(resetFixture);
  2517. })();
  2518. (function () {
  2519. // Only interact with URLs via window.location
  2520. var location = typeof window !== "undefined" && window.location;
  2521. if (!location) {
  2522. return;
  2523. }
  2524. var urlParams = getUrlParams();
  2525. QUnit.urlParams = urlParams;
  2526. // Match module/test by inclusion in an array
  2527. QUnit.config.moduleId = [].concat(urlParams.moduleId || []);
  2528. QUnit.config.testId = [].concat(urlParams.testId || []);
  2529. // Exact case-insensitive match of the module name
  2530. QUnit.config.module = urlParams.module;
  2531. // Regular expression or case-insenstive substring match against "moduleName: testName"
  2532. QUnit.config.filter = urlParams.filter;
  2533. // Test order randomization
  2534. if (urlParams.seed === true) {
  2535. // Generate a random seed if the option is specified without a value
  2536. QUnit.config.seed = Math.random().toString(36).slice(2);
  2537. } else if (urlParams.seed) {
  2538. QUnit.config.seed = urlParams.seed;
  2539. }
  2540. // Add URL-parameter-mapped config values with UI form rendering data
  2541. QUnit.config.urlConfig.push({
  2542. id: "hidepassed",
  2543. label: "Hide passed tests",
  2544. tooltip: "Only show tests and assertions that fail. Stored as query-strings."
  2545. }, {
  2546. id: "noglobals",
  2547. label: "Check for Globals",
  2548. tooltip: "Enabling this will test if any test introduces new properties on the " + "global object (`window` in Browsers). Stored as query-strings."
  2549. }, {
  2550. id: "notrycatch",
  2551. label: "No try-catch",
  2552. tooltip: "Enabling this will run tests outside of a try-catch block. Makes debugging " + "exceptions in IE reasonable. Stored as query-strings."
  2553. });
  2554. QUnit.begin(function () {
  2555. var i,
  2556. option,
  2557. urlConfig = QUnit.config.urlConfig;
  2558. for (i = 0; i < urlConfig.length; i++) {
  2559. // Options can be either strings or objects with nonempty "id" properties
  2560. option = QUnit.config.urlConfig[i];
  2561. if (typeof option !== "string") {
  2562. option = option.id;
  2563. }
  2564. if (QUnit.config[option] === undefined) {
  2565. QUnit.config[option] = urlParams[option];
  2566. }
  2567. }
  2568. });
  2569. function getUrlParams() {
  2570. var i, param, name, value;
  2571. var urlParams = Object.create(null);
  2572. var params = location.search.slice(1).split("&");
  2573. var length = params.length;
  2574. for (i = 0; i < length; i++) {
  2575. if (params[i]) {
  2576. param = params[i].split("=");
  2577. name = decodeQueryParam(param[0]);
  2578. // Allow just a key to turn on a flag, e.g., test.html?noglobals
  2579. value = param.length === 1 || decodeQueryParam(param.slice(1).join("="));
  2580. if (name in urlParams) {
  2581. urlParams[name] = [].concat(urlParams[name], value);
  2582. } else {
  2583. urlParams[name] = value;
  2584. }
  2585. }
  2586. }
  2587. return urlParams;
  2588. }
  2589. function decodeQueryParam(param) {
  2590. return decodeURIComponent(param.replace(/\+/g, "%20"));
  2591. }
  2592. })();
  2593. var stats = {
  2594. passedTests: 0,
  2595. failedTests: 0,
  2596. skippedTests: 0,
  2597. todoTests: 0
  2598. };
  2599. // Escape text for attribute or text content.
  2600. function escapeText(s) {
  2601. if (!s) {
  2602. return "";
  2603. }
  2604. s = s + "";
  2605. // Both single quotes and double quotes (for attributes)
  2606. return s.replace(/['"<>&]/g, function (s) {
  2607. switch (s) {
  2608. case "'":
  2609. return "&#039;";
  2610. case "\"":
  2611. return "&quot;";
  2612. case "<":
  2613. return "&lt;";
  2614. case ">":
  2615. return "&gt;";
  2616. case "&":
  2617. return "&amp;";
  2618. }
  2619. });
  2620. }
  2621. (function () {
  2622. // Don't load the HTML Reporter on non-browser environments
  2623. if (typeof window === "undefined" || !window.document) {
  2624. return;
  2625. }
  2626. var config = QUnit.config,
  2627. document$$1 = window.document,
  2628. collapseNext = false,
  2629. hasOwn = Object.prototype.hasOwnProperty,
  2630. unfilteredUrl = setUrl({ filter: undefined, module: undefined,
  2631. moduleId: undefined, testId: undefined }),
  2632. modulesList = [];
  2633. function addEvent(elem, type, fn) {
  2634. elem.addEventListener(type, fn, false);
  2635. }
  2636. function removeEvent(elem, type, fn) {
  2637. elem.removeEventListener(type, fn, false);
  2638. }
  2639. function addEvents(elems, type, fn) {
  2640. var i = elems.length;
  2641. while (i--) {
  2642. addEvent(elems[i], type, fn);
  2643. }
  2644. }
  2645. function hasClass(elem, name) {
  2646. return (" " + elem.className + " ").indexOf(" " + name + " ") >= 0;
  2647. }
  2648. function addClass(elem, name) {
  2649. if (!hasClass(elem, name)) {
  2650. elem.className += (elem.className ? " " : "") + name;
  2651. }
  2652. }
  2653. function toggleClass(elem, name, force) {
  2654. if (force || typeof force === "undefined" && !hasClass(elem, name)) {
  2655. addClass(elem, name);
  2656. } else {
  2657. removeClass(elem, name);
  2658. }
  2659. }
  2660. function removeClass(elem, name) {
  2661. var set = " " + elem.className + " ";
  2662. // Class name may appear multiple times
  2663. while (set.indexOf(" " + name + " ") >= 0) {
  2664. set = set.replace(" " + name + " ", " ");
  2665. }
  2666. // Trim for prettiness
  2667. elem.className = typeof set.trim === "function" ? set.trim() : set.replace(/^\s+|\s+$/g, "");
  2668. }
  2669. function id(name) {
  2670. return document$$1.getElementById && document$$1.getElementById(name);
  2671. }
  2672. function abortTests() {
  2673. var abortButton = id("qunit-abort-tests-button");
  2674. if (abortButton) {
  2675. abortButton.disabled = true;
  2676. abortButton.innerHTML = "Aborting...";
  2677. }
  2678. QUnit.config.queue.length = 0;
  2679. return false;
  2680. }
  2681. function interceptNavigation(ev) {
  2682. applyUrlParams();
  2683. if (ev && ev.preventDefault) {
  2684. ev.preventDefault();
  2685. }
  2686. return false;
  2687. }
  2688. function getUrlConfigHtml() {
  2689. var i,
  2690. j,
  2691. val,
  2692. escaped,
  2693. escapedTooltip,
  2694. selection = false,
  2695. urlConfig = config.urlConfig,
  2696. urlConfigHtml = "";
  2697. for (i = 0; i < urlConfig.length; i++) {
  2698. // Options can be either strings or objects with nonempty "id" properties
  2699. val = config.urlConfig[i];
  2700. if (typeof val === "string") {
  2701. val = {
  2702. id: val,
  2703. label: val
  2704. };
  2705. }
  2706. escaped = escapeText(val.id);
  2707. escapedTooltip = escapeText(val.tooltip);
  2708. if (!val.value || typeof val.value === "string") {
  2709. 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>";
  2710. } else {
  2711. urlConfigHtml += "<label for='qunit-urlconfig-" + escaped + "' title='" + escapedTooltip + "'>" + val.label + ": </label><select id='qunit-urlconfig-" + escaped + "' name='" + escaped + "' title='" + escapedTooltip + "'><option></option>";
  2712. if (QUnit.is("array", val.value)) {
  2713. for (j = 0; j < val.value.length; j++) {
  2714. escaped = escapeText(val.value[j]);
  2715. urlConfigHtml += "<option value='" + escaped + "'" + (config[val.id] === val.value[j] ? (selection = true) && " selected='selected'" : "") + ">" + escaped + "</option>";
  2716. }
  2717. } else {
  2718. for (j in val.value) {
  2719. if (hasOwn.call(val.value, j)) {
  2720. urlConfigHtml += "<option value='" + escapeText(j) + "'" + (config[val.id] === j ? (selection = true) && " selected='selected'" : "") + ">" + escapeText(val.value[j]) + "</option>";
  2721. }
  2722. }
  2723. }
  2724. if (config[val.id] && !selection) {
  2725. escaped = escapeText(config[val.id]);
  2726. urlConfigHtml += "<option value='" + escaped + "' selected='selected' disabled='disabled'>" + escaped + "</option>";
  2727. }
  2728. urlConfigHtml += "</select>";
  2729. }
  2730. }
  2731. return urlConfigHtml;
  2732. }
  2733. // Handle "click" events on toolbar checkboxes and "change" for select menus.
  2734. // Updates the URL with the new state of `config.urlConfig` values.
  2735. function toolbarChanged() {
  2736. var updatedUrl,
  2737. value,
  2738. tests,
  2739. field = this,
  2740. params = {};
  2741. // Detect if field is a select menu or a checkbox
  2742. if ("selectedIndex" in field) {
  2743. value = field.options[field.selectedIndex].value || undefined;
  2744. } else {
  2745. value = field.checked ? field.defaultValue || true : undefined;
  2746. }
  2747. params[field.name] = value;
  2748. updatedUrl = setUrl(params);
  2749. // Check if we can apply the change without a page refresh
  2750. if ("hidepassed" === field.name && "replaceState" in window.history) {
  2751. QUnit.urlParams[field.name] = value;
  2752. config[field.name] = value || false;
  2753. tests = id("qunit-tests");
  2754. if (tests) {
  2755. toggleClass(tests, "hidepass", value || false);
  2756. }
  2757. window.history.replaceState(null, "", updatedUrl);
  2758. } else {
  2759. window.location = updatedUrl;
  2760. }
  2761. }
  2762. function setUrl(params) {
  2763. var key,
  2764. arrValue,
  2765. i,
  2766. querystring = "?",
  2767. location = window.location;
  2768. params = QUnit.extend(QUnit.extend({}, QUnit.urlParams), params);
  2769. for (key in params) {
  2770. // Skip inherited or undefined properties
  2771. if (hasOwn.call(params, key) && params[key] !== undefined) {
  2772. // Output a parameter for each value of this key
  2773. // (but usually just one)
  2774. arrValue = [].concat(params[key]);
  2775. for (i = 0; i < arrValue.length; i++) {
  2776. querystring += encodeURIComponent(key);
  2777. if (arrValue[i] !== true) {
  2778. querystring += "=" + encodeURIComponent(arrValue[i]);
  2779. }
  2780. querystring += "&";
  2781. }
  2782. }
  2783. }
  2784. return location.protocol + "//" + location.host + location.pathname + querystring.slice(0, -1);
  2785. }
  2786. function applyUrlParams() {
  2787. var i,
  2788. selectedModules = [],
  2789. modulesList = id("qunit-modulefilter-dropdown-list").getElementsByTagName("input"),
  2790. filter = id("qunit-filter-input").value;
  2791. for (i = 0; i < modulesList.length; i++) {
  2792. if (modulesList[i].checked) {
  2793. selectedModules.push(modulesList[i].value);
  2794. }
  2795. }
  2796. window.location = setUrl({
  2797. filter: filter === "" ? undefined : filter,
  2798. moduleId: selectedModules.length === 0 ? undefined : selectedModules,
  2799. // Remove module and testId filter
  2800. module: undefined,
  2801. testId: undefined
  2802. });
  2803. }
  2804. function toolbarUrlConfigContainer() {
  2805. var urlConfigContainer = document$$1.createElement("span");
  2806. urlConfigContainer.innerHTML = getUrlConfigHtml();
  2807. addClass(urlConfigContainer, "qunit-url-config");
  2808. addEvents(urlConfigContainer.getElementsByTagName("input"), "change", toolbarChanged);
  2809. addEvents(urlConfigContainer.getElementsByTagName("select"), "change", toolbarChanged);
  2810. return urlConfigContainer;
  2811. }
  2812. function abortTestsButton() {
  2813. var button = document$$1.createElement("button");
  2814. button.id = "qunit-abort-tests-button";
  2815. button.innerHTML = "Abort";
  2816. addEvent(button, "click", abortTests);
  2817. return button;
  2818. }
  2819. function toolbarLooseFilter() {
  2820. var filter = document$$1.createElement("form"),
  2821. label = document$$1.createElement("label"),
  2822. input = document$$1.createElement("input"),
  2823. button = document$$1.createElement("button");
  2824. addClass(filter, "qunit-filter");
  2825. label.innerHTML = "Filter: ";
  2826. input.type = "text";
  2827. input.value = config.filter || "";
  2828. input.name = "filter";
  2829. input.id = "qunit-filter-input";
  2830. button.innerHTML = "Go";
  2831. label.appendChild(input);
  2832. filter.appendChild(label);
  2833. filter.appendChild(document$$1.createTextNode(" "));
  2834. filter.appendChild(button);
  2835. addEvent(filter, "submit", interceptNavigation);
  2836. return filter;
  2837. }
  2838. function moduleListHtml() {
  2839. var i,
  2840. checked,
  2841. html = "";
  2842. for (i = 0; i < config.modules.length; i++) {
  2843. if (config.modules[i].name !== "") {
  2844. checked = config.moduleId.indexOf(config.modules[i].moduleId) > -1;
  2845. 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>";
  2846. }
  2847. }
  2848. return html;
  2849. }
  2850. function toolbarModuleFilter() {
  2851. var allCheckbox,
  2852. commit,
  2853. reset,
  2854. moduleFilter = document$$1.createElement("form"),
  2855. label = document$$1.createElement("label"),
  2856. moduleSearch = document$$1.createElement("input"),
  2857. dropDown = document$$1.createElement("div"),
  2858. actions = document$$1.createElement("span"),
  2859. dropDownList = document$$1.createElement("ul"),
  2860. dirty = false;
  2861. moduleSearch.id = "qunit-modulefilter-search";
  2862. addEvent(moduleSearch, "input", searchInput);
  2863. addEvent(moduleSearch, "input", searchFocus);
  2864. addEvent(moduleSearch, "focus", searchFocus);
  2865. addEvent(moduleSearch, "click", searchFocus);
  2866. label.id = "qunit-modulefilter-search-container";
  2867. label.innerHTML = "Module: ";
  2868. label.appendChild(moduleSearch);
  2869. actions.id = "qunit-modulefilter-actions";
  2870. 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>";
  2871. allCheckbox = actions.lastChild.firstChild;
  2872. commit = actions.firstChild;
  2873. reset = commit.nextSibling;
  2874. addEvent(commit, "click", applyUrlParams);
  2875. dropDownList.id = "qunit-modulefilter-dropdown-list";
  2876. dropDownList.innerHTML = moduleListHtml();
  2877. dropDown.id = "qunit-modulefilter-dropdown";
  2878. dropDown.style.display = "none";
  2879. dropDown.appendChild(actions);
  2880. dropDown.appendChild(dropDownList);
  2881. addEvent(dropDown, "change", selectionChange);
  2882. selectionChange();
  2883. moduleFilter.id = "qunit-modulefilter";
  2884. moduleFilter.appendChild(label);
  2885. moduleFilter.appendChild(dropDown);
  2886. addEvent(moduleFilter, "submit", interceptNavigation);
  2887. addEvent(moduleFilter, "reset", function () {
  2888. // Let the reset happen, then update styles
  2889. window.setTimeout(selectionChange);
  2890. });
  2891. // Enables show/hide for the dropdown
  2892. function searchFocus() {
  2893. if (dropDown.style.display !== "none") {
  2894. return;
  2895. }
  2896. dropDown.style.display = "block";
  2897. addEvent(document$$1, "click", hideHandler);
  2898. addEvent(document$$1, "keydown", hideHandler);
  2899. // Hide on Escape keydown or outside-container click
  2900. function hideHandler(e) {
  2901. var inContainer = moduleFilter.contains(e.target);
  2902. if (e.keyCode === 27 || !inContainer) {
  2903. if (e.keyCode === 27 && inContainer) {
  2904. moduleSearch.focus();
  2905. }
  2906. dropDown.style.display = "none";
  2907. removeEvent(document$$1, "click", hideHandler);
  2908. removeEvent(document$$1, "keydown", hideHandler);
  2909. moduleSearch.value = "";
  2910. searchInput();
  2911. }
  2912. }
  2913. }
  2914. // Processes module search box input
  2915. function searchInput() {
  2916. var i,
  2917. item,
  2918. searchText = moduleSearch.value.toLowerCase(),
  2919. listItems = dropDownList.children;
  2920. for (i = 0; i < listItems.length; i++) {
  2921. item = listItems[i];
  2922. if (!searchText || item.textContent.toLowerCase().indexOf(searchText) > -1) {
  2923. item.style.display = "";
  2924. } else {
  2925. item.style.display = "none";
  2926. }
  2927. }
  2928. }
  2929. // Processes selection changes
  2930. function selectionChange(evt) {
  2931. var i,
  2932. item,
  2933. checkbox = evt && evt.target || allCheckbox,
  2934. modulesList = dropDownList.getElementsByTagName("input"),
  2935. selectedNames = [];
  2936. toggleClass(checkbox.parentNode, "checked", checkbox.checked);
  2937. dirty = false;
  2938. if (checkbox.checked && checkbox !== allCheckbox) {
  2939. allCheckbox.checked = false;
  2940. removeClass(allCheckbox.parentNode, "checked");
  2941. }
  2942. for (i = 0; i < modulesList.length; i++) {
  2943. item = modulesList[i];
  2944. if (!evt) {
  2945. toggleClass(item.parentNode, "checked", item.checked);
  2946. } else if (checkbox === allCheckbox && checkbox.checked) {
  2947. item.checked = false;
  2948. removeClass(item.parentNode, "checked");
  2949. }
  2950. dirty = dirty || item.checked !== item.defaultChecked;
  2951. if (item.checked) {
  2952. selectedNames.push(item.parentNode.textContent);
  2953. }
  2954. }
  2955. commit.style.display = reset.style.display = dirty ? "" : "none";
  2956. moduleSearch.placeholder = selectedNames.join(", ") || allCheckbox.parentNode.textContent;
  2957. moduleSearch.title = "Type to filter list. Current selection:\n" + (selectedNames.join("\n") || allCheckbox.parentNode.textContent);
  2958. }
  2959. return moduleFilter;
  2960. }
  2961. function appendToolbar() {
  2962. var toolbar = id("qunit-testrunner-toolbar");
  2963. if (toolbar) {
  2964. toolbar.appendChild(toolbarUrlConfigContainer());
  2965. toolbar.appendChild(toolbarModuleFilter());
  2966. toolbar.appendChild(toolbarLooseFilter());
  2967. toolbar.appendChild(document$$1.createElement("div")).className = "clearfix";
  2968. }
  2969. }
  2970. function appendHeader() {
  2971. var header = id("qunit-header");
  2972. if (header) {
  2973. header.innerHTML = "<a href='" + escapeText(unfilteredUrl) + "'>" + header.innerHTML + "</a> ";
  2974. }
  2975. }
  2976. function appendBanner() {
  2977. var banner = id("qunit-banner");
  2978. if (banner) {
  2979. banner.className = "";
  2980. }
  2981. }
  2982. function appendTestResults() {
  2983. var tests = id("qunit-tests"),
  2984. result = id("qunit-testresult"),
  2985. controls;
  2986. if (result) {
  2987. result.parentNode.removeChild(result);
  2988. }
  2989. if (tests) {
  2990. tests.innerHTML = "";
  2991. result = document$$1.createElement("p");
  2992. result.id = "qunit-testresult";
  2993. result.className = "result";
  2994. tests.parentNode.insertBefore(result, tests);
  2995. result.innerHTML = "<div id=\"qunit-testresult-display\">Running...<br />&#160;</div>" + "<div id=\"qunit-testresult-controls\"></div>" + "<div class=\"clearfix\"></div>";
  2996. controls = id("qunit-testresult-controls");
  2997. }
  2998. if (controls) {
  2999. controls.appendChild(abortTestsButton());
  3000. }
  3001. }
  3002. function appendFilteredTest() {
  3003. var testId = QUnit.config.testId;
  3004. if (!testId || testId.length <= 0) {
  3005. return "";
  3006. }
  3007. return "<div id='qunit-filteredTest'>Rerunning selected tests: " + escapeText(testId.join(", ")) + " <a id='qunit-clearFilter' href='" + escapeText(unfilteredUrl) + "'>Run all tests</a></div>";
  3008. }
  3009. function appendUserAgent() {
  3010. var userAgent = id("qunit-userAgent");
  3011. if (userAgent) {
  3012. userAgent.innerHTML = "";
  3013. userAgent.appendChild(document$$1.createTextNode("QUnit " + QUnit.version + "; " + navigator.userAgent));
  3014. }
  3015. }
  3016. function appendInterface() {
  3017. var qunit = id("qunit");
  3018. if (qunit) {
  3019. 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>";
  3020. }
  3021. appendHeader();
  3022. appendBanner();
  3023. appendTestResults();
  3024. appendUserAgent();
  3025. appendToolbar();
  3026. }
  3027. function appendTestsList(modules) {
  3028. var i, l, x, z, test, moduleObj;
  3029. for (i = 0, l = modules.length; i < l; i++) {
  3030. moduleObj = modules[i];
  3031. for (x = 0, z = moduleObj.tests.length; x < z; x++) {
  3032. test = moduleObj.tests[x];
  3033. appendTest(test.name, test.testId, moduleObj.name);
  3034. }
  3035. }
  3036. }
  3037. function appendTest(name, testId, moduleName) {
  3038. var title,
  3039. rerunTrigger,
  3040. testBlock,
  3041. assertList,
  3042. tests = id("qunit-tests");
  3043. if (!tests) {
  3044. return;
  3045. }
  3046. title = document$$1.createElement("strong");
  3047. title.innerHTML = getNameHtml(name, moduleName);
  3048. rerunTrigger = document$$1.createElement("a");
  3049. rerunTrigger.innerHTML = "Rerun";
  3050. rerunTrigger.href = setUrl({ testId: testId });
  3051. testBlock = document$$1.createElement("li");
  3052. testBlock.appendChild(title);
  3053. testBlock.appendChild(rerunTrigger);
  3054. testBlock.id = "qunit-test-output-" + testId;
  3055. assertList = document$$1.createElement("ol");
  3056. assertList.className = "qunit-assert-list";
  3057. testBlock.appendChild(assertList);
  3058. tests.appendChild(testBlock);
  3059. }
  3060. // HTML Reporter initialization and load
  3061. QUnit.begin(function (details) {
  3062. var i, moduleObj, tests;
  3063. // Sort modules by name for the picker
  3064. for (i = 0; i < details.modules.length; i++) {
  3065. moduleObj = details.modules[i];
  3066. if (moduleObj.name) {
  3067. modulesList.push(moduleObj.name);
  3068. }
  3069. }
  3070. modulesList.sort(function (a, b) {
  3071. return a.localeCompare(b);
  3072. });
  3073. // Initialize QUnit elements
  3074. appendInterface();
  3075. appendTestsList(details.modules);
  3076. tests = id("qunit-tests");
  3077. if (tests && config.hidepassed) {
  3078. addClass(tests, "hidepass");
  3079. }
  3080. });
  3081. QUnit.done(function (details) {
  3082. var banner = id("qunit-banner"),
  3083. tests = id("qunit-tests"),
  3084. abortButton = id("qunit-abort-tests-button"),
  3085. totalTests = stats.passedTests + stats.skippedTests + stats.todoTests + stats.failedTests,
  3086. 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(""),
  3087. test,
  3088. assertLi,
  3089. assertList;
  3090. // Update remaing tests to aborted
  3091. if (abortButton && abortButton.disabled) {
  3092. html = "Tests aborted after " + details.runtime + " milliseconds.";
  3093. for (var i = 0; i < tests.children.length; i++) {
  3094. test = tests.children[i];
  3095. if (test.className === "" || test.className === "running") {
  3096. test.className = "aborted";
  3097. assertList = test.getElementsByTagName("ol")[0];
  3098. assertLi = document$$1.createElement("li");
  3099. assertLi.className = "fail";
  3100. assertLi.innerHTML = "Test aborted.";
  3101. assertList.appendChild(assertLi);
  3102. }
  3103. }
  3104. }
  3105. if (banner && (!abortButton || abortButton.disabled === false)) {
  3106. banner.className = stats.failedTests ? "qunit-fail" : "qunit-pass";
  3107. }
  3108. if (abortButton) {
  3109. abortButton.parentNode.removeChild(abortButton);
  3110. }
  3111. if (tests) {
  3112. id("qunit-testresult-display").innerHTML = html;
  3113. }
  3114. if (config.altertitle && document$$1.title) {
  3115. // Show ✖ for good, ✔ for bad suite result in title
  3116. // use escape sequences in case file gets loaded with non-utf-8
  3117. // charset
  3118. document$$1.title = [stats.failedTests ? "\u2716" : "\u2714", document$$1.title.replace(/^[\u2714\u2716] /i, "")].join(" ");
  3119. }
  3120. // Scroll back to top to show results
  3121. if (config.scrolltop && window.scrollTo) {
  3122. window.scrollTo(0, 0);
  3123. }
  3124. });
  3125. function getNameHtml(name, module) {
  3126. var nameHtml = "";
  3127. if (module) {
  3128. nameHtml = "<span class='module-name'>" + escapeText(module) + "</span>: ";
  3129. }
  3130. nameHtml += "<span class='test-name'>" + escapeText(name) + "</span>";
  3131. return nameHtml;
  3132. }
  3133. QUnit.testStart(function (details) {
  3134. var running, testBlock, bad;
  3135. testBlock = id("qunit-test-output-" + details.testId);
  3136. if (testBlock) {
  3137. testBlock.className = "running";
  3138. } else {
  3139. // Report later registered tests
  3140. appendTest(details.name, details.testId, details.module);
  3141. }
  3142. running = id("qunit-testresult-display");
  3143. if (running) {
  3144. bad = QUnit.config.reorder && details.previousFailure;
  3145. running.innerHTML = [bad ? "Rerunning previously failed test: <br />" : "Running: <br />", getNameHtml(details.name, details.module)].join("");
  3146. }
  3147. });
  3148. function stripHtml(string) {
  3149. // Strip tags, html entity and whitespaces
  3150. return string.replace(/<\/?[^>]+(>|$)/g, "").replace(/\&quot;/g, "").replace(/\s+/g, "");
  3151. }
  3152. QUnit.log(function (details) {
  3153. var assertList,
  3154. assertLi,
  3155. message,
  3156. expected,
  3157. actual,
  3158. diff,
  3159. showDiff = false,
  3160. testItem = id("qunit-test-output-" + details.testId);
  3161. if (!testItem) {
  3162. return;
  3163. }
  3164. message = escapeText(details.message) || (details.result ? "okay" : "failed");
  3165. message = "<span class='test-message'>" + message + "</span>";
  3166. message += "<span class='runtime'>@ " + details.runtime + " ms</span>";
  3167. // The pushFailure doesn't provide details.expected
  3168. // when it calls, it's implicit to also not show expected and diff stuff
  3169. // Also, we need to check details.expected existence, as it can exist and be undefined
  3170. if (!details.result && hasOwn.call(details, "expected")) {
  3171. if (details.negative) {
  3172. expected = "NOT " + QUnit.dump.parse(details.expected);
  3173. } else {
  3174. expected = QUnit.dump.parse(details.expected);
  3175. }
  3176. actual = QUnit.dump.parse(details.actual);
  3177. message += "<table><tr class='test-expected'><th>Expected: </th><td><pre>" + escapeText(expected) + "</pre></td></tr>";
  3178. if (actual !== expected) {
  3179. message += "<tr class='test-actual'><th>Result: </th><td><pre>" + escapeText(actual) + "</pre></td></tr>";
  3180. if (typeof details.actual === "number" && typeof details.expected === "number") {
  3181. if (!isNaN(details.actual) && !isNaN(details.expected)) {
  3182. showDiff = true;
  3183. diff = details.actual - details.expected;
  3184. diff = (diff > 0 ? "+" : "") + diff;
  3185. }
  3186. } else if (typeof details.actual !== "boolean" && typeof details.expected !== "boolean") {
  3187. diff = QUnit.diff(expected, actual);
  3188. // don't show diff if there is zero overlap
  3189. showDiff = stripHtml(diff).length !== stripHtml(expected).length + stripHtml(actual).length;
  3190. }
  3191. if (showDiff) {
  3192. message += "<tr class='test-diff'><th>Diff: </th><td><pre>" + diff + "</pre></td></tr>";
  3193. }
  3194. } else if (expected.indexOf("[object Array]") !== -1 || expected.indexOf("[object Object]") !== -1) {
  3195. 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>";
  3196. } else {
  3197. message += "<tr class='test-message'><th>Message: </th><td>" + "Diff suppressed as the expected and actual results have an equivalent" + " serialization</td></tr>";
  3198. }
  3199. if (details.source) {
  3200. message += "<tr class='test-source'><th>Source: </th><td><pre>" + escapeText(details.source) + "</pre></td></tr>";
  3201. }
  3202. message += "</table>";
  3203. // This occurs when pushFailure is set and we have an extracted stack trace
  3204. } else if (!details.result && details.source) {
  3205. message += "<table>" + "<tr class='test-source'><th>Source: </th><td><pre>" + escapeText(details.source) + "</pre></td></tr>" + "</table>";
  3206. }
  3207. assertList = testItem.getElementsByTagName("ol")[0];
  3208. assertLi = document$$1.createElement("li");
  3209. assertLi.className = details.result ? "pass" : "fail";
  3210. assertLi.innerHTML = message;
  3211. assertList.appendChild(assertLi);
  3212. });
  3213. QUnit.testDone(function (details) {
  3214. var testTitle,
  3215. time,
  3216. testItem,
  3217. assertList,
  3218. good,
  3219. bad,
  3220. testCounts,
  3221. skipped,
  3222. sourceName,
  3223. tests = id("qunit-tests");
  3224. if (!tests) {
  3225. return;
  3226. }
  3227. testItem = id("qunit-test-output-" + details.testId);
  3228. assertList = testItem.getElementsByTagName("ol")[0];
  3229. good = details.passed;
  3230. bad = details.failed;
  3231. // This test passed if it has no unexpected failed assertions
  3232. var testPassed = details.failed > 0 ? details.todo : !details.todo;
  3233. if (testPassed) {
  3234. // Collapse the passing tests
  3235. addClass(assertList, "qunit-collapsed");
  3236. } else if (config.collapse) {
  3237. if (!collapseNext) {
  3238. // Skip collapsing the first failing test
  3239. collapseNext = true;
  3240. } else {
  3241. // Collapse remaining tests
  3242. addClass(assertList, "qunit-collapsed");
  3243. }
  3244. }
  3245. // The testItem.firstChild is the test name
  3246. testTitle = testItem.firstChild;
  3247. testCounts = bad ? "<b class='failed'>" + bad + "</b>, " + "<b class='passed'>" + good + "</b>, " : "";
  3248. testTitle.innerHTML += " <b class='counts'>(" + testCounts + details.assertions.length + ")</b>";
  3249. if (details.skipped) {
  3250. stats.skippedTests++;
  3251. testItem.className = "skipped";
  3252. skipped = document$$1.createElement("em");
  3253. skipped.className = "qunit-skipped-label";
  3254. skipped.innerHTML = "skipped";
  3255. testItem.insertBefore(skipped, testTitle);
  3256. } else {
  3257. addEvent(testTitle, "click", function () {
  3258. toggleClass(assertList, "qunit-collapsed");
  3259. });
  3260. testItem.className = testPassed ? "pass" : "fail";
  3261. if (details.todo) {
  3262. var todoLabel = document$$1.createElement("em");
  3263. todoLabel.className = "qunit-todo-label";
  3264. todoLabel.innerHTML = "todo";
  3265. testItem.className += " todo";
  3266. testItem.insertBefore(todoLabel, testTitle);
  3267. }
  3268. time = document$$1.createElement("span");
  3269. time.className = "runtime";
  3270. time.innerHTML = details.runtime + " ms";
  3271. testItem.insertBefore(time, assertList);
  3272. if (!testPassed) {
  3273. stats.failedTests++;
  3274. } else if (details.todo) {
  3275. stats.todoTests++;
  3276. } else {
  3277. stats.passedTests++;
  3278. }
  3279. }
  3280. // Show the source of the test when showing assertions
  3281. if (details.source) {
  3282. sourceName = document$$1.createElement("p");
  3283. sourceName.innerHTML = "<strong>Source: </strong>" + details.source;
  3284. addClass(sourceName, "qunit-source");
  3285. if (testPassed) {
  3286. addClass(sourceName, "qunit-collapsed");
  3287. }
  3288. addEvent(testTitle, "click", function () {
  3289. toggleClass(sourceName, "qunit-collapsed");
  3290. });
  3291. testItem.appendChild(sourceName);
  3292. }
  3293. });
  3294. // Avoid readyState issue with phantomjs
  3295. // Ref: #818
  3296. var notPhantom = function (p) {
  3297. return !(p && p.version && p.version.major > 0);
  3298. }(window.phantom);
  3299. if (notPhantom && document$$1.readyState === "complete") {
  3300. QUnit.load();
  3301. } else {
  3302. addEvent(window, "load", QUnit.load);
  3303. }
  3304. // Wrap window.onerror. We will call the original window.onerror to see if
  3305. // the existing handler fully handles the error; if not, we will call the
  3306. // QUnit.onError function.
  3307. var originalWindowOnError = window.onerror;
  3308. // Cover uncaught exceptions
  3309. // Returning true will suppress the default browser handler,
  3310. // returning false will let it run.
  3311. window.onerror = function (message, fileName, lineNumber) {
  3312. var ret = false;
  3313. if (originalWindowOnError) {
  3314. for (var _len = arguments.length, args = Array(_len > 3 ? _len - 3 : 0), _key = 3; _key < _len; _key++) {
  3315. args[_key - 3] = arguments[_key];
  3316. }
  3317. ret = originalWindowOnError.call.apply(originalWindowOnError, [this, message, fileName, lineNumber].concat(args));
  3318. }
  3319. // Treat return value as window.onerror itself does,
  3320. // Only do our handling if not suppressed.
  3321. if (ret !== true) {
  3322. var error = {
  3323. message: message,
  3324. fileName: fileName,
  3325. lineNumber: lineNumber
  3326. };
  3327. ret = QUnit.onError(error);
  3328. }
  3329. return ret;
  3330. };
  3331. // Listen for unhandled rejections, and call QUnit.onUnhandledRejection
  3332. window.addEventListener("unhandledrejection", function (event) {
  3333. QUnit.onUnhandledRejection(event.reason);
  3334. });
  3335. })();
  3336. /*
  3337. * This file is a modified version of google-diff-match-patch's JavaScript implementation
  3338. * (https://code.google.com/p/google-diff-match-patch/source/browse/trunk/javascript/diff_match_patch_uncompressed.js),
  3339. * modifications are licensed as more fully set forth in LICENSE.txt.
  3340. *
  3341. * The original source of google-diff-match-patch is attributable and licensed as follows:
  3342. *
  3343. * Copyright 2006 Google Inc.
  3344. * https://code.google.com/p/google-diff-match-patch/
  3345. *
  3346. * Licensed under the Apache License, Version 2.0 (the "License");
  3347. * you may not use this file except in compliance with the License.
  3348. * You may obtain a copy of the License at
  3349. *
  3350. * https://www.apache.org/licenses/LICENSE-2.0
  3351. *
  3352. * Unless required by applicable law or agreed to in writing, software
  3353. * distributed under the License is distributed on an "AS IS" BASIS,
  3354. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  3355. * See the License for the specific language governing permissions and
  3356. * limitations under the License.
  3357. *
  3358. * More Info:
  3359. * https://code.google.com/p/google-diff-match-patch/
  3360. *
  3361. * Usage: QUnit.diff(expected, actual)
  3362. *
  3363. */
  3364. QUnit.diff = function () {
  3365. function DiffMatchPatch() {}
  3366. // DIFF FUNCTIONS
  3367. /**
  3368. * The data structure representing a diff is an array of tuples:
  3369. * [[DIFF_DELETE, 'Hello'], [DIFF_INSERT, 'Goodbye'], [DIFF_EQUAL, ' world.']]
  3370. * which means: delete 'Hello', add 'Goodbye' and keep ' world.'
  3371. */
  3372. var DIFF_DELETE = -1,
  3373. DIFF_INSERT = 1,
  3374. DIFF_EQUAL = 0;
  3375. /**
  3376. * Find the differences between two texts. Simplifies the problem by stripping
  3377. * any common prefix or suffix off the texts before diffing.
  3378. * @param {string} text1 Old string to be diffed.
  3379. * @param {string} text2 New string to be diffed.
  3380. * @param {boolean=} optChecklines Optional speedup flag. If present and false,
  3381. * then don't run a line-level diff first to identify the changed areas.
  3382. * Defaults to true, which does a faster, slightly less optimal diff.
  3383. * @return {!Array.<!DiffMatchPatch.Diff>} Array of diff tuples.
  3384. */
  3385. DiffMatchPatch.prototype.DiffMain = function (text1, text2, optChecklines) {
  3386. var deadline, checklines, commonlength, commonprefix, commonsuffix, diffs;
  3387. // The diff must be complete in up to 1 second.
  3388. deadline = new Date().getTime() + 1000;
  3389. // Check for null inputs.
  3390. if (text1 === null || text2 === null) {
  3391. throw new Error("Null input. (DiffMain)");
  3392. }
  3393. // Check for equality (speedup).
  3394. if (text1 === text2) {
  3395. if (text1) {
  3396. return [[DIFF_EQUAL, text1]];
  3397. }
  3398. return [];
  3399. }
  3400. if (typeof optChecklines === "undefined") {
  3401. optChecklines = true;
  3402. }
  3403. checklines = optChecklines;
  3404. // Trim off common prefix (speedup).
  3405. commonlength = this.diffCommonPrefix(text1, text2);
  3406. commonprefix = text1.substring(0, commonlength);
  3407. text1 = text1.substring(commonlength);
  3408. text2 = text2.substring(commonlength);
  3409. // Trim off common suffix (speedup).
  3410. commonlength = this.diffCommonSuffix(text1, text2);
  3411. commonsuffix = text1.substring(text1.length - commonlength);
  3412. text1 = text1.substring(0, text1.length - commonlength);
  3413. text2 = text2.substring(0, text2.length - commonlength);
  3414. // Compute the diff on the middle block.
  3415. diffs = this.diffCompute(text1, text2, checklines, deadline);
  3416. // Restore the prefix and suffix.
  3417. if (commonprefix) {
  3418. diffs.unshift([DIFF_EQUAL, commonprefix]);
  3419. }
  3420. if (commonsuffix) {
  3421. diffs.push([DIFF_EQUAL, commonsuffix]);
  3422. }
  3423. this.diffCleanupMerge(diffs);
  3424. return diffs;
  3425. };
  3426. /**
  3427. * Reduce the number of edits by eliminating operationally trivial equalities.
  3428. * @param {!Array.<!DiffMatchPatch.Diff>} diffs Array of diff tuples.
  3429. */
  3430. DiffMatchPatch.prototype.diffCleanupEfficiency = function (diffs) {
  3431. var changes, equalities, equalitiesLength, lastequality, pointer, preIns, preDel, postIns, postDel;
  3432. changes = false;
  3433. equalities = []; // Stack of indices where equalities are found.
  3434. equalitiesLength = 0; // Keeping our own length var is faster in JS.
  3435. /** @type {?string} */
  3436. lastequality = null;
  3437. // Always equal to diffs[equalities[equalitiesLength - 1]][1]
  3438. pointer = 0; // Index of current position.
  3439. // Is there an insertion operation before the last equality.
  3440. preIns = false;
  3441. // Is there a deletion operation before the last equality.
  3442. preDel = false;
  3443. // Is there an insertion operation after the last equality.
  3444. postIns = false;
  3445. // Is there a deletion operation after the last equality.
  3446. postDel = false;
  3447. while (pointer < diffs.length) {
  3448. // Equality found.
  3449. if (diffs[pointer][0] === DIFF_EQUAL) {
  3450. if (diffs[pointer][1].length < 4 && (postIns || postDel)) {
  3451. // Candidate found.
  3452. equalities[equalitiesLength++] = pointer;
  3453. preIns = postIns;
  3454. preDel = postDel;
  3455. lastequality = diffs[pointer][1];
  3456. } else {
  3457. // Not a candidate, and can never become one.
  3458. equalitiesLength = 0;
  3459. lastequality = null;
  3460. }
  3461. postIns = postDel = false;
  3462. // An insertion or deletion.
  3463. } else {
  3464. if (diffs[pointer][0] === DIFF_DELETE) {
  3465. postDel = true;
  3466. } else {
  3467. postIns = true;
  3468. }
  3469. /*
  3470. * Five types to be split:
  3471. * <ins>A</ins><del>B</del>XY<ins>C</ins><del>D</del>
  3472. * <ins>A</ins>X<ins>C</ins><del>D</del>
  3473. * <ins>A</ins><del>B</del>X<ins>C</ins>
  3474. * <ins>A</del>X<ins>C</ins><del>D</del>
  3475. * <ins>A</ins><del>B</del>X<del>C</del>
  3476. */
  3477. if (lastequality && (preIns && preDel && postIns && postDel || lastequality.length < 2 && preIns + preDel + postIns + postDel === 3)) {
  3478. // Duplicate record.
  3479. diffs.splice(equalities[equalitiesLength - 1], 0, [DIFF_DELETE, lastequality]);
  3480. // Change second copy to insert.
  3481. diffs[equalities[equalitiesLength - 1] + 1][0] = DIFF_INSERT;
  3482. equalitiesLength--; // Throw away the equality we just deleted;
  3483. lastequality = null;
  3484. if (preIns && preDel) {
  3485. // No changes made which could affect previous entry, keep going.
  3486. postIns = postDel = true;
  3487. equalitiesLength = 0;
  3488. } else {
  3489. equalitiesLength--; // Throw away the previous equality.
  3490. pointer = equalitiesLength > 0 ? equalities[equalitiesLength - 1] : -1;
  3491. postIns = postDel = false;
  3492. }
  3493. changes = true;
  3494. }
  3495. }
  3496. pointer++;
  3497. }
  3498. if (changes) {
  3499. this.diffCleanupMerge(diffs);
  3500. }
  3501. };
  3502. /**
  3503. * Convert a diff array into a pretty HTML report.
  3504. * @param {!Array.<!DiffMatchPatch.Diff>} diffs Array of diff tuples.
  3505. * @param {integer} string to be beautified.
  3506. * @return {string} HTML representation.
  3507. */
  3508. DiffMatchPatch.prototype.diffPrettyHtml = function (diffs) {
  3509. var op,
  3510. data,
  3511. x,
  3512. html = [];
  3513. for (x = 0; x < diffs.length; x++) {
  3514. op = diffs[x][0]; // Operation (insert, delete, equal)
  3515. data = diffs[x][1]; // Text of change.
  3516. switch (op) {
  3517. case DIFF_INSERT:
  3518. html[x] = "<ins>" + escapeText(data) + "</ins>";
  3519. break;
  3520. case DIFF_DELETE:
  3521. html[x] = "<del>" + escapeText(data) + "</del>";
  3522. break;
  3523. case DIFF_EQUAL:
  3524. html[x] = "<span>" + escapeText(data) + "</span>";
  3525. break;
  3526. }
  3527. }
  3528. return html.join("");
  3529. };
  3530. /**
  3531. * Determine the common prefix of two strings.
  3532. * @param {string} text1 First string.
  3533. * @param {string} text2 Second string.
  3534. * @return {number} The number of characters common to the start of each
  3535. * string.
  3536. */
  3537. DiffMatchPatch.prototype.diffCommonPrefix = function (text1, text2) {
  3538. var pointermid, pointermax, pointermin, pointerstart;
  3539. // Quick check for common null cases.
  3540. if (!text1 || !text2 || text1.charAt(0) !== text2.charAt(0)) {
  3541. return 0;
  3542. }
  3543. // Binary search.
  3544. // Performance analysis: https://neil.fraser.name/news/2007/10/09/
  3545. pointermin = 0;
  3546. pointermax = Math.min(text1.length, text2.length);
  3547. pointermid = pointermax;
  3548. pointerstart = 0;
  3549. while (pointermin < pointermid) {
  3550. if (text1.substring(pointerstart, pointermid) === text2.substring(pointerstart, pointermid)) {
  3551. pointermin = pointermid;
  3552. pointerstart = pointermin;
  3553. } else {
  3554. pointermax = pointermid;
  3555. }
  3556. pointermid = Math.floor((pointermax - pointermin) / 2 + pointermin);
  3557. }
  3558. return pointermid;
  3559. };
  3560. /**
  3561. * Determine the common suffix of two strings.
  3562. * @param {string} text1 First string.
  3563. * @param {string} text2 Second string.
  3564. * @return {number} The number of characters common to the end of each string.
  3565. */
  3566. DiffMatchPatch.prototype.diffCommonSuffix = function (text1, text2) {
  3567. var pointermid, pointermax, pointermin, pointerend;
  3568. // Quick check for common null cases.
  3569. if (!text1 || !text2 || text1.charAt(text1.length - 1) !== text2.charAt(text2.length - 1)) {
  3570. return 0;
  3571. }
  3572. // Binary search.
  3573. // Performance analysis: https://neil.fraser.name/news/2007/10/09/
  3574. pointermin = 0;
  3575. pointermax = Math.min(text1.length, text2.length);
  3576. pointermid = pointermax;
  3577. pointerend = 0;
  3578. while (pointermin < pointermid) {
  3579. if (text1.substring(text1.length - pointermid, text1.length - pointerend) === text2.substring(text2.length - pointermid, text2.length - pointerend)) {
  3580. pointermin = pointermid;
  3581. pointerend = pointermin;
  3582. } else {
  3583. pointermax = pointermid;
  3584. }
  3585. pointermid = Math.floor((pointermax - pointermin) / 2 + pointermin);
  3586. }
  3587. return pointermid;
  3588. };
  3589. /**
  3590. * Find the differences between two texts. Assumes that the texts do not
  3591. * have any common prefix or suffix.
  3592. * @param {string} text1 Old string to be diffed.
  3593. * @param {string} text2 New string to be diffed.
  3594. * @param {boolean} checklines Speedup flag. If false, then don't run a
  3595. * line-level diff first to identify the changed areas.
  3596. * If true, then run a faster, slightly less optimal diff.
  3597. * @param {number} deadline Time when the diff should be complete by.
  3598. * @return {!Array.<!DiffMatchPatch.Diff>} Array of diff tuples.
  3599. * @private
  3600. */
  3601. DiffMatchPatch.prototype.diffCompute = function (text1, text2, checklines, deadline) {
  3602. var diffs, longtext, shorttext, i, hm, text1A, text2A, text1B, text2B, midCommon, diffsA, diffsB;
  3603. if (!text1) {
  3604. // Just add some text (speedup).
  3605. return [[DIFF_INSERT, text2]];
  3606. }
  3607. if (!text2) {
  3608. // Just delete some text (speedup).
  3609. return [[DIFF_DELETE, text1]];
  3610. }
  3611. longtext = text1.length > text2.length ? text1 : text2;
  3612. shorttext = text1.length > text2.length ? text2 : text1;
  3613. i = longtext.indexOf(shorttext);
  3614. if (i !== -1) {
  3615. // Shorter text is inside the longer text (speedup).
  3616. diffs = [[DIFF_INSERT, longtext.substring(0, i)], [DIFF_EQUAL, shorttext], [DIFF_INSERT, longtext.substring(i + shorttext.length)]];
  3617. // Swap insertions for deletions if diff is reversed.
  3618. if (text1.length > text2.length) {
  3619. diffs[0][0] = diffs[2][0] = DIFF_DELETE;
  3620. }
  3621. return diffs;
  3622. }
  3623. if (shorttext.length === 1) {
  3624. // Single character string.
  3625. // After the previous speedup, the character can't be an equality.
  3626. return [[DIFF_DELETE, text1], [DIFF_INSERT, text2]];
  3627. }
  3628. // Check to see if the problem can be split in two.
  3629. hm = this.diffHalfMatch(text1, text2);
  3630. if (hm) {
  3631. // A half-match was found, sort out the return data.
  3632. text1A = hm[0];
  3633. text1B = hm[1];
  3634. text2A = hm[2];
  3635. text2B = hm[3];
  3636. midCommon = hm[4];
  3637. // Send both pairs off for separate processing.
  3638. diffsA = this.DiffMain(text1A, text2A, checklines, deadline);
  3639. diffsB = this.DiffMain(text1B, text2B, checklines, deadline);
  3640. // Merge the results.
  3641. return diffsA.concat([[DIFF_EQUAL, midCommon]], diffsB);
  3642. }
  3643. if (checklines && text1.length > 100 && text2.length > 100) {
  3644. return this.diffLineMode(text1, text2, deadline);
  3645. }
  3646. return this.diffBisect(text1, text2, deadline);
  3647. };
  3648. /**
  3649. * Do the two texts share a substring which is at least half the length of the
  3650. * longer text?
  3651. * This speedup can produce non-minimal diffs.
  3652. * @param {string} text1 First string.
  3653. * @param {string} text2 Second string.
  3654. * @return {Array.<string>} Five element Array, containing the prefix of
  3655. * text1, the suffix of text1, the prefix of text2, the suffix of
  3656. * text2 and the common middle. Or null if there was no match.
  3657. * @private
  3658. */
  3659. DiffMatchPatch.prototype.diffHalfMatch = function (text1, text2) {
  3660. var longtext, shorttext, dmp, text1A, text2B, text2A, text1B, midCommon, hm1, hm2, hm;
  3661. longtext = text1.length > text2.length ? text1 : text2;
  3662. shorttext = text1.length > text2.length ? text2 : text1;
  3663. if (longtext.length < 4 || shorttext.length * 2 < longtext.length) {
  3664. return null; // Pointless.
  3665. }
  3666. dmp = this; // 'this' becomes 'window' in a closure.
  3667. /**
  3668. * Does a substring of shorttext exist within longtext such that the substring
  3669. * is at least half the length of longtext?
  3670. * Closure, but does not reference any external variables.
  3671. * @param {string} longtext Longer string.
  3672. * @param {string} shorttext Shorter string.
  3673. * @param {number} i Start index of quarter length substring within longtext.
  3674. * @return {Array.<string>} Five element Array, containing the prefix of
  3675. * longtext, the suffix of longtext, the prefix of shorttext, the suffix
  3676. * of shorttext and the common middle. Or null if there was no match.
  3677. * @private
  3678. */
  3679. function diffHalfMatchI(longtext, shorttext, i) {
  3680. var seed, j, bestCommon, prefixLength, suffixLength, bestLongtextA, bestLongtextB, bestShorttextA, bestShorttextB;
  3681. // Start with a 1/4 length substring at position i as a seed.
  3682. seed = longtext.substring(i, i + Math.floor(longtext.length / 4));
  3683. j = -1;
  3684. bestCommon = "";
  3685. while ((j = shorttext.indexOf(seed, j + 1)) !== -1) {
  3686. prefixLength = dmp.diffCommonPrefix(longtext.substring(i), shorttext.substring(j));
  3687. suffixLength = dmp.diffCommonSuffix(longtext.substring(0, i), shorttext.substring(0, j));
  3688. if (bestCommon.length < suffixLength + prefixLength) {
  3689. bestCommon = shorttext.substring(j - suffixLength, j) + shorttext.substring(j, j + prefixLength);
  3690. bestLongtextA = longtext.substring(0, i - suffixLength);
  3691. bestLongtextB = longtext.substring(i + prefixLength);
  3692. bestShorttextA = shorttext.substring(0, j - suffixLength);
  3693. bestShorttextB = shorttext.substring(j + prefixLength);
  3694. }
  3695. }
  3696. if (bestCommon.length * 2 >= longtext.length) {
  3697. return [bestLongtextA, bestLongtextB, bestShorttextA, bestShorttextB, bestCommon];
  3698. } else {
  3699. return null;
  3700. }
  3701. }
  3702. // First check if the second quarter is the seed for a half-match.
  3703. hm1 = diffHalfMatchI(longtext, shorttext, Math.ceil(longtext.length / 4));
  3704. // Check again based on the third quarter.
  3705. hm2 = diffHalfMatchI(longtext, shorttext, Math.ceil(longtext.length / 2));
  3706. if (!hm1 && !hm2) {
  3707. return null;
  3708. } else if (!hm2) {
  3709. hm = hm1;
  3710. } else if (!hm1) {
  3711. hm = hm2;
  3712. } else {
  3713. // Both matched. Select the longest.
  3714. hm = hm1[4].length > hm2[4].length ? hm1 : hm2;
  3715. }
  3716. // A half-match was found, sort out the return data.
  3717. if (text1.length > text2.length) {
  3718. text1A = hm[0];
  3719. text1B = hm[1];
  3720. text2A = hm[2];
  3721. text2B = hm[3];
  3722. } else {
  3723. text2A = hm[0];
  3724. text2B = hm[1];
  3725. text1A = hm[2];
  3726. text1B = hm[3];
  3727. }
  3728. midCommon = hm[4];
  3729. return [text1A, text1B, text2A, text2B, midCommon];
  3730. };
  3731. /**
  3732. * Do a quick line-level diff on both strings, then rediff the parts for
  3733. * greater accuracy.
  3734. * This speedup can produce non-minimal diffs.
  3735. * @param {string} text1 Old string to be diffed.
  3736. * @param {string} text2 New string to be diffed.
  3737. * @param {number} deadline Time when the diff should be complete by.
  3738. * @return {!Array.<!DiffMatchPatch.Diff>} Array of diff tuples.
  3739. * @private
  3740. */
  3741. DiffMatchPatch.prototype.diffLineMode = function (text1, text2, deadline) {
  3742. var a, diffs, linearray, pointer, countInsert, countDelete, textInsert, textDelete, j;
  3743. // Scan the text on a line-by-line basis first.
  3744. a = this.diffLinesToChars(text1, text2);
  3745. text1 = a.chars1;
  3746. text2 = a.chars2;
  3747. linearray = a.lineArray;
  3748. diffs = this.DiffMain(text1, text2, false, deadline);
  3749. // Convert the diff back to original text.
  3750. this.diffCharsToLines(diffs, linearray);
  3751. // Eliminate freak matches (e.g. blank lines)
  3752. this.diffCleanupSemantic(diffs);
  3753. // Rediff any replacement blocks, this time character-by-character.
  3754. // Add a dummy entry at the end.
  3755. diffs.push([DIFF_EQUAL, ""]);
  3756. pointer = 0;
  3757. countDelete = 0;
  3758. countInsert = 0;
  3759. textDelete = "";
  3760. textInsert = "";
  3761. while (pointer < diffs.length) {
  3762. switch (diffs[pointer][0]) {
  3763. case DIFF_INSERT:
  3764. countInsert++;
  3765. textInsert += diffs[pointer][1];
  3766. break;
  3767. case DIFF_DELETE:
  3768. countDelete++;
  3769. textDelete += diffs[pointer][1];
  3770. break;
  3771. case DIFF_EQUAL:
  3772. // Upon reaching an equality, check for prior redundancies.
  3773. if (countDelete >= 1 && countInsert >= 1) {
  3774. // Delete the offending records and add the merged ones.
  3775. diffs.splice(pointer - countDelete - countInsert, countDelete + countInsert);
  3776. pointer = pointer - countDelete - countInsert;
  3777. a = this.DiffMain(textDelete, textInsert, false, deadline);
  3778. for (j = a.length - 1; j >= 0; j--) {
  3779. diffs.splice(pointer, 0, a[j]);
  3780. }
  3781. pointer = pointer + a.length;
  3782. }
  3783. countInsert = 0;
  3784. countDelete = 0;
  3785. textDelete = "";
  3786. textInsert = "";
  3787. break;
  3788. }
  3789. pointer++;
  3790. }
  3791. diffs.pop(); // Remove the dummy entry at the end.
  3792. return diffs;
  3793. };
  3794. /**
  3795. * Find the 'middle snake' of a diff, split the problem in two
  3796. * and return the recursively constructed diff.
  3797. * See Myers 1986 paper: An O(ND) Difference Algorithm and Its Variations.
  3798. * @param {string} text1 Old string to be diffed.
  3799. * @param {string} text2 New string to be diffed.
  3800. * @param {number} deadline Time at which to bail if not yet complete.
  3801. * @return {!Array.<!DiffMatchPatch.Diff>} Array of diff tuples.
  3802. * @private
  3803. */
  3804. DiffMatchPatch.prototype.diffBisect = function (text1, text2, deadline) {
  3805. var text1Length, text2Length, maxD, vOffset, vLength, v1, v2, x, delta, front, k1start, k1end, k2start, k2end, k2Offset, k1Offset, x1, x2, y1, y2, d, k1, k2;
  3806. // Cache the text lengths to prevent multiple calls.
  3807. text1Length = text1.length;
  3808. text2Length = text2.length;
  3809. maxD = Math.ceil((text1Length + text2Length) / 2);
  3810. vOffset = maxD;
  3811. vLength = 2 * maxD;
  3812. v1 = new Array(vLength);
  3813. v2 = new Array(vLength);
  3814. // Setting all elements to -1 is faster in Chrome & Firefox than mixing
  3815. // integers and undefined.
  3816. for (x = 0; x < vLength; x++) {
  3817. v1[x] = -1;
  3818. v2[x] = -1;
  3819. }
  3820. v1[vOffset + 1] = 0;
  3821. v2[vOffset + 1] = 0;
  3822. delta = text1Length - text2Length;
  3823. // If the total number of characters is odd, then the front path will collide
  3824. // with the reverse path.
  3825. front = delta % 2 !== 0;
  3826. // Offsets for start and end of k loop.
  3827. // Prevents mapping of space beyond the grid.
  3828. k1start = 0;
  3829. k1end = 0;
  3830. k2start = 0;
  3831. k2end = 0;
  3832. for (d = 0; d < maxD; d++) {
  3833. // Bail out if deadline is reached.
  3834. if (new Date().getTime() > deadline) {
  3835. break;
  3836. }
  3837. // Walk the front path one step.
  3838. for (k1 = -d + k1start; k1 <= d - k1end; k1 += 2) {
  3839. k1Offset = vOffset + k1;
  3840. if (k1 === -d || k1 !== d && v1[k1Offset - 1] < v1[k1Offset + 1]) {
  3841. x1 = v1[k1Offset + 1];
  3842. } else {
  3843. x1 = v1[k1Offset - 1] + 1;
  3844. }
  3845. y1 = x1 - k1;
  3846. while (x1 < text1Length && y1 < text2Length && text1.charAt(x1) === text2.charAt(y1)) {
  3847. x1++;
  3848. y1++;
  3849. }
  3850. v1[k1Offset] = x1;
  3851. if (x1 > text1Length) {
  3852. // Ran off the right of the graph.
  3853. k1end += 2;
  3854. } else if (y1 > text2Length) {
  3855. // Ran off the bottom of the graph.
  3856. k1start += 2;
  3857. } else if (front) {
  3858. k2Offset = vOffset + delta - k1;
  3859. if (k2Offset >= 0 && k2Offset < vLength && v2[k2Offset] !== -1) {
  3860. // Mirror x2 onto top-left coordinate system.
  3861. x2 = text1Length - v2[k2Offset];
  3862. if (x1 >= x2) {
  3863. // Overlap detected.
  3864. return this.diffBisectSplit(text1, text2, x1, y1, deadline);
  3865. }
  3866. }
  3867. }
  3868. }
  3869. // Walk the reverse path one step.
  3870. for (k2 = -d + k2start; k2 <= d - k2end; k2 += 2) {
  3871. k2Offset = vOffset + k2;
  3872. if (k2 === -d || k2 !== d && v2[k2Offset - 1] < v2[k2Offset + 1]) {
  3873. x2 = v2[k2Offset + 1];
  3874. } else {
  3875. x2 = v2[k2Offset - 1] + 1;
  3876. }
  3877. y2 = x2 - k2;
  3878. while (x2 < text1Length && y2 < text2Length && text1.charAt(text1Length - x2 - 1) === text2.charAt(text2Length - y2 - 1)) {
  3879. x2++;
  3880. y2++;
  3881. }
  3882. v2[k2Offset] = x2;
  3883. if (x2 > text1Length) {
  3884. // Ran off the left of the graph.
  3885. k2end += 2;
  3886. } else if (y2 > text2Length) {
  3887. // Ran off the top of the graph.
  3888. k2start += 2;
  3889. } else if (!front) {
  3890. k1Offset = vOffset + delta - k2;
  3891. if (k1Offset >= 0 && k1Offset < vLength && v1[k1Offset] !== -1) {
  3892. x1 = v1[k1Offset];
  3893. y1 = vOffset + x1 - k1Offset;
  3894. // Mirror x2 onto top-left coordinate system.
  3895. x2 = text1Length - x2;
  3896. if (x1 >= x2) {
  3897. // Overlap detected.
  3898. return this.diffBisectSplit(text1, text2, x1, y1, deadline);
  3899. }
  3900. }
  3901. }
  3902. }
  3903. }
  3904. // Diff took too long and hit the deadline or
  3905. // number of diffs equals number of characters, no commonality at all.
  3906. return [[DIFF_DELETE, text1], [DIFF_INSERT, text2]];
  3907. };
  3908. /**
  3909. * Given the location of the 'middle snake', split the diff in two parts
  3910. * and recurse.
  3911. * @param {string} text1 Old string to be diffed.
  3912. * @param {string} text2 New string to be diffed.
  3913. * @param {number} x Index of split point in text1.
  3914. * @param {number} y Index of split point in text2.
  3915. * @param {number} deadline Time at which to bail if not yet complete.
  3916. * @return {!Array.<!DiffMatchPatch.Diff>} Array of diff tuples.
  3917. * @private
  3918. */
  3919. DiffMatchPatch.prototype.diffBisectSplit = function (text1, text2, x, y, deadline) {
  3920. var text1a, text1b, text2a, text2b, diffs, diffsb;
  3921. text1a = text1.substring(0, x);
  3922. text2a = text2.substring(0, y);
  3923. text1b = text1.substring(x);
  3924. text2b = text2.substring(y);
  3925. // Compute both diffs serially.
  3926. diffs = this.DiffMain(text1a, text2a, false, deadline);
  3927. diffsb = this.DiffMain(text1b, text2b, false, deadline);
  3928. return diffs.concat(diffsb);
  3929. };
  3930. /**
  3931. * Reduce the number of edits by eliminating semantically trivial equalities.
  3932. * @param {!Array.<!DiffMatchPatch.Diff>} diffs Array of diff tuples.
  3933. */
  3934. DiffMatchPatch.prototype.diffCleanupSemantic = function (diffs) {
  3935. var changes, equalities, equalitiesLength, lastequality, pointer, lengthInsertions2, lengthDeletions2, lengthInsertions1, lengthDeletions1, deletion, insertion, overlapLength1, overlapLength2;
  3936. changes = false;
  3937. equalities = []; // Stack of indices where equalities are found.
  3938. equalitiesLength = 0; // Keeping our own length var is faster in JS.
  3939. /** @type {?string} */
  3940. lastequality = null;
  3941. // Always equal to diffs[equalities[equalitiesLength - 1]][1]
  3942. pointer = 0; // Index of current position.
  3943. // Number of characters that changed prior to the equality.
  3944. lengthInsertions1 = 0;
  3945. lengthDeletions1 = 0;
  3946. // Number of characters that changed after the equality.
  3947. lengthInsertions2 = 0;
  3948. lengthDeletions2 = 0;
  3949. while (pointer < diffs.length) {
  3950. if (diffs[pointer][0] === DIFF_EQUAL) {
  3951. // Equality found.
  3952. equalities[equalitiesLength++] = pointer;
  3953. lengthInsertions1 = lengthInsertions2;
  3954. lengthDeletions1 = lengthDeletions2;
  3955. lengthInsertions2 = 0;
  3956. lengthDeletions2 = 0;
  3957. lastequality = diffs[pointer][1];
  3958. } else {
  3959. // An insertion or deletion.
  3960. if (diffs[pointer][0] === DIFF_INSERT) {
  3961. lengthInsertions2 += diffs[pointer][1].length;
  3962. } else {
  3963. lengthDeletions2 += diffs[pointer][1].length;
  3964. }
  3965. // Eliminate an equality that is smaller or equal to the edits on both
  3966. // sides of it.
  3967. if (lastequality && lastequality.length <= Math.max(lengthInsertions1, lengthDeletions1) && lastequality.length <= Math.max(lengthInsertions2, lengthDeletions2)) {
  3968. // Duplicate record.
  3969. diffs.splice(equalities[equalitiesLength - 1], 0, [DIFF_DELETE, lastequality]);
  3970. // Change second copy to insert.
  3971. diffs[equalities[equalitiesLength - 1] + 1][0] = DIFF_INSERT;
  3972. // Throw away the equality we just deleted.
  3973. equalitiesLength--;
  3974. // Throw away the previous equality (it needs to be reevaluated).
  3975. equalitiesLength--;
  3976. pointer = equalitiesLength > 0 ? equalities[equalitiesLength - 1] : -1;
  3977. // Reset the counters.
  3978. lengthInsertions1 = 0;
  3979. lengthDeletions1 = 0;
  3980. lengthInsertions2 = 0;
  3981. lengthDeletions2 = 0;
  3982. lastequality = null;
  3983. changes = true;
  3984. }
  3985. }
  3986. pointer++;
  3987. }
  3988. // Normalize the diff.
  3989. if (changes) {
  3990. this.diffCleanupMerge(diffs);
  3991. }
  3992. // Find any overlaps between deletions and insertions.
  3993. // e.g: <del>abcxxx</del><ins>xxxdef</ins>
  3994. // -> <del>abc</del>xxx<ins>def</ins>
  3995. // e.g: <del>xxxabc</del><ins>defxxx</ins>
  3996. // -> <ins>def</ins>xxx<del>abc</del>
  3997. // Only extract an overlap if it is as big as the edit ahead or behind it.
  3998. pointer = 1;
  3999. while (pointer < diffs.length) {
  4000. if (diffs[pointer - 1][0] === DIFF_DELETE && diffs[pointer][0] === DIFF_INSERT) {
  4001. deletion = diffs[pointer - 1][1];
  4002. insertion = diffs[pointer][1];
  4003. overlapLength1 = this.diffCommonOverlap(deletion, insertion);
  4004. overlapLength2 = this.diffCommonOverlap(insertion, deletion);
  4005. if (overlapLength1 >= overlapLength2) {
  4006. if (overlapLength1 >= deletion.length / 2 || overlapLength1 >= insertion.length / 2) {
  4007. // Overlap found. Insert an equality and trim the surrounding edits.
  4008. diffs.splice(pointer, 0, [DIFF_EQUAL, insertion.substring(0, overlapLength1)]);
  4009. diffs[pointer - 1][1] = deletion.substring(0, deletion.length - overlapLength1);
  4010. diffs[pointer + 1][1] = insertion.substring(overlapLength1);
  4011. pointer++;
  4012. }
  4013. } else {
  4014. if (overlapLength2 >= deletion.length / 2 || overlapLength2 >= insertion.length / 2) {
  4015. // Reverse overlap found.
  4016. // Insert an equality and swap and trim the surrounding edits.
  4017. diffs.splice(pointer, 0, [DIFF_EQUAL, deletion.substring(0, overlapLength2)]);
  4018. diffs[pointer - 1][0] = DIFF_INSERT;
  4019. diffs[pointer - 1][1] = insertion.substring(0, insertion.length - overlapLength2);
  4020. diffs[pointer + 1][0] = DIFF_DELETE;
  4021. diffs[pointer + 1][1] = deletion.substring(overlapLength2);
  4022. pointer++;
  4023. }
  4024. }
  4025. pointer++;
  4026. }
  4027. pointer++;
  4028. }
  4029. };
  4030. /**
  4031. * Determine if the suffix of one string is the prefix of another.
  4032. * @param {string} text1 First string.
  4033. * @param {string} text2 Second string.
  4034. * @return {number} The number of characters common to the end of the first
  4035. * string and the start of the second string.
  4036. * @private
  4037. */
  4038. DiffMatchPatch.prototype.diffCommonOverlap = function (text1, text2) {
  4039. var text1Length, text2Length, textLength, best, length, pattern, found;
  4040. // Cache the text lengths to prevent multiple calls.
  4041. text1Length = text1.length;
  4042. text2Length = text2.length;
  4043. // Eliminate the null case.
  4044. if (text1Length === 0 || text2Length === 0) {
  4045. return 0;
  4046. }
  4047. // Truncate the longer string.
  4048. if (text1Length > text2Length) {
  4049. text1 = text1.substring(text1Length - text2Length);
  4050. } else if (text1Length < text2Length) {
  4051. text2 = text2.substring(0, text1Length);
  4052. }
  4053. textLength = Math.min(text1Length, text2Length);
  4054. // Quick check for the worst case.
  4055. if (text1 === text2) {
  4056. return textLength;
  4057. }
  4058. // Start by looking for a single character match
  4059. // and increase length until no match is found.
  4060. // Performance analysis: https://neil.fraser.name/news/2010/11/04/
  4061. best = 0;
  4062. length = 1;
  4063. while (true) {
  4064. pattern = text1.substring(textLength - length);
  4065. found = text2.indexOf(pattern);
  4066. if (found === -1) {
  4067. return best;
  4068. }
  4069. length += found;
  4070. if (found === 0 || text1.substring(textLength - length) === text2.substring(0, length)) {
  4071. best = length;
  4072. length++;
  4073. }
  4074. }
  4075. };
  4076. /**
  4077. * Split two texts into an array of strings. Reduce the texts to a string of
  4078. * hashes where each Unicode character represents one line.
  4079. * @param {string} text1 First string.
  4080. * @param {string} text2 Second string.
  4081. * @return {{chars1: string, chars2: string, lineArray: !Array.<string>}}
  4082. * An object containing the encoded text1, the encoded text2 and
  4083. * the array of unique strings.
  4084. * The zeroth element of the array of unique strings is intentionally blank.
  4085. * @private
  4086. */
  4087. DiffMatchPatch.prototype.diffLinesToChars = function (text1, text2) {
  4088. var lineArray, lineHash, chars1, chars2;
  4089. lineArray = []; // E.g. lineArray[4] === 'Hello\n'
  4090. lineHash = {}; // E.g. lineHash['Hello\n'] === 4
  4091. // '\x00' is a valid character, but various debuggers don't like it.
  4092. // So we'll insert a junk entry to avoid generating a null character.
  4093. lineArray[0] = "";
  4094. /**
  4095. * Split a text into an array of strings. Reduce the texts to a string of
  4096. * hashes where each Unicode character represents one line.
  4097. * Modifies linearray and linehash through being a closure.
  4098. * @param {string} text String to encode.
  4099. * @return {string} Encoded string.
  4100. * @private
  4101. */
  4102. function diffLinesToCharsMunge(text) {
  4103. var chars, lineStart, lineEnd, lineArrayLength, line;
  4104. chars = "";
  4105. // Walk the text, pulling out a substring for each line.
  4106. // text.split('\n') would would temporarily double our memory footprint.
  4107. // Modifying text would create many large strings to garbage collect.
  4108. lineStart = 0;
  4109. lineEnd = -1;
  4110. // Keeping our own length variable is faster than looking it up.
  4111. lineArrayLength = lineArray.length;
  4112. while (lineEnd < text.length - 1) {
  4113. lineEnd = text.indexOf("\n", lineStart);
  4114. if (lineEnd === -1) {
  4115. lineEnd = text.length - 1;
  4116. }
  4117. line = text.substring(lineStart, lineEnd + 1);
  4118. lineStart = lineEnd + 1;
  4119. var lineHashExists = lineHash.hasOwnProperty ? lineHash.hasOwnProperty(line) : lineHash[line] !== undefined;
  4120. if (lineHashExists) {
  4121. chars += String.fromCharCode(lineHash[line]);
  4122. } else {
  4123. chars += String.fromCharCode(lineArrayLength);
  4124. lineHash[line] = lineArrayLength;
  4125. lineArray[lineArrayLength++] = line;
  4126. }
  4127. }
  4128. return chars;
  4129. }
  4130. chars1 = diffLinesToCharsMunge(text1);
  4131. chars2 = diffLinesToCharsMunge(text2);
  4132. return {
  4133. chars1: chars1,
  4134. chars2: chars2,
  4135. lineArray: lineArray
  4136. };
  4137. };
  4138. /**
  4139. * Rehydrate the text in a diff from a string of line hashes to real lines of
  4140. * text.
  4141. * @param {!Array.<!DiffMatchPatch.Diff>} diffs Array of diff tuples.
  4142. * @param {!Array.<string>} lineArray Array of unique strings.
  4143. * @private
  4144. */
  4145. DiffMatchPatch.prototype.diffCharsToLines = function (diffs, lineArray) {
  4146. var x, chars, text, y;
  4147. for (x = 0; x < diffs.length; x++) {
  4148. chars = diffs[x][1];
  4149. text = [];
  4150. for (y = 0; y < chars.length; y++) {
  4151. text[y] = lineArray[chars.charCodeAt(y)];
  4152. }
  4153. diffs[x][1] = text.join("");
  4154. }
  4155. };
  4156. /**
  4157. * Reorder and merge like edit sections. Merge equalities.
  4158. * Any edit section can move as long as it doesn't cross an equality.
  4159. * @param {!Array.<!DiffMatchPatch.Diff>} diffs Array of diff tuples.
  4160. */
  4161. DiffMatchPatch.prototype.diffCleanupMerge = function (diffs) {
  4162. var pointer, countDelete, countInsert, textInsert, textDelete, commonlength, changes, diffPointer, position;
  4163. diffs.push([DIFF_EQUAL, ""]); // Add a dummy entry at the end.
  4164. pointer = 0;
  4165. countDelete = 0;
  4166. countInsert = 0;
  4167. textDelete = "";
  4168. textInsert = "";
  4169. while (pointer < diffs.length) {
  4170. switch (diffs[pointer][0]) {
  4171. case DIFF_INSERT:
  4172. countInsert++;
  4173. textInsert += diffs[pointer][1];
  4174. pointer++;
  4175. break;
  4176. case DIFF_DELETE:
  4177. countDelete++;
  4178. textDelete += diffs[pointer][1];
  4179. pointer++;
  4180. break;
  4181. case DIFF_EQUAL:
  4182. // Upon reaching an equality, check for prior redundancies.
  4183. if (countDelete + countInsert > 1) {
  4184. if (countDelete !== 0 && countInsert !== 0) {
  4185. // Factor out any common prefixes.
  4186. commonlength = this.diffCommonPrefix(textInsert, textDelete);
  4187. if (commonlength !== 0) {
  4188. if (pointer - countDelete - countInsert > 0 && diffs[pointer - countDelete - countInsert - 1][0] === DIFF_EQUAL) {
  4189. diffs[pointer - countDelete - countInsert - 1][1] += textInsert.substring(0, commonlength);
  4190. } else {
  4191. diffs.splice(0, 0, [DIFF_EQUAL, textInsert.substring(0, commonlength)]);
  4192. pointer++;
  4193. }
  4194. textInsert = textInsert.substring(commonlength);
  4195. textDelete = textDelete.substring(commonlength);
  4196. }
  4197. // Factor out any common suffixies.
  4198. commonlength = this.diffCommonSuffix(textInsert, textDelete);
  4199. if (commonlength !== 0) {
  4200. diffs[pointer][1] = textInsert.substring(textInsert.length - commonlength) + diffs[pointer][1];
  4201. textInsert = textInsert.substring(0, textInsert.length - commonlength);
  4202. textDelete = textDelete.substring(0, textDelete.length - commonlength);
  4203. }
  4204. }
  4205. // Delete the offending records and add the merged ones.
  4206. if (countDelete === 0) {
  4207. diffs.splice(pointer - countInsert, countDelete + countInsert, [DIFF_INSERT, textInsert]);
  4208. } else if (countInsert === 0) {
  4209. diffs.splice(pointer - countDelete, countDelete + countInsert, [DIFF_DELETE, textDelete]);
  4210. } else {
  4211. diffs.splice(pointer - countDelete - countInsert, countDelete + countInsert, [DIFF_DELETE, textDelete], [DIFF_INSERT, textInsert]);
  4212. }
  4213. pointer = pointer - countDelete - countInsert + (countDelete ? 1 : 0) + (countInsert ? 1 : 0) + 1;
  4214. } else if (pointer !== 0 && diffs[pointer - 1][0] === DIFF_EQUAL) {
  4215. // Merge this equality with the previous one.
  4216. diffs[pointer - 1][1] += diffs[pointer][1];
  4217. diffs.splice(pointer, 1);
  4218. } else {
  4219. pointer++;
  4220. }
  4221. countInsert = 0;
  4222. countDelete = 0;
  4223. textDelete = "";
  4224. textInsert = "";
  4225. break;
  4226. }
  4227. }
  4228. if (diffs[diffs.length - 1][1] === "") {
  4229. diffs.pop(); // Remove the dummy entry at the end.
  4230. }
  4231. // Second pass: look for single edits surrounded on both sides by equalities
  4232. // which can be shifted sideways to eliminate an equality.
  4233. // e.g: A<ins>BA</ins>C -> <ins>AB</ins>AC
  4234. changes = false;
  4235. pointer = 1;
  4236. // Intentionally ignore the first and last element (don't need checking).
  4237. while (pointer < diffs.length - 1) {
  4238. if (diffs[pointer - 1][0] === DIFF_EQUAL && diffs[pointer + 1][0] === DIFF_EQUAL) {
  4239. diffPointer = diffs[pointer][1];
  4240. position = diffPointer.substring(diffPointer.length - diffs[pointer - 1][1].length);
  4241. // This is a single edit surrounded by equalities.
  4242. if (position === diffs[pointer - 1][1]) {
  4243. // Shift the edit over the previous equality.
  4244. diffs[pointer][1] = diffs[pointer - 1][1] + diffs[pointer][1].substring(0, diffs[pointer][1].length - diffs[pointer - 1][1].length);
  4245. diffs[pointer + 1][1] = diffs[pointer - 1][1] + diffs[pointer + 1][1];
  4246. diffs.splice(pointer - 1, 1);
  4247. changes = true;
  4248. } else if (diffPointer.substring(0, diffs[pointer + 1][1].length) === diffs[pointer + 1][1]) {
  4249. // Shift the edit over the next equality.
  4250. diffs[pointer - 1][1] += diffs[pointer + 1][1];
  4251. diffs[pointer][1] = diffs[pointer][1].substring(diffs[pointer + 1][1].length) + diffs[pointer + 1][1];
  4252. diffs.splice(pointer + 1, 1);
  4253. changes = true;
  4254. }
  4255. }
  4256. pointer++;
  4257. }
  4258. // If shifts were made, the diff needs reordering and another shift sweep.
  4259. if (changes) {
  4260. this.diffCleanupMerge(diffs);
  4261. }
  4262. };
  4263. return function (o, n) {
  4264. var diff, output, text;
  4265. diff = new DiffMatchPatch();
  4266. output = diff.DiffMain(o, n);
  4267. diff.diffCleanupEfficiency(output);
  4268. text = diff.diffPrettyHtml(output);
  4269. return text;
  4270. };
  4271. }();
  4272. }((function() { return this; }())));